<?php

//函数集合
if(!function_exists('log_broker_credit')) {
  function log_broker_credit($uid, $operation, $kind) {
    GLOBAL $db;

    $ss = array();
    $ss["uid"] = $uid;
    $ss["operation"] = $operation;
    $ss["kind"] = $kind;
    $ss["dateline"] = time();

    $q = insert_sql('log_broker_credit', $ss);
    $db->Execute($q);
}  
}
if(!function_exists('log_agent_credit')) {
function log_agent_credit($uid, $operation, $kind) {
    GLOBAL $db;

    $ss = array();
    $ss["uid"] = $uid;
    $ss["operation"] = $operation;
    $ss["kind"] = $kind;
    $ss["dateline"] = time();

    $q = insert_sql('log_agent_credit', $ss);
    $db->Execute($q);
}
}
//写日志
if(!function_exists('actionlog')) {
function actionlog($tbl, $rowid, $msg) {
    GLOBAL $db, $web_auth;

    $ss = array();
    $ss["tbl"] = $tbl;
    $ss["rowid"] = $rowid;
    $ss["operator"] = $_SESSION[$web_auth]["authname"];
    $ss["msg"] = $msg;
    $ss["ip"] = GetIP();
    $ss["date"] = date("YmdHi");

    $q = insert_sql('log', $ss);
    $db->Execute($q);
}
}

/**
 * 经纪人账号操作日志记录
 *
 * @param array 经纪人信息
 */
 if(!function_exists('brokeroperatorlog')) {
function brokeroperatorlog($data) {
    GLOBAL $db, $web_auth;
    $ss = array();
    $time = time();
    $ss["operators"] = $_SESSION[$web_auth]["authname"];
    $ss["object"] = $data['username'];
    $ss["truename"] = $data['truename'];
    $ss["operatedate"] = $time;
    $q = insert_sql('log_broker_operator', $ss);
    $db->Execute($q);
}
}
//获取IP
if(!function_exists('GetIP')) {
function GetIP() {

    $ip = $_SERVER["REMOTE_ADDR"];
    if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $tip = split(",", $_SERVER["HTTP_X_FORWARDED_FOR"]);
        $ip = $tip[0];
    }
    return(trim($ip));
}
}
if(!function_exists('tonyForm')) {
function tonyForm($tag, $name, $option_arr, $value = '', $td_num = 1, $validate = '') {
    switch ($tag) {

        case 'select':
            $str = "<select name='$name' id='$name' $validate>";
            foreach ($option_arr as $k => $v) {
                if ($value == $k && $value != '') {
                    $str .= "<option value='$k' selected>$v</option>";
                } else {
                    $str .= "<option value='$k'>$v</option>";
                }
            }
            $str.="</select>";
            break;

        case 'radio':
            $checked_arr = explode(',', $value);
            $td_width = "width=" . floor(100 / $td_num) . "%";
            $blank_i = ceil(count($option_arr) / $td_num) * $td_num - count($option_arr);
            for ($i = 0; $i < $blank_i; $i++)
                $option_arr[] = "";//补全使之成为整数

            $str = "<table align=center border=0 cellspacing=0 width=100%> \n";
            $i = 1;
            foreach ($option_arr as $k => $v) {
                $j = $i % $td_num;
                if ($j == 1)
                    $str.="<tr>";
                //$checked= $k==$value ? "checked":"";
                $checked = in_array($k, $checked_arr) ? "checked" : "";
                $input = $v ? "<input type=radio name=$name value='$k' $checked>$v" : "&nbsp;";
                $str.="<td $td_width>$input</td>";
                if ($j == 0)
                    $str.="</tr> \n";
                $i++;
            }
            $str.="</table> \n";
            break;

        case 'checkbox':
            $checked_arr = explode(',', $value);
            $td_width = "width=" . floor(100 / $td_num) . "%";
            $blank_i = ceil(count($option_arr) / $td_num) * $td_num - count($option_arr);
            for ($i = 0; $i < $blank_i; $i++)
                $option_arr[] = "";//补全使之成为整数

            $str = "<table align=center border=0 cellspacing=0 width=100%> \n";
            $i = 1;
            foreach ($option_arr as $k => $v) {
                $j = $i % $td_num;
                if ($j == 1)
                    $str.="<tr>";
                $checked = in_array($k, $checked_arr) ? "checked" : "";
                $input = $v ? "<input type=checkbox name={$name}[] value='$k' $checked>$v" : "&nbsp;";
                $str.="<td $td_width>$input</td>";
                if ($j == 0)
                    $str.="</tr> \n";
                $i++;
            }
            $str.="</table> \n";
            break;

        case 'text':
            $checked_arr = explode(',', $value);
            $td_width = "width=" . floor(100 / $td_num) . "%";
            $blank_i = ceil(count($option_arr) / $td_num) * $td_num - count($option_arr);
            for ($i = 0; $i < $blank_i; $i++)
                $option_arr[] = "";//补全使之成为整数

            $str = "<table align=center border=0 cellspacing=0 width=100%> \n";
            $i = 1;
            foreach ($option_arr as $k => $v) {
                $j = $i % $td_num;
                if ($j == 1)
                    $str.="<tr>";
                $checked = in_array($k, $checked_arr) ? "checked" : "";
                $input = $v ? "<input type=checkbox name={$name}[] value='$k' $checked>$v" : "&nbsp;";
                $str.="<td $td_width>$input</td>";
                if ($j == 0)
                    $str.="</tr> \n";
                $i++;
            }
            $str.="</table> \n";
            break;
    }
    return $str;
}
}
if(!function_exists('create_htmlable')) {
function create_htmlable($name,$label,$value='',$val='',$class='',$style='',$js=''){//创建html标签
		//name标签名称|label标签类型|value标签的值(当为checkbox时为数组)|val主要用于radio和checkbox
		$html = '';
		if($class) $cls = 'class="'.$class.'"';
		if($style) $sty = 'style="'.$style.'"';
		if($name)  $nam = 'name="'.$name.'"';

		if($label=='text' || $label=='password'){//文本框
			if($name) $id = 'id="'.$name.'"';
			$html = '<input '.$cls.' type="'.$label.'" '.$nam.' '.$id.' value="'.$value.'" '.$sty.' '.$js.'>';			
		}elseif($label=='radio'){//radio 
			if(is_array($val)){
				foreach($val as $key=>$item){
					if($key==$value) $checked='checked';else $checked = '';
					$html.=' <input type="'.$label.'" '.$nam.' '.$checked.' value="'.$key.'" '.$sty.' '.$js.'>'.$item;
				}
			}
		}elseif($label=='checkbox'){//checkbox
			if(is_array($val)){
				foreach($val as $key=>$item){
					if(in_array($key,$value)) $checked='checked';else $checked = '';
					$html.=' <input type="'.$label.'" '.$nam.' '.$checked.' value="'.$key.'" '.$sty.' '.$js.'>'.$item;
				}
			}
		}elseif($label=='select'){//下拉框
			if(is_array($val)){
				if($name) $id = 'id="'.$name.'"';
				$html.='<select '.$nam.' '.$id.'  '.$sty.' '.$js.'>';
				foreach($val as $key=>$item){
					if($key==$value) $selected = 'selected'; else $selected='';						
					$html.='<option '.$selected.' value="'.$key.'">'.$item.'</option>';
					
				}
				$html.='</select>';
			}			
		}
		return $html;
	}
}
if(!function_exists('ctrl_select')) {
function ctrl_select($opt_para, $ctrl_name, $ctrl_value, $style_ext = "class=flat1") {
    /**   2002.03.05
      ctrl_select 函数参数说明
      @param [opt_para]   : opt_para是一个数组，元素含义如下
      [opt_arr]    下拉框选项的数组，可以是简单数组，也可以是关联数组
      [field_key]  如果是关联数组，field_key表示，  下拉框的key  出自关联数组的哪一个field，为空表示出自简单数组的key
      [field_value]如果是关联数组，field_value表示，下拉框的value出自关联数组的哪一个field，为空表示出自简单数组的value
      @param [ctrl_name]  : select控件的名称
      @param [ctrl_value]	: select控件选择的值
      @param [style_ext]  : 扩充的样式，可以是样式或js
      返回select的string
     * */
    // 1.重新构建数组，将关联数组化为简单数组
    $old_opt_arr = (is_array($opt_para[opt_arr])) ? ($opt_para[opt_arr]) : (array());
    FOR ($opt_arr = array(), reset($old_opt_arr), $i = 0; $i < count($old_opt_arr); $i++) {
        $key = key($old_opt_arr);
        $field_key = ($opt_para[field_key] != "") ? ($old_opt_arr[$key][$opt_para[field_key]] ) : ($key);
        $field_value = ($opt_para[field_value] != "") ? ($old_opt_arr[$key][$opt_para[field_value]]) : ($old_opt_arr[$key]);
        $opt_arr[$field_key] = $field_value;
        next($old_opt_arr);
    }

    // 2.生成
    $ss = "<select name=\"" . $ctrl_name . "\" " . $style_ext . ">\n";
    for (reset($opt_arr), $i = 1; $i <= count($opt_arr); $i++) {
        $key = key($opt_arr);
        $value = $opt_arr[$key];
        if (strval($key) == strval($ctrl_value))
            $selected_flag = "selected"; else
            $selected_flag = "";
        $ss.="  <option value=\"" . $key . "\" " . $selected_flag . ">" . $value . "</option>\n";
        next($opt_arr);
    }
    $ss.="</select>";

//if ($ctrl_name=="") echo $key."___".$ctrl_value."<br>";

    RETURN $ss;
}
}
if(!function_exists('tony_flag2name')) {
function tony_flag2name($flag, $arr) {
    //return $flag;
    return $arr[$flag];
}
}
if(!function_exists('tony_flag2name2')) {
function tony_flag2name2($str, $arr) {
    $arr_flag = explode(",", $str);
    foreach ($arr_flag as $key => $flag) {
        $row[$key] = $arr[$flag];
    }
    return implode(",", $row);
}
}
if(!function_exists('csubstr2')) {
function csubstr2($str_cut, $length = 30) {

    if (strlen($str_cut) > $length) {
        for ($i = 0; $i < $length; $i++)
            if (ord($str_cut[$i]) > 128)
                $i++;
        //  $str_cut = substr($str_cut,0,$i) . "...";
        $str_cut = substr($str_cut, 0, $i);
    }
    return $str_cut;
}
}


if(!function_exists('telnotelist')) {
function telnotelist($telno) {
    GLOBAL $db, $house;

    $q = "select *  from telno_note where telno = '$telno' order by id desc";
    $rs = $db->SelectLimit($q, 10);

    $ss = "<div align='left'> $remark_add</div>";
    $ss = "<table width=700 border=0 cellspacing=0 cellpadding=0 align=center height=0><tr><td ><font color='#990000'>&nbsp;&nbsp;电话备注记录($telno)&nbsp;&nbsp;</font></td></tr></table><table " . LIST_TBL_STYLE . "><tr align=center bgcolor=#F7F4E8><td width=5%>类型</td><td width=10%>房源编号</td><td width=10%>房源地址</td><td width=10%>联系人</td><td width=10%>当时状态</td><td width=25%>电话备注</td><td width=15%>更新时间</td><td width=10%>操作员</td><td >操作</td></tr>";

    while ($row = $rs->FetchRow()) {
        $updatetime = date("Ymd H:i", $row["updatetime"]);   //登记时间
        $esta = tony_flag2name($row["esta"], $house['esta']);     //当前状态
        $address = csubstr2($row[address], 20);
        $act = "<a href='telno_note.php?tbl=$row[tbl]&rowid=$row[rowid]&telno=$row[telno]&esta=$row[esta]' target='_blank'>改</a> <a href='telno_note.php?action=del&id=$row[id]' target='_blank' onclick='if (!confirm(\\\"确定要删除该记录吗？\\\"))return false;'>删</a>";

        $ss.="<tr><td>$row[tbl]</td><td>$row[rowid]</td><td align=left><span title='$row[address]'>$address</span></td><td>$row[contactor]</td><td>$esta</td><td><font color=blue>" . addslashes($row[note]) . "</font></td><td>$updatetime</td><td>$row[operator]</td><td>$act</td></tr>";
    }
    $ss.="</table>";
    if ($rs->RecordCount() == 0)
        $ss = '';
    $rs->Close();
    return $ss;
}
}

if(!function_exists('broker_sync_refresh')) {
function broker_sync_refresh() {//同步刷新规则
    GLOBAL $db;

    $q = "select uid,postlimit,refresh from broker where valid_flag=1 order by uid asc";
    $broker = $db->GetAll($q);

    foreach ($broker as $b) {
        $uid = $b[uid];
        $refresh_single_limit = $b[refresh];
        $refresh_total_limit = $b[postlimit] * 3;
        //$refresh_num_limit = $b[postlimit];
		$refresh_num_limit = 0;

        $sql = "replace into broker_refresh (uid,refresh_single_limit,refresh_total_limit,refresh_num_limit) values ('" . $uid . "','" . $refresh_single_limit . "','" . $refresh_total_limit . "','" . $refresh_num_limit . "')";

        $db->Execute($sql);
    }
}
}

/* * **************************************************** */

if(!function_exists('fv')) {
function fv($name, $defalut = "") {
    global $row;
    if (is_array($_REQUEST[$name])) {
        $_REQUEST[$name] = implode(",", $_REQUEST[$name]);
    }
    $ss = $_REQUEST[$name] != "" ? $_REQUEST[$name] : $row[$name];
    return $ss != "" ? $ss : $defalut;
}
}
if(!function_exists('tony_date')) {
function tony_date($format, $timestamp) {
    $ss = $timestamp == '' ? '' : date($format, $timestamp);
    return $ss;
}
}
if(!function_exists('ischecked')) {
function ischecked($args) {
    $ss = $args > 0 ? "checked" : "";
    Return $ss;
}
}

//中间层刷新房源 2011-12-9上
if(!function_exists('refresh_housebymid')) {
function refresh_housebymid($uid, $tpl, $id) {
    global $midwork_refreshurl,$conf_city;
    $bd = @file_get_contents($midwork_refreshurl . "&app=" . $tpl . "&uid=" . $uid . "&hid=" . $id);
    return $bd;
}
}
/* * ******************************************************* */
if(!function_exists('tony_view2')) {
function tony_view2($pic, $picPath, $picid = '', $blockid = '') {
    GLOBAL $db;

    $url = $picPath;
    $ss = $picPath ? "<a href='$url' title='<img src=$url width=200 height=200 />'>查看</a>&nbsp;&nbsp;<a href=$url onclick=\"return delpic('$pic');\">删除</a>&nbsp;" . $block . "" : "";
    return $ss;
}
}
if(!function_exists('tony_view')) {
function tony_view($pic, $picPath) {
    //$url=PUBURL.$picPath;
    $url = $picPath;
    $ss = $picPath ? "<a href='$url' target='_blank' title='<img src=$url width=200 height=200 />' >查看</a>&nbsp;&nbsp;<a href=$url onclick=\"return delpic('$pic');\">删除</a>" : "";
    return $ss;
}
}
if(!function_exists('tony_actionlog')) {
function tony_actionlog($tbl, $rowid, $msg) {
    GLOBAL $db, $web_auth;

    $ss = array();
    $ss["tbl"] = $tbl;
    $ss["rowid"] = $rowid;
    $ss["operator"] = $_SESSION[$web_auth]["authname"];
    $ss["msg"] = $msg;
    $ss["ip"] = GetIP();
    $ss["date"] = date("YmdHi");

    $q = insert_sql('log', $ss);
    $db->Execute($q);
}
}
if(!function_exists('log_view')) {
function log_view($tbl, $rowid) {
    GLOBAL $db, $web_auth;

    $ss = array();
    $ss["tbl"] = $tbl;
    $ss["rowid"] = $rowid;
    $ss["username"] = $_SESSION[$web_auth]["authname"];
    $ss["dateline"] = date("YmdHi");
    $ss["ip"] = GetIP();

    $q = insert_sql('log_view', $ss);
    $db->Execute($q);
}
}
if(!function_exists('agent_actionlog')) {
function agent_actionlog($tbl, $rowid, $msg) {

    GLOBAL $db, $web_auth, $infotype, $statistics;

	if (is_array($rowid)) {
		$arr = $rowid;
	} else {
		$arr = explode(",", $rowid);
	}

    $ss = array();
    $ss["agentcode"] = $_SESSION[$web_auth]["agentcode"];
    $ss["uid"] = $_SESSION[$web_auth]["uid"];
    $ss["infotype"] = $infotype;
    $ss["tbl"] = $tbl;
    $ss["msg"] = $msg;       //0:删除 1:增加 2:刷新
    $ss["y"] = date('Y');
    $ss["m"] = date('m');
    $ss["d"] = date('d');
    $ss["time"] = date('Hi');
    $ss["ip"] = GetIP();

    foreach ($arr as $k => $v) {
        $ss["rowid"] = $v;
        $q = insert_sql('log_agent', $ss);
        $db->Execute($q);

		//新版统计2011-10-55
		if ($_SESSION[$web_auth]["agentcode"] == 'B000' && $msg == 2) {
			$ymd = date("Y-m-d");

			$s = "select id from log_refresh where uid='" . $_SESSION[$web_auth]["uid"] . "' and tbl='" . $tbl . "' and rowid='" . $v . "' and ymd='" . $ymd . "'";
			$r = $db->GetRow($s);
			if ($r) {
				$db->Execute("update log_refresh set num=num+1 where id=$r[id] ");
			} else {
				$db->Execute("insert into log_refresh(uid,tbl,rowid,ymd,num)values('" . $_SESSION[$web_auth]["uid"] . "','" . $tbl . "','" . $v . "','" . $ymd . "',1)");
			}
		}
	}

    if ($_SESSION[$web_auth]["agentcode"] == 'B000' && $msg != 0) {
        $time = date("Y-m-d");
        $num = count($arr);

        $s = "select id from log_broker_tmp where uid='" . $_SESSION[$web_auth]["uid"] . "' and updatetime='" . $time . "'";
        $r = $db->GetRow($s);
        if ($r) {
            $db->Execute("update log_broker_tmp set num=num+$num where id=$r[id] ");
        } else {
            $db->Execute("insert into log_broker_tmp(num,agentcode,uid,updatetime)values('" . $num . "','" . $_SESSION[$web_auth]["companycode"] . "','" . $_SESSION[$web_auth]["uid"] . "','" . $time . "')");
        }
    }
}
}
if(!function_exists('tony_str_replace')) {
function tony_str_replace($arr, $str) {
    foreach ($arr as $key => $value) {
        $arr_from[] = $key;
        $arr_to[] = $value;
    }

    return str_replace($arr_from, $arr_to, $str);
}
}
if(!function_exists('tony_fileupload_add')) {
function tony_fileupload_add($position) {
    $ss = "<input type=file name='$position'>&nbsp;图片描述:<input type='text' size=20 name='{$position}_title' id='{$position}_title'>";
    return $ss;
}
}
if(!function_exists('tony_fileupload_modify')) {
function tony_fileupload_modify($tbl, $rowid, $position) {
    global $db;

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

    $row = $db->GetRow("select * from $uploadtbl where tbl='$tbl' and rowid='$rowid' and position='$position'");

    $ss = "<input type=file name='$position'>&nbsp;图片描述:<input type='text' size=20 name='{$position}_title' id='{$position}_title' value='$row[title]'>&nbsp;<span id='{$position}_control'>" . tony_view($position, $row[filename]) . "</span>";

    return $ss;
}
}
if(!function_exists('get_upload_tblname')) {
function get_upload_tblname($tbl, $id) {

	return 'upload';

    if ($tbl == 'sell' and $id < 16679765)
        return 'upload0';

    if ($tbl == 'rent' and $id < 7672437)
        return 'upload0';

    return 'upload';
}
}
if(!function_exists('auth_diff')) {
function auth_diff($auth1, $auth2) {
    $arr = array_diff(explode(",", $auth1), explode(",", $auth2));

    return implode(",", $arr);
}
}
if(!function_exists('get_auth_cp')) {
function get_auth_cp($auth_scope, $auth_str, $name = 'auth') {
    $auth_module = get_auth_module($auth_scope);

    $ss = "<script>
	$(function() {
		$('.grpname').click(function() {
			v=$(this).attr('checked') ?true:false;
			$(this).parent().next('table').find('input[@type=checkbox]').attr('checked',v);

		});
	});
</script> ";
    foreach ($auth_module as $grpkey => $grpname) {

        $ss.="<span class=auth_module><input type='checkbox' class='grpname'><font color=green>$grpname</font></span>";
        $arr = get_authgrp_arr($auth_scope, $grpkey);
        $ss.=tonyForm('checkbox', $name, $arr, $auth_str, 6);
    }
    return $ss;
}
}

if(!function_exists('get_auth_module')) {
function get_auth_module($auth_str) {
    global $auth_grp;
    $arr = explode(",", $auth_str);
    foreach ($arr as $k => $v) {
        $tokin = explode("_", $v);
        if (array_key_exists($tokin[0], $auth_grp))
            $auth_module[$tokin[0]] = $auth_grp[$tokin[0]][name];
    }
    return $auth_module;
}
}

if(!function_exists('get_authgrp_arr')) {
function get_authgrp_arr($auth_str, $grpkey) {
    global $auth_arr;
    $arr0 = explode(",", $auth_str);

    foreach ($arr0 as $key => $authname) {
        if ($auth_arr[$authname][grp_id] == $grpkey)
            $arr[$authname] = $auth_arr[$authname][name];
    }
    return $arr;
}
}
if(!function_exists('csubstr')) {
function csubstr($str_cut, $length = 30, $p = 0) {

    if (strlen($str_cut) > $length) {
        for ($i = 0; $i < $length; $i++)
            if (ord($str_cut[$i]) > 128)
                $i++;
        if ($p == 0)
            $str_cut = substr($str_cut, 0, $i);
        if ($p == 1)
            $str_cut = substr($str_cut, 0, $i) . "...";
    }
    return $str_cut;
}
}
if(!function_exists('qstr')) {
function qstr($ss, $db_type = "mysql", $slash_flag = true) {
    /*
      stripslashes是用于去掉多余的slash，大多是form提交时产生的，他们不能存入数据库)
      无论是那种数据库，存进去的数据都是没有slash的。例如 abc'def"fff\hhh
      查询条件为'
      mssql：则查询语句需要写成select * from test where  col_1 like '%''%'
      mysql：则查询语句需要写成select * from test where  col_1 like '%\'%'
      查询条件为"
      mssql：则查询语句需要写成select * from test where  col_1 like '%"%'
      mysql：则查询语句需要写成select * from test where  col_1 like '%\"%'

      也就是说mysql查询时需要addslashes，mssql需要将'转化为''
      如果  是post过来的数据，会自动加上slash，因此无论mssql或是mysql都需要先stripslashes
      如果不是post过来的数据，不会加上slash  ，因此无需stripslashes
      这也就是$slash_flag开关的用途:post过来的数据$slashes_flag=true,其他=false
      (mysql的addslashes和mssql的''都是为了查询不出错)

      2001.8.1
      slash_flag参数已经去掉，because of stripslash_vars()
      stripslash_vars()将所有post,get过来的变量做了stripslashes处理，所以此处无需再strip
     */
    $replaceQuote["mssql"] = "''";
    $replaceQuote["ibase"] = "\'";
    $replaceQuote["sybase"] = "''";
    $replaceQuote["vfp"] = "'+chr(39)+'";
    $replaceQuote["oracle"] = "\'";

    if ($db_type == "mssql")
        return str_replace("'", $replaceQuote[$db_type], $ss);

    if ($db_type == "mysql") //针对mysql数据库，addslashes是用于sql查询不出错，相当于replaceQuote的操作
        return addslashes($ss);
}
}
if(!function_exists('no_html_str')) {
function no_html_str($str) {//用于数据库中读出(此时是没有slash)，显示
    $str = nl2br(htmlspecialchars($str));
    return $str;
}
}

//format_str_1("abc",4) 返回 &nbsp;abc
//format_str_1("a",4) 	返回 &nbsp;&nbsp;&nbsp;a
if(!function_exists('fmt_str_1')) {
function fmt_str_1($str, $strlen_total = 2, $fill_in = "&nbsp;", $direction = "before") {
    $str = strval(trim($str));
    for ($i = strlen($str); $i < $strlen_total; $i++)
        if ($direction == "before") //确定是在前面(before)加，还是在后面(after)加 //2001.10.9修改
            $str = $fill_in . $str;
        else
            $str = $str . $fill_in;

    return $str;
}
}

if(!function_exists('get_allowedhtml')) {
function get_allowedhtml($str) {
    $allow_tags = "<img><table><tbody><tr><td><div><span><p><ul><li><font><strong><b><em><u><sub><sup><embed><object><param>";

    $ss = strip_tags($str, $allow_tags);

    return $ss;
}
}
if(!function_exists('phpStrToHtml')) {
function phpStrToHtml($str) {
    if (strpos($str, "\n")) {
        $str = str_replace("\n", "<br>", $str);
    }
    return $str;
}
}
if(!function_exists('addressfilter')) {
function addressfilter($str) {
    $title = iconv('gbk', 'utf-8', $str);
    if (preg_match('/^[\x{4e00}-\x{9fa5}|0-9|a-z|\s]+$/ui', $title)) {
        return true;
    } else {
        return false;
    };
}
}
if(!function_exists('in_str')) {
function in_str($v, $str) {
    $arr = explode(",", $str);
    return in_array($v, $arr);
}
}
if(!function_exists('arraytosql')) {
function arraytosql($array) {
    foreach ($array as $v) {
        $i++;
        $sql.=$i == 1 ? $v : "," . $v;
    }
    return $sql;
}
}

/**
* getFeatureArr 获取房源特色数组
* 
* @param str $tbl
* @return array
*/
if(!function_exists('getFeatureArr')) {
function getFeatureArr($tbl = 'sell')
{
	global $db,$dbback,$mc,$conf_cityflag;

	$dbback = isset($dbback) ? $dbback : $db;

	$tbl = $tbl == 'sell' ? 'sell' : 'rent';

	$memkey = $conf_cityflag."_house_feature_".$tbl;
	$cache = $mc->get($memkey);

	$feature_arr = array();

	if($cache['isok'])
	{
		$feature_arr = $cache['data'];
	}
	else
	{
		$arr = $dbback->GetAll("SELECT id,name FROM house_feature WHERE tbl = '".$tbl."'");
		if(is_array($arr) && !empty($arr))
		{
			foreach($arr as $val)
			{
				$feature_arr[$val['id']] = $val['name'];
			}
		}
		$mc->add($memkey, array('isok'=>1, 'data'=>$feature_arr), false, 86400);
	}

	return $feature_arr;
}
}

/**
* getHouseFeature 获取房源特色
* 
* @param str $feature
* @param str $tbl
* @return array
*/
if(!function_exists('getHouseFeature')) {
function getHouseFeature($feature, $tbl = 'sell')
{
	global $conf_cityflag;

	$housefeatur = array();
	
	if($feature == '')
	{
		return $housefeatur;
	}
	$farr = explode("$", $feature);
	if(empty($farr) || !is_array($farr))
	{
		return $housefeatur;
	}
	else
	{
		$tbl = $tbl == 'sell' ? 'sell' : 'rent';
		$feature_arr = getFeatureArr($tbl);

		foreach($farr as $val)
		{
			$val = intval($val);
			if($val > 0 && $feature_arr[$val] != '')
			{
				$housefeatur[$val] = $feature_arr[$val];
				$temp++;
			}
		}
	}
	
	return $housefeatur;
}
}
if(!function_exists('insert_sql')) {
  function insert_sql($tablename,$field,$db_type="mysql") { //2001.12.27 修改 (加了$db_type参数)
	for ($i=1;$i<=count($field);$i++) {
	  if ($i==1)$ss1 =key($field) ;
	  else 		$ss1.=",".key($field) ;

	  if ($i==1)$ss2 =" '".qstr($field[key($field)],$db_type)."'" ;
	  else 		$ss2.=",'".qstr($field[key($field)],$db_type)."'" ;

	  next($field) ;
	}

	$q  = "INSERT INTO ".$tablename." ( ".$ss1." ) VALUES ( ".$ss2." ) " ;
	//echo $q;exit;
	//new LogOutputAY ($q);

    return $q;
  }
}
      /*
    数据库操作函数集合 by zain
    文件名：func_sql.php
    创建日期：2011.3.7
    更改日期：2011.3.7
    */
    if(!function_exists('update_sql')) {
    function update_sql($tablename,$field,$sswhere="",$db_type="mysql") {//2001.12.27 修改 (加了$db_type参数)
        for ($i=1;$i<=count($field);$i++) {
            if ($i==1) 	$ss =" ".key($field)."='".qstr($field[key($field)],$db_type)."' ";
            else 		$ss.=",".key($field)."='".qstr($field[key($field)],$db_type)."' ";

            next($field) ;
        } 
        $q  = "UPDATE ".$tablename." set ".$ss.$sswhere;
        return $q;
    }
    }


//图片上传
if(!function_exists('common_file_upload')) {
function common_file_upload($fileName, $watermark = false, $resize = false, $width = 640, $height = 480, $swidth = 120, $sheight = 90, $maxsize = "2048")
{
	global $conf_city;

	$uf = new UploadFile("$fileName");
	$uf->setFileType("jpg");
	$uf->setMaxSize($maxsize);
	$uf->setUploadType("ftp");
	$uf->setSaveDir("/".$conf_city."house/");

	$uf->setWatermark($watermark);
	$uf->setWatermarkType(1);
	$uf->setWatermarkPosition("rb");
	$uf->setWatermarkString("HOUSE365.COM");

	$uf->setImageCut(true);
	$uf->setImageWidth($width);
	$uf->setImageHeight($height);
	
	if($resize)
	{
		$uf->setResizeImage(true);
		$uf->setResizeCut(false);
		$uf->setResizeNeedWater(false);
		$uf->setResizeReality();
		$uf->setResizeWidth($swidth);
		$uf->setResizeHeight($sheight);
	}

	if ($uf->upload() == "success") {
        return $resize ? $uf->getResizeImageURL() : $uf->getSaveFileURL(); //图片地址
    } else {
        return false;
    }
}
}
if(!function_exists('curl_get_contents'))
{
	function curl_get_contents($str,$t_url="")
	{
		$ch = curl_init();
		$t_url = $t_url ? $t_url : "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		curl_setopt($ch, CURLOPT_URL, $str);
		curl_setopt($ch, CURLOPT_REFERER, $t_url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);

		$str = curl_exec($ch);
		curl_close($ch);
		return $str;
	}
}
/**
* 发送短消息
* @param string $mobile 电话号码
* @param string $msg 消息内容
* @return $msg
*/
if(!function_exists('sendsms'))
{
	function sendsms($mobile,$msg){
		global $conf_city;
		curl_get_contents("http://mysms.house365.com:81/index.php/Interface/apiSendMobil/jid/7/depart/3/city/".$conf_city."/mobileno/".$mobile."/?msg=".urlencode($msg));
	}
}

//产生随机数函数
if(!function_exists('random'))
{
   function random($length) {
	  $hash = '';
	  $chars = '0123456789';
	  $max = strlen($chars) - 1;

      for($i = 0; $i < $length; $i++) {
	     $hash .= $chars[mt_rand(0, $max)];
	  }
	  return $hash;
   }
}

if(!function_exists('curl_get_contents'))
{
	function curl_get_contents($str,$t_url="")
	{
		$ch = curl_init();
		$t_url = $t_url ? $t_url : "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		curl_setopt($ch, CURLOPT_URL, $str);
		curl_setopt($ch, CURLOPT_REFERER, $t_url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);

		$str = curl_exec($ch);
		curl_close($ch);
		return $str;
	}
}
/**
* js弹窗函数
* @param string $tip 弹窗消息
* @param int    $sty  返回类型
* @param string $href 返回地址
* @return $msg
*/
if(!function_exists('js_alert'))
{
	function js_alert($tip='',$href='',$sty=0)
	{
		echo "<script>";
		if($sty==0){
			if($tip)  echo "alert('".$tip."');";
		}elseif($sty==1){
		    if($tip)  echo "alert('".$tip."');";
            echo "window.close();";
		}elseif($sty==2){
			if($tip)  echo "alert('".$tip."');";
			echo "window.parent.location.reload();";
		}elseif($sty==3){
			if($tip)  echo "window.parent.alert('".$tip."');";
			if($href) echo "window.parent.location.href='".$href."'";
		}elseif($sty==4){
			if($tip)  echo "alert('".$tip."');";
			if($href) echo "location.href='".$href."'";
		}
		echo "</script>";
	}
}
?>