<?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;
   }
}


?>