<?php

/**
 *      【橙创家校通v4.0】 (C)2010-2012 Tuntron Inc.
 *      
 *    	 http://www.tuntron.com   QQ：1121251729
 *
 *      &用户基类文件&
 */

if (!defined('IS_RUN')) die('Forbidden');

class tj_user extends tj_model {
	
	var $dbpre;
	var $table = 'dbpre_users';
    var $key = 'uid';
	var $isLogin = '';
	var $userbid = '';
    var $hash = '';
    var $passport = array();
	var $uid ='';
	var $cpwd =1;
	var $username='';
	var  $G ;

    function __construct() {
    	global $_G;
        parent::__construct();
        $this->model_flag = 'user';
		$this->G =  G_class('usergroup');   //加载用户组类
		$this->B =  G_class('branch');      //加载部门类
        $this->init_field();
        $this->dbpre = $_G['dbinfo']['dbpre'];
    }

    function tj_user() {
        $this->__construct();
    }
	
	//过滤当前表字段
    function init_field() {
		$this->add_field('uid,username,phonenum,sex,realname,face,oldpasswd,password,password2,stu_num,email,groupid,bid,h_send_sms,nexttime,nextgroupid,resetpwd');
		$this->add_field_fun('username,realname', '_T');
        $this->add_field_fun('uid,groupid,bid,nexttime,nextgroupid,stu_num', 'intval');
        $this->add_field_fun('oldpasswd,password,password2,email', 'trim');
    }
	
	//读取用户
	function & read($uid,$isusername=FALSE,$select='*') {
        $result = '';
        if(!$isusername) {
            if(!$uid = (int) $uid) return $result;
            $result = parent::read($uid);
			if(empty($result['face'])&&$result['sex']==0) $result['face']='images/f_g.gif';
			if(empty($result['face'])&&$result['sex']==1) $result['face']='images/f_m.gif';
            return $result;
        }
        $this->db->from($this->table);
        $this->db->select($select);
        $this->db->where('username', $uid);
        if($row = $this->db->get()) {
            $result = $row->fetch_array();
            $row->free_result();
        }
        return $result;
    }
	
	//读取孩子用户
	function read_child($uid,$select='*') {
		
		 $this->db->from($this->table);
        $this->db->select($select);
        $this->db->where('parent_id', $uid);
        if($row = $this->db->get()) {
            $result = $row->fetch_array();
            $row->free_result();
        }
        return $result;
    }
	
	
	//读取用户数组
	function arrmember($gid,$bid,$c,$select='*',$keyword='') {
		
        $result = array();
		$this->db->from($this->table);
		$this->db->select($select);
		if($gid=='isbaned') $this->db->where('isbaned','0');
		if($keyword) $this->db->where_like('realname', '%'.trim($keyword).'%');
		
		$this->db->order_by('uid','DESC');
		
		 if($row = $this->db->get()) {
          	$results = $row->fetch_all_assoc();
        }
		if($gid){
			
			$gid = $gid;
			
			$gidarr = explode('_',$gid);
		}
		
		foreach($results as $key=>$item){
			
				
				if(in_array($item['groupid'],$gidarr)){
					
				$result[$key] = $item;
				
				if($item['groupid']){
					$result[$key]['usergroup'] = $this->G ->read($item['groupid']);
				}
				if($item['bid']){
					
					$result[$key]['branch'] = $this->B ->read($item['bid']);
					$bname = $this->B->findbranch($item['bid']);
					$result[$key]['branch']['bname']=$bname;
					
				}
					
				}elseif($gid=='isbaned'){
					
				$result[$key] = $item;
				$result[$key]['usergroup'] = $this->G->read($item['groupid']);
				}
			}
			
		if($bid>1){
		foreach($result as $key=>$item){
			
			$bname = $this->B->findbranch($bid);
			$bstr = $item['branch']['bname'];
			$rep = str_replace($bname,"",$bstr);
			if($rep!==$bstr||$bstr==$bname){
				
				$result_l[$key] = $item;
			}
			
			
			
		}
		
		}else{
			
			$result_l = $result;
		}
		
		//print_r($result);
		$total = count($result_l);
		$result_l = array($total,$result_l);
		return $result_l;
        
    }
	
	  function & find($where, $start, $offset) {
        $result = array();
        $this->db->from($this->table);
        if($where['username']) {
            $this->db->where_like('username', '%'.$where['username'].'%');
            unset($where['username']);
        }
        if($where) {
            foreach($where as $key => $val) $this->db->where($key, $val);
        }
        $total = $this->db->count();
        if(!$total) {
            $result = array(0,'');
            return $result;
        }
        $this->db->sql_roll_back('from,where');
        $this->db->order_by('uid');
        $this->db->limit($start, $offset);
        $result = array($total, $this->db->get());
        return $result;
    }

    function save(& $post,$uid=null) {
        $edit = $uid > 0;
		if($post['groupid']==5)   Note('本系统家长账户和学生账户是绑定的，只需导入学生账户系统便自动生成家长账户！');
        if($post['password'] != $post['password2']) {
            Note('两次输入的密码不一样，请重新输入！');
        }
        if($this->in_admin && empty($post['password'])) unset($post['password']);
        if($post['password']) {
			$this->check_password($post['password']);
			$post['password'] = md5($post['password']);
		}
		
		if($post['username']) {
			$this->check_username($post['username']);
		}
		if($post['groupid']==6){
			
			$post_p=$post;
			$post_p['groupid']= 5;
			$post_p['username']= 'p'.$post['username'];
			$post_p['realname']= $post['realname'].'的家长';

		}

        unset($post['password2']);
		unset($post_p['password2']);
        $post['nexttime'] =$post_p['nexttime'] = $post['nexttime'] ? strtotime($post['nexttime']) : 0;
	
		if($post['groupid']==6) $post['parent_id'] = parent::save($post_p, $uid);//转到父类保存
        $uid = parent::save($post, $uid);//转到父类保存

        // update point
        if(!$edit) {
           // $P =& $this->loader->model('member:point'); 处理更新
            //$P->update_point($uid, 'reg');
            //发送短消息
           // if($this->modcfg['salutatory']) $this->_send_salutatory_msg($uid);
        }
        return $uid;
    }
	

    //从反向整合
    function save_passport($post) {
        $this->db->from($this->table);
        $this->db->set($post);
        $this->db->insert();
        $uid = $this->db->insert_id();
        if(!$edit) {
            $P =& $this->loader->model('member:point');
            $P->update_point($uid, 'reg');
            //发送短消息
            if($this->modcfg['salutatory']) $this->_send_salutatory_msg($uid);
        }
        return $uid;
    }

    //更新短信数
    function update_smsnum($uid,$smsnum) {
        if(!$uid = abs ( (int) $uid)) Note(lang('global_sql_keyid_invalid','uid'));
        $this->db->from($this->table);
        $this->db->where('uid',$uid);
        $this->db->set('sms_balance',$smsnum);
        $this->db->update();
    }
	
	//更新已发短信数
    function update_h_smsnum($uid,$smsnum) {
        if(!$uid = abs ( (int) $uid)) Note(lang('global_sql_keyid_invalid','uid'));
        $this->db->from($this->table);
        $this->db->where('uid',$uid);
        $this->db->set('h_send_sms',$smsnum);
        $this->db->update();
    }
	
	//重置密码
    function update_resetpwd($email,$resetpwd,$type='email') {
        $this->db->from($this->table);
        $this->db->where($type,$email);
        $this->db->set('resetpwd',$resetpwd);
        $this->db->update();
    }
	
	//read by mobile
    function read_by_mobile($mobile) {
        $this->db->from($this->table);
        $this->db->where('phonenum',$mobile);
       	return $this->db->once_fetch_assoc();
    }
	
	//read by email
    function read_by_email($email) {
        $this->db->from($this->table);
        $this->db->where('email',$email);
       	return $this->db->once_fetch_assoc();
    }

    function delete($ids) {
        $ids = $this->get_keyids($ids);
        $this->db->where_in($this->key, $ids);
        $this->db->from($this->table);
        $this->db->delete();
        //其他模块关联的HOOK
        foreach(array_keys($this->global['modules']) as $flag) {
            if($flag == $this->model_flag) continue;
            $file = MUDDER_MODULE . $flag . DS . 'inc' . DS . 'member_delete_hook.php';
            if(is_file($file)) {
                @include $file;
            }
        }
    }
	
	function deleteusers($uid,$stop=TRUE) {
		
		$member = $this->read($uid);
		
		if($member['groupid']==6&&$stop){
			
			if($p_member = $this->read('p'.$member['username'],1)){
			$this->deleteusers($p_member['uid'],FALSE);
			}
			
		}
		
		if($member['groupid']==5&&$stop){
			if($s_member = $this->read(substr($member['username'],1),1)){
			$this->deleteusers($s_member['uid'],FALSE);
			}
			
		}
		
		
        $this->db->where('uid', $uid);  
		
		$this->db->from($this->table);     

        $this->db->delete();
		
        
    }
	
	function isbanedusers($uid,$isbaned='1') {
		$update = TRUE;
		$this->db->from($this->table);     
		$this->db->where('uid', $uid);  
		$this->db->set('isbaned',$isbaned);
        $this->db->update();
    }

    function check_post(& $post, $isedit) {
       	
		
		 if(!$post['realname'] && !$isedit) {
            Note('提交的姓名不能为空！');
        }
		
        if(!$post['username'] && !$isedit) {
            Note('提交的用户名不能为空！');
        } elseif(!$isedit && $post['username']) {
            $this->check_username($post['username']);
        }
        if(!$post['password'] && !$isedit) {
            Note('提交的密码不能为空！');
        }
        if($post['password']) {
            $this->check_password($post['password']);
        }
		/* 密码可以为空
        if(!$post['email'] || is_email($post['email'])) {
            Note('member_post_empty_email');
        }
		 if($post['groupid'] && $post['groupid'] < 0) {
            Note('member_post_empty_group');
        }
		*/
       
        if(!$isedit) {
            if($this->check_username_exists($post['username'])) 
                Note('提交的用户名已经被使用！');
               // if($this->check_email_exists($post['email'])) 
                  
        }
    }

    function check_username_exists($username, $without_uid = null) {
        $this->db->from($this->table);
        $this->db->where('username',$username);
        if($without_uid > 0) $this->db->where_not_equal('uid', $without_uid);
        return $this->db->count() > 0;
    }

    function check_email_exists($email, $without_uid = null) {
		if(!$email) Note('Email不能为空！');
        $this->db->from($this->table);
        $this->db->where('email',$email);
        if($without_uid > 0) $this->db->where_not_equal('uid', $without_uid);
        return $this->db->count() > 0;
    }

    function check_username($username, $echo = FALSE) {
        if(strlen($username) > 15) {
            if($echo) {echo '<font color="red">用户名不能大于15个字符</font>'; exit;}
            return Note('<font color="red">用户名不能大于15个字符</font>');
        }
        $guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
        if(preg_match("/^\s*$|^c:\\con\\con$|[%,\*\"\s\t\<\>\&]|$guestexp/is", $username)) {
            if($echo) {echo  '用户名不得包含(,)、(*)、(")、([TAB])、([SPACE])、([\r])、([\n])、(&lt;)、(&gt;)、(&amp;)其中之一'; exit;}
            Note( '用户名不得包含(,)、(*)、(")、([TAB])、([SPACE])、([\r])、([\n])、(&lt;)、(&gt;)、(&amp;)其中之一');   
        }
        if($censorwords = $this->modcfg['censoruser'] ? explode("\r\n", $this->modcfg['censoruser']) : '') {
            foreach($censorwords as $censor) {
				
                $preg = "/".str_replace("*", ".*?", $censor)."/is";
				
                if(preg_match($preg, $username)) {
                    if($echo) {echo '<font color="red">管理员限制了您输入的用户名进行注册</font>'; exit;}
                    Note('<font color="red">管理员限制了您输入的用户名进行注册</font>');
                }
            }
        }
    }
	
	function import_check_username($username) {
        if(strlen($username) > 15) {
            return '<font color="red">用户名不能大于15个字符</font>';
        }
        $guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
        if(preg_match("/^\s*$|^c:\\con\\con$|[%,\*\"\s\t\<\>\&]|$guestexp/is", $username)) {
            return '用户名不得包含(,)、(*)、(")、([TAB])、([SPACE])、([\r])、([\n])、(&lt;)、(&gt;)、(&amp;)其中之一';
        }
        if($censorwords = $this->modcfg['censoruser'] ? explode("\r\n", $this->modcfg['censoruser']) : '') {
            foreach($censorwords as $censor) {
				
                $preg = "/".str_replace("*", ".*?", $censor)."/is";
				
                if(preg_match($preg, $username)) {
                    return '<font color="red">管理员限制了您输入的用户名进行注册</font>';
                }
            }
        }
		$sql = "
			SELECT uid FROM {$this->dbpre}users WHERE username='$username'
		";
		$result = $this->db->fetch_all_assoc($sql);
		if($result != NULL){
			return '账户' . $username . '已存在';
		}
		return '0';
    }
	
	//修改密码
	 function change_password($old,$new,$new2,$uid,$cpwd='') {
    	if(!$old&&empty($cpwd))  Note("旧密码不能为空！");
    	if(!$new || $new != $new2) Note("两次输入的密码不相同！");
    	if($error = $this->check_password($new, 1)) Note($error);
        $this->db->from($this->table);
        $this->db->where('uid',$uid);
        $this->db->select('password');
    	$member = $this->db->get_one();

    	if(md5($old) != $member['password']&&empty($cpwd)) Note("您输入的旧密码不正确！");
    	//update pw
    	$md5pw = md5($new);
    	$this->db->from($this->table);
    	$this->db->set('password', $md5pw);
		if($cpwd) $this->db->set('cpwd', 0);
    	$this->db->where('uid', $uid);
    	$this->db->update();
    	$this->_save_login();
    }

    
    function check_password($password, $return_error = FALSE) {
        $len = 6;
        if(strlen($password) < $len) {
        	$error = sprintf('对不起，你设置的密码长度过短，不能少于 %d 个字符，请返回修改。', $len);
        	if($return_error) return $error;
            Note($error);
        }
        if(!preg_match("/[a-zA-Z0-9_~!@#]+/i", $password)) {
        	if($return_error) return '<font color="red">密码中只能包含数字，字母以及"_ ~ ! @ #"!</font>';
            Note('<font color="red">密码中只能包含数字，字母以及"_ ~ ! @ #"!</font>');
        }
    }
	
	function import_check_password($password) {
        $len = 6;
        if(strlen($password) < $len) {
        	$error = '<font color="red">对不起，你设置的密码长度过短，不能少于 ' . $len . '个字符，请返回修改。</font>';
        	return $error;
        }
        if(!preg_match("/[a-zA-Z0-9_~!@#]+/i", $password)) {
        	return '<font color="red">密码中只能包含数字，字母以及"_ ~ ! @ #"!</font>';
        }
		return '0';
    }

    function _send_salutatory_msg($uid) {
        if(!$member = $this->read($uid)) return;
        $subject = lang('member_reg_msg_subject', $this->global['cfg']['sitename']);
        $content = $this->modcfg['salutatory_msg'] ? $this->modcfg['salutatory_msg'] : lang('member_reg_msg_content');

        $rp = array('$sitename', '$username', '$time');
        $sm = array($this->global['cfg']['sitename'], $member['username'], date("Y-m-d H:i:s", $this->global['timestamp']));
        $content = str_replace($rp, $sm, $content);

        $MSG =& $this->loader->model('member:message');
        $MSG->send(0, $uid, $subject, $content);
        unset($MSG);
    }
	
	
	
	//登录系统
	 function login($username, $password, $life=3600) {
      if(!$username) Note('登录账户不能为空！');
      if(!$password) Note('登录密码不能为空！');
        if(!$member = $this->read($username, 1)) {
            return FALSE;
            $this->init_variable();
        }
        $md5pw = md5($password);
        if($md5pw == $member['password']) {
          
		  	if($member['groupid']==6) $member = $this->read('p'.$username, 1);//如果是学生就转换为家长账户。
			
            $hash = create_formhash($member['uid'], $member['username'], $member['password']);
            unset($member['passowrd']);
            $this->hash 	= $hash;
			$this->uid 		= $member['uid'];
			$this->username = $member['username'];
			$this->userbid  = $member['bid'];
			$this->groupid  = $member['groupid'];
			$this->cpwd     = $member['cpwd'];
            $this->isLogin  = TRUE;
			
            $M_sysnote = G_class('sysnote');
            $ip = getIP();
            $M_sysnote->insert_sysnote('5', '0', $member['uid'], $member['bid'], $ip);
            
            foreach($member as $key => $val) {
                $this->$key = $val;
            }
			
            $this->_save_login($life);
            $this->_update_user();
            return '&nbsp;';
        } else {
            return '';
        }
    }
	
	//添加用户
	function register(& $post) {
        $post['logintime'] = $post['regdate'] = $this->global['timestamp'];
        $post['loginip'] = $this->global['ip'];
        $post['logincount'] = 1;
        $post['groupid'] = 10;
        $username = $post['username'];
        $password = md5($post['password']);
        if($this->passport['enable']) {
            $this->uid = (int) $this->save_passport($post);
            $this->hash = create_formhash($this->uid, '', '');
        } else {
            $this->uid = (int) $this->save($post);
            $this->hash = create_formhash($this->uid, $username, $password);
        }
        $this->isLogin = TRUE;
        $this->_save_login();
		return '&nbsp;';
    }
	
	
	   function _save_login($life = 0) {
        $life = (int) $life;
		set_cookie('username', $this->username, $life);
		set_cookie('userbid', $this->userbid, $life);
		set_cookie('groupid', $this->groupid, $life);
        set_cookie('uid', $this->uid, $life);
		set_cookie('cpwd', $this->cpwd, $life);
        set_cookie('hash', $this->hash, $life);
    }
	
	
	function _update_user() {  //更新登录以及相关设置
        $update = FALSE;
        $this->db->clear();
		/*
        $groups = $this->variable('usergroup');
        $is_member_group = $groups[$this->groupid]['grouptype'] == 'member';
        if($is_member_group) {//普通用户组会随着积分变化
            $nextgroupid = $this->get_groupid();
            if($this->groupid != $nextgroupid) {
                $update = TRUE;
                $this->db->set('groupid', $nextgroupid);
            }
        } elseif($this->nexttime > 0) { //特殊组会员到期时间判断
            $now = strtotime(date('Y-m-d', $this->global['timestamp']));
            if($this->nexttime < $now) { //到期了
                $update = TRUE;
                $this->db->set('groupid', $this->nextgroupid ? $this->get_groupid() : $this->nextgroupid);
                $this->db->set('nexttime', 0);
            }
        }
		*/
        if($this->global['timestamp'] - $this->logintime > 43200 ) {
            $update = TRUE;
            $this->db->set_add('logincount', 1);
            $this->db->set('logintime', $this->global['timestamp']);
            $this->db->set('loginip', $this->global['ip']);
        }
        if($update) {
            $this->db->from($this->table);
            $this->db->where('uid', $this->uid);
            $this->db->update();
        }
    }
	
	function _init_variable() {
        $this->uid = 0;
        $this->groupid = 1;
        $this->isLogin = FALSE;
    }
	
	
	function auto_login() {

        $c_uid = $this->global['cookie']['uid'];
        $c_hash = $this->global['cookie']['hash'];

        if(!$c_uid || !$c_hash) {
            $this->_init_variable();
            return;
        } elseif(!$member = $this->read($c_uid)) {
            $this->_init_variable();
            return;
        }
      
        $hash = create_formhash($member['uid'],$member['username'],$member['password']);
        unset($member['passowrd']);
        if (strcmp($c_hash, $hash) == 0) {
            foreach($member as $key => $val) {
                $this->$key = $val;
            }
            $this->uid = (int)$this->uid;
            $this->hash = $hash;
            $this->isLogin = TRUE;
            $this->_update_user();
        } else {
            $this->_init_variable();
            return;
        }
    }
	
	 function logout() {
		 
        del_cookie(array('uid','groupid','hash','username','uid','userbid','cpwd'));
        $this->_init_variable();
    }
	
	
	//是否登录
	public function isLogin($jumpurl){
		
		global $_CO;
	
		if($_CO['username']){ 
		
			$ARRUSER = $this->read($_CO['uid']);
			if($ARRUSER['isbaned']==0) Note('该账户已被禁用，禁止登录系统！','点击返回',SITEURL.'?mod=login&do=login&c=out');
			
		}else{
			$jumpurl=base64_encode($jumpurl);
			location(SITEURL.'?mod=login&do=login&c=out&jumpurl='.$jumpurl);
		}
	}
	
	//Edit by zhaobin 14:36 2012/11/16
	function check_isuser($name){
		$sql = "
			SELECT uid FROM {$this->dbpre}users WHERE username='$name'
		";
		return $this->db->fetch_all_assoc($sql, 'select');
	}
	
	function get_username($uid){
		$sql = "
			SELECT uid, username, realname,face,phonenum
			FROM {$this->dbpre}users
			WHERE uid in ($uid)
		";
		return $this->db->fetch_all_assoc($sql);
	}
	
	function add_user_2($post, $uid=null){
		
      $uid = parent::save($post, $id, $upcache,FALSE);

	}
	
	function add_user_parent($realname, $sex, $username, $password, $groupid, $bid){
		$time = time();
		$sql = "
			INSERT INTO {$this->dbpre}users
			(email, `password`, username, realname, stu_num, sex, phonenum, newmsg, regdate, logintime, loginip, logincount, groupid, isbaned, nexttime, subjects, bid, responds, flowers, pictures)
			VALUES
			('','$password','$username','$realname', '', '$sex','','0','0','$time','','0','$groupid','1','0','0','$bid','0','0','0')
		";
		return $this->db->ady_query($sql, 'insert');
	}
	
	function get_my_balance($uid){
		$sql = "
			SELECT sms_balance FROM `{$this->dbpre}users` WHERE uid='$uid'
		";
		return $this->db->once_fetch_assoc($sql);
	}
	
	function update_sms_balance($uid, $value){
		$sql = "UPDATE {$this->dbpre}users SET sms_balance='$value' WHERE uid='$uid'";
		return $this->db->ady_query($sql, 'update');
	}
	
}

?>