= 1024 && $i < 6; $i++) {
$size /= 1024;
}
return round($size, $precision) . $delimiter . $units[$i];
}
}
if (!function_exists('datetime')) {
/**
* 将时间戳转换为日期时间
* @param int $time 时间戳
* @param string $format 日期时间格式
* @return string
*/
function datetime($time, $format = 'Y-m-d H:i:s')
{
$time = is_numeric($time) ? $time : strtotime($time);
return date($format, $time);
}
}
if (!function_exists('human_date')) {
/**
* 获取语义化时间
* @param int $time 时间
* @param int $local 本地时间
* @return string
*/
function human_date($time, $local = null)
{
return \fast\Date::human($time, $local);
}
}
if (!function_exists('cdnurl')) {
/**
* 获取上传资源的CDN的地址
* @param string $url 资源相对地址
* @param boolean $domain 是否显示域名 或者直接传入域名
* @return string
*/
function cdnurl($url, $domain = false)
{
$regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
$cdnurl = \think\Config::get('upload.cdnurl');
$url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
if ($domain && !preg_match($regex, $url)) {
$domain = is_bool($domain) ? request()->domain() : $domain;
$url = $domain . $url;
}
return $url;
}
}
if (!function_exists('is_really_writable')) {
/**
* 判断文件或文件夹是否可写
* @param string $file 文件或目录
* @return bool
*/
function is_really_writable($file)
{
if (DIRECTORY_SEPARATOR === '/') {
return is_writable($file);
}
if (is_dir($file)) {
$file = rtrim($file, '/') . '/' . md5(mt_rand());
if (($fp = @fopen($file, 'ab')) === false) {
return false;
}
fclose($fp);
@chmod($file, 0777);
@unlink($file);
return true;
} elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
return false;
}
fclose($fp);
return true;
}
}
if (!function_exists('rmdirs')) {
/**
* 删除文件夹
* @param string $dirname 目录
* @param bool $withself 是否删除自身
* @return boolean
*/
function rmdirs($dirname, $withself = true)
{
if (!is_dir($dirname)) {
return false;
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $fileinfo) {
$todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
$todo($fileinfo->getRealPath());
}
if ($withself) {
@rmdir($dirname);
}
return true;
}
}
if (!function_exists('copydirs')) {
/**
* 复制文件夹
* @param string $source 源文件夹
* @param string $dest 目标文件夹
*/
function copydirs($source, $dest)
{
if (!is_dir($dest)) {
mkdir($dest, 0755, true);
}
foreach (
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
) as $item
) {
if ($item->isDir()) {
$sontDir = $dest . DS . $iterator->getSubPathName();
if (!is_dir($sontDir)) {
mkdir($sontDir, 0755, true);
}
} else {
copy($item, $dest . DS . $iterator->getSubPathName());
}
}
}
}
if (!function_exists('mb_ucfirst')) {
function mb_ucfirst($string)
{
return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
}
}
if (!function_exists('addtion')) {
/**
* 附加关联字段数据
* @param array $items 数据列表
* @param mixed $fields 渲染的来源字段
* @return array
*/
function addtion($items, $fields)
{
if (!$items || !$fields) {
return $items;
}
$fieldsArr = [];
if (!is_array($fields)) {
$arr = explode(',', $fields);
foreach ($arr as $k => $v) {
$fieldsArr[$v] = ['field' => $v];
}
} else {
foreach ($fields as $k => $v) {
if (is_array($v)) {
$v['field'] = isset($v['field']) ? $v['field'] : $k;
} else {
$v = ['field' => $v];
}
$fieldsArr[$v['field']] = $v;
}
}
foreach ($fieldsArr as $k => &$v) {
$v = is_array($v) ? $v : ['field' => $v];
$v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
$v['primary'] = isset($v['primary']) ? $v['primary'] : '';
$v['column'] = isset($v['column']) ? $v['column'] : 'name';
$v['model'] = isset($v['model']) ? $v['model'] : '';
$v['table'] = isset($v['table']) ? $v['table'] : '';
$v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
}
unset($v);
$ids = [];
$fields = array_keys($fieldsArr);
foreach ($items as $k => $v) {
foreach ($fields as $m => $n) {
if (isset($v[$n])) {
$ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
}
}
}
$result = [];
foreach ($fieldsArr as $k => $v) {
if ($v['model']) {
$model = new $v['model'];
} else {
$model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
}
$primary = $v['primary'] ? $v['primary'] : $model->getPk();
$result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
}
foreach ($items as $k => &$v) {
foreach ($fields as $m => $n) {
if (isset($v[$n])) {
$curr = array_flip(explode(',', $v[$n]));
$linedata = array_intersect_key($result[$n], $curr);
$v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
}
}
}
return $items;
}
}
if (!function_exists('var_export_short')) {
/**
* 使用短标签打印或返回数组结构
* @param mixed $data
* @param boolean $return 是否返回数据
* @return string
*/
function var_export_short($data, $return = true)
{
return var_export($data, $return);
$replaced = [];
$count = 0;
//判断是否是对象
if (is_resource($data) || is_object($data)) {
return var_export($data, $return);
}
//判断是否有特殊的键名
$specialKey = false;
array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
$specialKey = true;
}
});
if ($specialKey) {
return var_export($data, $return);
}
array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
if (is_object($value) || is_resource($value)) {
$replaced[$count] = var_export($value, true);
$value = "##<{$count}>##";
} else {
if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
$index = array_search($value, $replaced);
if ($index === false) {
$replaced[$count] = var_export($value, true);
$value = "##<{$count}>##";
} else {
$value = "##<{$index}>##";
}
}
}
$count++;
});
$dump = var_export($data, true);
$dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
$dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
$dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
$dump = preg_replace('#\)$#', "]", $dump); //End
if ($replaced) {
$dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
}, $dump);
}
if ($return === true) {
return $dump;
} else {
echo $dump;
}
}
}
if (!function_exists('letter_avatar')) {
/**
* 首字母头像
* @param $text
* @return string
*/
function letter_avatar($text)
{
$total = unpack('L', hash('adler32', $text, true))[1];
$hue = $total % 360;
list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
$bg = "rgb({$r},{$g},{$b})";
$color = "#ffffff";
$first = mb_strtoupper(mb_substr($text, 0, 1));
$src = base64_encode('');
$value = 'data:image/svg+xml;base64,' . $src;
return $value;
}
}
if (!function_exists('hsv2rgb')) {
function hsv2rgb($h, $s, $v)
{
$r = $g = $b = 0;
$i = floor($h * 6);
$f = $h * 6 - $i;
$p = $v * (1 - $s);
$q = $v * (1 - $f * $s);
$t = $v * (1 - (1 - $f) * $s);
switch ($i % 6) {
case 0:
$r = $v;
$g = $t;
$b = $p;
break;
case 1:
$r = $q;
$g = $v;
$b = $p;
break;
case 2:
$r = $p;
$g = $v;
$b = $t;
break;
case 3:
$r = $p;
$g = $q;
$b = $v;
break;
case 4:
$r = $t;
$g = $p;
$b = $v;
break;
case 5:
$r = $v;
$g = $p;
$b = $q;
break;
}
return [
floor($r * 255),
floor($g * 255),
floor($b * 255)
];
}
}
if (!function_exists('check_nav_active')) {
/**
* 检测会员中心导航是否高亮
*/
function check_nav_active($url, $classname = 'active')
{
$auth = \app\common\library\Auth::instance();
$requestUrl = $auth->getRequestUri();
$url = ltrim($url, '/');
return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
}
}
if (!function_exists('check_cors_request')) {
/**
* 跨域检测
*/
function check_cors_request()
{
if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
$info = parse_url($_SERVER['HTTP_ORIGIN']);
$domainArr = explode(',', config('fastadmin.cors_request_domain'));
$domainArr[] = request()->host(true);
if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
} else {
$response = Response::create('跨域检测无效', 'html', 403);
throw new HttpResponseException($response);
}
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
}
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
$response = Response::create('', 'html');
throw new HttpResponseException($response);
}
}
}
}
if (!function_exists('xss_clean')) {
/**
* 清理XSS
*/
function xss_clean($content, $is_image = false)
{
return \app\common\library\Security::instance()->xss_clean($content, $is_image);
}
}
if (!function_exists('check_ip_allowed')) {
/**
* 检测IP是否允许
* @param string $ip IP地址
*/
function check_ip_allowed($ip = null)
{
$ip = is_null($ip) ? request()->ip() : $ip;
$forbiddenipArr = config('site.forbiddenip');
$forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
$forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
$response = Response::create('请求无权访问', 'html', 403);
throw new HttpResponseException($response);
}
}
}
if (!function_exists('build_suffix_image')) {
/**
* 生成文件后缀图片
* @param string $suffix 后缀
* @param null $background
* @return string
*/
function build_suffix_image($suffix, $background = null)
{
$suffix = mb_substr(strtoupper($suffix), 0, 4);
$total = unpack('L', hash('adler32', $suffix, true))[1];
$hue = $total % 360;
list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
$background = $background ? $background : "rgb({$r},{$g},{$b})";
$icon = <<
{$suffix}
EOT;
return $icon;
}
}
//我的
//结果集信息里,生日转换年龄
function list_birthday_age($list){
if(!$list || empty($list)){
return $list;
}
foreach($list as $vo => $info){
$list[$vo]['age'] = birthtime_to_age($info['birthday']);
}
return $list;
}
//结果集信息里,多个字段需要增加domain_cdnurl
function list_domain_image($list,$field){
if(!$list || empty($list)){
return $list;
}
foreach($list as $vo => $info){
$list[$vo] = info_domain_image($info,$field);
}
return $list;
}
//单条信息里,多个字段需要增加domain_cdnurl
//支持image,images
function info_domain_image($data,$field){
if(!$data || empty($data)){
return $data;
}
foreach($data as $key => $val){
if(in_array($key,$field)){
$more = strpos($key,'images');
$data[$key] = one_domain_image($val,$more);
}
}
return $data;
}
//支持单个字段,需要增加domain_cdnurl
//支持image,images
function one_domain_image($one,$more = false){
if(!$one){
return $one;
}
if(strpos($one,',') || $more !== false){
//逗号隔开的多个图片
$one = explode(',',$one);
foreach($one as $k => $v){
$one[$k] = localpath_to_netpath($v);
}
//$one = implode(',',$one);
}else{
$one = localpath_to_netpath($one);
}
return $one;
}
//本地地址转换为网络地址
function localpath_to_netpath($path)
{
if (empty($path)) {
return '';
} elseif (strrpos($path, 'http') !== false) {
return $path;
} else {
return config('upload.cdnurl') . str_replace("\\", "/", $path);
}
}
//秒 转换 日月分
function Sec2Time($time){
if(is_numeric($time)){
$value = array(
'years' => 0, 'days' => 0, 'hours' => 0,
'minutes' => 0, 'seconds' => 0,
);
/*if($time >= 31556926){
$value['years'] = floor($time/31556926);
$time = ($time%31556926);
}*/
if($time >= 86400){
$value['days'] = floor($time/86400);
$time = ($time%86400);
}
if($time >= 3600){
$value['hours'] = floor($time/3600);
$time = ($time%3600);
}
if($time >= 60){
$value['minutes'] = floor($time/60);
$time = ($time%60);
}
$value['seconds'] = floor($time);
//return (array) $value;
//$t=$value['years'] .'年'. $value['days'] .'天'.' '. $value['hours'] .'小时'. $value['minutes'] .'分'.$value['seconds'].'秒';
$t = $value['days'] .'天' . $value['hours'] .'小时'. $value['minutes'] .'分';
return $t;
}else{
return '0天';
}
}
//生日转年龄
function birthtime_to_age($birthtime){
// $birthtime = strtotime('1990-11-06');
if(!$birthtime){
return 0;
}
list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthtime));
list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
$age = $y2 - $y1;
if((int)($m2.$d2) < (int)($m1.$d1))
{$age -= 1;}
if($age < 0){
$age = 0;
}
return $age;
}
if(!function_exists('mk_dir')) {
/**
* 新建目录
*/
function mk_dir($dir, $mode = 0770, $tmp = true)
{
$mode = 0770;
if(is_file($dir)) {
//有同名文件
return false;
} else {
if(!is_dir($dir)) { //目录不存在
$dir_up = dirname($dir); //上级目录
if(!is_dir($dir_up)) {
//上级不存在
$rs = @mk_dir($dir_up);
if(!$rs) return false;
}
$rs = @mkdir($dir, $mode); //新建
if(!$rs) return false;
$rs = @chmod($dir, $mode); //改权限
if(!$rs) return false;
}
return true;
}
}
}
/**
* 在线支付日志
*/
function filePut($info,$text='notify.txt'){
if(is_array($info)) {
$info = json_encode($info, JSON_UNESCAPED_UNICODE);
}
if(!file_exist(RUNTIME_PATH.'paylog/')) {
mk_dir(RUNTIME_PATH.'paylog/');
}
$file = RUNTIME_PATH.'paylog/'.$text;
touch_file($file);
file_put_contents($file, "\r\n".date('Y-m-d H:i:s').' '.$info, FILE_APPEND);
}
if(!function_exists('touch_file')) {
/**
* 新建文件
*/
function touch_file($file = '')
{
if($file) {
if(!file_exists($file)) {
@touch($file);
@chmod($file, 0770);
}
}
}
}
if(!function_exists('file_exist')) {
/**
* 检测文件是否存在
* @param $file
* @return string
*/
function file_exist($file)
{
if(false === strpos($file, 'http')) { //本地文件
if(0 === strpos($file, '/upload')) {
$file = '.'.$file;
}
return file_exists($file);
} else { //网络文件
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
if(in_array(substr($status, 0, 1), [2, 3])) {
return true;
} else {
return false;
}
}
}
}
/**
* 发起HTTPS请求
*/
function curl_post($url, $data, $header = '', $timeOut = 0)
{
//初始化curl
$ch = curl_init();
//参数设置
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if($header != '') {
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
$result = curl_exec($ch);
//连接失败
if($result == FALSE) {
//\think\Log::record('[ CURL ] ERROR ' . curl_error($ch)."\n".var_export(debug_backtrace(), true)."\n", 'error');
}
curl_close($ch);
return $result;
}
/**
* 发起HTTP GET请求
*/
function curl_get($url)
{
$oCurl = curl_init();
if(stripos($url, "https://") !== FALSE) {
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
}
curl_setopt($oCurl, CURLOPT_TIMEOUT, 3);
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
$error = curl_error($oCurl);
curl_close($oCurl);
if($error) {
$sContent = file_get_contents($url);
return $sContent;
}
if(intval($aStatus["http_code"]) == 200) {
return $sContent;
} else {
return false;
}
}
//创建订单号
function createUniqueNo($prifix = 'P',$id = 0)
{
$s = 0;
$ms = 0;
list($ms, $s) = explode(' ', microtime());
$ms = substr($ms, 2, 6); //获取微妙
$rt = $prifix.date('ymdHis', $s).$ms.rand(10, 99).$id; //年月日时分秒.用户id对10取余.微秒
return $rt;
}
//下载远程图片 到指定目录
function downloadfile($file_url, $path = '', $save_file_name = '')
{
$basepath = '/uploaded/';
if ($path) {
$basepath = $basepath . $path . '/';
}
$basepath = $basepath . date('Ymd');
$dir_path = ROOT_PATH . '/public' . $basepath;
if (!is_dir($dir_path)) {
mkdir($dir_path, 0777, true);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $file_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch);
curl_close($ch);
//传入保存文件的名称
$filename = $save_file_name ?: pathinfo($file_url, PATHINFO_BASENAME);
$resource = fopen($dir_path. '/'. $filename, 'a');
fwrite($resource, $file);
fclose($resource);
return $dir_path . '/' . $filename;
}
//获取视频时长
function get_video_seconds($netpath = ''){
$local_url = downloadfile($netpath,'video','');
$playtime = 0;
Vendor('getid3.getid3.getid3');
$getID3 = new \getID3();
$fileinfo = $getID3->analyze($local_url);
if(isset($fileinfo['playtime_seconds'])){
$playtime = (int)$fileinfo['playtime_seconds'];
}
return $playtime;
}
//post接收参数中心,只接非必须
function request_post_hub($field_array = [],$required = [],$noempty = []){
if(empty($field_array)){
return [];
}
$data = [];
foreach($field_array as $key => $field){
//接收
if(!request()->has($field,'post')){
continue;
}
$newone = request()->post($field);
//追加
$data[$field] = $newone;
}
//必传
if(!empty($required)){
foreach($required as $k => $mustone){
if(!isset($data[$mustone])){
return $mustone.' required';
}
}
}
//必传,且不能空
if(!empty($noempty)){
foreach($noempty as $havekey => $haveone){
if(!isset($data[$havekey]) || empty($data[$havekey])){
return $haveone.' 必填';
}
}
}
return $data;
}
if(!function_exists('getAccessToken')) {
/**
* 获取access_token
* @return string
*/
function getAccessToken()
{
$accessToken = cache('access_token');
if (!$accessToken) {
$config = \think\Config::get('user_wxMiniProgram');
$appId = isset($config['appid']) ? $config['appid'] : '';
$appSecret = isset($config['secret']) ? $config['secret'] : '';
$getAccountTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
$accessTokenRes = httpRequest($getAccountTokenUrl, 'GET');
$accessTokenData = json_decode($accessTokenRes,true);
$accessToken = isset($accessTokenData['access_token']) ? $accessTokenData['access_token'] : '';
if (!empty($accessToken)) {
cache('access_token',$accessToken,['expire'=>7100]);
}
}
return $accessToken;
}
}
if (!function_exists('getDistance')) {
/**
* 根据坐标计算距离
*/
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=false, $decimal=0,$hasUnit=false){
$EARTH_RADIUS = 6370.996; // 地球半径系数
$PI = 3.1415926;
$FLAT = 180.0;
$radLat1 = $latitude1 * $PI / $FLAT;
$radLat2 = $latitude2 * $PI / $FLAT;
$radLng1 = $longitude1 * $PI / $FLAT;
$radLng2 = $longitude2 * $PI / $FLAT;
$a = $radLat1 - $radLat2;
$b = $radLng1 - $radLng2;
$distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
$distance = $distance * $EARTH_RADIUS * 1000;
if($unit){//转换成km
$distance = $distance / 1000;
}
if ($hasUnit) {//是否需要待单位
$unitStr = 'm';
if ($distance/1000 >= 1) {
$distance = $distance/1000;
$unitStr = 'km';
}
return round($distance, $decimal).$unitStr;
}
return round($distance, $decimal);
}
}
/**
* 文章时间友好化
* @param null $time 添加时间,时间戳
* @return string
*/
if (!function_exists('weixinDate')) {
function weixinDate($time = null)
{
if (!$time) {
return '';
}
// 获取当前时间戳
$cTime = time();
$date = date('Y.m.d', $time);
$xyh = intval(($cTime - $time) / 24 / 3600);
// 获取当前时间戳与$time的差
$dTime = $cTime - $time;
if ($dTime < 1) {
return '刚刚';
} elseif ($dTime < 60) {
return intval($dTime) . "秒前";
} elseif ($dTime < 3600) {
return intval($dTime / 60) . "分钟前";
} elseif ($dTime >= 3600 && $xyh < 1) {
return intval($dTime / 3600) . "小时前";
} elseif ($xyh > 365) {
// 如果时间大于1年,返回具体日期
return $date;
} elseif ($xyh == 1) {
return "昨天";
} elseif ($xyh >= 2 && $xyh <= 13) {
return intval($xyh) . "天前";
} elseif ($xyh > 13 && $xyh <= 60) {
return intval($xyh / 7) . "周前";
} elseif ($xyh > 60) {
return intval($xyh / 30) . "月前";
}
}
}
if(!function_exists('build_qrcode')) {
/**
* 生成二维码
* @param string $url 二维码的内容
* @param string $logo 二维码中间的LOGO
* @param string $save_dir 保存路径
* @return bool|string
*/
function build_qrcode($url, $logo, $save_dir,$fileName='') {
require_once("../vendor/phpqrcode/phpqrcode.php");
$QRcode = new \QRcode();
$value = $url; //二维码内容
$errorCorrectionLevel = 'H'; //容错级别
$matrixPointSize = 7; //生成图片大小
//生成二维码图片
if(!is_dir($save_dir)) {
mkdir($save_dir,0766,true);
}
$filename = $save_dir.time().rand(10000,99999).'.png';
if (!empty($fileName)) {
$filename = $save_dir.$fileName.'.png';
}
$QRcode::png($value,$filename, $errorCorrectionLevel, $matrixPointSize, 2);
$QR = $filename; //已经生成的原始二维码图片文件
$QR = imagecreatefromstring(file_get_contents($QR)); //目标图象连接资源。
if ($logo) { //LOGO是否存在
$logo = imagecreatefromstring(file_get_contents($logo)); //源图象连接资源。
//将真彩色图像logo变成调色板图像
if (imageistruecolor($logo)) imagetruecolortopalette($logo, false, 65535);
$QR_width = imagesx($QR); //二维码图片宽度
//$QR_height = imagesy($QR); //二维码图片高度
$logo_width = imagesx($logo); //logo图片宽度
$logo_height = imagesy($logo); //logo图片高度
$logo_qr_width = $QR_width / 4; //组合之后logo的宽度(占二维码的1/4)
$scale = $logo_width/$logo_qr_width; //logo的宽度缩放比(本身宽度/组合后的宽度)
$logo_qr_height = $logo_height/$scale; //组合之后logo的高度
$from_width = ($QR_width - $logo_qr_width) / 2; //组合之后logo左上角所在坐标点
//重新组合图片并调整大小
imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
imagedestroy($logo);
}
//输出图片
$res = imagepng($QR, $filename);
imagedestroy($QR);
if($res === false) {
return $res;
}
return $filename;
}
}
if(!function_exists('getProvince')) {
/**
* 获取省市区名称
* @return bool|string
*/
function getProvince($params=[]) {
$provinceId = isset($params['province_id']) ? $params['province_id'] : 0;
$cityId = isset($params['city_id']) ? $params['city_id'] : 0;
$areaId = isset($params['area_id']) ? $params['area_id'] : 0;
$address = isset($params['address']) ? $params['address'] : '';
$areaWhere['id'] = ['in',[$provinceId,$cityId,$areaId]];
$areaData = Db::name('shopro_area')->where($areaWhere)->column('id,name');
$params['province_name'] = isset($areaData[$provinceId]) ? $areaData[$provinceId] : '';
$params['city_name'] = isset($areaData[$cityId]) ? $areaData[$cityId] : '';
$params['area_name'] = isset($areaData[$areaId]) ? $areaData[$areaId] : '';
$params['full_address'] = $params['province_name'].$params['city_name'].$params['area_name'].$address;
return $params;
}
}
if(!function_exists('httpRequest')) {
/**
* 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, $postfields = null, $headers = array(), $debug = false)
{
$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, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "POST":
curl_setopt($ci, CURLOPT_POST, true);
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) {
echo "=====post data======\r\n";
var_dump($postfields);
echo "=====info===== \r\n";
print_r($requestinfo);
echo "=====response=====\r\n";
print_r($response);
}
curl_close($ci);
return $response;
//return array($http_code, $response,$requestinfo);
}
}
if(!function_exists('is_mobile')) {
/**
* 手机格式验证
* @param string $mobile 验证的手机号码
* @return boolean
*/
function is_mobile($mobile)
{
if (!empty($mobile)) {
return preg_match('/^1[3|4|5|6|7|8|9][0-9]\d{8}$/', $mobile);
}
return false;
}
}
if (!function_exists('httpurllocal')) {
/**
* 判断当前url是否为全路径,并返回全路径
*/
function httpurllocal($path) {
if(!$path) return $path;
$host = $_SERVER["REQUEST_SCHEME"]."://".$_SERVER["HTTP_HOST"];
// 获取当前域名
if(strpos($path,'http://') === false && strpos($path,'https://') === false) {
$url = $host.$path;
} else {
$url = $path;
}
return $url;
}
}