<?php
/*
*文件说明： 本函数为CP后台通用函数
*
*/



/**
 * 新分页
 *
 * @param int $page_now 当前页
 * @param int $pages 总页数
 * @param int $numrows  总条数
 * @return mixed
 */
function new_pagenavi($page_now,$pages,$numrows,$form="search_form"){

	$form ='document.'.$form;
	$ss = "<div class='panelBar'>";

	//如果页数小于1则返回空
	if( $pages <= 1 || !is_numeric($page_now) ){
		return '';
	} else{
		$pre = $page_now == 1		? $page_now : $page_now-1;	//前一页
		$end = $page_now == $pages	? $pages : $page_now+1;	//下一页
		$ss .= "<div class='pages'><span>共".$numrows."条</span></div>";
		$ss .= "<div class='pagination'><ul>";

		//首页、前一页
		if( $page_now == 1 ){
			$ss .= "<li class='j-first disabled'><span class='first'><span>首页</span></span></li>";
			$ss .= "<li class='j-prev disabled'><span class='previous'><span>上一页</span></span></li>";
		}else{
			$first_page = 1;//第一页
			$ss .= "<li class='j-first'>"
					."<a class='first' onclick=\"$form.page_now.value=".$first_page.";$form.submit();return false;\"><span>首页</span></a>"
					."</li>";
			$ss .= "<li class='j-prev'>"
					."<a class='previous' onclick=\"$form.page_now.value=".$pre.";$form.submit();return false;\"><span>上一页</span></a>"
					."</li>";
		}

		//当前页面
		$ss .= "<li class='selected j-num'><a onclick=\"$form.page_now.value=".$page_now.";$form.submit();return false;\">{$page_now}</a></li>";

		//下一页、尾页
		if( ($page_now == $pages) || ($pages == 0) ){
			$last_page = $pages;
			$ss .= "<li class='j-next disabled'><span class='next'><span>下一页</span></span></li>";
			$ss .= "<li class='j-last disabled'><span class='last'><span>末页</span></span></li>";
		} else {
			$next_page = $page_now +1;
			$last_page = $pages;
			$ss .= "<li class='j-next'>"
					."<a onclick=\"$form.page_now.value=".$next_page.";$form.submit();return false;\" class='next'><span>下一页</span></a>"
					."</li>";
			$ss .= "<li class='j-last'>"
					."<a onclick=\"$form.page_now.value=".$last_page.";$form.submit();return false;\" class='last'><span>末页</span></a>"
					."</li>";
		}

		//跳转部分
		$text_page = $page_now <= $pages ? $page_now : $pages;
		$ss .= "<li class='jumpto'>"
					."<input type='text' name ='page_now' value=\"".$text_page."\" size='4' class='textInput page_now'>"
					."<input type='button' value='跳 转' class='goto' onclick=\"$form.submit();return false;\">"
				."</li>";
	}

	$ss .= "</div>";

	return $ss;
}


/**
 * 新分页
 *
 * @param int $page_now 当前页
 * @param int $pages 总页数
 * @param int $numrows  总条数
 * @return mixed
 */
function new_pagenavi2($page_now,$pages,$numrows,$form="search_form"){

	$form ='document.'.$form;
	$ss = "<div class='panelBar'>";

	//如果页数小于1则返回空
	if( $pages <= 1 || !is_numeric($page_now) ){
		return '';
	} else{
		$pre = $page_now == 1		? $page_now : $page_now-1;	//前一页
		$end = $page_now == $pages	? $pages : $page_now+1;	//下一页
		$ss .= "<div class='pages'><span>共".$numrows."条</span></div>";
		$ss .= "<div class='pagination'><ul>";

		//首页、前一页
		if( $page_now == 1 ){
			$ss .= "<li class='j-first disabled'><span class='first'><span>首页</span></span></li>";
			$ss .= "<li class='j-prev disabled'><span class='previous'><span>上一页</span></span></li>";
		}else{
			$first_page = 1;//第一页
			$ss .= "<li class='j-first'>"
					."<a class='first' onclick=\"$form.page_now.value=".$first_page.";$form.action ='';$form.submit();return false;\"><span>首页</span></a>"
					."</li>";
			$ss .= "<li class='j-prev'>"
					."<a class='previous' onclick=\"$form.page_now.value=".$pre.";$form.action ='';$form.submit();return false;\"><span>上一页</span></a>"
					."</li>";
		}

		//当前页面
		$ss .= "<li class='selected j-num'><a onclick=\"$form.page_now.value=".$page_now.";$form.action ='';$form.submit();return false;\">{$page_now}</a></li>";

		//下一页、尾页
		if( ($page_now == $pages) || ($pages == 0) ){
			$last_page = $pages;
			$ss .= "<li class='j-next disabled'><span class='next'><span>下一页</span></span></li>";
			$ss .= "<li class='j-last disabled'><span class='last'><span>末页</span></span></li>";
		} else {
			$next_page = $page_now +1;
			$last_page = $pages;
			$ss .= "<li class='j-next'>"
					."<a onclick=\"$form.page_now.value=".$next_page.";$form.action ='';$form.submit();return false;\" class='next'><span>下一页</span></a>"
					."</li>";
			$ss .= "<li class='j-last'>"
					."<a onclick=\"$form.page_now.value=".$last_page.";$form.action ='';$form.submit();return false;\" class='last'><span>末页</span></a>"
					."</li>";
		}

		//跳转部分
		$text_page = $page_now <= $pages ? $page_now : $pages;
		$ss .= "<li class='jumpto'>"
					."<input type='text' name ='page_now' value=\"".$text_page."\" size='4' class='textInput page_now'>"
					."<input type='button' value='跳 转' class='goto' onclick=\"$form.action ='';$form.submit();return false;\">"
				."</li>";
	}

	$ss .= "</div>";

	return $ss;
}


/**
 * user_login(&$d)
 *
 * cp后台登陆
 * @param    $d
 * @update   2012-9-8 fisher
*/
function user_login(&$d) {
    GLOBAL $web_auth, $dbback_sys;

    $q = " SELECT * from admin_user ";
    $q .= " WHERE username ='" . qstr($d["username"]) . "' ";
    $q .= " AND   password ='" . md5($d["password"]) . "' ";
    $rs = $dbback_sys->GetRow($q);

    if ($rs["uid"] == '')
        return 0; //登录名密码不对

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

    //init_user_auth($rs["groupid"]);

    $_SESSION[$web_auth]["uid"] = $rs["uid"];
    $_SESSION[$web_auth]["username"] = $rs["username"];
    $_SESSION[$web_auth]["truename"] = $rs["truename"];
	$_SESSION[$web_auth]["telno"] = $rs["telno"];
	$_SESSION[$web_auth]["password"] = $rs["password"];

	init_user_auth($rs["purview"], $rs["role"]);//初始化用户权限

    user_login_note($d['username']); //记录登陆的相关信息

    return 1;
}

/**
 * 初始化用户权限
 */
function init_user_auth($purview, $role) {
    GLOBAL $web_auth, $global_purview;

	$_SESSION[$web_auth]["purview_arr"] = $purview != "" ? unserialize($purview) : array();
	$_SESSION[$web_auth]["open_citys"] = array();
    //角色加载默认权限
	if($global_purview[$role] != "")
	{
		$_SESSION[$web_auth]["purview_arr"] = array_merge(array($role=>$global_purview[$role]), $_SESSION[$web_auth]["purview_arr"]);
	}

	if(is_array($_SESSION[$web_auth]["purview_arr"]) && !empty($_SESSION[$web_auth]["purview_arr"]))
	{
		foreach($_SESSION[$web_auth]["purview_arr"] as $key=>$val)
		{
			$_SESSION[$web_auth]["open_citys"][] = $key;
		}
	}

	//把第一个城市保存
	$_SESSION[$web_auth]["now_city"] = $_SESSION[$web_auth]["open_citys"][0];
}

/**
 * 清空用户权限
 */
function auth_init()
{
	GLOBAL $web_auth;

	unset($_SESSION[$web_auth]);
}


/**
 * 初始化用户权限
 */
function get_page_purview($type = 0)
{
	GLOBAL $dao_sys,$web_auth;

	//等于1的为普通权限读取
	$sswhere = $type == 1 ? " id > 9 " : " 1 ";
	$params = " * ";
	$memkey = $web_auth."_page_purview_".$type;
	$memsec = '600';
	$delcache = false;//改为TRUE可立即触发菜单修改 2013-11-28

	$page_purview_arr = $return  = array();

	$page_purview_arr = $dao_sys->getAll("admin_pages", $sswhere, $params, $memkey, $memsec, $delcache);

	if(is_array($page_purview_arr) && !empty($page_purview_arr))
	{
		foreach($page_purview_arr as $val)
		{
			if($val['status'] == 1)
			{
				$purview['id'] = $val['id'];
				$purview['fid'] = $val['fid'];
				$purview['title'] = $val['title'];
				$purview['path'] = $val['path'];

				$return[$val['fid']][$purview['id']] = $purview;
			}
		}
	}

	return $return;
}

/*
 * 获取该分类下的权限
*/
function get_group_purview($groupid, $needdelcache = false)
{
	GLOBAL $dao_sys,$web_auth;

	$groupid = intval($groupid);
	$sswhere = " id = '".$groupid."' ";
	$params = " auth ";
	$memkey = $web_auth."_group_purview_".$groupid;
	$memsec = '600';
	$delcache = $needdelcache;

	$group_purview = $dao_sys->getOne("admin_user_group", $sswhere, $params, $memkey, $delcache);
	$now_purview_arr = $group_purview != "" ? explode(";",$group_purview) : array();
	return $now_purview_arr;
}

/**
 * frame_menu_create($user_auth)
 *
 * 生成cp后台左侧菜单
 * @param    $page_grp
 * @update   2012-9-8 fisher
*/
function frame_menu_create($user_auth) {
    GLOBAL $web_auth;

	$page_menu = $auth_arr = array();
	$page_purview_arr = get_page_purview();
	if(is_array($page_purview_arr[0]) && !empty($page_purview_arr[0]))
	{
		foreach($page_purview_arr[0] as $key => $grp)
		{
			if(in_array($key, $user_auth))
			{
				$page_menu[$key]['menu'] = $grp['title'];

				if(is_array($page_purview_arr[$key]) && !empty($page_purview_arr[$key]))
				{
					foreach($page_purview_arr[$key] as $p)
					{
						if($p['fid'] == $key && in_array($p['id'], $user_auth))
						{
							$auth_arr = array(
								"title" => $p['title'],
								"path"	=> FRAME_URL.'module'.$p['path']
							);
							$page_menu[$key]['pages'][] = $auth_arr;
						}
					}
				}

			}
		}
	}

    return $page_menu;
}

/**
 * 登陆 有关信息（ip。。）的存储
 *
 * @param var 登陆用户的账号
 * wyy 2010.4.6
 */
function user_login_note($username) {
    GLOBAL $db_sys;
    $arrData = array();
    $arrData['username'] = $username;
    $arrData['ip'] = GetIP();
    $arrData['log_time'] = time();
    $q = insert_sql('log_admin_user_login', $arrData);
    $db_sys->Execute($q);
}

/**
* checkAuth($pageid)
*
* @param int $pageid
*/
function checkAuth($pageid) {
    GLOBAL $web_auth;

    if($_SESSION[$web_auth]["uid"] <= 0 || empty($_SESSION[$web_auth]["group_purview"]) || empty($_SESSION[$web_auth]["open_citys"]))
    {
        gotoUrl(FRAME_LOGIN, "请先登录！");
        exit;
    }

    if($pageid != 0 && !in_array($pageid, $_SESSION[$web_auth]["group_purview"]))
    {
        js_redirect(FRAME_DEFAULT, "没有权限！");
        exit;
    }
}

/**
* gotoUrl($url)
*
* @param str $url
*/
function gotoUrl($url, $msg='') {

    echo "<p>".$msg."</p>";
    echo "<script>";
    echo "setTimeout(function(){if(parent.window.location.href != ''){parent.window.location.href='".$url."';} window.location.href='".$url."';}, 1000);";
    echo "</script>";
    exit;
}

/**
* gotoUrl($url)
*
* @param str $url
*/
function js_redirect($url, $msg='') {

    echo "<p>".$msg."</p>";
    echo "<script>";
    echo "setTimeout(function(){if(window.location.href != ''){window.location.href='".$url."';} window.location.href='".$url."';}, 1000);";
    echo "</script>";
    exit;
}

/**
* 函数名称：uploadFile
*
* 函数功能：上传图片到服务器，返回图片保存路径。
* @param    $fileName='userFile',	上传文件空间名称
*$maxsize='512000', 上传文件最大尺寸
*$ResizeWidth='120',	裁剪宽度
*$ResizeHeight='90',	裁剪高度
*$Watermark='HOUSE365.COM', 水印文字
*$WatermarkPosition='rb' 水印位置
* @return    string 图片地址
* @update    2012/8/28 xz
*/
function uploadFile($fileName='userFile',$maxsize='512000',$ResizeWidth='120',$ResizeHeight='90',$Watermark='HOUSE365.COM',$WatermarkPosition='rb')
{
    $uf = new UploadFile("$fileName");
    $uf->setMaxSize($maxsize);
    $uf->setUploadType("ftp");
    $uf->setSaveDir("/njhouse/");
    $uf->setWatermark(true);
    $uf->setWatermarkType(1);
    $uf->setWatermarkPosition($WatermarkPosition);
    $uf->setWatermarkString($Watermark);
    $uf->setResizeImage(true);
    $uf->setResizeWidth($ResizeWidth);
    $uf->setResizeHeight($ResizeHeight);

    if($uf->upload()=="success")
    {
        return $uf->getResizeImageURL();    //图片地址
    }
    else
    {
        return false;
    }
}

//lvtao添加密码匹配规则
function checkPass($loginpassword)
{
    $f=1;
    if(strlen($loginpassword)<8)
    {
        $f=3;
    }
    $ls = 0;

    if(preg_match("/([a-z])+/", $loginpassword)) $ls++;
    if(preg_match("/([0-9])+/", $loginpassword)) $ls++;
    if(preg_match("/([A-Z])+/", $loginpassword)) $ls++;
    if(preg_match("/[^a-zA-Z0-9]+/", $loginpassword)) $ls++;

    if($ls<3)
    {
        $f=3;
    }

    return $f;
}

/**
* 获取指定日期所在月的上个月,本月开始日期与结束日期
* @param string $date
* @param int  $flag 默认1返回上个月日期，2返回本月日期
* @return array
*/
function getMonthRange($date,$flag=1){
    $time = strtotime($date);
    if($flag == 1){
        $monthFirstDay = date('Y-m-01',strtotime(date('Y',$time).'-'.(date('m',$time)-1).'-01'));
        $monthLastDay = date('Y-m-d',strtotime("$monthFirstDay +1 month -1 day"));
    }else if($flag == 2){
        $monthFirstDay = date('Y-m-01',strtotime(date('Y',$time).'-'.date('m',$time).'-01'));
        $monthLastDay = date('Y-m-d',strtotime("$monthFirstDay +1 month -1 day"));
    }
    return array($monthFirstDay,$monthLastDay);
}

 /**
 * 获取select下拉列表
 * @param array  $data  下拉列表数据源
 * @param string $name  下拉列表的name名称
 * @param str  $selected  下拉列表选中的值
 * @return str
 */
function getSelect($data,$name,$selected=''){
    if(!is_array($data) || empty($data)){
        return '';
    }
    $select_info = "<select name=".$name.">";
    foreach($data as $key=>$val){
        if($key == $selected && $selected != ''){
            $select_info .= "<option value=".$key." selected='true'>".$val."</option>";
        }else{
            $select_info .= "<option value=".$key.">".$val."</option>";
        }
    }

    $select_info .= "</select>";
    return $select_info;
}

    /**
    * street_cache
    *
    * 街道缓存
    *
    * @access	public
    * @param	string $district 区属
    * @return	array   $arr_street 板块数组
    */
    function street_cache( $district = '' )
    {
        GLOBAL  $mc , $dbback , $conf_city;

        //缓存查询结果
        $mem_key = 'esf_street_info_'.urlencode($district).'_'.$conf_city;
        $cache = $mc->get($mem_key);

        if($cache['is_ok'] == '1')
        {
            $arr_street = $cache['data'];
        }
        else
        {
            if( $district != '')
            {
                $cond_where = "WHERE district = '$district' AND spell != ''";
            }

            $sql = "SELECT id,streetname FROM street ";
            $sql .= $cond_where;
            $arr_street = $dbback->GetAssoc( $sql );
            //添加缓存
            $mc->add( $mem_key , array('is_ok'=>'1','data'=>$arr_street) , false , 3600);
        }

        return $arr_street;
    }


    /**
    * subway_cache
    *
    * 地铁站点
    *
    * @access	public
    * @param	void
    * @return	array   $arr_subway 地铁站点数组
    */
    function subway_cache($line = '')
    {
        GLOBAL  $mc , $dbback , $conf_city;

        //缓存查询结果
        $mem_key = 'esf_subway_station_info_'.urlencode($line).'_'.$conf_city;
        $cache = $mc->get($mem_key);

        if($cache['is_ok'] == '1')
        {
            $arr_subway = $cache['data'];
        }
        else
        {
            $cond_where = " WHERE type = 2 ";
            if( $line != '')
            {
                $cond_where .= " AND line = '$line' ";
            }

            $sql = "SELECT bid,line,station FROM traffic ";
            $sql .= $cond_where;
            $arr_subway = $dbback->GetAssoc( $sql );

            //添加缓存
            $mc->add( $mem_key , array('is_ok'=>'1','data'=>$arr_subway) , false , 3600);
        }

        return $arr_subway;
    }


    /**
    * q_type_cache
    *
    * 问答分类缓存
    *
    * @access	public
    * @param	int $t_level 类别层级
    * @param	int $fid 父级分类编号
    * @return	array   $arr_q_type 问答类别数组
    */
    function q_type_cache($t_level , $fid = 0)
    {
        GLOBAL  $mc , $dbback , $conf_city;

        $t_level = intval($t_level);
        $fid = intval($fid);

        //缓存查询结果
        $mem_key = 'esf_question_type_info_t_level_'.$t_level.'_fid_'.$fid.'_'.$conf_city;
        $cache = $mc->get($mem_key);

        if($cache['is_ok'] == '1')
        {
            $arr_q_type = $cache['data'];
        }
        else
        {
            $cond_where = "WHERE t_level = '".$t_level."'";

            //如果父类编号大于0则代表查询某个父类别的子类
            if( $fid > 0 )
            {
                $cond_where .= " AND t_fid = '".$fid."'";
            }

            $sql = "SELECT t_id,t_name FROM qa_type ";
            $sql .= $cond_where;

            $arr_q_type = $dbback->GetAssoc( $sql );

            //添加缓存
            $mc->add( $mem_key , array('is_ok'=>'1','data'=>$arr_q_type) , false , 600);
        }

        return $arr_q_type;
    }
?>