<?php
/**
 * 用户管理
 *
 * @author 阿一 yandy@yanwee.com
 * @package 1.0
 * @version $Id$
 */

/**
 * Member 会员管理类
 * @package Apps
 */

class Member {

	/**
	 * @var Object $db 数据库查询对象
	 * @access private
	 */
	var $db = NULL;
	
	/**
	 * 主用户表
	 *
	 * @var string
	 */
	var $tName = "fke_member";
	
	/**
	 * VIP用户时间表
	 *
	 * @var string
	 */
	var $tNameVip = "fke_member_vip";
	
	/**
	 * 经纪人的详细信息
	 *
	 * @var string
	 */
	
	var $tNameBrokerInfo = "fke_broker_info";
	/**
	 * 业主的详细信息
	 *
	 * @var string
	 */
	var $tNameOwnerInfo = "fke_owner_info";
	/**
	 * 用户小区专家表
	 *
	 * @var string
	 */
	var $tNameAdviser = "fke_borough_adviser";
	
	/**
	 * 用户充值记录
	 *
	 * @var string
	 */
	var $tNameMoneyLog = "fke_money_log";
	
	/**
	 * 用户登陆日志
	 *
	 * @var string
	 */
	var $tNameLoginlog = "fke_member_loginlog ";
	/**
	 * 构造函数
	 *
	 * @param source $db
	 */
	function __construct($db) {
		$this->db = $db;
	}
	
	/**
	 * 用户登录
	 * @param string $username 用户名
	 * @param string $passwd 密码
	 * @access public
	 * @return mixed
	 */
	function login($username, $passwd,$wap=0) {
		global $cfg;
		$username = strtolower($username);
		if (isset($_POST['valid'])) {
			if (md5(strtolower($_POST['valid']))!=$_COOKIE['validString']) {
				$result = '验证码错误！';
				return $result;
			}
		}
		if ($username && $passwd) {
			$info = $this->db->getValue('select * from '.$this->tName.' where username=\''. $username . '\'');
			if (!$info) {
				$result = '用户不存在！';
			} elseif (strtolower($info['passwd'])!=md5($passwd)) {
				$result = '密码错误！';
			} else {
				if (isset($_POST['notForget']) && intval($_POST['notForget'])==1) {
					setcookie('AUTH_MEMBER_FORGET',$username,time()+60*60*24*365,'/',$cfg['domain']);
				}
				$auth_code = authcode($info['id']. "\t" . md5($passwd). "\t" .$info['user_type'], 'ENCODE', $cfg['auth_key']);
				setcookie('AUTH_MEMBER_STRING',$auth_code,0,'/',$cfg['domain']);
				$_COOKIE['AUTH_MEMBER_STRING'] = $auth_code;
				setcookie('AUTH_MEMBER_NAME',$username,0,'/',$cfg['domain']);
				$_COOKIE['AUTH_MEMBER_NAME'] = $username;
				$realname = $this->getRealName($info['id'],$info['user_type']);
				setcookie('AUTH_MEMBER_REALNAME',$realname,0,'/',$cfg['domain']);
				$_COOKIE['AUTH_MEMBER_REALNAME'] = $realname;
				
				//更新最后登陆时间和登陆次数
				$this->db->execute("update ".$this->tName." set last_login ='".$cfg['time']."' , logins=logins+1 where id = ".$info['id']);
				
				//重新计算用户活跃度
				//1:记录loginlog
				$this->addLoginLog($username);
				//2:计算活跃度
				if($info['user_type']==1){
					//7天前
					$dateNow = mktime(0,0,0,date('m'),date('d'),date('Y'));
					$dateBefore =  $dateNow - 518400;
					$loginlog = $this->db->select("select add_time from ".$this->tNameLoginlog." where username = '".$username."' and add_time>=".$dateBefore." order by add_time asc");
					$active_arr = array_fill(0, 7, 0);
					$activeRate = 0;
					foreach($loginlog as $item){
						for($i=0;$i<=6;$i++){
							if($dateBefore+$i*86400 == $item ){
								$activeRate += 1000+pow(2, $i);
								$active_arr[$i]=1;
								break;
							}
						}
					}

					if($active_arr){
						$active_str = implode('|',$active_arr);
					}else{
						$active_str = '';
					}
					$this->db->execute("update ".$this->tName." set active_str ='".$active_str."' , active_rate='".$activeRate."' where id = ".$info['id']);
					
				}
				//3：总活跃度每天统计一次，这里不做统计
				
				$result = true;
			}
		} else {
			if (trim($username)==''){
				$result = '用户名必须填写！';
			}else{
				$result = '用户密码必须填写！';
			}
			
		}
		return $result;
	}
	/**
	 * 注册数据
	 *
	 * @param unknown_type $postInfo
	 */
	function register($postInfo)
	{
		global $cfg;
		$postInfo['username'] = strtolower($postInfo['username']);
		if($this->db->getValue('select id from '.$this->tName.' where username=\''.$postInfo['username'].'\'')){
			return -1;
		}
		$user_type = intval($postInfo['user_type']);
		$insertInfo = array(
			'username'=>$postInfo['username'],
			'passwd'=>md5($postInfo['passwd']),
			'email'=>$postInfo['email'],
			'user_type'=>$user_type,
			'logins'=>1,
			'last_login'=>time(),
			'add_time'=>time(),
			'status'=>$postInfo['status']
		);

		
		try{
			$this->db->insert($this->tName,$insertInfo);
			$user_id = $this->db->getInsertId();
			//自动登录
			$auth_code = authcode($user_id. "\t" . md5($postInfo['passwd']). "\t" .$user_type, 'ENCODE', $cfg['auth_key']);
			setcookie('AUTH_MEMBER_STRING',$auth_code,0,'/',$cfg['domain']);
			$_COOKIE['AUTH_MEMBER_STRING'] = $auth_code;
			setcookie('AUTH_MEMBER_NAME',$postInfo['username'],0,'/',$cfg['domain']);
			$_COOKIE['AUTH_MEMBER_NAME'] = $postInfo['username'];
			$realname = $this->getRealName($user_id,$user_type);
			setcookie('AUTH_MEMBER_REALNAME',$realname,0,'/',$cfg['domain']);
			$_COOKIE['AUTH_MEMBER_REALNAME'] = $realname;
			
			//重新计算用户活跃度
			//1:记录loginlog
			$this->addLoginLog($username);
			//2:计算活跃度
			if($user_type ==1){
				//7天前
				$dateNow = mktime(0,0,0,date('m'),date('d'),date('Y'));
				$dateBefore =  $dateNow -604800;
				$loginlog = $this->db->select("select add_time from ".$this->tNameLoginlog." where username = '".$postInfo['username']."' and add_time>=".$dateBefore." order by add_time asc");
				$active_arr = array_fill(0, 7, 0);
				$activeRate = 0;
				foreach($loginlog as $item){
					for($i=0;$i<=6;$i++){
						if($dateBefore+$i*86400 == $item ){
							$activeRate += 1000+pow(2, $i);
							$active_arr[$i]=1;
							break;
						}
					}
				}

				if($active_arr){
					$active_str = implode('|',$active_arr);
				}else{
					$active_str = '';
				}
				$this->db->execute("update ".$this->tName." set active_str ='".$active_str."' , active_rate='".$activeRate."' where id = ".$user_id);
				
			}
			//3：总活跃度每天统计一次，这里不做统计
			
			//插入一条用户详细信息
			
			$insertInfo = array(
				'realname'=>$postInfo['realname'],
				'id'=>$user_id,
				'mobile'=>$postInfo['mobile'],
				'cityarea_id'=>$postInfo['cityarea_id'],
				'cityarea2_id'=>$postInfo['cityarea2_id'],
				'gender'=>$postInfo['gender'],
				'outlet_first'=>$postInfo['outlet_first'],
				'outlet_last'=>$postInfo['outlet_last'],
			     );
				$this->db->insert($this->tNameBrokerInfo,$insertInfo);
			
			return $user_id;
		}catch (Exception $e){
			return 0;
		}
	}
	/**
	 * 用户登出
	 * @access public
	 * @return mixed
	 */
	function logout($wap=0) {
		global $cfg;
		setcookie('AUTH_MEMBER_STRING', 0, time()-1,'/',$cfg['domain']);
		setcookie('AUTH_MEMBER_NAME',0,time()-1,'/',$cfg['domain']);
		setcookie('AUTH_MEMBER_REALNAME',0,time()-1,'/',$cfg['domain']);
	}
	
	/**
	 * 取当前用户信息
	 * @access public
	 * @return array
	 */ 
	function getAuthInfo($field=NULL) {
		global $cfg;
		$authInfo = authcode($_COOKIE['AUTH_MEMBER_STRING'], 'DECODE', $cfg['auth_key']);
		$authInfo = explode("\t",$authInfo);
		$result['id'] = $authInfo[0];
		$result['passwd'] = $authInfo[1];
		$result['user_type'] = $authInfo[2];
		if ($_COOKIE['AUTH_MEMBER_NAME']) {
			$result['username'] = $_COOKIE['AUTH_MEMBER_NAME'];
		}
		if ($_COOKIE['AUTH_MEMBER_REALNAME']) {
			$result['realname'] = $_COOKIE['AUTH_MEMBER_REALNAME'];
		}
		
		if ($field) {
			if ($result[$field]) {
				return $result[$field];
			} else {
				$info = $this->getInfo($result['id'],'*',true);
				return $info[$field];
			}
		}
		return $result;
	}
	
	/**
	 * VIP用户到期脚本执行
	 * @return array
	 */
	function doVipTime() {
		$today = mktime(0,0,0,date('m'),date('d'),date('Y'));
		$dataList = $this->getVipDoTimeList('*','to_time<'.$today);
		foreach ($dataList as $key => $value){
			$this->deleteVip($dataList[$key]['member_id']);  //删除会员VIP时间表
		    $this->update($dataList[$key]['member_id'],'vip',0);  //在member表中将vip更新为0
			$this->update($dataList[$key]['member_id'],'vexation',0);  //在member表中将vexation更新为0
      	}

	}
	
	 /**
	 * 取得符合到期时间的VIP用户
	 * @access public
	 * 
	 * @param array $pageLimit
	 * @return array
	 **/
	 function getVipDoTimeList($fileld='*' ,$where=''){
		$this->db->open('select * from '.$this->tNameVip.' where '.$where);
		$result = array();
		while ($rs = $this->db->next()) {
			$result[] = $rs;
		}
		return $result;
	 }
	
	/**
	 * 升级vip
	 * @param array $days 天数
	 * @access public
	 * @return bool
	 */
	function vipSave($fileddata,$value) {
		global $page;
		$field_array  = array(
			'member_id'=>$fileddata['member_id'],
			'add_time'=>time(),
			'to_time'=>$fileddata['to_time'],
		);
		
		//增加急售标签
		if($value==1){
			$this->update($fileddata['member_id'],'vexation',$page->vip1Vexation);
			}
		if($value==2){
			$this->update($fileddata['member_id'],'vexation',$page->vip2Vexation);
			}
		
		
		//如果有之前有会员vip记录 要删除
		if($this->getVipTime($fileddata['member_id'],'*')){
			$this->deleteVip($fileddata['member_id']);
			}
		$this->update($fileddata['member_id'],'vip',$value);
		return $this->db->insert($this->tNameVip,$field_array);
		}
		
	 /**
	 * 减少加急房源条数
	 * @access public
	 * @return bool
	 */
	function deleteVexation($id,$value) {
		return $this->db->execute('update '.$this->tName.' set vexation = vexation -'.$value.' where id='.$id);
	}
		
	/**
	 * 删除vip记录
	 * @param array $days 天数
	 * @access public
	 * @return bool
	 */
	function deleteVip($id) {
		return $this->db->execute('delete from '.$this->tNameVip.' where member_id='.$id);
		}
	
	/**
	 * 检查认证信息
	 * @access public
	 * @return NULL
	 */
	function auth() {
		global $cfg,$page;
		$authSuc = false;
		$back_to = $_SERVER['REQUEST_URI'];
		if ($_COOKIE['AUTH_MEMBER_STRING']) {
			if (!$_COOKIE['AUTH_CHECKTIME']) {
				// 间隔AUTH_CHECKTIME时间检查一次cookie信息是否和数据库一至
				$authInfo = $this->getAuthInfo();
				$user = $this->db->getValue('select * from '.$this->tName.' where id=\''.$authInfo['id'].'\' and  passwd=\''.$authInfo['passwd'].'\'');
				
				if ($user['id']) {
					$authSuc = true;
					setcookie('AUTH_CHECKTIME',1, time()+$GLOBALS['auth_time']);
					//重新设置cookie使用户的Cookie在2个小时内不再失效 ， 如果是cookie设置关闭即失效就没有必要
					/*
					setcookie('AUTH_MEMBER_STRING',authcode($user_id. "\t" . md5($postInfo['passwd']. "\t" .$user_type), 'ENCODE', $cfg['auth_key']),$cfg['time']+7200,'/',$cfg['domain']);
					setcookie('AUTH_MEMBER_NAME',$postInfo['username'],$cfg['time']+7200,'/',$cfg['domain']);
					$_COOKIE['AUTH_MEMBER_NAME'] = $postInfo['username'];
					*/
				}
			} else {
				$authSuc = true;
			}
			$user_type = $this->getAuthInfo('user_type');
			if($user_type == 1 ){
				if(strpos($back_to,'owner') != ""){
					$back_to = str_replace('owner','member',$back_to);
					header("location:".$back_to);
				}
			}else{
				if(strpos($back_to,'member') != 0){
					$back_to = str_replace('member','owner',$back_to);
				
					header("location:".$back_to);
				}	
			}
		}
		if ($authSuc===false) {
			$page->goto($cfg['url'].'login/login.php?back_to='.$back_to);
		}
	}
	/**
	 * 检查密码
	 * @access public
	 * 
	 * @param string $pwd
	 * @param int $memberId
	 * @return bool
	 **/
	function checkPwd($pwd,$memberId){
		if (!empty($pwd)){
			return $this->db->getValue('select * from '.$this->tName.' where passwd=\''.md5($pwd).'\' and id='.$memberId);
		} else {
			return false;
		}
	}
	/**
	 * 修改会员密码
	 *
	 * @param  string $password
	 * 
	 * @return bool
	 */
	function updatePasswd($id , $email,$pssword)
	{
		return $this->db->execute('update '.$this->tName.' set passwd =\''.md5($pssword).'\' where username = \''.$username.'\' and email=\''.$email.'\'');	
	}
	
	/**
	 * 取回密码的修改密码
	 *
	 * @param string $username
	 * @param string $email
	 * @param  string $password
	 * 
	 * @return bool
	 */
	function updateFromGetPsw($username , $email,$pssword)
	{
		return $this->db->execute('update '.$this->tName.' set passwd =\''.md5($pssword).'\' where username = \''.$username.'\' and email=\''.$email.'\'');	
	}
	/**
	 * 保存经纪人会员信息
	 * @access public
	 * 
	 * @param array $memberInfo
	 * @return bool
	 **/
	 function saveBroker($memberInfo){
		$memberInfo['id'] = intval($memberInfo['id']);
		//修改用户信息
		$updateField = array(
			'email'=>$memberInfo['email']
		);
		$this->db->update($this->tName,$updateField,'id='.$memberInfo['id']);
		if($this->db->getValue('select id from '.$this->tNameBrokerInfo.' where id='.$memberInfo['id'])){
			//update
			$updateField = array(
				'cityarea_id'=>intval($memberInfo['cityarea_id']),
				'mobile'=>$memberInfo['mobile'],
				'signed'=>$memberInfo['signed'],
				'company'=>$memberInfo['company'],
				'outlet_first'=>$memberInfo['outlet_first'],
				'outlet_last'=>$memberInfo['outlet_last'],
				'outlet_addr'=>$memberInfo['outlet_addr'],
				'com_tell'=>$memberInfo['com_tell'],
				'com_fax'=>$memberInfo['com_fax'],
				'gender'=>intval($memberInfo['gender']),
				'birthday'=>$memberInfo['birthday'],
				'borough_id'=>intval($memberInfo['borough_id']),
				'qq'=>$memberInfo['qq'],
				'msn'=>$memberInfo['msn'],
				'introduce'=>$memberInfo['introduce'],
				'broker_type'=>intval($memberInfo['broker_type']),
			);
			$this->db->update($this->tNameBrokerInfo,$updateField,'id='.$memberInfo['id']);
		}else{
			//insert
			
			$insertField = array(
				'id'=>$memberInfo['id'],
				'cityarea_id'=>intval($memberInfo['cityarea_id']),
				'mobile'=>$memberInfo['mobile'],
				'realname'=>$memberInfo['realname'],
				'signed'=>$memberInfo['signed'],
				'company'=>$memberInfo['company'],
				'outlet_first'=>$memberInfo['outlet_first'],
				'outlet_last'=>$memberInfo['outlet_last'],
				'outlet_addr'=>$memberInfo['outlet_addr'],
				'com_tell'=>$memberInfo['com_tell'],
				'com_fax'=>$memberInfo['com_fax'],
				'gender'=>intval($memberInfo['gender']),
				'birthday'=>$memberInfo['birthday'],
				'borough_id'=>intval($memberInfo['borough_id']),
				'qq'=>$memberInfo['qq'],
				'msn'=>$memberInfo['msn'],
				'introduce'=>$memberInfo['introduce'],
				'broker_type'=>intval($memberInfo['broker_type']),
			);
			$this->db->insert($this->tNameBrokerInfo,$insertField);
		}
		return $result;
		
	 }
	 
	
	 
	 /**
	 * 检查会员重复信息
	 * @access public
	 * 
	 * @param string $username
	 * @return bool
	 **/
	 function checkMemberUnique($username){
		return $this->db->getValue('select id from '.$this->tName.' where username=\''. $username.'\'');
	 }
	 
	 /**
	 * 检查是否有重复的身份证，认证审核时使用
	 * @access public
	 * 
	 * @param string $username
	 * @return bool
	 **/
	 function checkIdcardUnique($idcard){
		return $this->db->getValue('select id from '.$this->tNameBrokerInfo.' where idcard =\''. $idcard.'\'');
	 }
	 
	 /**
	 * 检查用户输入的用户名和邮件地址 ， 取回密码时使用
	 * @access public
	 * 
	 * @param string $username
	 * @return bool
	 **/
	 function checkMemberEmail($username,$email){
		return $this->db->getValue('select id from '.$this->tName.' where username=\''. $username.'\' and email =\''. $email.'\'');
	 }
	 /**
	 * 取得member信息列表
	 * @access public
	 * 
	 * @param array $pageLimit
	 * @return array
	 **/
	 function getList($pageLimit, $fileld='*' ,$where='', $order=' order by id desc ') {
	 	if($where){
			$where=' where '.$where;
		}
		$this->db->open('select * from '.$this->tName.' '.$where.' '.$order , $pageLimit['rowFrom'],$pageLimit['rowTo']);
		$result = array();
		while ($rs = $this->db->next()) {
			$result[] = $rs;
		}
		return $result;
	 }
	
	/**
	 * 取用户信息
	 * @param string $memberId 用户ID
	 * @param string $field 字段
	 * @access public
	 * @return array
	 */
	function getInfo($memberId, $field = '*',$moreInfo=false) {
		if($moreInfo){
			$userInfo = $this->db->getValue('select ' . $field . ' from '.$this->tName.' where id=' . $memberId);
			
			$detailInfo = $this->db->getValue('select * from '.$this->tNameBrokerInfo.' where id=' . $memberId);
		
			return array_merge((array)$userInfo,(array)$detailInfo);
			
		}else{
			return  $this->db->getValue('select ' . $field . ' from '.$this->tName.' where id=' . $memberId);
		}
		
	}
	
	/**
	 * 查询VIP表字段
	 * @param string $memberId 用户ID
	 * @param string $field 字段
	 * @access public
	 * @return array
	 */
	function getVipTime($memberId, $field = '*') {
			return  $this->db->getValue('select ' . $field . ' from '.$this->tNameVip.' where member_id=' . $memberId);
		}
		
	
	/**
	 * 取用户信息
	 * @param string $memberId 用户ID
	 * @param string $user_type 用户类型
	 * @access public
	 * @return array
	 */
	function getRealName($memberId,$user_type) {

			return $this->db->getValue('select realname from '.$this->tNameBrokerInfo.' where id=' . $memberId);
		
	}
	/**
	 * 修改用户信息 ，区别于直接保存全部信息，这里如果需要修改用户的基本信息和详细信息，需要执行两次的操作
	 * 例如：
	 * $member->updateInfo($id , $basicArray, $isInfo=false ,$user_type=1);
	 * $member->updateInfo($id , $extentArray, $isInfo=true ,$user_type=1);
	 *
	 * @param int $id
	 * @param array $fieldArray
	 * @param bool $isInfo
	 * @param 1 or 2 $user_type
	 */
	function updateInfo($id , $fieldArray, $isInfo=false ,$user_type=1){
		if($isInfo){
		
				$this->db->update($this->tNameBrokerInfo,$fieldArray,' id ='.$id);
		}else{
			$this->db->update($this->tName,$fieldArray,' id ='.$id);
		}
	}
	/**
	 * 插入扩展用户信息 
	 * 例如：
	 * $member->insertInfo($id , $basicArray, $isInfo=false ,$user_type=1);
	 *
	 * @param array $fieldArray
	 * @param 1 or 2 $user_type
	 */
	function insertInfo($fieldArray, $isInfo=false ,$user_type=1){

			$this->db->insert($this->tNameBrokerInfo,$fieldArray);
	
	}
	
	/**
	 * 删除用户信息
	 * @param mixed $members 用户ID
	 * @access public
	 * @return bool
	 */
	function delete($members) {
		if (is_array($members)) {
			$members = implode(',',$members);
			$where = ' id in (' . $members . ')';
			$shopwhere = ' broker_id in (' . $members . ')';
			$memberwhere = ' member_id in (' . $members . ')';
			
		} else {
			$where = ' id=' . intval($members);
			$shopwhere = ' broker_id=' . intval($members);
			$memberwhere = ' member_id=' . intval($members);
			
		}
		$username = $this->db->select('select username from '.$this->tName.' where '.$where);
		
		//删除出售房源记录
		$this->db->execute('delete from fke_housesell where ' . $shopwhere);
		
		//删除出租房源记录
		$this->db->execute('delete from fke_houserent where ' . $shopwhere);
		
		//删除fke_member_loginlog会员登录记录
		foreach ($username as $value){
        $this->db->execute('delete from fke_member_loginlog where username = "'.$value.'"');
        }
		
		//删除会员fke_borker_info 经纪人表信息
		$this->db->execute('delete from fke_broker_info where ' . $where);
		
		//删除会员fke_borker_identity 经纪人身份认证表信息
		$this->db->execute('delete from fke_broker_identity where ' . $shopwhere);
		
		//删除会员fke_borker_friends 经纪人好友表信息
		$this->db->execute('delete from fke_broker_friends where ' . $shopwhere);
		
		//删除会员fke_broker_avatar 经纪人头像表信息
		$this->db->execute('delete from fke_broker_avatar where ' . $shopwhere);
		
		//删除会员fke_broker_aptitude 经纪人执业认证表信息
		$this->db->execute('delete from fke_broker_aptitude where ' . $shopwhere);
		
		//删除fke_innernote会员站内信接收记录
		foreach ($username as $value){
        $this->db->execute('delete from fke_innernote where msg_to = "'.$value.'"');
        }
		
		//删除fke_innernote会员站内信发送记录
		foreach ($username as $value){
        $this->db->execute('delete from fke_innernote where msg_from = "'.$value.'"');
        }
		
		//删除会员fke_integral_log 积分记录
		$this->db->execute('delete from fke_integral_log where ' . $memberwhere);
		
		//如果是经纪人删除fke_shop_conf经纪人网店信息
		$this->db->execute('delete from fke_shop_conf where ' . $shopwhere);
		
		//删除店铺fke_shop_viewlog 好友信息
		$this->db->execute('delete from fke_shop_viewlog where ' . $shopwhere);
		
		//删除会员fke_member 表信息
		$this->db->execute('delete from '.$this->tName.' where ' . $where);
		
		return true;
		

	}
	
	/**
	 * 操作用户状态 不物理删除
	 * @param mixed $members 用户ID
	 * @access public
	 * @return bool
	 */
	function changeStatus($members,$status) {
		if (is_array($members)) {
			$members = implode(',',$members);
			$where = ' id in (' . $members . ')';
		} else {
			$where = ' id=' . intval($members);
		}
		return $this->db->execute('update '.$this->tName.' set status = '.$status.' where ' . $where);
	}
	
 	/**
	 * 更新某个字段
	 * @param mixed $ids ID
	 * @access public
	 * @return bool
	 */
	function update($ids,$field,$value) {
		if (is_array($ids)) {
			$ids = implode(',',$ids);
			$where = ' id in (' . $ids . ')';
		} else {
			$where = ' id=' . intval($ids);
		}
		return $this->db->execute('update '.$this->tName.' set '.$field.' = \''.$value.'\' where ' . $where);
	}
	 /**
	 * 用户充值
	 * @access public
	 * @return bool
	 */
	function updatemoney($id,$value) {
		return $this->db->execute('update '.$this->tName.' set money = money +'.$value.' where id='.$id);
	}
	
	 /**
	 * 扣费处理
	 * @access public
	 * @return bool
	 */
	function deletemoney($id,$value) {
		return $this->db->execute('update '.$this->tName.' set money = money -'.$value.' where id='.$id);
	}
	 /**
	 * 用户充值记录
	 * @param $id 用户ID
	 * @param $money 充值金额
	 * @access public
	 * @return bool
	 */
	function moneylog($id,$money) {
			$insertField = array(
				'member_id'=>intval($id),
				'money'=>$money,
				'time'=>time(),
			);
	return $this->db->insert($this->tNameMoneyLog,$insertField);
	}
	
	 /**
	 * 购买条数
	 * @access public
	 * @return bool
	 */
	function updateNum($flag,$id,$value) {
		if($flag == 0){
			return $this->db->execute('update '.$this->tName.' set addsale = addsale +'.$value.' where id='.$id);
			}else{
				return $this->db->execute('update '.$this->tName.' set addrent = addrent +'.$value.' where id='.$id);
				}
		
	}
	
	/**
	 * 取类别总数
	 * @access public
	 * @return int
	 */
	function getCount($where = '') {
		if($where){
			$where=' where '.$where;
		}
		return $this->db->getValue('select count(*) from '.$this->tName.' '.$where );
	}
	/**
	 * 取得所有类型的用户
	 *
	 * @param int $user_type 1：经纪人；2：业主 0：所有
	 */
	function getAll($user_type=0,$field='*'){
		if($user_type ){
			$where = ' where user_type = '.$user_type;
		}
		return $this->db->select('select '.$field.' from '.$this->tName.' '.$where);
	}
	/**
	 * 用户是否是小区专家
	 *
	 * @param int $member_id
	 * @return bool
	 */
	function is_expert($member_id)
	{
		return $this->db->getValue('select count(*) from '.$this->tNameAdviser.' where member_id = '.$member_id.' and status =1');
	}
	
	/**
	 * 取类别总数
	 * @access public
	 * @return int
	 */
	function getCountBroker($where = '') {
		if($where){
			$where=' where '.$where;
		}
		$sql = "select count(*) from ".$this->tName." as m
			 left join ".$this->tNameBrokerInfo." as b ".
			" on m.id = b.id". $where ;
		return $this->db->getValue($sql);
	}
	
	 /**
	 * 取得member信息列表
	 * @access public
	 * 
	 * @param array $pageLimit
	 * @return array
	 **/
	 function getListBroker($pageLimit, $fileld='*' ,$where='', $order=' order by m.id desc ') {
	 	if($where){
			$where=' where '.$where;
		}
		$sql = "select m.id as mid,m.*,b.* from ".$this->tName." as m
			 left join ".$this->tNameBrokerInfo." as b ".
			" on m.id = b.id ". $where.' '.$order;
		$this->db->open($sql , $pageLimit['rowFrom'],$pageLimit['rowTo']);
		$result = array();
		while ($rs = $this->db->next()) {
			$result[] = $rs;
		}
		return $result;
	 }
	 
	 
	 /**
	 * 判断用户是否为中介(多选)
	 * @access public
	 * 
	 * @param array $pageLimit
	 * @return array
	 **/
	 function isbroker($ids) {
      	if (is_array($ids)) {
			$ids = implode(',',$ids);
			$where = ' id in (' . $ids . ')';
		} else {
			$where = ' id=' . intval($ids);
		}
		
		$this->db->open("select user_type from " .$this->tName. " where " .$where);
		$result = array();
		while ($rs = $this->db->next()) {
			$result[] = $rs;
		}
		return $result;
	 }
	 
	 
	 /**
	  * 增加loginLog
	  *
	  * @param string $username
	  * @return bool
	  */
	 function addLoginLog($username)
	 {
	 	$today = mktime(0,0,0,date('m'),date('d'),date('Y'));
	 	$loginLogId = $this->db->getValue("select id from ".$this->tNameLoginlog." where username = '".$username."' and add_time = '".$today."'");
	 	if($loginLogId){
	 		$this->db->execute("update ".$this->tNameLoginlog." set login_times =login_times+1 where id =".$loginLogId);
	 	}else{
	 		$this->db->execute("insert into  ".$this->tNameLoginlog." (username ,login_times,add_time) values ('".$username."','1','".$today."')");
	 	}
	 	return true;
	 }
	 /**
	  * 增加积分
	  */
	 function addScore($member_id,$scores){
	 	return $this->db->execute("update ".$this->tName." set scores = scores +".$scores." where id=".$member_id);
	 }
	 
	  /**
	  * 修改积分
	  */
	 function updateScore($member_id,$scores){
	 	return $this->db->execute("update ".$this->tName." set scores = ".$scores." where id=".$member_id);
	 }
	 
	 /**
	  * 根据用户名取用户ID
	  *
	  * @param string $username
	  * @return int
	  */
	 function getIdByUsername($username)
	 {
	 	return $this->db->getValue('select id from '.$this->tName.' where username=\''. $username . '\'');
	 }
	 /**
	  * 根据字段来搜索用户名信息 ， 返回array id
	  *
	  * @param string $field
	  * @param string $keyword
	  * @return array
	  */
	 function searchMember($field,$keyword)
	 {
	 	switch($field){
	 		case "realname":
	 			$sql = "select id from ".$this->tNameBrokerInfo." where realname like '%".$keyword."%' union select id  from ".$this->tNameOwnerInfo." where concat(first_name,last_name) like '%".$keyword."%'";
	 			return $this->db->select($sql);
	 			break;
	 		case "tel":
	 			$sql = "select id from ".$this->tNameBrokerInfo." where mobile like '%".$keyword."%' or com_tell like '%".$keyword."%' union select id  from ".$this->tNameOwnerInfo." where mobile like '%".$keyword."%' or tell like '%".$keyword."%'";
	 			return $this->db->select($sql);
	 			break;
	 		case "idcard":
	 			$sql = "select id from ".$this->tNameBrokerInfo." where idcard like '%".$keyword."%'";
	 			return $this->db->select($sql);
	 			break;
	 		case "com":
	 			$sql = "select id from ".$this->tNameBrokerInfo." where company like '%".$keyword."%' or outlet like '%".$keyword."%' or outlet_addr like '%".$keyword."%' ";
	 			return $this->db->select($sql);
	 			break;
	 		case "avatar":
	 			$sql = "select id from ".$this->tNameBrokerInfo." where avatar <> '' ";
	 			return $this->db->select($sql);
	 			break;
	 		case "identity":
	 			$sql = "select id from ".$this->tNameBrokerInfo." where idcard<>'' ";
	 			return $this->db->select($sql);
	 			break;	
	 		default:
	 			break;
	 	}
	 }
	 /**
	  * 取的用户扩展信息
	  *
	  * @param int $memberId
	  * @param int $user_type
	  * @return array
	  */
	 function getMoreInfo($memberId,$user_type)
	 {
	 	
			return $this->db->getValue('select * from '.$this->tNameBrokerInfo.' where id=' . $memberId);
		
	 }
}
?>