<?php !defined('APP_DIR') ? die('acceess not defined') : '';

/**
 * 自动加载类
 *
 * @param string $class_name
 */
spl_autoload_register('myAutoload');
function myAutoload($class_name){
    if (preg_match('/^'.ACTIONS.'_[0-9a-zA-Z_]+$/',$class_name)) {  //控制器的单独处理
        $class_name = str_replace('_','/',$class_name);
    	$class_file = APP_DIR."/$class_name.php";
    }else if ($class_name[0]>='a' && $class_name[0]<='z') {
        $class_name = strtolower(str_replace('_','/',$class_name));
    	$class_file = ROOT_DIR."/system/$class_name.php";
    }elseif ($class_name[0]>='A' && $class_name[0]<='Z'){
        if( substr($class_name,0,4)=='DAO_' ){  //dao的单独处理，目的是为了自动生成DAO
            $class_name = 'dao/'.substr($class_name,4);
        }else {
            if (strpos($class_name,'_')) {
            	$class_name = str_replace('_','/',$class_name);
            }
            $class_name = strtolower($class_name);
        }
        $class_file = ROOT_DIR."/library/$class_name.php";
    }
    if(file_exists($class_file)){	
        require_once($class_file);
        return true;
    }
    return false;
}

/**
 * 获取bm对象的函数
 *
 * @param string $bm_name
 * @return obj
 */
function bm($bm_name){
    return BM::instance($bm_name);
}

/**
 * 获取widget对象
 *
 * @param string $widget_name
 * @return obj
 */
function widget($widget_name){
    return WIDGET::instance($widget_name);
}

/**
 * 缓存快速调用方法
 *
 * @param string $city
 * @return cache Obj
 */
function cache($city='local',$file=false){
    return cache::instance($city,$file);
}

/**
 * 判断是否是ajax请求
 *
 * @return bool
 */
function is_ajax(){
	return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
}




/**
 * 取得数组中某一字段的集合
 *
 * @param array_type $data_lists
 * @param string_type $col_name
 * @param string_type $ret a:返回array, s:返回,隔开的字符串
 * @return array or string
 */
function get_col(&$data_lists, $col_name, $ret_type = 'a', $dimension = 2) {
	$ret = array();
	
	if ( is_array($data_lists) ) {
		switch ($dimension) {
			case 2:
				foreach ($data_lists as $r) {
					if ( $r[$col_name] && !in_array($r[$col_name], $ret) ) {
						$ret[] = $r[$col_name];
					}
				}
				break;
			case 3:
				foreach ($data_lists as $tmp_r) {
					foreach ($tmp_r as $r) {
						if ( $r[$col_name] && !in_array($r[$col_name], $ret) ) {
							$ret[] = $r[$col_name];
						}
					}
				}
				break;
		}
	}
	if($ret_type != 'a') {
		return implode(',', $ret); 
	}
	return $ret; 
}

/**
 * 将二维数组的索引变为 第二维某索引
 * 
 * @param array $arr
 * @param int $key
 */
function change_array_key($arr, $index){
	$arr1 = array();
	foreach ($arr as $key => $val) {
		$arr1[$val[$index]] = $val;
	}
	return $arr1;
}



function pagebar($total,$query,$pagesize=20,$pageseg=7){
	
	$page = $_GET['page'];//当前分页
	$page = $page?$page:1;//
	$pagenum = ceil($total/$pagesize);
	if($page==1 && $pagenum==1){//如果只有一页的话
		$firstPage = $nextPage = $prevPage = $endPage = 1;
	}elseif($page==1 && $pagenum==0){
		$firstPage = $nextPage = $prevPage = $endPage = 1;
	}elseif($page==1){
		$firstPage = $prevPage =1;
		$nextPage  = $page+1;
		$endPage   = $pagenum;
	}elseif($page==$pagenum){
		$firstPage = 1;
		$endPage = $nextPage  = $pagenum;
		$prevPage = $page-1;		
	}else{
		$firstPage = 1;
		$nextPage = $page+1;
		$prevPage = $page-1;
		$endPage = $pagenum;
	}
	
	$tmp = (int)(($page-1)/$pageseg);
	$start = $tmp*$pageseg+1;
	$start = $start<=0?1:$start;
	$navstr = '';
	$tag = (strpos($query,"?")===false)?"?":"&";

	if($page>=4){

		$start = $page-3;//只适用pagesize=7的情况
		for($i= $start;$i<$start+$pageseg && $i<=$pagenum;$i++){
			if($i==$page) $class='class="current"'; else $class='';
			$navstr.='<li><a '.$class.' href="'.$query.$tag.'page='.$i.'">'.$i.'</a></li>';
		}
	}else{

		for($i= $start;$i<$start+$pageseg && $i<=$pagenum;$i++){
			if($i==$page) $class='class="active"'; else $class='';
			$navstr.='<li '.$class.'><a  href="'.$query.$tag.'page='.$i.'">'.$i.'</a></li>';
		}
	}
	
	$prev = '<li><a href="'.$query.$tag.'page='.$prevPage.'">&lt; 上一页</a></li>';
	$end = '<li><a href="'.$query.$tag.'page='.$nextPage.'">下一页 &gt;</a></li> 共<span class="c-orange fb plr5">'.$total.'</span>条信息';
	$nav['start'] = ($page-1)*$pagesize;
	$nav['pagenation'] ='<ul class="pagination">'. $prev.$navstr.$end.'</ul>';
	return $nav;
}


function pagebar_2($total,$query,$pagesize=20,$pageseg=7){
	
	$page = $_GET['page'];//当前分页
	$page = $page?$page:1;//
	$pagenum = ceil($total/$pagesize);
	if($page==1 && $pagenum==1){//如果只有一页的话
		$firstPage = $nextPage = $prevPage = $endPage = 1;
	}elseif($page==1 && $pagenum==0){
		$firstPage = $nextPage = $prevPage = $endPage = 1;
	}elseif($page==1){
		$firstPage = $prevPage =1;
		$nextPage  = $page+1;
		$endPage   = $pagenum;
	}elseif($page==$pagenum){
		$firstPage = 1;
		$endPage = $nextPage  = $pagenum;
		$prevPage = $page-1;		
	}else{
		$firstPage = 1;
		$nextPage = $page+1;
		$prevPage = $page-1;
		$endPage = $pagenum;
	}
	
	$tmp = (int)(($page-1)/$pageseg);
	$start = $tmp*$pageseg+1;
	$start = $start<=0?1:$start;
	$navstr = '';
	$tag = (strpos($query,"?")===false)?"?":"&";
	
	if($total>$pageseg){
		if($page>=4){

			$start = $page-3;//只适用pagesize=7的情况
			for($i= $start;$i<$start+$pageseg && $i<=$pagenum;$i++){
				if($i==$page) $class='class="on"'; else $class='';
				$navstr.='<a '.$class.' href="'.$query.$tag.'page='.$i.'">'.$i.'</a>';
			}
		}else{

			for($i= $start;$i<$start+$pageseg && $i<=$pagenum;$i++){
				if($i==$page) $class='class="on"'; else $class='';
				$navstr.='<a '.$class.' href="'.$query.$tag.'page='.$i.'">'.$i.'</a>';
			}
		}
	}
	if($total>$pageseg){
		$prev = '<a class="cur" href="'.$query.$tag.'page='.$prevPage.'">&lt; 上一页</a>';
		$end = '<a class="cur" href="'.$query.$tag.'page='.$nextPage.'">下一页 &gt;</a> ';
	}
	$end .= '共<span class="c-orange fb plr5">'.$total.'</span>条信息';
	$nav['start'] = ($page-1)*$pagesize;
	$nav['pagenation'] = $prev.$navstr.$end;
	return $nav;
}
/**
*   page  当前页 
*	pages 总页数
*	nums  每页记录条数
*	url  点击上下页时要跳转的url（包含要传的参数）
*   num  所有的记录条数
*/
function getPageHtml($page, $pages, $nums,$url,$num){
	$_pageNum = 5;
	$page = $page<1?1:$page;
	$page = $page > $pages ? $pages : $page;
	$pages = $pages < $page ? $page : $pages;
	$_start = $page - floor($_pageNum/2);
	$_start = $_start<1 ? 1 : $_start;
	$_end = $page + floor($_pageNum/2);
	$_end = $_end>$pages? $pages : $_end;

	$_curPageNum = $_end-$_start+1;
	if($_curPageNum<$_pageNum && $_start>1){  
		$_start = $_start - ($_pageNum-$_curPageNum);
		$_start = $_start<1 ? 1 : $_start;
		$_curPageNum = $_end-$_start+1;
	}

	if($_curPageNum<$_pageNum && $_end<$pages){ 
		$_end = $_end + ($_pageNum-$_curPageNum);
		$_end = $_end>$pages? $pages : $_end;
	}

	$_pageHtml = '<ul class="pagination">';
	if($page>1){
		$_pageHtml .= '<li ><a title="上一页" href="'.$url.'&disNums='.$nums.'&page='.($page-1).'">上一页</a></li>';
	}
	for ($i = $_start; $i <= $_end; $i++) {
		if($i == $page){
			$_pageHtml .= '<li class="active"><a>'.$i.'</a></li>';
		}else{
			$_pageHtml .= '<li><a href="'.$url.'&disNums='.$nums.'&page='.$i.'">'.$i.'</a></li>';
		}
    }
	if($page<$_end){
		$_pageHtml .= '<li ><a title="下一页" href="'.$url.'&disNums='.$nums.'&page='.($page+1).'">下一页</a></li>';
	}
    $_pageHtml .= '&nbsp;共 '.$num.' 条记录';
	$_pageHtml .= '</ul>';
	
	switch($nums){
		case 10:
			$_pageHtml .= '<ul class="pagination1"><li style="width: 185px;" align="center">每页显示 <a class="slc" href="'.$url.'&disNums=10&page='.$page.'">10</a> <a href="'.$url.'&disNums=20&page='.$page.'">20</a> <a href="'.$url.'&disNums=30&page='.$page.'">30</a> 行</li></ul>';
			break;
		case 20:
			$_pageHtml .= '<ul class="pagination1"><li style="width: 185px;" align="center">每页显示 <a href="'.$url.'&disNums=10&page='.$page.'">10</a> <a class="slc" href="'.$url.'&disNums=20&page='.$page.'">20</a> <a href="'.$url.'&disNums=30&page='.$page.'">30</a> 行</li></ul>';
			break;
		case 30:
			$_pageHtml .= '<ul class="pagination1"><li style="width: 185px;" align="center">每页显示 <a href="'.$url.'&disNums=10&page='.$page.'">10</a> <a href="'.$url.'&disNums=20&page='.$page.'">20</a> <a class="slc" href="'.$url.'&disNums=30&page='.$page.'">30</a> 行</li></ul>';
			break;
		default :
			$_pageHtml .= '<ul class="pagination1"><li style="width: 185px;" align="center">每页显示 <a class="slc" href="'.$url.'&disNums=10&page='.$page.'">10</a> <a href="'.$url.'&disNums=20&page='.$page.'">20</a> <a href="'.$url.'&disNums=30&page='.$page.'">30</a> 行</li></ul>';
			break;
	}
    
	
	return $_pageHtml;
 }


/**
 * 通过CURL方式获取远程地址内容
 * 
 * @param $t_url：需要伪装的来源地址（例：http://www.sina.com）
 * @param $proxy：需要使用的代理地址和端口（例：127.0.0.1:8080）
 * 
 */
function curl_get_contents($str, $t_url='', $proxy='') {
	$ch = curl_init();
	$t_url = $t_url ? $t_url : 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	if ($proxy) curl_setopt($ch, CURLOPT_PROXY, $proxy); 
	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;
}

function _get_fetch($url){
	$ch = curl_init($url) ; 
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); // 连接超时（秒） 
	curl_setopt($ch, CURLOPT_REFERER,$url); 
	curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch) ;
	curl_close($ch);
	return $output;
}

/*
*导出
*/
function xlsBOF() {
	echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
	return;
}
function xlsEOF() {
	echo pack("ss", 0x0A, 0x00);
	return;
}
function xlsWriteNumber($Row, $Col, $Value) {
	echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
	echo pack("d", $Value);
	return;
}
function xlsWriteLabel($Row, $Col, $Value ) {
	$L = strlen($Value);
	echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
	echo $Value;
	return;
}
function exportexcel($filename,$fields=array(),$records=array()){
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Content-type: application/vnd.ms-excel;charset=gb2312");
	header("Content-Type: application/force-download");
	header("Content-Type: application/octet-stream");
	header("Content-Type: application/download");;
	header("Content-Disposition: attachment;filename=$filename.xls");
	header("Content-Transfer-Encoding: binary ");//*/		
	xlsBOF();
	$I=0;
	foreach ($fields as $key=>$item){
		$name = $item;
		xlsWriteLabel(0,$I,$name);
		$I++;
	}			
	foreach ($records as $key=>$item){
		$I=0;
		for($j=0;$j<count($item);$j=$j+1){
			$value = $item[$j];
			xlsWriteLabel($key+1,$I,"$value");
			$I++;
		}																					
	}
	xlsEOF();	
}

function exportexcel_tj($filename,$fields=array(),$records=array()){
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Content-type: application/vnd.ms-excel;charset=gb2312");
	header("Content-Type: application/force-download");
	header("Content-Type: application/octet-stream");
	header("Content-Type: application/download");;
	header("Content-Disposition: attachment;filename=$filename.xls");
	header("Content-Transfer-Encoding: binary ");//*/		
	xlsBOF();
	$I=0;
	foreach ($fields as $key=>$item){
		$name = $item;
		xlsWriteLabel($I,0,$name);
		$I++;
	}			
	foreach ($records as $key=>$item){
		$I=0;
		for($j=0;$j<count($item);$j=$j+1){
			$value = $item[$j];
			xlsWriteLabel($I,$key+1,"$value");
			$I++;
		}																					
	}
	xlsEOF();	
}

function array_remove(&$arr, $offset)
{
	array_splice($arr, $offset, 1);
} 

function htmldecode($str)  
{  
	if(empty($str)) return;  
	if($str=="") return $str;  
	$str=str_replace("&",chr(34),$str);  
	$str=str_replace(">",">",$str);  
	$str=str_replace("<","<",$str);  
	$str=str_replace("&","&",$str);  
	$str=str_replace(" ",chr(32),$str);  
	$str=str_replace(" ",chr(9),$str);  
	$str=str_replace("'",chr(39),$str);  
	$str=str_replace("<br />",chr(13),$str);  
	$str=str_replace("''","'",$str);  
	$str=str_replace("select","select",$str);  
	$str=str_replace("join","join",$str);  
	$str=str_replace("union","union",$str);  
	$str=str_replace("where","where",$str);  
	$str=str_replace("insert","insert",$str);  
	$str=str_replace("delete","delete",$str);  
	$str=str_replace("update","update",$str);  
	$str=str_replace("like","like",$str);  
	$str=str_replace("drop","drop",$str);  
	$str=str_replace("create","create",$str);  
	$str=str_replace("modify","modify",$str);  
	$str=str_replace("rename","rename",$str);  
	$str=str_replace("alter","alter",$str);  
	$str=str_replace("cas","cast",$str);  
	$farr = array(   
	"//s+/" , //过滤多余的空白   
	"/<(//?)(img|script|i?frame|style|html|body|title|link|meta|/?|/%)([^>]*?)>/isU" , //过滤 <script 防止引入恶意内容或恶意代码,如果不需要插入flash等,还可以加入<object的过滤   
	"/(<[^>]*)on[a-zA-Z]+/s*=([^>]*>)/isU" , //过滤javascript的on事件   
	);   
	$tarr = array(   
	" " ,   
	"<//1//2//3>" , //如果要直接清除不安全的标签，这里可以留空   
	"//1//2" ,   
	);   
	$str = preg_replace ( $farr , $tarr , $str );   
	return $str;  
} 

function filterStr($str){
    return trim(str_replace(array('&nbsp;','n'), array('',''), strip_tags($str)));
}

/**
 **推送
 **/
 function send_push($arr){
	$pusharr = tool::json_encode($arr);   //只接受UTF-8
	//print_r($pusharr);
	//线上环境
	//$url='http://mps.house365.com/house365-mps-web/message/messageAddOuter';
	//测试环境
	$url='http://192.168.105.28:8682/house365-mps-web/message/messageAddOuter'; 
	$push_re=http_post_data($url,$pusharr);
	//写入文件
	/*file_put_contents("log_title_tmp.txt", $pusharr,FILE_APPEND);
	fclose($file);*/
	return $push_re;
 }

 //php 模拟请求json数据,比较特殊,需要制定header
function http_post_data($url, $data_string) {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
	curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string))
    );
    ob_start();
    curl_exec($ch);
    $return_content = ob_get_contents();
    ob_end_clean();

    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);//200代表正常访问
    return array($return_code, $return_content);
}

//将二维数组按照某字段的拼音排序  城市排序
	function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR"){ 
		if(!is_array($ArrayData) || empty($ArrayData)) { 
            return $ArrayData; 
		}
		$ArgCount = func_num_args(); 
		for($I = 1;$I < $ArgCount;$I ++){ 
			$Arg = func_get_arg($I); 
			if(!preg_match("/^SORT/i",$Arg)) { 
				$KeyNameList[] = $Arg; 
				$SortRule[] = '$'.$Arg; 
			}else{ 
				$SortRule[] = $Arg; 
			} 
		} 
		foreach($ArrayData AS $Key => $Info) 
		{ 
			foreach($KeyNameList AS $KeyName){ 
				${$KeyName}[$Key] = $Info[$KeyName]; 
			}	
		} 
		$EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);'; 
		eval ($EvalString); 
		return $ArrayData; 
    }

	function writeLog($content = ""){
		global $yii_start_time;
		global $yii_seed;
		if(isset($_COOKIE['yii_debug']) && $_COOKIE['yii_debug']){
			if(!$yii_seed){
				$yii_seed = rand(10000,99999);
				echo $yii_seed;
			}
			if(!$yii_start_time){
				list($msec, $sec) = explode(' ', microtime());
				$msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
				$yii_start_time = $msectime;
			}


			list($msec, $sec) = explode(' ', microtime());
			$cur_time =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
			$gap_time = $cur_time - $yii_start_time;
			$content.= "  execute_time=$gap_time,seed=$yii_seed";
			echo curl_get_contents("http://newrent.house365.com/server-task/sentry-log?key=srwjZ1UjUw4O5X08py78m1J4PEJrWhMM&content=$content");
		}
	}


