<?php
function register_globals_vars() {


    if (!empty($_REQUEST))
        $vars = $_REQUEST;


    else {//GPC的顺序
        $vars = array_merge($_GET, $_POST, $_COOKIE);
    }


    //1.去掉slashes
    $vars = stripslashes_arr($vars);

    //2.注册全局变量
    for (reset($vars), $i = 0; $i < count($vars); $i++) {
        $key = key($vars);
        GLOBAL $$key;
        $$key = $vars[$key];
        next($vars);
    }
    return $vars;
}

function stripslashes_arr($arr, $force_flag = 0) { //force_flag表示强制标志
    if ((get_magic_quotes_gpc() == 1) or ($force_flag)) {
        while (list ($key, $val) = each($arr)) {
            if (is_array($arr[$key])) {
                $arr[$key] = stripslashes_arr($arr[$key]);
                continue;
            }
            $arr[$key] = stripslashes($val);
        }
    }
    return $arr;
}

function house_syn_tag($tbl,$houseid){//同步标签房源状态//ps:非多图房源，或失效、冻结时，标签也跟随自动失效

	GLOBAL $house,$db,$dbback,$config_hitch,$statistics;
    if($config_hitch==1){
		$s = stripos($houseid,',');
	    if($s){
		   $q	= "update house_tag set esta=2 where tbl='".$tbl."' and rowid in (".$houseid.") and esta=1 ";
		   $rs	= $db->Execute($q);
		      if($rs){
			      $housetbl = array();
			      $housetbl['istag'] = 0;
			      $q	= update_sql($tbl,$housetbl," where id in (".$houseid.") ");
			      $db->Execute($q);
		      }
	    }else{
		    $q="update house_tag set esta=2 where tbl='".$tbl."' and rowid=".$houseid." and esta=1 ";
		    $rs=$db->Execute($q);
		    if($rs){
				$housetbl=array();
				$housetbl[istag]=0;
				$q=update_sql($tbl,$housetbl," where id=".$houseid);
				$db->Execute($q);
		    }
	    }
	}

}

function nowindow($id, $tbl,$uid){//同时取消橱窗
	GLOBAL $db,$config_windows;
	if($config_windows==1){
		//经纪人租售宝显示用于橱窗的积分
	   include_once(CORE_LIB . "/class_BrokerCredit.php");

       $I = new BrokerCredit($uid);
	   $s = stripos($id,',');
	   if($s){
          $ary_id = explode(",",$id);
          foreach($ary_id as $key => $val){
		     $I->dealCreditWindowback($val, $tbl);
             $q="update w_broker_house set esta = 3 where rowid = '".$val."' and tbl = '".$tbl."'";
	         $db->Execute($q);
		  }
       }else{
           $I->dealCreditWindowback($id, $tbl);
	       $q="update w_broker_house set esta = 3 where rowid = '".$id."' and tbl = '".$tbl."'";
	       $db->Execute($q);
	   }

	}

}

//SESSION变量初始化
function set_account_session($row) {
    global $web_auth, $conf_city;

    $_SESSION[$web_auth]["uid"] = $row["uid"];
    $_SESSION[$web_auth]["username"] = $row["username"];
    $_SESSION[$web_auth]["truename"] = $row["truename"];
    $_SESSION[$web_auth]["agentcode"] = "B000";
    $_SESSION[$web_auth]["companycode"] = $row["agentcode"];
    $_SESSION[$web_auth]["groupid"] = $row["groupid"];
    $_SESSION[$web_auth]["groupname"] = $row["groupname"];
    $_SESSION[$web_auth]["postlimit"] = $row["postlimit"];
    $_SESSION[$web_auth]["refresh"] = $row["refresh"];
    $_SESSION[$web_auth]["stocklimit"] = 5 * $row["postlimit"];
    $_SESSION[$web_auth]["expiredate"] = $row["expiredate"];
    $_SESSION[$web_auth]["contactor"] = $row["contactor"];
    $_SESSION[$web_auth]["telno"] = $row["telno"];
    $_SESSION[$web_auth]["bbsuserid"] = $row["bbsuserid"];
    $_SESSION[$web_auth]["bloguserid"] = $row["bloguserid"];
    $_SESSION[$web_auth]["auth"] = $row["auth"] . ",base," . $row["add_auth"];
    $_SESSION[$web_auth]["h_ok"] = $row["dist"] && $row["hotarea"] && $row["skill"];
    $_SESSION[$web_auth]["city"] = $conf_city;
	$_SESSION[$web_auth]["is_pay"] = $row["is_pay"];//0表示付费、1表示非付费
    $_SESSION[$web_auth]["package_tag_num"] = $row["tag_num"];
    $_SESSION[$web_auth]["isstar_credit_upper_limit"] = $row["isstar_credit_upper_limit"];
    $_SESSION[$web_auth]["credit_upper_limit"] = $row["credit_upper_limit"];
    $_SESSION[$web_auth]["nofee_num"] = $row["nofee_num"];
	//print_r($_SESSION[$web_auth]);die();
}


//SESSION变量初始化 增加一个类给门店用 by luyang
function set_account_session_agent($row) {
    global $web_auth, $conf_city;

    $_SESSION[$web_auth]["uid_for_agent"] = $row["uid"];
    $_SESSION[$web_auth]["username_for_agent"] = $row["username"];
    $_SESSION[$web_auth]["truename_for_agent"] = $row["truename"];
    $_SESSION[$web_auth]["agentcode_for_agent"] = "B000";
    $_SESSION[$web_auth]["companycode_for_agent"] = $row["agentcode"];
    $_SESSION[$web_auth]["groupid_for_agent"] = $row["groupid"];
    $_SESSION[$web_auth]["groupname_for_agent"] = $row["groupname"];
    $_SESSION[$web_auth]["postlimit_for_agent"] = $row["postlimit"];
    $_SESSION[$web_auth]["refresh_for_agent"] = $row["refresh"];
    $_SESSION[$web_auth]["stocklimit_for_agent"] = 5 * $row["postlimit"];
    $_SESSION[$web_auth]["expiredate_for_agent"] = $row["expiredate"];
    $_SESSION[$web_auth]["contactor_for_agent"] = $row["contactor"];
    $_SESSION[$web_auth]["telno_for_agent"] = $row["telno"];
    $_SESSION[$web_auth]["bbsuserid_for_agent"] = $row["bbsuserid"];
    $_SESSION[$web_auth]["bloguserid_for_agent"] = $row["bloguserid"];
    $_SESSION[$web_auth]["auth_for_agent"] = $row["auth"] . ",base," . $row["add_auth"];
    $_SESSION[$web_auth]["h_ok_for_agent"] = $row["dist"] && $row["hotarea"] && $row["skill"];
    $_SESSION[$web_auth]["city_for_agent"] = $conf_city;
	$_SESSION[$web_auth]["is_pay_for_agent"] = $row["is_pay"];//0表示付费、1表示非付费
    $_SESSION[$web_auth]["package_tag_num_for_agent"] = $row["package_tag_num"];
    $_SESSION[$web_auth]["isstar_credit_upper_limit_for_agent"] = $row["isstar_credit_upper_limit"];
    $_SESSION[$web_auth]["credit_upper_limit_for_agent"] = $row["credit_upper_limit"];
    $_SESSION[$web_auth]["nofee_num_for_agent"] = $row["nofee_num"];
	//print_r($_SESSION[$web_auth]);die();
}


//检测memcache黑名单
function login_memcahe($username, $action = "add") {
    global $mc, $conf_city;
    if ($action == "add") {
        $key = $conf_city . "login_" . $username;
        //$mc->delete($key);
        $info = $mc->get($key);
        if ($info) {
            if ($info >= 3) {
                $key = $conf_city . "ip_" . $usernmae;

                if ($ip = $mc->get($key)) {
                    if (strpos($ip, GetIP()) === false) {
                        $ip = $ip . "||" . GetIP();
                    }
                    $mc->replace($key, $ip, false, 3600);
                } else {
                    $ip = GetIP();
                    $mc->add($key, $ip, false, 3600);
                }
                //echo "ip黑名单:".$mc->get($key);
                //$mc->delete($key);
            } else {
                $mc->replace($key, $info + 1, false, 5);
                //echo "加一次错误之后:".$mc->get($key);
            }
        } else {
            $value = 1;
            $mc->add($key, $value, false, 5);
            //echo "初始化错误一次:".$mc->get($key);
        }
    } else if ($action == "check") {
        $key = $conf_city . "ip_" . $usernmae;
        if (strpos($str, $ip) !== false)
            return false;
        return true;
    }
}

//今日登陆次数过滤成一次
function log_broker_login($kind, $uid){
	global $web_auth,$db;

	$time = time();
	$today = strtotime(date('Y-m-d', $time).' 00:00:00');
	$id = $db->GetOne("SELECT id FROM log_login WHERE uid = '".$uid."' and kind = '".$kind."' and logintime > '".$today."'");

	if($id > 0)
	{
		$sql = "update log_login set logintime = '".$time."' where id = '".$id."' ";
		$rs = $db->Execute($sql);
	}
	else
	{
		$ss=array();
		$ss["kind"]	     = $kind;
		$ss["uid"]	     = $uid;
		$ss["logintime"] = $time;
		$q=insert_sql('log_login',$ss);
		$db->Execute($q);
	}
}


//检测登录函数
function user_login($d) {
    GLOBAL $web_auth, $db, $auth_str, $conf_cityflag;

    $q = " SELECT broker.*,broker_group.refresh as grefresh,groupname,auth,tag_num,isstar_credit_limit_day,isstar_credit_upper_limit,credit_upper_limit,nofee_num from broker left join broker_group on broker.groupid = broker_group.id ";
    $q .= " WHERE broker.username ='" . $d["username"] . "' ";
    $q .= " AND   broker.password ='" . md5($d["password"]) . "' ";

    $row = $db->GetRow($q);
    if (empty($row)) {
        return 0; //登录名密码不对
    }

    if ($row["valid_flag"] != "1")
        return 2; //账号被禁用

    if ($row["expiredate"] < date("Y-m-d") && $row['groupid'] != VISITORS_GROUPID)
        return 3; //账号到期

    if (!login_memcahe($d["username"], "check"))
        return 4;

    //成功后的处理
    //session_regenerate_id(TRUE);
    //处理刷新次数 沙羡 by 2012-8-30
    if($row['refresh'] != $row['grefresh'] ) {
	//更新刷新次数
	$query = " UPDATE `broker` SET refresh = '{$row['grefresh']}' WHERE uid= '{$row['uid']}' LIMIT 1";
	$query2 = " UPDATE `broker_refresh` SET refresh_single_limit = '{$row['grefresh']}' WHERE uid= '{$row['uid']}' LIMIT 1";
	$db->Execute($query);
	$db->Execute($query2);
	$row['refresh']  = $row['grefresh'];
	unset($row['grefresh']);
    }

    set_account_session($row);
	 //过滤重复登陆写日志
	log_broker_login("brokercp", $row['uid']);

	//经纪人登录加积分
	include_once(CORE_LIB."/class_brokercredit.php");
	$I = new BrokerCredit($_SESSION[$web_auth]["uid"]);
	$I->dealCredit('plus_login');

    if ($row['groupid'] == 1)
        echo "<script>alert(\"您的账户功能使用受到限制\");</script>";
    else if ($row["expiredate"] < date("Y-m-d", strtotime("+1 weeks")))
        echo "<script>alert(\"您的账户即将到期，请续费！\");</script>";

    return 1;
}

//Fisher 2013-5-22 V3.5经纪人发布房源删除房源进行记录
function broker_actionlog($tbl,$rowid,$msg)
{
	GLOBAL $db,$web_auth;
	
    $arr=explode(",",$rowid);
	$ss=array();
	$ss["agentcode"]=$_SESSION[$web_auth]["companycode"];
	$ss["uid"]		=$_SESSION[$web_auth]["uid"];
	$ss["tbl"]	    =$tbl;
	$ss["msg"]		=$msg;       //0:删除房源 1:新增有效房源 2:新增失效效房源 3:房源再发布 4:失效房源
 	$ss["y"]		=date('Y');
	$ss["m"]	    =date('m');
	$ss["d"]		=date('d');
	$ss["time"]		=date('Hi');
	$ss["ip"]		=GetIP();
	
	if(is_array($arr) && !empty($arr))
	{   
        $success=0;
		foreach($arr as $k=>$v){
			$ss["rowid"] = $v;
			$q = insert_sql('log_broker',$ss);
			$db->Execute($q);
            $success++;
		}
	}
    return $success;
	
}

/*
 * @use 改变经纪人,房源,图片状态
 * @param $field 状态字段名称
 * @param $oldState  改变前的状态值
 * @param $newState  改变后的状态值
 * @param $primaryKey 归属的外键字段
 * @param $primaryKeyArr 所有归属的值
 */

function changeState($tableName, $field, $newState, $primaryKey, $primaryKeyArr, $sys = '') {
    global $db;
    $primaryKeyStrs = is_array($primaryKeyArr) ? implode(',', $primaryKeyArr) : '';

	//同步修改 2013-3-14
	$moreupdatesql = $tableName == "sell" && $field == "esta" && $newState != 1 ? ",nofee=0" : "";

    if ($primaryKeyStrs) {
        $sql = "UPDATE $tableName SET $field=$newState $moreupdatesql WHERE $primaryKey IN ($primaryKeyStrs)";
    } else {
        $sql = "UPDATE $tableName SET $field=$newState $moreupdatesql WHERE $primaryKey = $primaryKeyArr";
    }


    if ($sys == 'broker') {
        $sql = $sql . " and infofrom = '5'";
    }

    $rs = $db->Execute($sql);
    if ($rs) {
        return true;
    } else {
        return false;
    }
}

if(!function_exists('get_sellinfo_url')) {
	function get_sellinfo_url($id)
	{
		global $conf_city;
		if ($id == '') {return false;}
		return 'http://sell.' . $conf_city . '.house365.com/s_' . $id . '.html';
	}
}

if(!function_exists('get_rentinfo_url')) {
	function get_rentinfo_url($id)
	{
		global $conf_city;
		if ($id == '') {return false;}
		return 'http://rent.' . $conf_city . '.house365.com/r_' . $id . '.html';
	}
}

if(!function_exists('jumpto'))
{
	function jumpto($url, $message = "执行完毕！", $sec = 1000, $template = "jump_page")
	{
		$page_text = $message;
		require(Template($template));
		echo "<script>setTimeout(function(){window.location.href='".$url."';}, ".$sec.");</script>";
		exit;
	}
}

//算出两时间的差值
function get_days($date1, $date2) {
    $d1 = strtotime($date1);
    $d2 = strtotime($date2);
    $days = round(($d2 - $d1) / 3600 / 24);
    return $days;
}

//时间格式转换函数
function to_dhm($str) {
    $d = $str / 24 / 3600;

    $info['d'] = intval($d);

    $h = ($d - $info['d']) * 24;

    $info['h'] = intval($h);

    $m = ($h - $info['h']) * 60;

    $info['m'] = intval($m);

    return $info;
}

if(!function_exists('profile_check'))
{
    function profile_check($fieldid, $value) {
	  $profilevalidate = array(
		'telephone' => '/^((\\(?\\d{3,4}\\)?)|(\\d{3,4}-)?)\\d{7,8}$/',
		'mobile' => '/^(\+)?(86)?0?1\\d{10}$/',
		'smsmobile' => '/^0?1\\d{10}$/',
		'zipcode' => '/^\\d{5,6}$/',
		'revenue' => '/^\\d+$/',
		'height' => '/^\\d{1,3}$/',
		'weight' => '/^\\d{1,3}$/',
		'qq' => '/^[1-9]*[1-9][0-9]*$/'
	  );

	  if($profilevalidate[$fieldid] && preg_match($profilevalidate[$fieldid], $value)) {
		  return true;
	  }

	  return false;
   }
}


?>