$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_expirestimewhere(array('ERPId' => $erpid))->save($up_store); } else { mlog("执行重新授权:".$erpid, "getylp_reauthorize/".getAdmStoId()); //重新授权 $getylp_token= getylp_reauthorize($erpid); } } return $getylp_token; } //有礼派重新授权 function getylp_reauthorize($ERPId) { //$res = M('admin')->alias('a')->join('store b', 'a.store_id=b.store_id', 'left')->where(array('a.admin_id' => getAdminId(), 'b.ERPId' => $ERPId))->field('a.ERPUser,b.*')->find(); $res1 = M('admin')->where(array('admin_id' => getAdminId()))->field('ERPUser')->find(); $res=tpCache('shop_info',$res1['store_id']); $res['ERPUser']=$res1['ERPUser']; if ($ERPId == "ppt" || $ERPId == "tpty") { $ylp_postdata["clientId"] = $ERPId; $ylp_postdata["userName"] = $res['ERPUser']; $ylp_postdata["password"] = "123456"; $ylp_postdata["displayName"] = $res['store_contact']; $ylp_postdata["phoneNumber"] = $res['store_tel']; $ylp_postdata["enterpriseName"] = $res['store_name']; } else { $erpai_res = json_decode(httpRequest(WXD_OPENURL . "/api/wxd/customer/page?accdb=" .$ERPId),true); if ($erpai_res && $erpai_res['code'] == 0 && $erpai_res['data']['pageData']!=null) { $erpai_res=$erpai_res['data']['pageData'][0]; $ylp_postdata["clientId"] = $ERPId; $ylp_postdata["userName"] = $res['ERPUser']; $ylp_postdata["password"] = "123456"; $ylp_postdata["displayName"] = $erpai_res['BossMan']; $ylp_postdata["phoneNumber"] = $erpai_res['MobileTel']; $ylp_postdata["enterpriseName"] = $erpai_res['CustName']; } } try { mlog("执行重新授权2:" . json_encode($ylp_postdata), "getylp_reauthorize/" . getAdmStoId()); $ylpres = httpRequest(YLPSQ_URL . "/third/erp/authorize", 'POST', $ylp_postdata); if (empty($ylpres)) { return ""; } mlog("授权:" . $ylpres, "getylp_reauthorize/" . getAdmStoId()); $ylpres = json_decode($ylpres, true);//数组 mlog("授权CODE:" . $ylpres['code'], "getylp_reauthorize/" . getAdmStoId()); if ($ylpres['code'] == 0) { mlog("执行重新授权3:", "getylp_reauthorize/" . getAdmStoId()); $up_store['ylp_token'] = $ylpres['data']['token']; $up_store['ylp_refreshtoken'] = $ylpres['data']['refreshToken']; $up_store['ylp_expiresin'] = $ylpres['data']['expiresIn']; $up_store['ylp_expirestime'] = time() + (int)$ylpres['data']['expiresIn']; M('store')->where(array('store_id' => $res['store_id']))->save($up_store); F("ylptoken" . "_" . $res['ERPId'], $ylpres['data']['token'] . "|" . $ylpres['data']['refreshToken'] . "|" . time() + (int)$ylpres['data']['expiresIn'], TEMP_PATH); return $ylpres['data']['token']; } else{ return ""; } } catch (Exception $ex) { return ""; } } /*---获取域名地址---*/ function curHostURL() { $pageURL = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://'; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"]; } else { $pageURL .= $_SERVER["SERVER_NAME"]; } return $pageURL; } /*---获取域名http或https---*/ function curhttpon() { $pageURL = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://'; return $pageURL; } //活动状态 function getactsstate($stime,$etime) { if (empty($stime) && empty($etime)) { return "未开始"; } $stime=strtotime($stime); $etime=strtotime($etime); $nowtime=time(); if ($nowtime<$stime) { return "未开始"; } else if ($nowtime>=$stime && $nowtime<=$etime) { return "进行中"; } else { return "已结束"; } } /*--保证json_encode--*/ function ext_json_decode($str, $mode=false){ $str = preg_replace('/([{,])(\s*)([A-Za-z0-9_\-]+?)\s*:/','$1"$3":',$str); $str = str_replace('\'','"',$str); $str = str_replace(" ", "", $str); $str = str_replace('\t', "", $str); $str = str_replace('\r', "", $str); $str = str_replace("\l", "", $str); $str = preg_replace('/s+/', '',$str); $str = trim($str,chr(239).chr(187).chr(191)); return json_decode($str, $mode); } /*--查找字符串中的数字--*/ function findNum($str=''){ $str=trim($str); if(empty($str)){return '';} $temp=array('1','2','3','4','5','6','7','8','9','0'); $result=''; for($i=0;$i array( 'method' => 'GET', 'header' => 'Content-type:application/x-www-form-urlencoded', 'timeout' => 15 * 60 // 超时时间(单位:s) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return $result; } /*--easy--*/ function get_easy_url($url){ $ch = curl_init(); $timeout = 1200; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $file_contents = curl_exec($ch); curl_close($ch); return $file_contents; } /*--获取电脑的MAC--*/ function get_pc_mac() { @exec("arp -a",$array); //执行arp -a命令,结果放到数组$array中 foreach($array as $value){ //匹配结果放到数组$mac_array if(strpos($value,$_SERVER["REMOTE_ADDR"]) && preg_match("/(:?[0-9A-F]{2}[:-]){5}[0-9A-F]{2}/i",$value,$mac_array)){ $mac = $mac_array[0]; break; } } return $mac; } /** * 获取客户端操作系统信息包括win10 * @param null * @author Jea杨 * @return string */ function get_os(){ $agent = $_SERVER['HTTP_USER_AGENT']; $os = false; if (preg_match('/win/i', $agent) && strpos($agent, '95')) { $os = 'Windows 95'; } else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) { $os = 'Windows ME'; } else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) { $os = 'Windows 98'; } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) { $os = 'Windows Vista'; } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) { $os = 'Windows 7'; } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) { $os = 'Windows 8'; }else if(preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) { $os = 'Windows 10';#添加win10判断 }else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) { $os = 'Windows XP'; } else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) { $os = 'Windows 2000'; } else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) { $os = 'Windows NT'; } else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) { $os = 'Windows 32'; } else if (preg_match('/linux/i', $agent)) { $os = 'Linux'; } else if (preg_match('/unix/i', $agent)) { $os = 'Unix'; } else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) { $os = 'SunOS'; } else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) { $os = 'IBM OS/2'; } else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent)) { $os = 'Macintosh'; } else if (preg_match('/PowerPC/i', $agent)) { $os = 'PowerPC'; } else if (preg_match('/AIX/i', $agent)) { $os = 'AIX'; } else if (preg_match('/HPUX/i', $agent)) { $os = 'HPUX'; } else if (preg_match('/NetBSD/i', $agent)) { $os = 'NetBSD'; } else if (preg_match('/BSD/i', $agent)) { $os = 'BSD'; } else if (preg_match('/OSF1/i', $agent)) { $os = 'OSF1'; } else if (preg_match('/IRIX/i', $agent)) { $os = 'IRIX'; } else if (preg_match('/FreeBSD/i', $agent)) { $os = 'FreeBSD'; } else if (preg_match('/teleport/i', $agent)) { $os = 'teleport'; } else if (preg_match('/flashget/i', $agent)) { $os = 'flashget'; } else if (preg_match('/webzip/i', $agent)) { $os = 'webzip'; } else if (preg_match('/offline/i', $agent)) { $os = 'offline'; } else { $os = '未知操作系统'; } return $os; } /*---- 客户端类型 ----*/ function order_source(){ $useragent=strtolower($_SERVER["HTTP_USER_AGENT"]); // iphone $is_iphone =strripos($useragent,'iphone'); if($is_iphone){ return 'iphone'; } // android $is_android =strripos($useragent,'android'); if($is_android){ return 'android'; } //微信 $is_weixin=strripos($useragent,'micromessenger'); if($is_weixin){ return 'weixin'; } // ipad $is_ipad =strripos($useragent,'ipad'); if($is_ipad){ return 'ipad'; } // ipod $is_ipod=strripos($useragent,'ipod'); if($is_ipod){ return 'ipod'; } // pc电脑 $is_pc=strripos($useragent,'windows nt'); if($is_pc){ return 'pc'; } return 'other'; } /*------ 根据IP获取地区 -------*/ function GetIpLookup($ip = ''){ if(empty($ip)){ $ip = GetIp(); } $res = @file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip='.$ip.'&qq-pf-to=pcqq.c2c'); if(empty($res)){ return false; } $jsonMatches = array(); preg_match('#\{.+?\}#', $res, $jsonMatches); if(!isset($jsonMatches[0])){ return false; } $json = json_decode($jsonMatches[0], true); if(isset($json['ret']) && $json['ret'] == 1){ $json['ip'] = $ip; unset($json['ret']); }else{ return false; } return $json; } /*-----获取用户客户端基本信息----*/ function get_vip_base() { $clientIp=getIP();//urldecode(getFullUrl());//当前ip $time =date('Y-m-d H:i:s',time()); $info=getalllocal(); $osVersion=$info['os'];//get_os();//当前操作系统 $browser=$info['browser'];//userBrowser(); //浏览器 $mobilebrand=$info['mobilebrand'];//getmobileBrand();//手机品牌,pc端为空 $mobilemodel=$info['mobilemodel'];//getMobileModel();//手机型号,pc端为空 // $appSourceType=$info['appSourceType'];//4; //事件来源 1 pc 2 ios 3 android 4 其他 $deviceId= $_SESSION['openid']; //手机端为微信openid 电脑端为电脑MAC $productId=1003;//1001= 万信达旗舰 1002= 万信达专业版 1003= 美得得手店 1004=万信达助手 $storageid=getMobileStoId();//门店ID $area='';//GetIpLookup($clientIp); $username=''; $imei=''; $accdb=''; if(!empty($area)) { $country=$area['country']; $province=$area['region']; $city=$area['city']; $isp=$area['isp']; } if(empty($storageid)) { $username=$_COOKIE['newshop_admin_erpuser'];//用户名 $accdb=$_COOKIE['newshop_admin_erpid'];//帐套 $imei=md5($_COOKIE['newshop_admin_supplyid'].' '.$_COOKIE['newshop_admin_id']); $storageid=$_COOKIE['newshop_admin_stoid'];//门店ID } else { $accdb= $_SESSION['user']['ERPId'];//帐套 $username=$_SESSION['user']['nickname'];//用户Id $imei=$_SESSION['user']['token'];// } $basehardword=array( 'clientIp'=>$clientIp, // 'time'=>$time, 'browser'=>$browser, 'osVersion'=>$osVersion, 'mobilebrand'=>$mobilebrand, 'mobilemodel'=>$mobilemodel, 'appSourceType'=>$appSourceType, 'deviceId'=>$deviceId, 'productId'=>$productId, 'sessionId'=>session_id(), 'username'=>$username, 'accdb'=>$accdb, 'storageid'=>$storageid, 'country'=>$country, 'city'=>$city, 'province'=>$province, 'isp'=>$isp, // 'lastPath'=>'', 'funcid'=>'', 'imei'=>$imei, // 'startTime'=>'', 'yuns'=>'', 'loginType'=>'', 'thirdLogin'=>'', 'channelId'=>'', 'platformId'=>'', 'version'=>'', 'net'=>'', 'cpu'=>'', 'stayTime'=>'', 'serverTime'=>'', 'adclient'=>'', 'adID'=>'', ); //mlog(json_encode($basehardword),'basehardword'); return $basehardword; } /** * 记录日志ylp * @param string $remark 事件说明 * @param string $apptype 事件类型 * @param string $keyword 搜索关键字 */ function upload_ylp_log($remark='',$apptype='点击',$keyword='') { $Event = \think\Loader::controller('home/Api'); if(strstr($apptype,"点击")!==false || strstr($apptype,"查询")!==false)//0=页面浏览 1=单独点击 2=列表点击 3=滑动浏览 { $apptype=1; } else if(strstr($apptype,"列表")!==false) { $apptype=2; } else { $apptype=0; } $result=$Event->get_event_log($remark,$apptype,$keyword); //异步处理 // $port=$_SERVER['SERVER_PORT']; // $arr=array('event_explain'=>$remark,'event_type'=>$apptype,'keyword'=>$keyword); // mlog(json_encode($arr[0]),'eventlog'); // /*--异步调用的方法--*/ // ignore_user_abort(true); // 忽略客户端断开 // set_time_limit(0); // 设置执行不超时 // doRequest(U('home/api/get_event_log'),$arr,$port); } /***** 客户端类型、操作系统、浏览器、手机品牌、手机型号 *****/ function getalllocal() { $appSourceType=4;//客户端类型 事件来源 1 pc 2 ios 3 android 4 其他 $os=''; //操作系统 $browser=''; //浏览器 $mobilebrand='';//手机品牌 $mobilemodel='';//手机类型 $Agent = $_SERVER['HTTP_USER_AGENT']; $useragent=strtolower($Agent); //客户端类型 $is_iphone =strripos($useragent,'iphone'); $is_ipad =strripos($useragent,'ipad'); $is_ipod=strripos($useragent,'ipod'); $is_android =strripos($useragent,'android'); $is_pc=strripos($useragent,'windows nt'); if($is_iphone || $is_ipad || $is_ipod){ $appSourceType=2; } if($is_android){ $appSourceType=3; } if($is_pc){ $appSourceType=1; } //操作系统 if (stripos($Agent, 'window')) { $os = 'Windows'; if (preg_match('/nt 6.0/i', $Agent)) { $os .= ' Vista'; } else if (preg_match('/nt 6.1/i', $Agent)) { $os .= ' 7'; } else if (preg_match('/nt 6.2/i', $Agent)) { $os .= ' 8'; } else if (preg_match('/nt 10.0/i', $Agent)) { $os .= ' 10'; } else if (preg_match('/nt 5.1/i', $Agent)) { $os .= ' XP'; } else { //其他window操作系统 } } else if (stripos($Agent, 'android')) { preg_match('/android\s([\d\.]+)/i', $Agent, $match); $os = 'Android '; $os .= $match[1]; } else if(preg_match('/iPhone|iPad|iPod/i',$Agent)) { preg_match('/OS\s([0-9_\.]+)/i', $ua, $match); $os = 'IOS '; $os .= str_replace('_','.',$match[1]); } else if (stripos($Agent, 'mac os')) { preg_match('/Mac OS X\s([0-9_\.]+)/i', $Agent, $match); $os = 'Mac OS X '; $os .= str_replace('_','.',$match[1]); } else if (stripos($Agent, 'unix')) { $os = 'Unix'; } else if (stripos($Agent, 'linux')) { $os = 'Linux'; } else { $os = 'Other'; } //浏览器类型及版本 $browser=userBrowser($Agent).getBrowserVer($Agent); //手机品牌、类型 if($appSourceType!=1) { $mobilebrand=getmobileBrand($Agent); $mobilemodel=getMobileModel($Agent); } $info=array( 'appSourceType'=> $appSourceType, 'os'=> $os, 'browser'=> $browser, 'mobilebrand'=> $mobilebrand, 'mobilemodel'=> $mobilemodel, ); return $info; } //获取上一页地址 function getlasturl() { $lasturl=$_SESSION['currurl']; if(empty($lasturl)) { $lasturl=''; } session('lasturl', $lasturl); //上一页地址 session('currurl', $_SERVER["HTTP_HOST"].$_SERVER["PHP_SELF"]."?".$_SERVER["QUERY_STRING"]); //当前地址 } //key 1=加密 2=解密 des function getdes($text,$type=1) { $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $key = "xinda100xinda100";//密钥 if ($type=="1") { return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv)); }else { return mcrypt_decrypt(MCRYPT_RIJNDAEL_256,$key,base64_decode($text),MCRYPT_MODE_ECB,$iv);//解密后的内容 } } /*---文件流发送文件20171030--*/ function sendStreamFile($url, $file) { if (file_exists($file)) { $opts = array( 'http' => array( 'method' => 'POST', 'header' => 'content-type:application/x-www-form-urlencoded', 'content' => file_get_contents($file) ) ); $context = stream_context_create($opts); $response = file_get_contents($url, false, $context); $ret = json_decode($response, true); return $ret['success']; } else { return false; } } //生成四位流水号 function create_4no($num){ $str=$num.''; switch (strlen($str)){ case "1":$str='000'.$str; break; case "2":$str='00'.$str; break; case "3":$str='0'.$str; break; case "4": break; } return $str; } //生成随机的不重复数组,$count是数据的$min-$max之间的随机数,$n个不重复数组, function rand_my($min,$max,$n){ if(($max-$min)<$n) return null; $tmp=array(); while(count($tmp)<$n){ $tmp[]=mt_rand($min,$max); $tmp=array_unique($tmp); } return $tmp; } //是否有礼派调用APP function getylapp_res($store_id,$type) { $ylpapp_list = tpCache('shopping.ylpapp_list', $store_id); $is_ylpapp = tpCache('shop_info.is_ylpapp', $store_id); if ($is_ylpapp && $ylpapp_list) { $getshow=0; if ($type=="all")//其他页面 { $getshow=1; } else { if ($type && strpos($ylpapp_list, $type)) { $getshow = 1; } else { $getshow = 0; } } if (empty($getshow)) { return ""; } if (F('ylpapp_' . $store_id)) { return F('ylpapp_' . $store_id); } else { $erpid = tpCache('shop_info.ERPId', $store_id); $post_data = "{\"ACCDB\":\"" . $erpid . "\"}"; $req_headers = [ 'Content-Type:application/json;' ]; $ylpres = httpRequest(YLPAPP_URL . '/api/erp/enterprise/getAppInfo', 'POST', $post_data, $req_headers);// $ylpres = json_decode($ylpres, true); if ($ylpres['STATE'] == 1) { return $ylpres['ITEMS']; } } } } //图片转64 function base64EncodeImage($url,$type=0,$timeout=30) { $msg = ['code' => 2100, 'status' => 'error', 'msg' => '未知错误!']; $imgs = ['image/jpeg' => 'jpeg', 'image/jpg' => 'jpg', 'image/gif' => 'gif', 'image/png' => 'png', 'text/html' => 'html', 'text/plain' => 'txt', 'image/pjpeg' => 'jpg', 'image/x-png' => 'png', 'image/x-icon' => 'ico' ]; if (!stristr($url, 'http')) { $msg['code'] = 2101; $msg['msg'] = 'url地址不正确!'; return $msg; } $dir = pathinfo($url); //var_dump($dir); $host = $dir['dirname']; $refer = $host . '/'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_REFERER, $refer); //伪造来源地址 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//返回变量内容还是直接输出字符串,0输出,1返回内容 curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);//在启用CURLOPT_RETURNTRANSFER的时候,返回原生的(Raw)输出 curl_setopt($ch, CURLOPT_HEADER, 0); //是否输出HEADER头信息 0否1是 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //超时时间 $data = curl_exec($ch); //$httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE); //$httpContentType = curl_getinfo($ch,CURLINFO_CONTENT_TYPE); $info = curl_getinfo($ch); curl_close($ch); $httpCode = intval($info['http_code']); $httpContentType = $info['content_type']; $httpSizeDownload = intval($info['size_download']); if ($httpCode != '200') { $msg['code'] = 2102; $msg['msg'] = 'url返回内容不正确!'; return $msg; } if ($type > 0 && !isset($imgs[$httpContentType])) { $msg['code'] = 2103; $msg['msg'] = 'url资源类型未知!'; return $msg; } if ($httpSizeDownload < 1) { $msg['code'] = 2104; $msg['msg'] = '内容大小不正确!'; return $msg; } $msg['code'] = 200; $msg['status'] = 'success'; $msg['msg'] = '资源获取成功'; if ($type == 0 or $httpContentType == 'text/html') $msg['data'] = $data; $base_64 = base64_encode($data); if ($type == 1) $msg['data'] = $base_64; elseif ($type == 2) $msg['data'] = "data:{$httpContentType};base64,{$base_64}"; elseif ($type == 3) $msg['data'] = ""; else $msg['msg'] = '未知返回需求!'; unset($info, $data, $base_64); return $msg; } /*--上传剪切图片 * @param $filename原文件名 * @param $fpath文件存储路径 * @param $w缩放比例 * $issmall 是否生成小图 * @return 缩放的比例 --*/ function m_format_img($filename,$w=800){ list($width, $height)=getimagesize($filename); $image = \think\Image::open($filename); $image->thumb($w,$w,2)->save($filename, NULL, 100);//如果不够,用填充 return $filename; } /** * @param $file 二进制文件流 * @return $fileType 返回的文件类型 */ function getFileType($file) { // 文件头标识 (2 bytes) $bin = substr($file,0,2); $strInfo = @unpack("C2chars", $bin);; $typeCode = intval($strInfo['chars1'].$strInfo['chars2']); $fileType = ""; switch($typeCode) { case 255216 : $fileType = "jpg"; break; case 7173 : $fileType = "gif"; break; case 13780 : $fileType = "png"; break; case 6677: $fileType = 'bmp'; break; case 7790: $fileType = 'exe'; break; case 7784: $fileType = 'midi'; break; case 8297: $fileType = 'rar'; break; default : $fileType = "unknow"; break; } return $fileType; } // 递归删除文件夹 function delFile2($dir,$file_type='') { //不删除temp目的文件 if(strpos($dir,'temp')!==false){ return false; } if($dir==ROOT_PATH || $dir=="" || $dir==".sync" ) return; try { 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 { delFile2($dir . '/' . $filename); } } } } else { if (file_exists($dir)) unlink($dir); } }catch (Exception $e){ mlog($e->getMessage(),'delFile2'); } } /**设置缓存值 * @param $modulename * @param $functionname * @param $othername * @param $value * @param int $expire 默认2个小时 */ function setRedisKey($modulename,$functionname,$othername,$value,$expire = 7200) { $getkey= SYS_NAME . ":" . SYS_ENV . ":".$modulename.":".$functionname.$othername; F($getkey, $value,"",$expire); } /**获取缓存值 * @param $modulename * @param $functionname * @param $othername * @return mixed */ function getRedisKey($modulename,$functionname,$othername) { $getkey= SYS_NAME . ":" . SYS_ENV . ":".$modulename.":".$functionname.$othername; return F($getkey); } function clearRedisKey($modulename,$functionname,$othername) { $getkey= SYS_NAME . ":" . SYS_ENV . ":".$modulename.":".$functionname.$othername; return Cache::rm($getkey); } //---只插入一条记录,避免重复--- /** * @param $table 表名 * @param $data 数据 * @param $where 条件 * @return string */ function one_insert($table,$data,$where){ $k_name=array_keys($data); $vals=array_values($data); $sql="INSERT INTO ".$table." (".implode(",",$k_name).") SELECT ".implode(",",$vals)." FROM DUAL WHERE NOT EXISTS ( SELECT * FROM ".$table." WHERE ".$where.")"; return $sql; }