$val){
		$arr2[$val[$key_name]] = $val;        
	}
	return $arr2;
}
function encrypt($str){
	return md5(C("AUTH_CODE").$str);
}
            
/**
 * 获取数组中的某一列
 * @param type $arr 数组
 * @param type $key_name  列名
 * @return type  返回那一列的数组
 */
function get_arr_column($arr, $key_name)
{
	$arr2 = array();
	foreach($arr as $key => $val){
		$arr2[] = $val[$key_name];        
	}
	return $arr2;
}
/**
 * 获取url 中的各个参数  类似于 pay_code=alipay&bank_code=ICBC-DEBIT
 * @param type $str
 * @return type
 */
function parse_url_param($str){
    $data = array();
    $str = explode('?',$str);
    $str = end($str);
    $parameter = explode('&',$str);
    foreach($parameter as $val){
        $tmp = explode('=',$val);
        $data[$tmp[0]] = $tmp[1];
    }
    return $data;
}
/**
 * 二维数组排序
 * @param $arr
 * @param $keys
 * @param string $type
 * @return array
 */
function array_sort($arr, $keys, $type = 'desc')
{
    $key_value = $new_array = array();
    foreach ($arr as $k => $v) {
        $key_value[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($key_value);
    } else {
        arsort($key_value);
    }
    reset($key_value);
    foreach ($key_value as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}
/**
 * 多维数组转化为一维数组
 * @param 多维数组
 * @return array 一维数组
 */
function array_multi2single($array)
{
    static $result_array = array();
    foreach ($array as $value) {
        if (is_array($value)) {
            array_multi2single($value);
        } else
            $result_array [] = $value;
    }
    return $result_array;
}
/**
 *时间戳 转   日期格式 : 精确到毫秒,x代表毫秒
 */
/**
 * 毫秒转日期
 */
function getMsecToMescdate($msectime)
{
    if (empty($msectime))
    {
        return "无";
    }
    $msectime = $msectime * 0.001;
    if(strstr($msectime,'.')){
        sprintf("%01.3f",$msectime);
        list($usec, $sec) = explode(".",$msectime);
        $sec = str_pad($sec,3,"0",STR_PAD_RIGHT);
    }else{
        $usec = $msectime;
        $sec = "000";
    }
    $date = date("Y-m-d H:i:s.x",$usec);
    return $mescdate = str_replace('x', $sec, $date);
}
/**
 * 友好时间显示
 * @param $time
 * @return bool|string
 */
function friend_date($time)
{
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d日 H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d日', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}
/**
 * 返回状态和信息
 * @param $status
 * @param $info
 * @return array
 */
function arrayRes($status, $info, $url = "")
{
    return array("status" => $status, "info" => $info, "url" => $url);
}
       
/**
 * @param $arr
 * @param $key_name
  * @param $key_name2
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名 数组指定列为元素 的一个数组
 */
function get_id_val($arr, $key_name,$key_name2)
{
	$arr2 = array();
	foreach($arr as $key => $val){
		$arr2[$val[$key_name]] = $val[$key_name2];
	}
	return $arr2;
}
 
 // 定义一个函数getIP() 客户端IP,
function getIP(){
        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
            {
                if (isset($_SERVER['REMOTE_ADDR']))
                {
                    $realip = $_SERVER['REMOTE_ADDR'];
                }
                else
                {
                    $realip = '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');
            }
        }
        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
        return $realip;
    }
// 服务器端IP
 function serverIP(){
  return gethostbyname($_SERVER["SERVER_NAME"]);
 }  
 
 
 /**
  * 自定义函数递归的复制带有多级子目录的目录
  * 递归复制文件夹
  * @param type $src 原目录
  * @param type $dst 复制到的目录
  */                        
//参数说明:            
//自定义函数递归的复制带有多级子目录的目录
function recurse_copy($src, $dst)
{
	$now = time();
	$dir = opendir($src);
	@mkdir($dst);
	while (false !== $file = readdir($dir)) {
		if (($file != '.') && ($file != '..')) {
			if (is_dir($src . '/' . $file)) {
				recurse_copy($src . '/' . $file, $dst . '/' . $file);
			}
			else {
				if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
					if (!is_writeable($dst . DIRECTORY_SEPARATOR . $file)) {
						exit($dst . DIRECTORY_SEPARATOR . $file . '不可写');
					}
					@unlink($dst . DIRECTORY_SEPARATOR . $file);
				}
				if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
					@unlink($dst . DIRECTORY_SEPARATOR . $file);
				}
				$copyrt = copy($src . DIRECTORY_SEPARATOR . $file, $dst . DIRECTORY_SEPARATOR . $file);
				if (!$copyrt) {
					echo 'copy ' . $dst . DIRECTORY_SEPARATOR . $file . ' failed
';
				}
			}
		}
	}
	closedir($dir);
}
// 递归删除文件夹
function delFile($dir,$file_type='') {
    //不删除temp目的文件
    if(strpos($dir,'temp')!==false){
        return false;
    }
    try{
           if($dir==ROOT_PATH || $dir=="" || $dir==".sync" ) return;
           if(is_dir($dir)){
                $files = scandir($dir);
                //打开目录 //列出目录中的所有文件并去掉 . 和 ..
                foreach($files as $filename){
                    if($filename!='.' && $filename!='..'){
                        if(!is_dir($dir.'/'.$filename)){
                            if(empty($file_type)){
                                unlink($dir.'/'.$filename);
                            }else{
                                if(is_array($file_type)){
                                    //正则匹配指定文件
                                    if(preg_match($file_type[0],$filename)){
                                        unlink($dir.'/'.$filename);
                                    }
                                }else{
                                    //指定包含某些字符串的文件
                                    if(false!=stristr($filename,$file_type)){
                                        unlink($dir.'/'.$filename);
                                    }
                                }
                            }
                        }else{
                            delFile($dir.'/'.$filename);
                            rmdir($dir.'/'.$filename);
                        }
                    }
                }
            }else{
                if(file_exists($dir)) unlink($dir);
           }
     }catch (Exception $e){
         mlog($e->getMessage(),"delFile");
     }
}
/*--删除文件--*/
function mdelFile($dir){
    if(file_exists($dir)) unlink($dir);}
/**
 * 多个数组的笛卡尔积
*
* @param unknown_type $data
*/
function combineDika() {
	$data = func_get_args();
	$data = current($data);
	$cnt = count($data);
	$result = array();
    $arr1 = array_shift($data);
	foreach($arr1 as $key=>$item) 
	{
		$result[] = array($item);
	}		
	foreach($data as $key=>$item) 
	{                                
		$result = combineArray($result,$item);
	}
	return $result;
}
/**
 * 两个数组的笛卡尔积
 * @param unknown_type $arr1
 * @param unknown_type $arr2
*/
function combineArray($arr1,$arr2) {		 
	$result = array();
	foreach ($arr1 as $item1) 
	{
		foreach ($arr2 as $item2) 
		{
			$temp = $item1;
			$temp[] = $item2;
			$result[] = $temp;
		}
	}
	return $result;
}
/**
 * 将二维数组以元素的某个值作为键 并归类数组
 * array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') )
 * array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') ))
 * @param $arr 数组
 * @param $key 分组值的key
 * @return array
 */
function group_same_key($arr,$key){
    $new_arr = array();
    foreach($arr as $k=>$v ){
        $new_arr[$v[$key]][] = $v;
    }
    return $new_arr;
}
/**
 * 获取随机字符串
 * @param int $randLength  长度
 * @param int $addtime  是否加入当前时间戳
 * @param int $includenumber   是否包含数字
 * @return string
 */
function get_rand_str($randLength=6,$addtime=1,$includenumber=0){
    if ($includenumber){
        $chars='abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    }else {
        $chars='abcdefghijklmnopqrstuvwxyz';
    }
    $len=strlen($chars);
    $randStr='';
    for ($i=0;$i<$randLength;$i++){
        $randStr.=$chars[rand(0,$len-1)];
    }
    $tokenvalue=$randStr;
    if ($addtime){
        $tokenvalue=$randStr.time();
    }
    return $tokenvalue;
}
/**
 * CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug  调试开启 默认false
 * @return mixed
 */
function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false,$timeout=10,$accdb="") {
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 600); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, $timeout); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                //curl_setopt($ci, CURLOPT_SAFE_UPLOAD, false);
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        case "PUT" :
            curl_setopt ($ci, CURLOPT_CUSTOMREQUEST, "PUT");
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        case "PATCH":
            curl_setopt($ci, CULROPT_CUSTOMREQUEST, 'PATCH');
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        case "DELETE":
            curl_setopt ($ci, CURLOPT_CUSTOMREQUEST, "DELETE");
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if($ssl){
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        $errorinfo=curl_error($ci);
        if ($errorinfo) {
            mlog("访问网址:" . $url, "httperror/".$accdb);
            mlog("出错信息:" . curl_error($ci), "httperror/".$accdb);
            mlog("返回http状态:" . $http_code, "httperror/".$accdb);
        }
    }
    curl_close($ci);
    return $response;
	//return array($http_code, $response,$requestinfo);
}
//微信提交图片专用
function wx_https_request($url,$type="get",$res="json",$data = ''){
    //1.初始化curl
    $curl = curl_init();
    //2.设置curl的参数
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,2);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    if ($type == "post"){
        if (class_exists('\CURLFile')) {
            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    //3.采集
    $output = curl_exec($curl);
    mlog('rp:'.$output,'uploadify');
    //4.关闭
    curl_close($curl);
    if ($res == 'json') {
        return json_decode($output,true);
    }
}
/**
 * 过滤数组元素前后空格 (支持多维数组)
 * @param $array 要过滤的数组
 * @return array|string
 */
function trim_array_element($array){
    if(!is_array($array))
        return trim($array);
    return array_map('trim_array_element',$array);
}
/**
 * 检查手机号码格式
 * @param $mobile 手机号码
 */
function check_mobile($mobile){
    if(preg_match('/1[123456789]\d{9}$/',$mobile))
        return true;
    return false;
}
/**
 * 检查是否是手机
 * @param $mobile 检查是否是手机
 */
function check_mobile_nickname($nickname){
    if(preg_match('/1[123456789]\d{9}$/',$nickname))
        return substr($nickname,0,3)."****".substr($nickname,8,3);
    return $nickname;
}
/**
 * 检查固定电话
 * @param $mobile
 * @return bool
 */
function check_telephone($mobile){
    if(preg_match('/^([0-9]{3,4}-)?[0-9]{7,8}$/',$mobile))
        return true;
    return false;
}
/**
 * 检查邮箱地址格式
 * @param $email 邮箱地址
 */
function check_email($email){
    if(filter_var($email,FILTER_VALIDATE_EMAIL))
        return true;
    return false;
}
/**
 *   实现中文字串截取无乱码的方法
 */
function getSubstr($string, $start, $length) {
      if(mb_strlen($string,'utf-8')>$length){
          $str = mb_substr($string, $start, $length,'utf-8');
          return $str.'...';
      }else{
          return $string;
      }
}
/**
 * 判断当前访问的用户是  PC端  还是 手机端  返回true 为手机端  false 为PC 端
 * @return boolean
 */
/**
  * 是否移动端访问访问
  *
  * @return bool
  */
function isMobile()
{
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    return true;
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    {
    // 找不到为flase,否则为true
    return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法,判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile');
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            return true;
    }
        // 协议法,因为有可能不准确,放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    {
    // 如果只支持wml并且不支持html那一定是移动设备
    // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        }
    }
            return false;
 }
function is_weixin() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    } return false;
}
function is_qq() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'QQ') !== false) {
        return true;
    } return false;
}
function is_alipay() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
        return true;
    } return false;
}
//php获取中文字符拼音首字母
function getFirstCharter($str){
      if(empty($str))
      {
            return '';
      }
      $fchar=ord($str{0});
      if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
      $s1=iconv('UTF-8','gb2312',$str);
      $s2=iconv('gb2312','UTF-8',$s1);
      $s=$s2==$str?$s1:$str;
      $asc=ord($s{0})*256+ord($s{1})-65536;
     if($asc>=-20319&&$asc<=-20284) return 'A';
     if($asc>=-20283&&$asc<=-19776) return 'B';
     if($asc>=-19775&&$asc<=-19219) return 'C';
     if($asc>=-19218&&$asc<=-18711) return 'D';
     if($asc>=-18710&&$asc<=-18527) return 'E';
     if($asc>=-18526&&$asc<=-18240) return 'F';
     if($asc>=-18239&&$asc<=-17923) return 'G';
     if($asc>=-17922&&$asc<=-17418) return 'H';
     if($asc>=-17417&&$asc<=-16475) return 'J';
     if($asc>=-16474&&$asc<=-16213) return 'K';
     if($asc>=-16212&&$asc<=-15641) return 'L';
     if($asc>=-15640&&$asc<=-15166) return 'M';
     if($asc>=-15165&&$asc<=-14923) return 'N';
     if($asc>=-14922&&$asc<=-14915) return 'O';
     if($asc>=-14914&&$asc<=-14631) return 'P';
     if($asc>=-14630&&$asc<=-14150) return 'Q';
     if($asc>=-14149&&$asc<=-14091) return 'R';
     if($asc>=-14090&&$asc<=-13319) return 'S';
     if($asc>=-13318&&$asc<=-12839) return 'T';
     if($asc>=-12838&&$asc<=-12557) return 'W';
     if($asc>=-12556&&$asc<=-11848) return 'X';
     if($asc>=-11847&&$asc<=-11056) return 'Y';
     if($asc>=-11055&&$asc<=-10247) return 'Z';
     return null;
}
//扩展函数
/*--获取全路径--*/
function getFullUrl(){
   return urlencode(curHostURL().$_SERVER["REQUEST_URI"]);
}
function mlog($content,$path='')
{
    if(empty($path)) {
        $savepath = ROOT_PATH.SYSTEM.date('Y').'/'.date('m').'/'; //保存路径
    }else{
        $savepath = ROOT_PATH.SYSTEM.date('Y').'/'.date('m').'/'.$path.'/'; //保存路径
    }
    if (is_dir($savepath) || mkdir($savepath,0777,true)) {
        $file = $savepath . date('md') . "log.txt";//要写入文件的文件名,如果文件不存在,将会创建一个
    }
    $result= date('Y-m-d H:i:s',time())."\r\n".$content."\r\n";
    $f = file_put_contents($file, $result, FILE_APPEND);
}
/*--日志--
$content 内容
$path 目录
$loglevel 级别 debug/info/warn/erro
$postion 代码位置	产生此日志的类、行号
$uuid 请求id	表示此日志是由哪个请求产生的
$type
1=记录请求开始信息,含url
2=[日志前缀]|request start:[用户名]|[操作角色]|[商家编号]|[ip地址]|[浏览器类型]|[浏览器版本]|[手机品牌]|[系统版本]|[微信版本号]|[手机型号]|[网络环境]
3=[日志前缀]|日志内容
4=[日志前缀]|request end:[结果]
$user 用户名
$userlevel  级别
$shopid  商家编号
*/
function apilog($content,$path='',$loglevel='info',$postion="",$uuid="",$type=3,$user="",$userlevel="",$shopid="")
{
    if(empty($path)) {
        $savepath = ROOT_PATH.APILOG.date('Y').'/'.date('m').'/'; //保存路径
    }else{
        $savepath = ROOT_PATH.APILOG.date('Y').'/'.date('m').'/'.$path.'/'; //保存路径
    }
    if (is_dir($savepath) || mkdir($savepath,0777,true)) {
        $file = $savepath . date('md')."log.txt";//要写入文件的文件名,如果文件不存在,将会创建一个
        $logsm ="V1|P|".microtime_format('Ymd H:i:s,x',microtime_float())."|".$loglevel;
        $logsm.="|".serverIP();
        if (!empty($postion))
        {
            $logsm.="|".$postion;
        }
        if (!empty($uuid))
        {
            $logsm.="|".$uuid;
        }
        switch ($type)
        {
            case 1:
                $result= $logsm."|request start:".urldecode(getFullUrl())."\r\n";
                break;
            case 2:
                $logsm.="|request start:";
                if (!empty($user))
                {
                    $logsm.=$user;
                }
                if (!empty($userlevel))
                {
                    $logsm.="|".$userlevel;
                }
                if (!empty($shopid))
                {
                    $logsm.="|".$shopid;
                }
                $logsm.="|".getIP();
                if (isMobile())//如果是移动端
                {
                    $logsm.=getALLMobileInfo();
                }
                $logsm.= "|" . userBrowser() . "|" . getBrowserVer();
                $result= $logsm."\r\n";
                break;
            case 3:
                $result= $logsm."|".$content."\r\n";
                break;
            case 4:
                $result= $logsm."|request end:\r\n";
                break;
        }
        //$content.="\r\n系统:".$_SERVER['HTTP_USER_AGENT'];//
        $f = file_put_contents($file, $result, FILE_APPEND);
    }
}
/** 获取当前时间戳,精确到毫秒 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}
/*
    *
    *返回字符串的毫秒数时间戳
    */
function get_total_millisecond()
{
    $time = explode (" ", microtime () );
    $time = $time [1] . ($time [0] * 1000);
    $time2 = explode ( ".", $time );
    $time = $time2 [1];
    return $time;
}
/** 格式化时间戳,精确到毫秒,x代表毫秒 */
function microtime_format($tag, $time)
{
    list($usec, $sec) = explode(".", $time);
    $date = date($tag,$usec);
    return str_replace('x', $sec, $date);
}
/*--上传剪切图片
 * @param $filename原文件名
 * @param $fpath文件存储路径
 * @param $w缩放比例
 * $issmall 是否生成小图
 * @return 缩放的比例
--*/
function m_cut_img($filename,$fpath,$w=800,$issmall=0){
    list($width, $height)=getimagesize($fpath.$filename);
    $image = \think\Image::open($fpath . $filename);
    $ext=pathinfo($filename, PATHINFO_EXTENSION);
    $ext=strtolower($ext);
    if($ext=='gif'){
        return $filename;
    }
    //缩放比例
    //当宽度大于高度的时候
    if($width>$height) {
        if ($w >= $width) {
            if ($issmall == 1) {
                //copy($fpath . $filename, $fpath . "s_" . $filename);
                $image->thumb($w, $w, 3)->save($fpath . "s_" . $filename, NULL, 100);
            }
            return $filename;
        }
    //当高度大于宽度的时候
    }else{
        if ($w >= $height) {
            if ($issmall == 1) {
                //copy($fpath . $filename, $fpath . "s_" . $filename);
                $image->thumb($w, $w, 3)->save($fpath . "s_" . $filename, NULL, 100);
            }
            return $filename;
        }
    }
    //图像输出新图片、另存为
    if ($issmall==1)
    {
       /*---
        switch ($ext) {
            case ".jpg":
            case ".jpeg":
                 imagejpeg($new, $fpath."s_".$filename);
                break;
            case ".gif":
                imagegif($new, $fpath."s_".$filename);
                break;
            case ".png":
                imagepng($new, $fpath."s_".$filename);
                break;
            default:
                return $filename;
        }--*/
        $image->thumb($w, $w, 2)->save($fpath . "s_" . $filename, NULL, 100);//400固定大小
    }
    else{
        if($width>$w) {
            $per = round($w / $width, 3);
            $n_h=$height*$per;
            $image->thumb($w, $n_h)->save($fpath . $filename, NULL, 100);//等比例缩放
        }
    }
    return $filename;
}
//删除空格, 制表符 换行符 回车符
function trimall($str)
{
    $qian=array(" "," ","\t","\n","\r","\\","\r\n");$hou=array("","","","","","","");
    return str_replace($qian,$hou,$str);
}
//json字符串格式化
function jsonFormat($str){
    $result =  preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', trim($str));
    $content = htmlspecialchars_decode($result);
    return $result;
}
/*---判断图片是否存在---*/
//$imgurl 图片地址
//$defaultimg 默认图片
//$islocal 是否显示本地 1本地 0=腾讯云
//$issmall 1小图   0=原图
//$imgtype  $imgurl存储是  0=本地路径   1=网上路径
function getImg($imgurl,$defaultimg='/public/images/not_adv.jpg',$islocal='0',$issmall='0',$imgtype='0')
{
    if(empty($imgurl)){
        return ALIYUNCS_LIB.$defaultimg;
    }
    $bak_imgurl=$imgurl;
    if ($issmall=="1")
    {
        $getfilename="s_".basename($imgurl);
        $getdirname=dirname($imgurl);
        $imgurl=$getdirname."/".$getfilename;
    }
    if ($imgtype=='0') {
        switch ($islocal) {
            case "0":
                //vendor('qcloudcos.myqcloudcos');
                /*---
                $resfolder = Myqcloudcos::stat('wxd', $imgurl);
                if ($resfolder && $resfolder['code'] != 0)//不存在
                {
                    $resfolder = Myqcloudcos::stat('wxd', $bak_imgurl);
                    if ($resfolder && $resfolder['code'] != 0)//不存在
                    {
                        return $defaultimg;
                    }
                    else {
                        return QCLOUD_IMGURL . $bak_imgurl;
                    }
                } else {
                    return QCLOUD_IMGURL . $imgurl;
                }---*/
                return QCLOUD_IMGURL . $imgurl;
                break;
            case "1":
                if (!file_exists(ROOT_PATH . $imgurl) || $imgurl == "") {
                    return $defaultimg;
                } else {
                    return $imgurl;
                }
                break;
                return $imgurl;
                break;
        }
    }else
    {
        return $imgurl;
    }
}
function getALLMobileInfo()
{
    $info =  "|" . getmobileBrand();
    // 获取版本号
    $ua = $_SERVER['HTTP_USER_AGENT'];//这里只进行IOS和Android两个操作系统的判断,其他操作系统原理一样
    if (strpos($ua, 'Android') !== false) {//strpos()定位出第一次出现字符串的位置,这里定位为0
        preg_match("/(?<=Android )[\d\.]{1,}/", $ua, $version);
        $info .= "|" . $version[0];
    } elseif (strpos($ua, 'iPhone') !== false) {
        preg_match("/(?<=CPU iPhone OS )[\d\_]{1,}/", $ua, $version);
        $info .= "|" . str_replace('_', '.', $version[0]);
    } elseif (strpos($ua, 'iPad') !== false) {
        preg_match("/(?<=CPU OS )[\d\_]{1,}/", $ua, $version);
        $info .= "|" . str_replace('_', '.', $version[0]);
    }
    //如果是微信
    if (is_weixin()) {
        // 微信浏览器,允许访问
        preg_match('/.*?(MicroMessenger\/([0-9.]+))\s*/', $ua, $matches);
        $info .= "|weixin" .$matches[2];// 获取版本号
    }
    $info.="|".getMobileModel();
    preg_match('/.*?(NetType\/([\W\w]+))\s/', $ua, $matches);
    $info .= "|" .$matches[2];// 获取版本号
    return $info;
}
//判断浏览器类型方法:
 function userBrowser($user_OSagent) {
     mlog($user_OSagent,"eventlog");
     if (strpos($user_OSagent, "Maxthon") && strpos($user_OSagent, "MSIE")) {
         $visitor_browser = "Maxthon(Microsoft IE)";
     } elseif (strpos($user_OSagent, "Maxthon 2.0")) {
         $visitor_browser = "Maxthon 2.0";
     } elseif (strpos($user_OSagent, "Maxthon")) {
         $visitor_browser = "Maxthon";
     } elseif (strpos($user_OSagent, "MSIE 9.0")) {
         $visitor_browser = "MSIE 9.0";
     } elseif (strpos($user_OSagent, "MSIE 8.0")) {
         $visitor_browser = "MSIE 8.0";
     } elseif (strpos($user_OSagent, "MSIE 7.0")) {
         $visitor_browser = "MSIE 7.0";
     } elseif (strpos($user_OSagent, "MSIE 6.0")) {
         $visitor_browser = "MSIE 6.0";
     } elseif (strpos($user_OSagent, "MSIE 5.5")) {
         $visitor_browser = "MSIE 5.5";
     } elseif (strpos($user_OSagent, "MSIE 5.0")) {
         $visitor_browser = "MSIE 5.0";
     } elseif (strpos($user_OSagent, "MSIE 4.01")) {
         $visitor_browser = "MSIE 4.01";
     } elseif (strpos($user_OSagent, "MSIE")) {
         $visitor_browser = "MSIE 较高版本";
     } elseif (strpos($user_OSagent, "NetCaptor")) {
         $visitor_browser = "NetCaptor";
     } elseif (strpos($user_OSagent, "Netscape")) {
         $visitor_browser = "Netscape";
     } elseif (strpos($user_OSagent, "Chrome")) {
         $visitor_browser = "Chrome";
     } elseif (strpos($user_OSagent, "Lynx")) {
         $visitor_browser = "Lynx";
     } elseif (strpos($user_OSagent, "Opera")) {
         $visitor_browser = "Opera";
     } elseif (strpos($user_OSagent, "Konqueror")) {
         $visitor_browser = "Konqueror";
     } elseif (strpos($user_OSagent, "Mozilla/5.0")) {
         $visitor_browser = "Mozilla";
     } elseif (strpos($user_OSagent, "Firefox")) {
         $visitor_browser = "Firefox";
     } elseif (strpos($user_OSagent, "U")) {
         $visitor_browser = "Firefox";
     } else {
         $visitor_browser = "其它";
     }
     return $visitor_browser;
 }
//浏览器版本
function getBrowserVer($agent){
    if (preg_match('/MSIE\s(\d+)\..*/i', $agent, $regs))
        return $regs[1];
    elseif (preg_match('/FireFox\/(\d+)\..*/i', $agent, $regs))
        return $regs[1];
    elseif (preg_match('/Opera[\s|\/](\d+)\..*/i', $agent, $regs))
        return $regs[1];
    elseif (preg_match('/Chrome\/(\d+)\..*/i', $agent, $regs))
        return $regs[1];
    elseif ((strpos($agent,'Chrome')==false)&&preg_match('/Safari\/(\d+)\..*$/i', $agent, $regs))
        return $regs[1];
    else
        return 'unknow';
}
//手机品牌
function getmobileBrand($user_agent)
{
    if (stripos($user_agent, "iPhone")!==false) {
        $brand = 'iPhone';
    } else if (stripos($user_agent, "SAMSUNG")!==false || stripos($user_agent, "Galaxy")!==false || strpos($user_agent, "GT-")!==false || strpos($user_agent, "SCH-")!==false || strpos($user_agent, "SM-")!==false) {
        $brand = '三星';
    } else if (stripos($user_agent, "Huawei")!==false || stripos($user_agent, "Honor")!==false || stripos($user_agent, "H60-")!==false || stripos($user_agent, "H30-")!==false) {
        $brand = '华为';
    } else if (stripos($user_agent, "Lenovo")!==false) {
        $brand = '联想';
    } else if (strpos($user_agent, "MI")!==false) {
        $brand = '小米';
    } else if (strpos($user_agent, "HM NOTE")!==false || strpos($user_agent, "HM201")!==false) {
        $brand = '红米';
    } else if (stripos($user_agent, "Coolpad")!==false || strpos($user_agent, "8190Q")!==false || strpos($user_agent, "5910")!==false) {
        $brand = '酷派';
    } else if (stripos($user_agent, "ZTE")!==false || stripos($user_agent, "X9180")!==false || stripos($user_agent, "N9180")!==false || stripos($user_agent, "U9180")!==false) {
        $brand = '中兴';
    } else if (stripos($user_agent, "OPPO")!==false || strpos($user_agent, "X9007")!==false || strpos($user_agent, "X907")!==false || strpos($user_agent, "X909")!==false || strpos($user_agent, "R831S")!==false || strpos($user_agent, "R827T")!==false || strpos($user_agent, "R821T")!==false || strpos($user_agent, "R811")!==false || strpos($user_agent, "R2017")!==false) {
        $brand = 'OPPO';
    } else if (strpos($user_agent, "HTC")!==false || stripos($user_agent, "Desire")!==false) {
        $brand = 'HTC';
    } else if (stripos($user_agent, "vivo")!==false) {
        $brand = 'vivo';
    } else if (stripos($user_agent, "K-Touch")!==false) {
        $brand = '天语';
    } else if (stripos($user_agent, "Nubia")!==false || stripos($user_agent, "NX50")!==false || stripos($user_agent, "NX40")!==false) {
        $brand = '努比亚';
    } else if (strpos($user_agent, "M045")!==false || strpos($user_agent, "M032")!==false || strpos($user_agent, "M355")!==false) {
        $brand = '魅族';
    } else if (stripos($user_agent, "DOOV")!==false) {
        $brand = '朵唯';
    } else if (stripos($user_agent, "GFIVE")!==false) {
        $brand = '基伍';
    } else if (stripos($user_agent, "Gionee")!==false || strpos($user_agent, "GN")!==false) {
        $brand = '金立';
    } else if (stripos($user_agent, "HS-U")!==false || stripos($user_agent, "HS-E")!==false) {
        $brand = '海信';
    } else if (stripos($user_agent, "Nokia")!==false) {
        $brand = '诺基亚';
    } else {
        $brand = '其他手机';
    }
    return $brand;
}
//手机型号
function getMobileModel($user_agent)
{
    if (empty($user_agent)){    //当浏览器没有发送访问者的信息的时候
        return '';
    }
    if(stristr($user_agent, 'Android')){//返回值中是否有Android这个关键字
        $a =  explode(";",$user_agent);
        $b = substr($a[2],1,strpos($a[2],"Build")-2);
        return $b;
    }else{
        if(stristr($user_agent, 'iPhone')){
            $a =  explode(" ",$user_agent);
            return "iPhone";
        }else{
            return "";
        }
    }
}
/**
 * 配置文件操作(查询了与修改)
 * 默认没有第三个参数时,按照字符串读取提取''中或""中的内容
 * 如果有第三个参数时为int时按照数字int处理。
 *调用demo
$name="admin";//kkkk
$bb='234';
$bb=getconfig("./2.php", "bb", "string");
updateconfig("./2.php", "name", "admin");
 */
function get_config($file, $ini, $type="string"){
    if(!file_exists($file)) return false;
    $str = file_get_contents($file);
    if ($type=="int"){
        $config = preg_match("/".preg_quote($ini)."=(.*);/", $str, $res);
        return $res[1];
    }
    else{
        $config = preg_match("/".preg_quote($ini)."=\"(.*)\";/", $str, $res);
        if($res[1]==null){
            $config = preg_match("/".preg_quote($ini)."='(.*)';/", $str, $res);
        }
        return $res[1];
    }
}
function update_config($file, $ini, $value,$type="string"){
    if(!file_exists($file)) return false;
    $str = file_get_contents($file);
    $str2="";
    if($type=="int"){
        $str2 = preg_replace("/".preg_quote($ini)."=(.*);/", $ini."=".$value.";",$str);
    }
    else{
        $str2 = preg_replace("/".preg_quote($ini)."=(.*);/",$ini."=\"".$value."\";",$str);
    }
    file_put_contents($file, $str2);
}
function str_format(){
    $args = func_get_args();
    if (count($args) == 0) { return;}
    if (count($args) == 1) { return $args[0]; }
    $str = array_shift($args);
    $str = preg_replace_callback('/\\{(0|[1-9]\\d*)\\}/', create_function('$match', '$args = '.var_export($args, true).'; return isset($args[$match[1]]) ? $args[$match[1]] : $match[0];'), $str);
    return $str;
}
function myHttpRspone($url,$jsonStr=''){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        )
    );
    $response = json_decode(curl_exec($ch),true);//将json转成数组
    curl_close($ch);
    return $response;
}
//获取ylp_token  $erpid账套
function getylp_token($erpid)
{
    $re_token="0";
    $gettoken= F("ylptoken" . "_" . $erpid, "", TEMP_PATH);
    mlog("token缓存值:".$gettoken,"getylp_token");
    $getylp_token="";
    $getylp_refreshtoken="";
    $ylp_expirestime="";
    $gettoken1=explode("|",$gettoken);
    $i = count($gettoken1);
    if (empty($gettoken) || $i<2)
    {
       $res=M('store')->where(array('ERPId'=>$erpid))->find();
        if ($res)
        {
            $getylp_token=$res['ylp_token'];
            $getylp_refreshtoken=$res['ylp_refreshtoken'];
            $ylp_expirestime=$res['ylp_expirestime'];
            F("ylptoken" . "_" . $erpid, $getylp_token."|".$getylp_refreshtoken."|".$ylp_expirestime, TEMP_PATH);
        }
    }
    else
    {
        if ($i>=2) {
            $getylp_token = $gettoken1[0];
            $getylp_refreshtoken = $gettoken1[1];
            $ylp_expirestime = $gettoken1[2];
        }
    }
    if (empty($ylp_expirestime))
    {
        $ylp_expirestime=0;
    }
    //超出时间
    if ($ylp_expirestime