<?php

//检测登陆状态
function header_auth_check($pay = 0, $visitor = 0) {
    GLOBAL $web_auth,$justjump;

    //判断登陆，默认判断
    if ((!isset($_SESSION[$web_auth]["username"])) or ($_SESSION[$web_auth]["username"] == "")) {
		if(1 != $justjump)
		{
			$page_text = "您尚未登录租售宝，请先登录！";
			jumpto(FRAME_LOGIN, $page_text, 3000);	
		}
		else
		{
			header("Location: ".FRAME_LOGIN."");
		}
		exit;
    }
	
	//判断付费，默认不判断
    if ($pay) {
        if ($_SESSION[$web_auth]["is_pay"] == IS_PAY) {
			if(1 != $justjump)
			{
				$page_text = "您当前套餐没有此功能的权限，请联系客户经理开通！";
				jumpto(FRAME_INDEX, $page_text, 3000);
			}
			else
			{
				header("Location: ".FRAME_INDEX."");
			}
			exit;
        }
    }

	if ($visitor) {
        if ($_SESSION[$web_auth]["groupid"] == VISITORS_GROUPID) {
			if(1 != $justjump)
			{
				$page_text = "您当前套餐没有此功能的权限，请联系客户经理开通！";
				jumpto(FRAME_INDEX, $page_text, 3000);
			}
			else
			{
				header("Location: ".FRAME_INDEX."");
			}
			exit;
        }
    }
}



//检测登陆状态 门店虚拟登陆 by luyang
function header_auth_check_agent($pay = 0, $visitor = 0) {
    GLOBAL $web_auth,$justjump;

    //判断登陆，默认判断
    if ((!isset($_SESSION[$web_auth]["username_for_agent"])) or ($_SESSION[$web_auth]["username_for_agent"] == "")) {
		if(1 != $justjump)
		{
			$page_text = "您尚未登录租售宝，请先登录！";
			jumpto(FRAME_LOGIN, $page_text, 3000);	
		}
		else
		{
			header("Location: ".FRAME_LOGIN."");
		}
		exit;
    }
	
	//判断付费，默认不判断
    if ($pay) {
        if ($_SESSION[$web_auth]["is_pay_for_agent"] == IS_PAY) {
			if(1 != $justjump)
			{
				$page_text = "您当前套餐没有此功能的权限，请联系客户经理开通！";
				jumpto(FRAME_INDEX, $page_text, 4000);
			}
			else
			{
				header("Location: ".FRAME_INDEX."");
			}
			exit;
        }
    }

	if ($visitor) {
        if ($_SESSION[$web_auth]["groupid_for_agent"] == VISITORS_GROUPID) {
			if(1 != $justjump)
			{
				$page_text = "您当前套餐没有此功能的权限，请联系客户经理开通！";
				jumpto(FRAME_INDEX, $page_text, 4000);
			}
			else
			{
				header("Location: ".FRAME_INDEX."");
			}
			exit;
        }
    }
}


function get_pay($uid = '') {
    GLOBAL $web_auth, $db, $dbback;
    if (!$uid)
        $uid = $_SESSION[$web_auth]["uid"];
    $sql = "select is_pay from broker where uid=$uid";
    $value = $dbback->GetOne($sql);
    if ($value == IS_PAY) {
        return false;
    }
    return true;
}

//房源刷新量(2011-01-06切换)
function post_manage_row_new($uid, $tbl, $rowid) {
    global $db, $dbback;
    if (!$uid)
        return 0;
    $sql = "select num from log_refresh where uid=" . $uid . " and tbl='" . $tbl . "' and rowid=" . $rowid . " and ymd='" . date('Y-m-d') . "'";
    return (int) $db->GetOne($sql);
}

//用户刷新量(2011-01-06切换)
function post_manage_uid_new($uid) {
    global $db, $dbback;
    $sql = "select count(rowid) from log_refresh where uid=" . $uid . " and ymd='" . date('Y-m-d') . "'";
    return (int) $db->GetOne($sql);
}

//判断房源是否可刷新(2011-01-07切换)
function is_refresh($uid, $tbl, $rowid) {
    global $db, $web_auth, $dbback;

    $num = post_manage_row_new($uid, $tbl, $rowid);

    $refresh = $dbback->GetOne("select refresh from broker where uid='" . $_SESSION[$web_auth]["uid"] . "'");

    if ($tbl && $rowid && $num > 0 && $num < $refresh)
        return true;

    $postlimit = $dbback->GetOne("select postlimit from broker where uid='" . $_SESSION[$web_auth]["uid"] . "'");

    if ($num == 0 && post_manage_uid_new($uid) < $postlimit)
        return true;

    return false;
}

//判断房源是否可刷新(用于踢掉激活)
function del_valig($tbl, $rowid = '') {
    GLOBAL $db, $web_auth, $dbback;

    $postlimit = $dbback->GetOne("select postlimit from broker where uid='" . $_SESSION[$web_auth]["uid"] . "'");

    if (!$rowid && post_manage_uid_new($_SESSION[$web_auth]["uid"]) < $postlimit)
        return true;

    if ($rowid) {

        $num = post_manage_row_new($_SESSION[$web_auth]["uid"], $tbl, $rowid);

        $refresh = $dbback->GetOne("select refresh from broker where uid='" . $_SESSION[$web_auth]["uid"] . "'");

        if ($num == 0 && $num > 0 && $num < $refresh)
            return true;
    }

    return false;
}

//有效房源是否已满
function estapost() {
    GLOBAL $db, $web_auth, $dbback;
    $postlimit = $dbback->GetOne("select postlimit from broker where uid='" . $_SESSION[$web_auth]["uid"] . "'");
    $posted = stock_esta('read');
    if ($posted >= $postlimit) {
        return false;
    } else {
        return true;
    }
}

//扩展有效房源是否已满
function devEstaPost($num = 1) {
    GLOBAL $db, $web_auth, $dbback;

    $postlimit = $dbback->GetOne("select postlimit from broker where uid='" . $_SESSION[$web_auth]["uid"] . "'");

    $posted = stock_esta('read');

    if ($postlimit < $posted + $num) {
        return array('postlimit' => $postlimit, 'posted' => $posted);
    } else {
        return true;
    }
}

function addpost() {
    GLOBAL $db, $web_auth, $dbback;

    $postlimit = $dbback->GetOne("select postlimit from broker where uid='" . $_SESSION[$web_auth]["uid"] . "'"); //端口上限
    $stocklimit = post_stock($_SESSION[$web_auth][uid]); //库存量
    $stocked = stock_manage('read'); //现有的房源数量
    if ($stocked >= $stocklimit) {
		$page_text = "对不起,已超过帐号房源库存量上限!";
        jumpto("index.php", $page_text);
        exit;
        return false;
    } else {

        return true;
    }
}

//房源最近预约待刷新
function post_reserve_row($uid, $tbl, $rowid, $day) {
    global $db, $dbback;
    $sql = "select count(*) from house_reserve where uid=" . $uid . " and tbl='" . $tbl . "' and rowid=" . $rowid . " and isdel='0' and reservetime>=" . strtotime($day) . " and reservetime <" . (strtotime($day) + 24 * 3600);
    return $dbback->GetOne($sql);
}

//房源最近预约待刷新
function reserve_flg($uid, $tbl, $rowid) {
    global $db, $dbback;
    $sql = "select id from house_reserve where uid=" . $uid . " and tbl='" . $tbl . "' and rowid=" . $rowid . " and isdel='0'";
    return $dbback->GetOne($sql);
}

//1、	有经纪人头像
//2、	有3张以上房源图片
//3、	有房源描述
//4、	收费经纪人
function valid_top($tbl, $id) {//上传图片
    global $db, $dbback, $web_auth, $remark;

    if (!get_pay($_SESSION[$web_auth]["uid"]))
        return false;

    $sql = "select id,address,remark from $tbl where id=$id";
    $info = $db->GetRow($sql);
    if (strlen($info[address]) < 20)
        return false;

    if (strlen($info[remark]) < 60)
        return false;

    $sql = "select smallphoto from broker where uid=" . $_SESSION[$web_auth]["uid"];
    if ($db->GetOne($sql) == '')
        return false;

    $uploadtbl = get_upload_tblname($tbl, $id);
    $sql = "select count(*) from $uploadtbl where tbl='$tbl' and rowid=$id and sort=2 and flg in (0,1)";
    if ($db->GetOne($sql) < 3)
        return false;

    return true;
}

/**
* checkHouseGrade 检查房源等级，需在valid_top之后使用
* 
* @param string $tbl
* @param int $id
* @return boolen
*/
function checkHouseGrade($tbl, $id)
{
	global $db;

	$uploadtbl = get_upload_tblname($tbl, $id);
    $sql0 = "select count(*) from $uploadtbl where tbl='$tbl' and rowid=$id and sort=0 and (flg = 0 or flg = 1)";
	$sort0 = $db->GetOne($sql0);
	$sql1 = "select count(*) from $uploadtbl where tbl='$tbl' and rowid=$id and sort=1 and (flg = 0 or flg = 1)";
	$sort1 = $db->GetOne($sql1);

	if($sort0 >= 1 && $sort1 >= 1)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function uploadmorepic($tbl, $id, $pic1 = '', $blockid) {//上传图片
    global $db,$dbback,$web_auth;

	$return = array();
	$temp = 0;

    $uploadtbl = get_upload_tblname($tbl, $id);

    //先删除原上传的图片，再重新添加上传图片数据，这个不知道是谁设计的
    if ($_REQUEST['deleteupload'] == 1) {
        $db->Execute("delete from $uploadtbl where tbl='$tbl' and rowid='$id'");
    }

    if (isset($_REQUEST['p_filename'])) {
        $i = 1;
        $indexpic = $firstpic = '';
        $temppic1 = false; //判断设置的封面图片是否被上传

        foreach ($_REQUEST['p_filename'] as $k => $v)
		{
            if (!in_array($_REQUEST['p_sort'][$k], array(1,2,0,9,10))) {
                echo '<script type="text/javascript">alert("上传图片的类型有误！");history.go(-1);</script>';
                exit();
            }

            $token = explode("=", $v);
			$pid = intval($token[1]);
            $filename = substr($v, 0, strpos($v, '?'));
			$idkind = substr($token[0], -3);
			$title = $_REQUEST['p_title'][$k] == '图片描述..限30字' ? '' : strip_tags($_REQUEST['p_title'][$k]);
			
			$sort = $_REQUEST['p_sort'][$k];

			$flg = $sort == 9 || $sort == 10 ? 1 : 0;//图库选择的图片不需要再次审核。
			
			//图库图片使用记录
			if($sort == 9 || $sort == 10)
			{
				$sort = $sort == 9 ? 0 : ($sort == 10 ? 1 : $sort);//图库选择的户型图为9，外景图为10
				$db->Execute("insert into block_img_used_count (`blockid`,`tbl`,`rowid`,`pic`,`type`,`dateline`)VALUES('$blockid','$tbl',$id,'$filename','$sort','".date("Ymd")."')");
			}
			
			$sort = $sort == 9 ? 0 : ($sort == 10 ? 1 : $sort);//图库选择的户型图为9，外景图为10
			$isblock = $blockid > 0 ? intval($_REQUEST['p_block'][$k]) : 0;

			$createtime = time();
			
			if($filename != '')
			{
				$db->Execute("insert into $uploadtbl (`tbl`,`rowid`,`position`,`filename`,`title`,`blockid`,`sort`,`isblock`,`createtime`,`flg`,`isfrom`,`isinfotype`)VALUES('$tbl',$id,'pic$i','$filename','$title','$blockid','$sort','$isblock','$createtime','$flg','2','$_REQUEST[infotype]')");

				if($idkind=='pid' && $pid > 0)
				{
					$picid = $db->Insert_ID();
					//审图用，获取缓存图片库中的图片信息
					$parr = $dbback->GetRow("SELECT from_device, file_md5 FROM house_upload_provisional WHERE id = $pid");
					//$db->Execute("delete from house_upload_provisional where id = $pid");
					//审图用，组合图片信息
					$return[$temp]['pictbl'] = $uploadtbl;
					$return[$temp]['picid'] = $picid;
					$return[$temp]['picurl'] = $filename;
					$return[$temp]['sort'] = $sort;
					$return[$temp]['surface'] = 0;
					$return[$temp]['from_device'] = $parr['from_device'];
					$return[$temp]['file_md5'] = $parr['file_md5'];
					
					$temp++;
				}

				$temppic1 = $temppic1 ? true : $pic1 == $filename; //判断设置的封面图片是否被上传

				if ($firstpic == '') $firstpic = $filename;
			}

			$i++;
        }

        $indexpic = $temppic1 ? $pic1 : $firstpic; //当封面被删除，默认设定第一张图片为封面

		//审图用，设置封面图并过滤掉来自设备的非封面图
		if(is_array($return) && !empty($return))
		{
			foreach($return as $key=>$val)
			{
				if($val['picurl'] == $indexpic)
				{	
					$return[$key]['surface'] = 1;
				}
			}
		}

        $db->Execute("update $tbl set pic1='$indexpic' where id='$id'");
    }
    else {
        $db->Execute("update $tbl set pic1='' where id='$id'");
    }

	return $return;
}

//发布刷新统计(修改后只统计发布)
function post_manage($type, $js = '1') {
    global $web_auth, $db;

    $uid = $_SESSION[$web_auth]["uid"];
    $date = date("Ymd");
    $time = time();
    
    if ($type == "init") {
        $q = "select updatetime  from log_counter_broker  where uid='$uid' ";
        $row = $db->GetRow($q);
        if ($row) {
            if (date("Ymd", $row[updatetime]) != $date) {
                $db->Execute("update log_counter_broker  set counter=0,updatetime='$time' where uid='$uid' ");
            }
        } else {
            $db->Execute("INSERT INTO log_counter_broker (uid,updatetime) VALUES ('$uid','$time')");
        }
        return true;
    }

    if ($type == "read") {
        $row = $db->GetRow("select counter from log_counter_broker  where uid='$uid' and FROM_UNIXTIME(updatetime,'%Y%m%d')='$date'");
        return $row["counter"] ? $row["counter"] : 0;
    }

    if ($type == "write") {
        $rs = $db->Execute("update log_counter_broker  set counter=counter+$js,updatetime='$time' where uid='$uid' and FROM_UNIXTIME(updatetime,'%Y%m%d')='$date'");

        if ($rs->Affected_Rows() == 0) {
            $rs = $db->Execute("update log_counter_broker set counter=$js,updatetime='$time' where uid='$uid' and FROM_UNIXTIME(updatetime,'%Y%m%d')!='$date'");
        }
        return $rs ? true : false;
    }
}

function get_blockid($str) {
    global $web_auth, $db;
    $sql = "select id from block where blockname ='$str'";
    $blockid = $db->GetOne($sql);
    if (!$blockid) {
        $sql = "select id from block where blockname like '$str%'";
        $blockid = $db->GetOne($sql);
    }
    return (int) $blockid;
}

//修正过期房源状态的方法
function revise_house($uid) {
    global $web_auth, $db;
    $sql = "update sell set esta='2' where uid=" . $uid . " and agentcode='B000' and esta in (1,5) and expiretime<'" . time() . "'";
    $db->Execute($sql);
    $sql = "update rent set esta='2' where uid=" . $uid . " and agentcode='B000' and esta in (1,5) and expiretime<'" . time() . "'";
    $db->Execute($sql);
}

//合并数组和
function array_add($arr1, $arr2) {
    foreach ($arr2 as $k => $v) {
        if (array_key_exists($k, $arr1)) {
            $arr1[$k] += $v;
        } else {
            $arr1[$k] = $v;
        }
    }
    return $arr1;
}

/**
 *  判断房源的状态
 *  为了修复失效房源修改成有效的bug
 *
 * @author	 shaxian
 * @version     1.0 ctime:2012-1-12
 * @copyright   www.house365.com
 */
function act_valig($tbl, $rowid = '') {
    GLOBAL $dbback;
    if ($rowid) {
        $esta = $dbback->GetOne("select esta from `$tbl` where id='{$rowid}'");
        if ($esta == 1)
            return FALSE;
        else
            return TRUE;
    }
    return TRUE;
}

function get_infofrom($agentcode) {
    //$token=substr($agentcode,0,2);
    //if($token=="WS") return 4;
    //if($token=="TZ") return 3;
    if ($agentcode == "Z000")
        return 1;
    if ($agentcode == "B000")
        return 5;
    return 2;
}

function set_cookie_array($info, $tbl = "sell") {
    $arr = array("infotype", "district", "streetid", "blockid", "blockshowname", "mright", ",tructure", "buildyear", "forward", "payment", "rentday", "priceunit", "priceterm", "pricety", "perenttype", "rentday", "enterdate", "baseservice", "equipment", "traffic", "school", "fitment", "rentremark", "fitment");
    foreach ($info as $key => $value) {
        if (!in_array($key, $arr))
            continue;
        setcookie($tbl . "_" . $key, $value, time() + 60 * 60 * 24 * 30);
    }
}
?>
