<?php
/*******************************************************************
 * 版权协议：2009-2019
 * 版权所有: PHP-北京金南曦网络技术有限公司旗下PHPWMS，PHP商城系统技术支持中心http://www.php188.net，并保留所有权利。 
* PHP商城系统网址: http://www.php188.com
 * PHPWMS系统网址：http://www.phpwms.com
 * 销售电话：010-87875088
 * 销售电话：010-87875188 
*------------------------------------------------------------------
 * 这不是一个完全免费软件！您只能在不用于商业目的的前提下对程序代码进
 * 行修改和使用；不允许对程序代码以任何形式任何目的的再发布。
 *------------------------------------------------------------------
 * 文件名称：phpwms.common.fun.php
 * 摘　　要：全局调用函数
 * 适用范围：PHPWMS 1.0
 * 版　　本：1.0
 *------------------------------------------------------------------
 * Script Written By phpwms项目组
 * 最后更新： 2009-09-24 phpwms 由PHP金南曦网络技术有限公司整理发布
 *******************************************************************/
if(!function_exists('to_int')){
	function to_int($string){
		return abs(intval(trim($string)));
	}
}

function formart_ids($ary,$join = true){
	if(empty($ary)|| !is_array($ary))return FALSE;
	foreach ($ary as &$a)$a = abs(intval(trim($a)));
	$ary = array_filter($ary);
	if(empty($ary))return FALSE;
	return $join?join(',',$ary):$ary;
}
if(!function_exists('is_mulit_array')){
	function is_mulit_array($array){
		if(!is_array($array))return FALSE;
		foreach ($array as $t){
			return is_array($t)?TRUE:FALSE;
		}
		return FALSE;
	}
}
function mulitarray_to_array($array,$sort = true){
	if(!is_array($array))return $array;
	static $arr = array();
	if(is_array($array)){
		foreach ($array as $key=> $v){
			if(is_array($v)){
				$sort?mulitarray_to_array($v):mulitarray_to_array($v,false);
			}else{
				if($sort){
					$arr[trim($key)] = trim($v);	
				}else{
					$arr[] = trim($v);
				}
			}
		}
	}
	return $arr;
}
if(!function_exists('dump')){
	function dump($str,$dump = false,$echo = true,$char = 'GBK'){
		@ob_start();
		@header("Content-Type:text/html;charset=\"$char\"");
		echo '<pre><div style="text-align:left;">';
		if($dump)var_dump($str);else print_r($str);
		echo '</div></pre>';
		$out =  ob_get_contents();
		ob_end_clean();
		if($echo){
			echo $out;
		}else{
			return $out;
		}
		return NULL;
   	}
}
if(!function_exists('microtime_float')){
	function microtime_float(){
	   $fusec = (float)array_shift(explode(" ", microtime()));
	   if($fusec > 0) $fusec -= floor($fusec);
	   return $fusec + time();
	}
}
function format_bytes($bytes,$showBt = true) {
    $display = array('Byte', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $level = 0;
    while ($bytes > 1024) {
        $bytes /= 1024;
        $level++;
    }
    return round($bytes, 1) . ' ' . ($showBt?$display[$level]:'');
}
if(!function_exists('create_file')){
	function create_file($data,$file,$cover="wb",$return = true){//ab追加 WB 覆盖
				$file = str_replace("\\",'/',$file);
				$p = dirname($file);
				$p = substr($p,-1,1)!='/'?$p.'/':$p;
				@mkdirs($p);
			    $fp=fopen($file, $cover);
			    fwrite($fp,$data);//="\xEF\xBB\xBF".$text; 
				@flock($fp,2);
				@fclose($fp);
				@chmod($file, 0777);
				if(!file_exists($file))return FALSE;
		return $return?(filesize($file)?$file:0):FALSE;
	}
}
if(!function_exists('mkdirs')){
	function mkdirs($path, $mode = 0777){
			$path = str_replace("\\",'/',$path);
			$dirs = explode('/',($path=substr($path,-1,1)!='/'?$path.'/':$path)); 
			$pos = strrpos($path, "."); 
			$subamount = $pos === false?0:1;
			for ($c=0;$c < count($dirs) - $subamount; $c++) { 
				$thispath=""; 
			for ($cc=0; $cc <= $c; $cc++) { 
				$thispath.=$dirs[$cc].'/'; 
			} 
			if (!file_exists($thispath))@mkdir($thispath,$mode); 
		} 
	}
}
if(!function_exists('is_post')){
	function is_post(){
		return $_SERVER['REQUEST_METHOD']==='POST'?TRUE:FALSE;
	}
}
function array_group_by($arr, $key_field){
	if(!is_array($arr)||empty($arr))return array();
        $ret = array();
        foreach ($arr as $row){
            $key = $row[$key_field];
            $ret[$key][] = $row;
        }
        return $ret;
}
function obj_to_array($obj){
	$array = array();
	if (is_object($obj)){
			foreach (get_object_vars($obj) as $k => $v){
				$array[$k] = is_object($v)?obj_to_array($v):$v;
			}
		}
	return $array;
}
if(!function_exists('json_decodes')){
	function json_decodes($str,$obj = true){
		if(!class_exists('Services_JSON'))require SYS_ROOT.'pub/phpwms.json.class.php';
		$json = new Services_JSON();
		if(!$obj){
			return obj_to_array($json->decode($str));
		}else{
			return $json->decode($str);
		}
	}	
}
if(!function_exists('json_encodes')){
	function json_encodes($encode){
		if(!class_exists('Services_JSON'))require SYS_ROOT.'pub/phpwms.json.class.php';
		$json = new Services_JSON();
		return $json->encode(string_to_utf8($encode));
	}	
}
function string_to_utf8($array){
  	if(is_array($array)){
			$end = array();
			foreach ($array as $key=> $val)$end[$key] = string_to_utf8($val);
			return $end;
		}else{
			return !is_utf8($array)?@iconv("GBK//IGNORE","UTF-8",$array):$array;
		}
}
function is_utf8($string) { 
	$bo =  preg_match('%^(?: 
	[\x09\x0A\x0D\x20-\x7E]
	| [\xC2-\xDF][\x80-\xBF]
	| \xE0[\xA0-\xBF][\x80-\xBF]
	| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
	| \xED[\x80-\x9F][\x80-\xBF]
	| \xF0[\x90-\xBF][\x80-\xBF]{2}
	| [\xF1-\xF3][\x80-\xBF]{3}
	| \xF4[\x80-\x8F][\x80-\xBF]{2}
	)*$%xs', $string); 
	return $bo=='1'?TRUE:FALSE;
}
/**
 * @return string
 */
if(!function_exists('get_ip')){
function get_ip(){
	 static $realip = NULL;
	    if ($realip !== NULL)return $realip;
    if (isset($_SERVER)){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($arr AS $ip){
                $ip = trim($ip);
                if ($ip != 'unknown'){
                    $realip = $ip;
                     break;
                }
            }
        }elseif(isset($_SERVER['HTTP_CLIENT_IP'])){
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else{
            $realip = isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'0.0.0.0';
        }
    }else{
        if (getenv('HTTP_X_FORWARDED_FOR')){
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }elseif (getenv('HTTP_CLIENT_IP')){
            $realip = getenv('HTTP_CLIENT_IP');
        }else{
            $realip = getenv('REMOTE_ADDR');
        }
    }
    $onlineip = array();
    preg_match("/[\\d\\.]{7,15}/", $realip, $onlineip);
    return  !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
}
}
function daddslashes($string) {
	return addslashes_deep_char_request($string);
}
/**
 * array uniques的扩展
 *
 * @param unknown_type $array
 * @param unknown_type $keep_key_assoc
 * @return unknown
 */
function array_uniques($array, $keep_key_assoc = false){
   $duplicate_keys = array();
   $tmp        = array();
   foreach ($array as $key=>$val){
       if (is_object($val))
           $val = (array)$val;
       if (!in_array($val, $tmp))
           $tmp[] = $val;
       else
           $duplicate_keys[] = $key;
   }
   foreach ($duplicate_keys as $key)
       unset($array[$key]);
   return $keep_key_assoc ? $array : array_values($array);
}
function array_to_tree($arr, $fid = 'id', $fparent = 'parent_id',$fchildrens = 'childrens', $returnReferences = false){ 
    $pkvRefs = array(); 
    foreach ($arr as $offset => $row)$pkvRefs[$row[$fid]] =& $arr[$offset]; 
    $tree = array(); 
    foreach ($arr as $offset => $row) { 
        $parentId = $row[$fparent]; 
        if ($parentId) { 
            if (!isset($pkvRefs[$parentId])) { continue; } 
            $parent =& $pkvRefs[$parentId]; 
            $parent[$fchildrens][] =& $arr[$offset]; 
        } else { 
            $tree[] =&$arr[$offset]; 
        } 
    } 
    if ($returnReferences) { 
        return array('tree' => $tree, 'analyze_data' => $pkvRefs); 
    } else { 
        return $tree; 
    } 
}
if(!function_exists('delete_folder')){
	 function delete_folder($dir, $DeleteMe=true){
		   if(!$dh = @opendir($dir)) return FALSE;
		   while (false !== ($obj = readdir($dh))){
		      	 if($obj=='.' || $obj=='..') continue;
		      	// @rmdir($obj);
		      	 if (!@unlink($dir.'/'.$obj))delete_folder($dir.'/'.$obj, true);
		       }
		  if ($DeleteMe){closedir($dh); @rmdir($dir);}
		  return TRUE;
	}
}
	function chkMoney($money) { 
		$flag = true;
		!ereg("^[0-9][.][0-9]$",$money) and $flag = false; 
		return $flag; 
	} 

 function chkEmail($email) { 
		$flag = true;
		!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*$",$email) and $flag = false;
		return $flag;
} 

		 function chkUrl($url) {
			$flag = true;
			!ereg("^http://[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*$", $url) and $flag = false;
			return $flag; 
		} 
		 function chkUserName($string,$len_1,$len_2) { 
			if (!$this -> chkLength($string,$len_1,$len_2)) return false;
			//if (!ereg("^[_a-zA-Z0-9]*$", $string)) return false;
			//中文
			if (!preg_match("/^[".chr(0xa1)."-".chr(0xff)."_\-a-zA-Z0-9"."]*$/",$string)) return false;
			return true; 
		} 

		 function chkUserPwd($string,$len_1,$len_2) { 
			if (!$this -> chkLength($string,$len_1,$len_2)) return false;
			//if (!ereg("^[_a-zA-Z0-9]*$",$string)) return false;
			return true; 
		} 

		 function chkTelephone($string) { 
			$flag = true;
			!ereg("^[+]?[0-9]+([xX-][0-9]+)*$",$flag) and $flag = false; 
			return $flag; 
		}

		function chkMobile($mobile) { 
			$flag = true;
			!preg_match("/^[0-9a-zA-Z]{10,12}$/",$mobile) and $flag = false; 
			return $flag; 
		}

		 function chkZipCode($num) { 
			$flag = true;
			$num  = trim($num); 
			if (strlen($num) == 6) {
				!is_numeric($num) and $flag = false;
			} else {
				$flag = false;
			}
		} 

		//检测扩展名: 0 - 没有文件,-1 - 扩展名符合要求,1 - 扩展名正确
		function chkExtendName($file_name,$extend = array()) { 
			if(strlen(trim($file_name)) < 5) {
				return 0;
			}
			$last_dot = strrpos($file_name,".");
			$extend_name = substr($file_name,$last_dot+1);

			for($i=0;$i<count($extend);$i++) { 
				if (trim(strtolower($extend_name)) == trim(strtolower($extend[$i]))) { 
					$flag = 1;
					break;
				}
			}
			$flag != 1 and $flag = -1;
			return $flag;
		} 


		function chkFileSize($file_name,$limit_size) { 
			$size = GetImageSize($file_name); 
			if ($size[0] > $file_name[0] || $size[1] > $limit_size[1]) { 
				return false; 
			} 
			return true; 
		}
		
		// 检查数据是否为日期格式
		function isDate($data) {
			$re = "#^\d{4}([/-])([0][0-9]|[1][0-2])\\1([0-2][0-9]|[3][0-1])$#";
			return $this -> match($data,$re);
		}

		function match($data,$re) {
			return preg_match($re,$data);
		}
/**
 *	关于多字节字符问题在mysql中处理
 *
 */
function addslashes_deep_char_request($string){
	if(empty($string))return $string;
	if(is_array($string)){
		$end = array();
		foreach ($string as $k=>$v)$end[$k] = addslashes_deep_char_request($v);
		return $end;
	}else{
		return !get_magic_quotes_gpc()?addslashes(trim($string)):trim($string);
	}
}
function pages($num, $perpage, $curpage, $mpurl,$flag = '&',$page = 10) {
	//处理路由重写
	$curpage = abs(intval($curpage));
	$curpage = empty($curpage)||$curpage<0 ? 1 : $curpage ;
	$multipage = '';
	$mpurl = $mpurl.$flag;
	$pages = 1;//总页数
	if($num > $perpage) {
		$offset = $page - 1;
		$pages = @abs(ceil($num / $perpage));
		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if($from < 1) {
				$to = $page;
				$from = 1;
				if($to - $from < $page) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}
		$curpage = $curpage <= $pages ? $curpage : $pages;
		//获得站点配置信息 处理路由重写
		$rewrite  = 'page=';
		$ext = '';
		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a onclick="this.blur()" href="'.$mpurl.$rewrite.'1'.$ext.'" class="first">'.(1).'<!--...--></a>': '').
			($curpage > 1 ? '<a  onclick="this.blur()" href="'.$mpurl.$rewrite.($curpage - 1).$ext.'" class="prev">上一页</a>' : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<b>'.$i.'</b>' :
				'<a onclick="this.blur()"  href="'.$mpurl.$rewrite.$i.$ext.'">'.$i.'</a>';
		}
		$multipage .= ($curpage < $pages ? '<a href="'.$mpurl.$rewrite.($curpage + 1).$ext.'"  onclick="this.blur()" class="next">下一页</a>' : '').
			($to < $pages ? '<a onclick="this.blur()" href="'.$mpurl.$rewrite.$pages.$ext.'" class="last"><!--...-->'.$pages.'</a>' : '').
			($pages > $page ? '<kbd><input type="text" alt="'.$mpurl.$rewrite.'" name="custompage" ext="'.$ext.'" size="3" onkeydown="if(event.keyCode==13) {window.location=\''.$mpurl.$rewrite.'\'+this.value'.$ext.'; return false;}" /></kbd>' : '');
		$multipage = $multipage ? '<div class="pages">'.('&nbsp;<em>'.$perpage.'/'.$num.'</em>&nbsp;').$multipage.'</div>' : '';
	}
	return $multipage;
}
function page_for_db_extend($total,$sql,$mpurl,$perpage='',$dbObj = NULL,$curpage=0,$flag = '&amp;',$showInputpage = 10){
		global $db;
		if(empty($total)||!is_numeric($total))return array(); 
		$dbObj = !is_object($dbObj)?$db:$dbObj;
		//处理页码
		if(!defined('PAGE_NUM'))define('PAGE_NUM',20);
		$perpage = empty($perpage)?PAGE_NUM:$perpage;
		$pages = isset($_GET['page'])?$_GET['page']:1;
		//计算并检查数据
		$curent_page = empty($curpage)?abs(ceil(intval(trim($pages)))):$curpage;
		$curent_page = empty($curent_page)||$curent_page<=0?1:$curent_page;
		$total_page = abs(ceil($total/$perpage));
		$curent_page = $curent_page>$total_page?$total_page:$curent_page;
		$curent_select_num = ($curent_page-1)*$perpage;
		$curent_select_num = $curent_select_num<0?0:$curent_select_num;
		$select_sql = $sql." LIMIT "." $curent_select_num,$perpage ;";
		$data = $dbObj->fetch($select_sql);
		unset($pages);
		unset($curent_select_num);
		unset($dbObj);
		return array(
			'total'=>$total,
			'data'=>$data,
			'curpage'=>$curent_page,
			'page'=>pages($total,$perpage,$curent_page,$mpurl,$flag,$showInputpage)
		);
	}
function pages_for_array($data,$perpage='',$curpage=1,$mpurl,$flag = '&amp;',$page = 10){
	if(defined('PAGE_NUM'))define('PAGE_NUM',20);
		$perpage = empty($perpage)?PAGE_NUM:$perpage;#每页显示的数量
		$pages = isset($_GET['page'])&&!empty($_GET['page'])?$_GET['page']:1;
		$curpage = empty($curpage)?abs(ceil(intval(trim($pages)))):$curpage;#浏览器上显示的page数
		$curpage = empty($curpage)||$curpage<0?'1':$curpage;
		$total = count($data);
		$pages = @ceil($total/$perpage);
		$curpage = $curpage>$pages?$pages:$curpage;
		if($total>$perpage){
			$key = $curpage-1;
			$key = $key<0?0:$key;
			$split = array_chunk($data,$perpage);
			$data = $split[$key];
		}
		return array(
			'total'=>$total,
			'data'=>$data,
			'curpage'=>$curpage,
			'page'=>pages($total,$perpage,$curpage,$mpurl,$flag,$page),
		);
	}
function get_site_url($http = true){
		if($_SERVER['SERVER_PORT']!=='80'){
			 $url = $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/'.$_SERVER['REQUEST_URI'];
		}else{
			 $url = $_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI'];
		}
		return ($http?'http://':'').str_replace('//','/',$url);
}
function html_encode($array){
	if(empty($array))return $array;
	return is_array($array)?array_map('html_encode',$array):addslashes(stripslashes(str_replace(array('\&quot','\&#039;','\\'),array('&quot','&#039;',''),trim(htmlspecialchars($array,ENT_QUOTES)))));
}
function html_decode($array){
	if(empty($array))return $array;
	return is_array($array)?array_map("html_decode",$array):htmlspecialchars_decode($array,ENT_QUOTES);
}
function stripslashes_deep ($str){
	if(empty($str))return $str;
	return is_array($str)?array_map('stripslashes_deep',$str):stripslashes($str);
}
function serialize_deep($data){
	return addslashes(serialize( stripslashes_deep($data)));
}
function unserialize_deep($data){
	if(empty($data))return $data;
	if(is_array($data)){
		$end = array();
		foreach ($data as $k=>$v)$end[$k]= unserialize_deep($v);
		return $end;
	}else{
		return unserialize($data);
	}
}
function get_self($add_index = false){
	$self = explode('/',$_SERVER['PHP_SELF']);
	array_pop($self);
	$string = join('/',$self).'/';
	$file = $add_index?$string.'index.php':$string;
	return str_replace(array('/'.ADMIN_PATH.'/'),'/',$file);
}
/**
 * 构造URL
 */
function building_url($model,$action,$params = array(),$append = array(),$add_index = false,$absolute_url = false){
	$params = !is_array($params)?(array)$params:$params;
	$append_data = !empty($append) && is_array($append)?'&'.http_build_query($append):'';
	$ab_url = $absolute_url?'http://'.$_SERVER['SERVER_NAME'].get_self():get_self();
	$a_url = '?'.$model.(!empty($action)?'_'.$action:'').(!empty($params)?'-':'').join('-',$params).'.html'.$append_data;
	$url = $add_index?$ab_url.'index.php'.$a_url:$ab_url.$a_url;
	return str_replace(array('/'.ADMIN_PATH,ADMIN_PATH),'',$url);	
}
function dheader($string, $replace = true, $http_response_code = 0) {
	$string = str_replace(array("\r", "\n"), array('', ''), $string);
	if(empty($http_response_code) || PHP_VERSION < '4.3' ) {
		@header($string, $replace);
	} else {
		@header($string, $replace, $http_response_code);
	}
	if(preg_match('/^\s*location:/is', $string)) {
		exit();
	}
}
// 创建无极目录
function createDir($dir) {
	$flag = true;
	$dir = str_replace(array('//','\\','\\\\'),'/',$dir);
	if (!is_dir($dir))
	{
		$temp = explode('/',$dir);
		$cur_dir = '';
		for($i=0;$i<count($temp);$i++) 
		{
			$cur_dir .= $temp[$i].'/';
			if (!@is_dir($cur_dir)) 
			{
				if(!@mkdir($cur_dir,0777))
					$flag = false;
			}
			$flag !== false and @chmod($cur_dir,0777);
		}
	}
	return $flag;
}

function dsetcookie($var, $value, $life = 0, $prefix = 1) {
	global $cookiedomain, $cookiepath, $_SERVER;
	setcookie($var, $value,
		$life ? time() + $life : 0, $cookiepath,
		$cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}

function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

function removedir($dirname, $keepdir = FALSE) {
	$dirname = wipespecial($dirname);
	if(!is_dir($dirname)) {
		return FALSE;
	}
	$handle = opendir($dirname);
	while(($file = readdir($handle)) !== FALSE) {
		if($file != '.' && $file != '..') {
			$dir = $dirname . DIRECTORY_SEPARATOR . $file;
			is_dir($dir) ? removedir($dir) : unlink($dir);
		}
	}
	closedir($handle);
	return !$keepdir ? (@rmdir($dirname) ? TRUE : FALSE) : TRUE;
}
/**
 * $msg string 需要些的内容
 * $admin string 操作人员
 * $type  string 操作类型 operation|login|other
 */
function writelog($msg,$admin,$type = 'operation') {
	global $db;
	$insert_data = array(
		'content'=>$msg,
		'manager'=>$admin,
		'type'=>$type
	);
	$db->insert($insert_data,'logs');
}

function writefile($filename,$data,$method="rb+",$iflock=1,$check=1,$chmod=1) {
	$check && strpos($filename,'..')!==false && exit('What are you doing?');
	touch($filename);
	$handle=fopen($filename,$method);
	if($iflock){
		flock($handle,LOCK_EX);
	}
	fwrite($handle,$data);
	if($method=="rb+") ftruncate($handle,strlen($data));
	fclose($handle);
	if($chmod)@chmod($filename,0777);
}
function dfopen($url, $limit = 500000, $post = '', $cookie = '', $bysocket = FALSE) {
	global $version, $boardurl;
	if(ini_get('allow_url_fopen') && !$bysocket && !$post) {
		$fp = @fopen($url, 'r');
		$s = @fread($fp, $limit);
		@fclose($fp);
		return $s;
	}
	$return = '';
	$matches = parse_url($url);
	$host = $matches['host'];
	$script = $matches['path'].'?'.$matches['query'].'#'.$matches['fragment'];
	$port = !empty($matches['port']) ? $matches['port'] : 80;
	if($post) {
		$out = "POST $script HTTP/1.1\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$out .= "Accept-Encoding: none\r\n";
		$out .= "User-Agent: Comsenz/1.0 ($version)\r\n";
		$out .= "Host: $host\r\n";
		$out .= 'Content-Length: '.strlen($post)."\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cache-Control: no-cache\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
		$out .= $post;
	} else {
		$out = "GET $script HTTP/1.1\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "Accept-Encoding:\r\n";
		$out .= "User-Agent: Comsenz/1.0 ($version)\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
	}
	$fp = fsockopen($host, $port, $errno, $errstr, 30);
	if(!$fp) {
		return "";
	} else {
		@fwrite($fp, $out);
		while(!feof($fp) && $limit > -1) {
			$limit -= 524;
			$return .= @fread($fp, 524);
		}
		@fclose($fp);
		$return = preg_replace("/\r\n\r\n/", "\n\n", $return, 1);
		$strpos = strpos($return, "\n\n");
		$strpos = $strpos !== FALSE ? $strpos + 2 : 0;
		$return = substr($return, $strpos);
		return $return;
	}
}

//将ip转化为长整型字符串
function ipToLong($ip) {
	return sprintf("%u",ip2long($ip));
}

//获得一个guid
function mgGetGuid() {
	return md5(uniqid(time()));
}

/*
 * 中文截取，支持gb2312,gbk,utf-8,big5 
 *
 * @param string $str 要截取的字串
 * @param int $start 截取起始位置
 * @param int $length 截取长度
 * @param string $charset utf-8|gb2312|gbk|big5 编码
 * @param $suffix 是否加尾缀
 */
function csubstr($str, $start=0, $length, $cut_charset="GBK", $suffix=true) {
	if(function_exists("mb_substr"))
		return mb_substr($str, $start, $length, $cut_charset);
	$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	$re['gbk']	  = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	$re['big5']	  = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	preg_match_all($re[$charset], $str, $match);
	$slice = join("",array_slice($match[0], $start, $length));
	if($suffix) return $slice."…";
	return $slice;
}
function delHtmlCode($vStr) { 
	for($i=0;$i<strlen($vStr);$i++) 
	{ 
	if (substr($vStr,$i,1)=="<") 
	{ 
		while(substr($vStr,$i,1)!=">")$i++; 
		$i++; 
	} 
		$Str=$str.substr($vStr,$i,1); 
	} 
	return($Str); 
}
function channel_type_arr($m_id)
{
		global $db,$tbprefix;
		
		if(!$m_id)
		{
			$row=$db -> sql_query("SELECT * FROM ".$tbprefix."model");
		}else{
			$row=$db -> sql_query("SELECT * FROM ".$tbprefix."model where id=$m_id");
		}
		
		$rs = $db -> sql_fetchrowset($row);
		for($i=0;$i<count($rs);$i++)
		{
			$channel_type_arr.="<option value='".$rs[$i]['id']."'>".$rs[$i]['cn_name']."</option>";
			//$rs[$i]['m_id'],$rs[$i]['db_table'],,$rs[$i]['en_name'];
		}
		return $channel_type_arr;
}
/* 上传程序扩展程序之缩略图*/
function ResizeImage($im,$maxwidth,$maxheight,$name)
{
	
	if(!empty($im) && file_exists($im))
	{
		$ground_info = getimagesize($im);
		$width    = $ground_info[0];//取得背景图片的宽
		$height   = $ground_info[1];//取得背景图片的高
		
		switch($ground_info[2])//取得水印图片的格式
        {
             case 1:$ims = imagecreatefromgif($im);break;
             case 2:$ims = imagecreatefromjpeg($im);break;
             case 3:$ims = imagecreatefrompng($im);break;
        }
	}else{
		exit;
	}
	
	if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight))
	{
		/*将缩略宽和高按比例放大到原始图片大小（原始图最宽或者最高）*/
		if($width>$height)
		{//高度优先
			$h=$height;
		}elseif($height>$width)
		{//宽度优先
			$w=$width;
		}else{
			$w=$width;
		}
		
		if($h)
		{ //高度优先
			$b=round($h/$maxheight);
		}else{//宽度优先
			$b=round($w/$maxwidth);
		}
		
		$newwidth=round($maxwidth*$b);
		
		$newheight=round($maxheight*$b);
		
		$oX=($width/2-$newwidth/2)<0?0:($width/2-$newwidth/2);
		
		$oY=($height/2-$newheight/2)<0?0:($height/2-$newheight/2);
		
		$newim = imagecreatetruecolor($newwidth,$newheight);
		
		imagecopyresampled($newim, $ims, 0, 0,$oX, $oY,$newwidth,$newheight, $width-$oX*2, $height-$oY*2);
		
		$new = imagecreatetruecolor($maxwidth, $maxheight);
		imagecopyresampled($new, $newim, 0, 0, 0, 0, $maxwidth, $maxheight, $width-$oX*2, $height-$oY*2);
			
		ImageJpeg ($new,$name);
		ImageDestroy ($new);
		ImageDestroy ($newim);
	}else{
		
		ImageJpeg ($ims,$name);
	}
}

/*
* 功能：PHP图片水印 (水印支持图片或文字)
* 参数：
*       $groundImage     背景图片，即需要加水印的图片，暂只支持GIF,JPG,PNG格式；
*       $waterPos         水印位置，有10种状态，0为随机位置；
*                         1为顶端居左，2为顶端居中，3为顶端居右；
*                         4为中部居左，5为中部居中，6为中部居右；
*                         7为底端居左，8为底端居中，9为底端居右；
*       $waterImage         图片水印，即作为水印的图片，暂只支持GIF,JPG,PNG格式；
*       $waterText         文字水印，即把文字作为为水印，支持ASCII码，不支持中文；
*       $textFont         文字大小，值为1、2、3、4或5，默认为5；
*       $textColor         文字颜色，值为十六进制颜色值，默认为#FF0000(红色)；
*
* 注意：Support GD 2.0，Support FreeType、GIF Read、GIF Create、JPG 、PNG
*       $waterImage 和 $waterText 最好不要同时使用，选其中之一即可，优先使用 $waterImage。
*       当$waterImage有效时，参数$waterString、$stringFont、$stringColor均不生效。
*       加水印后的图片的文件名和 $groundImage 一样。
* 作者：longware @ 2004-11-3 14:15:13
*/
function imageWaterMark($groundImage,$waterPos=0,$waterImage="",$waterText="",$textFont=5,$textColor="#FF0000")
{
    $isWaterImage = FALSE;
    $formatMsg = "暂不支持该文件格式，请用图片处理软件将图片转换为GIF、JPG、PNG格式。";

    //读取水印文件
    if(!empty($waterImage) && file_exists($waterImage))
     {
        $isWaterImage = TRUE;
        $water_info = getimagesize($waterImage);
        $water_w    = $water_info[0];//取得水印图片的宽
        $water_h    = $water_info[1];//取得水印图片的高

        switch($water_info[2])//取得水印图片的格式
        {
             case 1:$water_im = imagecreatefromgif($waterImage);break;
             case 2:$water_im = imagecreatefromjpeg($waterImage);break;
             case 3:$water_im = imagecreatefrompng($waterImage);break;
             default:die($formatMsg);
         }
     }

    //读取背景图片
    if(!empty($groundImage) && file_exists($groundImage))
     {
        $ground_info = getimagesize($groundImage);
        $ground_w    = $ground_info[0];//取得背景图片的宽
        $ground_h    = $ground_info[1];//取得背景图片的高

        switch($ground_info[2])//取得背景图片的格式
        {
             case 1:$ground_im = imagecreatefromgif($groundImage);break;
             case 2:$ground_im = imagecreatefromjpeg($groundImage);break;
             case 3:$ground_im = imagecreatefrompng($groundImage);break;
             default:die($formatMsg);
         }
     }
     else
     {
         die("需要加水印的图片不存在！");
     }

    //水印位置
    if($isWaterImage)//图片水印
    {
        $w = $water_w;
        $h = $water_h;
        $label = "图片的";
     }
     else//文字水印
    {
        $temp = imagettfbbox(ceil($textFont*2.5),0,"./cour.ttf",$waterText);//取得使用 TrueType 字体的文本的范围
        $w = $temp[2] - $temp[6];
        $h = $temp[3] - $temp[7];
         unset($temp);
        $label = "文字区域";
     }
     if( ($ground_w<$w) || ($ground_h<$h) )
     {
         echo "需要加水印的图片的长度或宽度比水印".$label."还小，无法生成水印！";
         return;
     }
     switch($waterPos)
     {
         case 0://随机
            $posX = rand(0,($ground_w - $w));
            $posY = rand(0,($ground_h - $h));
             break;
         case 1://1为顶端居左
            $posX = 0;
            $posY = 0;
             break;
         case 2://2为顶端居中
            $posX = ($ground_w - $w) / 2;
            $posY = 0;
             break;
         case 3://3为顶端居右
            $posX = $ground_w - $w;
            $posY = 0;
             break;
         case 4://4为中部居左
            $posX = 0;
            $posY = ($ground_h - $h) / 2;
             break;
         case 5://5为中部居中
            $posX = ($ground_w - $w) / 2;
            $posY = ($ground_h - $h) / 2;
             break;
         case 6://6为中部居右
            $posX = $ground_w - $w;
            $posY = ($ground_h - $h) / 2;
             break;
         case 7://7为底端居左
            $posX = 0;
            $posY = $ground_h - $h;
             break;
         case 8://8为底端居中
            $posX = ($ground_w - $w) / 2;
            $posY = $ground_h - $h;
             break;
         case 9://9为底端居右
            $posX = $ground_w - $w;
            $posY = $ground_h - $h;
             break;
         default://随机
            $posX = rand(0,($ground_w - $w));
            $posY = rand(0,($ground_h - $h));
             break;     
     }

    //设定图像的混色模式
    imagealphablending($ground_im, true);

     if($isWaterImage)//图片水印
    {
        imagecopy($ground_im, $water_im, $posX, $posY, 0, 0, $water_w,$water_h);//拷贝水印到目标文件         
    }
     else//文字水印
    {
         if( !empty($textColor) && (strlen($textColor)==7) )
         {
            $R = hexdec(substr($textColor,1,2));
            $G = hexdec(substr($textColor,3,2));
            $B = hexdec(substr($textColor,5));
         }
         else
         {
             die("水印文字颜色格式不正确！");
         }
        imagestring ( $ground_im, $textFont, $posX, $posY, $waterText, imagecolorallocate($ground_im, $R, $G, $B));         
     }

    //生成水印后的图片
    @unlink($groundImage);
     switch($ground_info[2])//取得背景图片的格式
    {
         case 1:imagegif($ground_im,$groundImage);break;
         case 2:imagejpeg($ground_im,$groundImage);break;
         case 3:imagepng($ground_im,$groundImage);break;
         default:die($errorMsg);
     }

    //释放内存
    if(isset($water_info)) unset($water_info);
     if(isset($water_im)) imagedestroy($water_im);
     unset($ground_info);
    imagedestroy($ground_im);
} 
/*读取大图片*/
function bigimg($path)
{
	$p=explode('/',$path);
	
	$p[count($p)-1]=substr($p[count($p)-1],1,strlen($p[count($p)-1]));
	
	return implode('/',$p);
}
/*产生注册时激活随机码*/
function MakeRandomCode($length) 
{ 
	$possible = "DE!FGH067#81259TUxytu+". 
                "cghdefijkabl34PQRSvwz". 
                "KLIJMBCNOAmVnoYWpqXrsZ"; 
	$str = ""; 
	while(strlen($str) < $length) 
	{ 
	   $str .= substr($possible, (rand() % strlen($possible)), 1); 
	} 
	return($str); 
} 
/*身份证验证函数群*/
function idcard_verify_number($idcard_base)
{
    if (strlen($idcard_base) != 17){ return false; }

    // 加权因子
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    
    // 校验码对应值
    $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');

    $checksum = 0;
    for ($i = 0; $i < strlen($idcard_base); $i++){
        $checksum += substr($idcard_base, $i, 1) * $factor[$i];
    }

    $mod = $checksum % 11;
    $verify_number = $verify_number_list[$mod];

    return $verify_number;

}

// 将15位身份证升级到18位
function idcard_15to18($idcard){
    if (strlen($idcard) != 15){
        return false;
    }else{
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false){
            $idcard = substr($idcard, 0, 6) . '18'. substr($idcard, 6, 9);
        }else{
            $idcard = substr($idcard, 0, 6) . '19'. substr($idcard, 6, 9);
        }
    }

    $idcard = $idcard . idcard_verify_number($idcard);

    return $idcard;
}

// 18位身份证校验码有效性检查
function idcard_checksum18($idcard){
    if (strlen($idcard) != 18){ return false; }
    $idcard_base = substr($idcard, 0, 17);
    if (idcard_verify_number($idcard_base) != strtoupper(substr($idcard, 17, 1))){
        return false;
    }else{
        return true;
    }
}
/*返回*/
function backtrack()
{
    return $_SERVER["HTTP_REFERER"];
}
function toGbk($str,$in = 'UTF-8',$out = 'GBK')
{
	return iconv($in,$out,$str);
}
/* 保存远程图片 ---- start---- */
function getFileEx($file_name) {
	return trim(substr(strrchr($file_name,'.'),1));
}

function getRemoteFileLink($text) {
	$matches = array();
	if(!preg_match_all('/(https?|ftp):\/\/([^\[\<\r\n]+?)\.(gif|jpg|jpeg|bmp|png)/im', $text, $matches)) {
		return array();
	}
	$arr = array();
	foreach($matches[0] as $matche)	{
		if(strpos($matche,'phpwms.com') !== false) continue;
		$arr[] = $matche;
	}
	return array_unique($arr);
}

function saveRemoteFiles($text,$upload_dir) {
	global $root_dir,$sys_dir;

	$links = getRemoteFileLink($text);

	foreach($links as $v) {
		if(strpos($v, '://') === false) continue;
		srand ((double) microtime() * 1000000);
		$file_name = 'phpwms'.date("YmdHis").rand(100,999).'.'.getFileEx($v);
		$tmp_dir   = 'files/upfiles/image/'.$upload_dir.'/'.date("Y-m");
		$file_dir  = $sys_dir.$tmp_dir;
		$save_name = $file_dir.'/'.$file_name;
		$new_link  = $root_dir.$tmp_dir.'/'.$file_name;

		if (createDir($file_dir)) {
			if(copy5($v,$save_name)) {
				$old_path[] = $v;
				$new_path[] = $new_link;
				//加水印
				require_once SYS_ROOT.CLASS_PATH.'cls.image.php';
				$srcimage = str_replace('\\','/',$sys_dir.$new_link);
				$srcimage = str_replace('//','/',$srcimage);
				$t=new ThumbHandler();
				$t->angle = 0;
				$t->setSrcImg($srcimage);
				$t->setCutType(0);
				$t->setDstImg($srcimage);
				$t->setMaskImg($sys_dir.$root_dir.'files/common/image/watermark.jpg');
				$t->setMaskPosition(0);
				$t->setMaskImgPct(60);
				$t->createImg(800,600);
			} else {
				echo '保存图片'.$v.'失败<br>';
			}
		}
	}
	return str_replace($old_path,$new_path,$text);
}
function send_mail($type = '',$from = '',$fromName = '',$reciver=array(),$subject = '',$body = '',$add_other_replay=''){
	require PUB_CLASS.'phpmail/class.phpmailer.php';
	$mail = new PHPMailer();
	$mail->CharSet = 'GBK';//设置邮件编码
	$site_cfg = get_cache('site_mail_cfg');
	if(empty($site_cfg))return FALSE;
	$mail->From = trim($from?$from:$site_cfg['smtp_user']);
	$mail->FromName = trim($fromName?$fromName:$site_cfg['sender']);
	//处理多个收信人
	if(is_array($reciver)&&!empty($reciver)){
		foreach ($reciver as $r){
			$mail->AddAddress($r, array_shift(explode('@',$r)));
		}
	}
	$mail->WordWrap = 50;   
	$mail->Subject = strip_tags($subject);
	$mail->AltBody = strip_tags($body);//如果邮箱不支持HTML就用他
	$mail->IsHTML(true); 
	//处理回复
	if(!empty($add_other_replay)){
		$mail->AddReplyTo($add_other_replay,$fromName);
	}else{
		$mail->AddReplyTo($from,$fromName);
	}
	$type = empty($type)?$site_cfg['mail_send_type']:$type;
	switch ($type){//获得站内邮箱配置
		case 'mail':
		$mail->MsgHTML($body);
			break;
		case 'sendmail':
			$mail->IsSendmail();
			$mail->MsgHTML($body);
			break;
		case 'smtp':
		$mail->IsSMTP();   
		$mail->Host = trim($site_cfg['smtp_host']); 
		$mail->SMTPAuth = true;     
		$mail->Username = trim($site_cfg['smtp_user']); 
		$mail->Password = trim($site_cfg['smtp_pass']);
		$mail->MsgHTML($body);
			break;
		default:return FALSE;
	}
	 return $mail->Send()?TRUE:FALSE;	 
}
function is_email($str){
	return preg_match("/^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$/", $str);
}
/**
 * 检查  是否 含有特殊字符  不符合 false  符合 为 true
 * 
 * @param string $str
 * @return boolean
 */
function is_chekChar($str){
	// 首先 去掉汉字
	$str = preg_replace("/[".chr(228).chr(128).chr(128)."-".chr(233).chr(191).chr(191)."]/",'',$str);//将所有的中文替换为空
	if(preg_match("/[\~\！\@ \#\￥\%\……\&\*\（\）\—\+\=\-\}\{\】\【\；\：\“\‘\|\、\，\《\，\》\？\、]/",$str)){//对无中文字符串操作
	   return false; // 有特殊 字符
	}else{
	   return true; // 无特殊字符
	}
}
/** 
* 检验手机号码是否合法 
* @param    string      $str       待检验的手机号码字符串
* @return   boolean     true是合法的手机号码,false为非法的手机号码
*/
function is_mobile($str){
	 return preg_match("/^1(3[0-9]|5[0,1,2,3,6,8,9]|8[6,8,9])[0-9]{8}$/", $str);
}

/** 
* 检验坐机电话号码是否合法 
* @param    string      $str       待检验的坐机电话号码字符串
* @return   boolean     true是合法的坐机电话号码,false为非法的坐机电话号码
*/
function is_phone($str){
	return preg_match("/^((\\(\\d{3}\\))|(\\d{3}\\-)|(\\d{3}))?(\\(0\\d{2,3}\\)|0\\d{2,3}-)?[1-9]\\d{6,7}$/",$str);
}
/**
 * 移动一个目录下的文件到另外一个文件夹下
 * @param string $old_dir
 * @param sting $aim_dir
 * @param boolean $over_write
 * @return boolean
 */
 function cpdir($old_dir, $aim_dir, $over_write = false) {
		$aim_dir = str_replace('\\', '/', $aim_dir);
		$aim_dir = substr($aim_dir, -1) == '/' ? $aim_dir : $aim_dir.'/';
		$old_dir = str_replace('\\', '/', $old_dir);
		$old_dir = substr($old_dir, -1) == '/' ? $old_dir : $old_dir.'/';
		if (FALSE !== strpos($aim_dir, $old_dir))return false;
		if (!is_dir($old_dir))return false;
		if (!file_exists($aim_dir))mkdirs($aim_dir);
		$dir_handle = opendir($old_dir);
		while(false !== ($file = readdir($dir_handle))) {
			if ($file == '.' || $file == '..') {
				continue;
			}
			!is_dir($old_dir . $file)?cp_file($old_dir . $file, $aim_dir . $file, $over_write):cpdir($old_dir . $file, $aim_dir . $file, $over_write);
		}
		closedir($dir_handle);
		return true;
	}
	/**
 * 复制一个文件 目录不存在创建之
 *
 * @param string $file_url
 * @param string $aim_url
 * @param boolean $over_write
 * @return boolean
 */
 function cp_file($file_url, $aim_url, $over_write = false) {
		if (!file_exists($file_url))return false;
		if (file_exists($aim_url) && $over_write == false) {
			return false;
		} elseif (file_exists($aim_url) && $over_write == true) {
			@unlink($aim_url);
		}
		$path = pathinfo($aim_url);
		$dir = $path['dirname'];
		if(!is_dir($dir))mkdirs($dir.'/');
		@copy($file_url, $aim_url);
		return TRUE;
}
/**
 * 移动一个文件夹下的所有文件到指定的文件夹下（若不存在创建之）
 * @param string $old_dir
 * @param string $aim_dir
 * @param boolean $over_write
 * @return boolean
 */
function mv_dir($old_dir, $aim_dir, $over_write = false) {
		$aim_dir = str_replace('\\', '/', $aim_dir);
		$aim_dir = substr($aim_dir, -1) == '/' ? $aim_dir : $aim_dir . '/';
		$old_dir = str_replace('\\', '/', $old_dir);
		$old_dir = substr($old_dir, -1) == '/' ? $old_dir : $old_dir . '/';
		if (FALSE !== strpos($aim_dir, $old_dir))return false;
		if (!is_dir($old_dir))return false;
		if (!file_exists($aim_dir))	mkdirs($aim_dir);
		@$dir_handle = opendir($old_dir);
		if (!$dir_handle)return false;
		while(false !== ($file = readdir($dir_handle))) {
			if ($file == '.' || $file == '..') {
				continue;
			}
			if (!is_dir($old_dir.$file)) {
				mv_file($old_dir . $file, $aim_dir . $file, $over_write);
			} else {
				mv_dir($old_dir . $file, $aim_dir . $file, $over_write);//递归
			}
		}
		closedir($dir_handle);
		return delete_folder($old_dir,TRUE);
	}
/**
 * 移动一个文件到指定文件
 * @param string $file_url
 * @param string $aim_url
 * @param boolean $over_write
 * @return boolean
 */
 function mv_file($file_url, $aim_url, $over_write = false) {
		if (!file_exists($file_url))return false;
		if (file_exists($aim_url) && $over_write == false) {
			return false;
		} elseif (file_exists($aim_url) && $over_write == true && is_file($aim_url)) {
			unlink($aim_url);
		}
		$aim_dir = dirname($aim_url);
		mkdirs($aim_dir);
		@rename($file_url, $aim_url);
		return true;
	}
?>