// +---------------------------------------------------------------------- // 此文件为系统框架核心公共函数文件,为了系统的稳定与安全,未经允许不得擅自改动 if (!function_exists('getValidatorError')) { /** * 错误验证 * @param $error * @return mixed */ function getValidatorError($validator) { $errors = $validator->errors()->all(); return isset($errors[0]) ? $errors[0] : 1013; } } if (!function_exists('array_sort')) { /** * 数组排序 * @param array $arr 数据源 * @param $keys KEY * @param bool $desc 排序方式(默认:asc) * @return array 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function array_sort($arr, $keys, $desc = false) { $key_value = $new_array = array(); foreach ($arr as $k => $v) { $key_value[$k] = $v[$keys]; } if ($desc) { arsort($key_value); } else { asort($key_value); } reset($key_value); foreach ($key_value as $k => $v) { $new_array[$k] = $arr[$k]; } return $new_array; } } if (!function_exists('xml2array')) { /** * xml转数组 * @param $xml xml文本 * @return string * @author laravel开发员 * @date 2019/6/6 */ function xml2array(&$xml) { $xml = ""; foreach ($xml as $key => $val) { if (is_numeric($val)) { $xml .= "<" . $key . ">" . $val . ""; } else { $xml .= "<" . $key . ">"; } } $xml .= ""; return $xml; } } if (!function_exists('array2xml')) { /** * 数组转xml * @param $arr 原始数据(数组) * @param bool $ignore 是否忽视true或fasle * @param int $level 级别(默认:1) * @return string 返回结果 * @author laravel开发员 * @date 2019/6/6 */ function array2xml($arr, $ignore = true, $level = 1) { $s = $level == 1 ? "\r\n\r\n" : ''; $space = str_repeat("\t", $level); foreach ($arr as $k => $v) { if (!is_array($v)) { $s .= $space . "" . ($ignore ? '' : '') . "\r\n"; } else { $s .= $space . "\r\n" . array2xml($v, $ignore, $level + 1) . $space . "\r\n"; } } $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s); return $level == 1 ? $s . "" : $s; } } if (!function_exists('array_merge_multiple')) { /** * 多为数组合并 * @param array $array1 数组1 * @param array $array2 数组2 * @return array 返回合并后的数组 * @author laravel开发员 * @date 2019/6/6 */ function array_merge_multiple($array1, $array2) { $merge = $array1 + $array2; $data = []; foreach ($merge as $key => $val) { if (isset($array1[$key]) && is_array($array1[$key]) && isset($array2[$key]) && is_array($array2[$key]) ) { $data[$key] = array_merge_multiple($array1[$key], $array2[$key]); } else { $data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key]; } } return $data; } } if (!function_exists('array_key_value')) { /** * 获取数组中某个字段的所有值 * @param array $arr 数据源 * @param string $name 字段名 * @return array 返回结果 * @author laravel开发员 * @date 2019/6/6 */ function array_key_value($arr, $name = "") { $result = []; if ($arr) { foreach ($arr as $key => $val) { if ($name) { $result[] = $val[$name]; } else { $result[] = $key; } } } $result = array_unique($result); return $result; } } if (!function_exists('curl_url')) { /** * 获取当前访问的完整地址 * @return string 返回结果 * @author laravel开发员 * @date 2019/6/6 */ function curl_url() { $page_url = 'http'; if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] === 'on') { $page_url .= "s"; } $page_url .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $page_url .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"]; } else { $page_url .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]; } return $page_url; } } if (!function_exists('curl_get')) { /** * curl请求(GET) * @param $url 请求地址 * @param array $data 请求参数 * @return bool|string 返回结果 * @author laravel开发员 * @date 2019/6/5 */ function curl_get($url, $data = []) { if (!empty($data)) { $url = $url . '?' . http_build_query($data); } // 初始化 $ch = curl_init(); // 设置抓取的url curl_setopt($ch, CURLOPT_URL, $url); // 设置头文件的信息作为数据流输出 curl_setopt($ch, CURLOPT_HEADER, false); // 是否要求返回数据 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 是否检测服务器的证书是否由正规浏览器认证过的授权CA颁发的 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 执行命令 $result = curl_exec($ch); // 关闭URL请求(释放句柄) curl_close($ch); return $result; } } if (!function_exists('curl_post')) { /** * curl请求(POST) * @param $url 请求地址 * @param array $data 请求参数 * @return bool|string 返回结果 * @author laravel开发员 * @date 2019/6/5 */ function curl_post($url, $data = []) { // 初始化 $ch = curl_init(); // 设置post方式提交 curl_setopt($ch, CURLOPT_POST, 1); // 设置头文件的信息作为数据流输出 curl_setopt($ch, CURLOPT_HEADER, 0); // 是否要求返回数据 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 设置抓取的url curl_setopt($ch, CURLOPT_URL, $url); // 提交的数据 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 是否检测服务器的证书是否由正规浏览器认证过的授权CA颁发的 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 执行命令 $result = curl_exec($ch); // 关闭URL请求(释放句柄) curl_close($ch); return $result; } } if (!function_exists('curl_request')) { /** * curl请求(支持get和post) * @param $url 请求地址 * @param array $data 请求参数 * @param string $type 请求类型(默认:post) * @param bool $https 是否https请求true或false * @return bool|string 返回请求结果 * @author laravel开发员 * @date 2019/6/6 */ function curl_request($url, $data = [], $type = 'post', $https = false) { // 初始化 $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // 设置超时时间 curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 是否要求返回数据 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if ($https) { // 对认证证书来源的检查 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 从证书中检查SSL加密算法是否存在 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } if (strtolower($type) == 'post') { // 设置post方式提交 curl_setopt($ch, CURLOPT_POST, true); // 提交的数据 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } elseif (!empty($data) && is_array($data)) { // get网络请求 $url = $url . '?' . http_build_query($data); } // 设置抓取的url curl_setopt($ch, CURLOPT_URL, $url); // 执行命令 $result = curl_exec($ch); if ($result === false) { return false; } // 关闭URL请求(释放句柄) curl_close($ch); return $result; } } if (!function_exists('datetime')) { /** * 格式化日期函数 * @param $time 时间戳 * @param string $format 输出日期格式 * @return string 返回格式化的日期 * @author laravel开发员 * @date 2019/5/23 */ function datetime($time, $format = 'Y-m-d H:i:s') { if($time == '0000-00-00 00:00:00'){ return ''; } $time = is_numeric($time) ? $time : strtotime($time); return date($format, $time); } } if (!function_exists('dateForWeek')) { /** * 返回星期格式时间 * @param $time 时间戳 * @return false|string */ function dateForWeek($time) { if(empty($time)){ return false; } $time = !is_int($time)? strtotime($time) : $time; $weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]; $week = date("w", $time); $cweek = date("w"); if ($cweek - $week >= 0 && (time() - $time) <= 7 * 86400) { return isset($weeks[$week]) ? $weeks[$week] . ' ' . date('H:i', $time) : date('m月d日 H:i', $time); } else { return date('m月d日 H:i', $time); } } } if (!function_exists('dateFormat')) { /** * 格式化时间日期 * @param $time 时间戳 * @return false|string */ function dateFormat($time, $format='m月d日') { if(empty($time)){ return false; } $time = !is_int($time)? strtotime($time) : $time; $weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]; $week = date("w", $time); $cweek = date("w"); $dateTime = strtotime(date('Y-m-d')); // 今日 if ($time >= $dateTime) { return date('今日 H:i', $time); } // 昨日 else if ($time >= $dateTime - 86400) { return date('昨天 H:i', $time); } else if ($cweek - $week > 0 && (time() - $time) < 7 * 86400) { return isset($weeks[$week]) ? $weeks[$week] . ' ' . date('H:i', $time) : date('m月d日 H:i', $time); } else { return date($format, $time); } } } if (!function_exists('dayFormat')) { /** * 格式化时间日期 * @param $time 时间戳 * @return false|string */ function dayFormat($time, $format='m月d日') { if(empty($time)){ return false; } $time = !is_int($time)? strtotime($time) : $time; $weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]; $week = date("w", $time); $cweek = date("w"); $dateTime = strtotime(date('Y-m-d')); // 今日 if ($time >= $dateTime) { return '今日 '.date('H:i', $time); } // 昨日 else if ($time >= $dateTime - 86400) { return date('昨天 H:i', $time); } else if ($cweek - $week > 0 && (time() - $time) < 7 * 86400) { return isset($weeks[$week]) ? date('m月d日 H点', $time).'('.$weeks[$week].')' : date('m月d日 H:i', $time); } else { return date($format, $time); } } } if (!function_exists('formatHour')) { /** * 格式化时间 * @param $time 时间/秒 * @return false|string */ function formatHour($time) { if(empty($time)){ return '00:00'; } $hour = intval($time/3600); $hour = $hour<10?'0'.$hour : $hour; $minute = intval($time%3600/60); $minute = $minute<10?'0'.$minute : $minute; return $hour.':'.$minute; } } if (!function_exists('data_auth_sign')) { /** * 数据签名认证 * @param $data 数据源 * @return string * @author laravel开发员 * @date 2019/6/6 */ function data_auth_sign($data) { // 数据类型检测 if (!is_array($data)) { $data = (array)$data; } // 排序 ksort($data); // url编码并生成query字符串 $code = http_build_query($data); // 生成签名 $sign = sha1($code); return $sign; } } if (!function_exists('decrypt')) { /** * DES解密 * @param string $str 解密字符串 * @param string $key 解密KEY * @return mixed * @author laravel开发员 * @date 2019/6/6 */ function decrypt($str, $key = 'p@ssw0rd') { $str = base64_decode($str); $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB); $block = mcrypt_get_block_size('des', 'ecb'); $pad = ord($str[($len = strlen($str)) - 1]); if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str)) { $str = substr($str, 0, strlen($str) - $pad); } return unserialize($str); } } if (!function_exists('encrypt')) { /** * * @param string $str 加密字符串 * @param string $key 加密KEY * @return string * @author laravel开发员 * @date 2019/6/6 */ function encrypt($str, $key = 'p@ssw0rd') { $prep_code = serialize($str); $block = mcrypt_get_block_size('des', 'ecb'); if (($pad = $block - (strlen($prep_code) % $block)) < $block) { $prep_code .= str_repeat(chr($pad), $pad); } $encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB); return base64_encode($encrypt); } } if (!function_exists('export_excel')) { /** * 导出Excel文件 * @param string $file_name 文件名 * @param array $title 标题 * @param array $data 数据源 * @author laravel开发员 * @date 2019/6/6 */ function export_excel($file_name, $title = [], $data = []) { // 默认支持最大512M ini_set('memory_limit', '512M'); ini_set('max_execution_time', 0); ob_end_clean(); ob_start(); header("Content-Type: text/csv"); header("Content-Disposition:filename=" . $file_name); $fp = fopen('php://output', 'w'); // 转码 防止乱码(比如微信昵称) fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF)); fputcsv($fp, $title); $index = 0; foreach ($data as $item) { if ($index == 1000) { $index = 0; ob_flush(); flush(); } $index++; fputcsv($fp, $item); } ob_flush(); flush(); ob_end_clean(); } } if (!function_exists('ecm_define')) { /** * 定义常量(读取数组或引用文件) * @param $value 数据源 * @return bool * @author laravel开发员 * @date 2019/6/6 */ function ecm_define($value) { if (is_string($value)) { /* 导入数组 */ $value = include($value); } if (!is_array($value)) { /* 不是数组,无法定义 */ return false; } foreach ($value as $key => $val) { if (is_string($val) || is_numeric($val) || is_bool($val) || is_null($val)) { // 判断是否已定义过,否则进行定义 defined(strtoupper($key)) or define(strtoupper($key), $val); } } } } if (!function_exists('format_time')) { /** * 格式化时间段 * @param int $time 时间戳 * @return string 输出格式化时间 * @author laravel开发员 * @date 2019/5/23 */ function format_time($time) { $interval = time() - $time; $format = array( '31536000' => '年', '2592000' => '个月', '604800' => '星期', '86400' => '天', '3600' => '小时', '60' => '分钟', '1' => '秒', ); foreach ($format as $key => $val) { $match = floor($interval / (int)$key); if (0 != $match) { return $match . $val . '前'; } } return date('Y-m-d', $time); } } if (!function_exists('format_bytes')) { /** * 将字节转换为可读文本 * @param int $size 字节大小 * @param string $delimiter 分隔符 * @return string 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function format_bytes($size, $delimiter = '') { $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); for ($i = 0; $size >= 1024 && $i < 6; $i++) { $size /= 1024; } return round($size, 2) . $delimiter . $units[$i]; } } if (!function_exists('format_yuan')) { /** * 以分为单位的金额转换成元 * @param int $money 金额 * @return string 返回格式化的金额 * @author laravel开发员 * @date 2019/5/23 */ function format_yuan($money = 0) { if ($money > 0) { return number_format($money / 100, 2, ".", ""); } return "0.00"; } } if (!function_exists('format_cent')) { /** * 以元为单位的金额转化成分 * @param $money 金额 * @return string 返回格式化的金额 * @author laravel开发员 * @date 2019/5/23 */ function format_cent($money) { return (string)($money * 100); } } if (!function_exists('format_bank_card')) { /** * 银行卡格式转换 * @param string $card_no 银行卡号 * @param bool $is_format 是否格式化 * @return string 输出结果 * @author laravel开发员 * @date 2019/5/23 */ function format_bank_card($card_no, $is_format = true, $hidden=true) { if($hidden){ $format_card_no = substr($card_no, 0, 4).'**********'.substr($card_no, -4, 4); }else if ($is_format) { // 截取银行卡号前4位 $prefix = substr($card_no, 0, 4); // 截取银行卡号后4位 $suffix = substr($card_no, -4, 4); $format_card_no = $prefix . " **** **** **** " . $suffix; } else { // 4的意思就是每4个为一组 $arr = str_split($card_no, 4); $format_card_no = implode(' ', $arr); } return $format_card_no; } } if (!function_exists('format_mobile')) { /** * 格式化手机号码 * @param string $mobile 手机号码 * @return string 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function format_mobile($mobile) { return substr($mobile, 0, 3) . "****" . substr($mobile, -4, 4); } } if (!function_exists('format_name')) { /** * 格式化姓名 * @param string $name 姓名 * @return string 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function format_name($name) { return substr($name, 0, 1) . "*" . substr($name, -1, 1); } } if (!function_exists('get_random_code')) { /** * 生成唯一字符串 * @param int $length * @param string $prefix * @param string $ext * @return string */ function get_random_code($length = 8, $prefix = '', $ext = '') { $length = $length < 4 ? 4 : $length; $code = strtoupper(md5(uniqid(mt_rand(), true) . $ext . microtime())); $start = rand(1, strlen($code) - $length); return $prefix . mb_substr($code, $start, $length); } } if (!function_exists('get_username')) { /** * 生成唯一字符串 * @param int $length * @param string $prefix * @param string $ext * @return string */ function get_username($id, $prefix = 'RRC') { $length = strlen($id); if ($length >= 8) { return $prefix . $id; } return $prefix . str_repeat('0', 2) . $id; } } if (!function_exists('get_realname')) { /** * 格式化真实姓名 * @param string $realname * @return string */ function get_realname($realname) { return $realname? mb_substr($realname,0,1,'utf-8').'师傅' : '李师傅'; } } if (!function_exists('get_address')) { /** * 格式化地址 * @param string $realname * @return string */ function get_address($address) { return $address? mb_substr($address,0,6,'utf-8').'xxx' : 'xxx'; } } if (!function_exists('get_password')) { /** * 获取双MD5加密密码 * @param string $password 加密字符串 * @return string 输出MD5加密字符串 * @author laravel开发员 * @date 2019/5/23 */ function get_password($password) { return md5(md5($password)); } } if (!function_exists('get_order_num')) { /** * 生成订单号 * @param string $prefix 订单前缀(如:JD-) * @return string 输出订单号字符串 * @author laravel开发员 * @date 2019/5/23 */ function get_order_num($prefix = '') { $micro = substr(microtime(), 2, 2); return $prefix . date("ymdHis") . $micro . rand(100, 999); } } if (!function_exists('getter')) { /** * 获取数组的下标值 * @param array $data 数据源 * @param string $field 字段名称 * @param string $default 默认值 * @return mixed|string 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function getter($data, $field, $default = '') { $result = $default; if (isset($data[$field])) { $result = $data[$field]; } return $result; } } if (!function_exists('get_zodiac_sign')) { /** * 根据月、日获取星座 * @param $month 月份 * @param $day 日期 * @return string 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function get_zodiac_sign($month, $day) { // 检查参数有效性 if ($month < 1 || $month > 12 || $day < 1 || $day > 31) { return false; } // 星座名称以及开始日期 $signs = array( array("20" => "水瓶座"), array("19" => "双鱼座"), array("21" => "白羊座"), array("20" => "金牛座"), array("21" => "双子座"), array("22" => "巨蟹座"), array("23" => "狮子座"), array("23" => "处女座"), array("23" => "天秤座"), array("24" => "天蝎座"), array("22" => "射手座"), array("22" => "摩羯座") ); list($sign_start, $sign_name) = each($signs[(int)$month - 1]); if ($day < $sign_start) { list($sign_start, $sign_name) = each($signs[($month - 2 < 0) ? $month = 11 : $month -= 2]); } return $sign_name; } } if (!function_exists('get_image_url')) { /** * 获取图片地址 * @param $image_url 图片地址 * @return string $domain 域名 * @author laravel开发员 * @date 2019/6/6 */ function get_image_url($image_url, $domain = '') { if (empty($image_url)) { return ''; } if($domain){ $host = $domain.'/uploads'; }else{ $host = request()->header('HOST'); $https = request()->secure(); $host = ($https ? 'https://' : 'http://') . $host . '/uploads'; } return strpos($image_url, 'http') === false ? $host . '/' . ltrim($image_url, '/') : $image_url; } } if (!function_exists('get_image_path')) { /** * 获取图片相对路径 * @param $image_url 图片地址 * @param $https 是否有证书 * @return string 返回图片网络地址 * @author laravel开发员 * @date 2019/6/6 */ function get_image_path($image_url, $https = true) { if (empty($image_url)) { return false; } // 是否七牛 $driver = \App\Services\ConfigService::make()->getConfigByCode('file_upload_driver','local'); if($driver == 'qiniu'){ return $image_url; } $data = explode('/uploads', $image_url); return $data ? end($data) : $image_url; } } if (!function_exists('get_format_images')) { /** * 获取多图片相对路径数组或json * @param $images 图片地址 * @return string 返回图片网络地址 * @author laravel开发员 * @date 2019/6/6 */ function get_format_images($images, $key = '', $dataType = 'json') { if (empty($images) || !is_array($images)) { return ''; } $datas = []; foreach ($images as $v) { $url = $key? (isset($v[$key])? $v[$key] : ''):$v; if ($url) { $datas[] = $key?[$key=>get_image_path($url)]:['url'=>get_image_path($url)]; } } if ($datas) { return $dataType == 'json' ? json_encode($datas, 256) : $datas; } else { return $dataType == 'json' ? '' : []; } } } // 获取图片数组预览 if (!function_exists('get_images_preview')) { /** * @param $urls 图片数组 * @param string $keyName 图片地址键名,空则无键名 * @return false */ function get_images_preview($urls, $keyName = 'url', $level = 1) { if (empty($urls)) { return []; } $urls = is_array($urls)? $urls : json_decode($urls, true); foreach ($urls as &$item) { if ($keyName && $level==2) { $item[$keyName] = get_image_url($item[$keyName]); } else if($keyName && $level==1){ $item = get_image_url($item[$keyName]); } else if($level==1){ $item = get_image_url($item); } } unset($item); return $urls; } } if (!function_exists('get_web_url')) { /** * 获取预览地址 * @param $url 地址 * @return string 返回网络地址 * @author laravel开发员 * @date 2019/6/6 */ function get_web_url($url) { $host = request()->header('HOST'); $host = ((strpos($host, '127') === false) && strpos($host, 'localhost') === false) ? env('WEB_URL') : 'http://' . $host; return strpos($url, 'http') === false ? $host . '/' . ltrim($url, '/') : $url; } } if (!function_exists('set_format_content')) { /** * 获取文章图片格式化后内容 * @param $content * @return false|mixed|string */ function set_format_content($content) { if (empty($content)) { return false; } $domain = request()->header('HOST'); if(preg_match("/127/", $domain)){ $host = env('IMG_URL',''); if(empty($host)){ $https = request()->secure(); $host = ($https ? 'https://' : 'http://') . $host . '/uploads'; } }else{ $https = request()->secure(); $host = ($https ? 'https://' : 'http://') . $domain . '/uploads'; } $content = str_replace("{$host}",'/uploads', htmlspecialchars_decode($content)); return $content; } } if (!function_exists('get_format_content')) { /** * 获取文章图片格式化后内容 * @param $content * @return false|mixed|string */ function get_format_content($content) { if (empty($content)) { return false; } $domain = request()->header('HOST'); $driver = \App\Services\ConfigService::make()->getConfigByCode('file_upload_driver','local'); if(preg_match("/127/", $domain)){ $host = env('IMG_URL',''); if(empty($host)){ $https = request()->secure(); $host = ($https ? 'https://' : 'http://') . $host . '/uploads'; } }else if($driver == 'qiniu'){ $host = \App\Services\ConfigService::make()->getConfigByCode('qiniu_host',''); }else{ $https = request()->secure(); $host = ($https ? 'https://' : 'http://') . $domain . '/uploads'; } $content = str_replace(["\"/uploads","'/uploads"],["\"{$host}","'{$host}"], htmlspecialchars_decode($content)); return $content; } } if (!function_exists('format_content')) { /** * 格式化文本换行内容 * @param $content * @return false|mixed|string */ function format_content($content) { if (empty($content)) { return false; } $content = str_replace(["\n"],["
"], htmlspecialchars_decode($content)); return get_format_content($content); } } if (!function_exists('get_hash')) { /** * 获取HASH值 * @return string 返回hash字符串 * @author laravel开发员 * @date 2019/6/6 */ function get_hash() { $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()+-'; $random = $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)]; $content = uniqid() . $random; return sha1($content); } } if (!function_exists('get_server_ip')) { /** * 获取服务端IP地址 * @return string 返回IP地址 * @author laravel开发员 * @date 2019/6/6 */ function get_server_ip() { if (isset($_SERVER)) { if ($_SERVER['SERVER_ADDR']) { $server_ip = $_SERVER['SERVER_ADDR']; } else { $server_ip = $_SERVER['LOCAL_ADDR']; } } else { $server_ip = getenv('SERVER_ADDR'); } return $server_ip; } } if (!function_exists('get_client_ip')) { /** * 获取客户端IP地址 * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字 * @param bool $adv 否进行高级模式获取(有可能被伪装) * @return mixed 返回IP * @author laravel开发员 * @date 2019/5/23 */ function get_client_ip($type = 0, $adv = false) { $type = $type ? 1 : 0; static $ip = null; if ($ip !== null) { return $ip[$type]; } if ($adv) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos = array_search('unknown', $arr); if (false !== $pos) { unset($arr[$pos]); } $ip = trim($arr[0]); } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } } elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } // IP地址合法验证 $long = sprintf("%u", ip2long($ip)); $ip = $long ? array($ip, $long) : array('0.0.0.0', 0); return $ip[$type]; } } if (!function_exists('get_guid_v4')) { /** * 获取唯一性GUID * @param bool $trim 是否去除{} * @return string 返回GUID字符串 * @author laravel开发员 * @date 2019/6/6 */ function get_guid_v4($trim = true) { // Windows if (function_exists('com_create_guid') === true) { $charid = com_create_guid(); return $trim == true ? trim($charid, '{}') : $charid; } // OSX/Linux if (function_exists('openssl_random_pseudo_bytes') === true) { $data = openssl_random_pseudo_bytes(16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100 $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10 return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } // Fallback (PHP 4.2+) mt_srand((double)microtime() * 10000); $charid = strtolower(md5(uniqid(rand(), true))); $hyphen = chr(45); // "-" $lbrace = $trim ? "" : chr(123); // "{" $rbrace = $trim ? "" : chr(125); // "}" $guidv4 = $lbrace . substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12) . $rbrace; return $guidv4; } } if (!function_exists('is_email')) { /** * 判断是否为邮箱 * @param string $str 邮箱 * @return false 返回结果true或false * @author laravel开发员 * @date 2019/5/23 */ function is_email($str) { return preg_match('/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/', $str); } } if (!function_exists('is_mobile')) { /** * 判断是否为手机号 * @param string $num 手机号码 * @return false 返回结果true或false * @author laravel开发员 * @date 2019/5/23 */ function is_mobile($num) { return preg_match('/^1(3|4|5|7|8)\d{9}$/', $num); } } if (!function_exists('is_zipcode')) { /** * 验证邮编是否正确 * @param string $code 邮编 * @return false 返回结果true或false * @author laravel开发员 * @date 2019/5/23 */ function is_zipcode($code) { return preg_match('/^[1-9][0-9]{5}$/', $code); } } if (!function_exists('is_idcard')) { /** * 验证身份证是否正确 * @param string $idno 身份证号 * @return bool 返回结果true或false * @author laravel开发员 * @date 2019/5/23 */ function is_idcard($idno) { $idno = strtoupper($idno); $regx = '/(^\d{15}$)|(^\d{17}([0-9]|X)$)/'; $arr_split = array(); if (!preg_match($regx, $idno)) { return false; } // 检查15位 if (15 == strlen($idno)) { $regx = '/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/'; @preg_match($regx, $idno, $arr_split); $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4]; if (!strtotime($dtm_birth)) { return false; } else { return true; } } else { // 检查18位 $regx = '/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/'; @preg_match($regx, $idno, $arr_split); $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4]; // 检查生日日期是否正确 if (!strtotime($dtm_birth)) { return false; } else { // 检验18位身份证的校验码是否正确。 // 校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。 $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); $sign = 0; for ($i = 0; $i < 17; $i++) { $b = (int)$idno[$i]; $w = $arr_int[$i]; $sign += $b * $w; } $n = $sign % 11; $val_num = $arr_ch[$n]; if ($val_num != substr($idno, 17, 1)) { return false; } else { return true; } } } } } if (!function_exists('is_empty')) { /** * 判断是否为空 * @param $value 参数值 * @return bool 返回结果true或false * @author laravel开发员 * @date 2019/6/5 */ function is_empty($value) { // 判断是否存在该值 if (!isset($value)) { return true; } // 判断是否为empty if (empty($value)) { return true; } // 判断是否为null if ($value === null) { return true; } // 判断是否为空字符串 if (trim($value) === '') { return true; } // 默认返回false return false; } } if (!function_exists('mkdirs')) { /** * 递归创建目录 * @param string $dir 需要创建的目录路径 * @param int $mode 权限值 * @return bool 返回结果true或false * @author laravel开发员 * @date 2019/6/6 */ function mkdirs($dir, $mode = 0777) { if (is_dir($dir) || mkdir($dir, $mode, true)) { return true; } if (!mkdirs(dirname($dir), $mode)) { return false; } return mkdir($dir, $mode, true); } } if (!function_exists('rmdirs')) { /** * 删除文件夹 * @param string $dir 文件夹路径 * @param bool $rmself 是否删除本身true或false * @return bool 返回删除结果 * @author laravel开发员 * @date 2019/6/6 */ function rmdirs($dir, $rmself = true) { if (!is_dir($dir)) { return false; } $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $file) { $todo = ($file->isDir() ? 'rmdir' : 'unlink'); $todo($file->getRealPath()); } if ($rmself) { @rmdir($dir); } return true; } } if (!function_exists('copydirs')) { /** * 复制文件夹 * @param string $source 原文件夹路径 * @param string $dest 目的文件夹路径 * @author laravel开发员 * @date 2019/6/6 */ function copydirs($source, $dest) { if (!is_dir($dest)) { mkdir($dest, 0755, true); } $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $item) { if ($item->isDir()) { $sent_dir = $dest . "/" . $iterator->getSubPathName(); if (!is_dir($sent_dir)) { mkdir($sent_dir, 0755, true); } } else { copy($item, $dest . "/" . $iterator->getSubPathName()); } } } } if (!function_exists('lang')) { function lang($msg, $replace = [], $local = '') { $local = $local ? $local : config('app.locale'); $data = __('api.' . $msg, $replace, $local); if (strpos($data, 'api', 0) !== false) { return __($msg, $replace, $local); } return __('api.' . $msg, $replace, $local); } } if (!function_exists('message')) { /** * 消息数组 * @param string $msg 提示文字 * @param bool $success 是否成功true或false * @param array $data 结果数据 * @param int $code 编码 * @return array 返回结果 * @author laravel开发员 * @date 2019/5/28 */ function message($msg = "操作成功", $success = true, $data = [], $code = 0, $type = 'json') { $result = ['success' => $success, 'msg' => lang($msg), 'data' => $data,'stime'=>time()]; if ($success) { $result['code'] = 0; } else { $result['code'] = $code ? $code : -1; } return $result; } } if (!function_exists('showJson')) { /** * 消息数组 * @param string $msg 提示文字 * @param bool $success 是否成功true或false * @param array $data 结果数据 * @param int $code 编码 * @return array 返回结果 * @author laravel开发员 * @date 2019/5/28 */ function showJson($msg = "操作成功", $success = true, $data = [], $code = 0, $type = 'json') { $result = ['success' => $success, 'msg' => lang($msg), 'data' => $success || env('APP_DEBUG')? $data :[],'stime'=>time()]; if ($success) { $result['code'] = 0; } else { $result['code'] = $code ? $code : -1; } return $type=='json'?response()->json($result, 200, [])->setEncodingOptions(256):$result; } } if (!function_exists('num2rmb')) { /** * 数字金额转大写 * @param float $num 金额 * @return string 返回大写金额 * @author laravel开发员 * @date 2019/6/6 */ function num2rmb($num) { $c1 = "零壹贰叁肆伍陆柒捌玖"; $c2 = "分角元拾佰仟万拾佰仟亿"; $num = round($num, 2); $num = $num * 100; if (strlen($num) > 10) { return "oh,sorry,the number is too long!"; } $i = 0; $c = ""; while (1) { if ($i == 0) { $n = substr($num, strlen($num) - 1, 1); } else { $n = $num % 10; } $p1 = substr($c1, 3 * $n, 3); $p2 = substr($c2, 3 * $i, 3); if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) { $c = $p1 . $p2 . $c; } else { $c = $p1 . $c; } $i = $i + 1; $num = $num / 10; $num = (int)$num; if ($num == 0) { break; } } $j = 0; $slen = strlen($c); while ($j < $slen) { $m = substr($c, $j, 6); if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') { $left = substr($c, 0, $j); $right = substr($c, $j + 3); $c = $left . $right; $j = $j - 3; $slen = $slen - 3; } $j = $j + 3; } if (substr($c, strlen($c) - 3, 3) == '零') { $c = substr($c, 0, strlen($c) - 3); } // if there is a '0' on the end , chop it out return $c . "整"; } } if (!function_exists('object_array')) { /** * 对象转数组 * @param $object 对象 * @return mixed 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function object_array($object) { //先编码成json字符串,再解码成数组 return json_decode(json_encode($object), true); } } if (!function_exists('parse_attr')) { /** * 配置值解析成数组 * @param string $value 参数值 * @return array 返回结果 * @author laravel开发员 * @date 2019/6/6 */ function parse_attr($value = '') { if (is_array($value)) { return $value; } $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n")); if (strpos($value, ':')) { $value = array(); foreach ($array as $val) { list($k, $v) = explode(':', $val); $value[$k] = $v; } } else { $value = $array; } return $value; } } if (!function_exists('strip_html_tags')) { /** * 去除HTML标签、图像等 仅保留文本 * @param string $str 字符串 * @param int $length 长度 * @return string 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function strip_html_tags($str, $length = 0) { // 把一些预定义的 HTML 实体转换为字符 $str = htmlspecialchars_decode($str); // 将空格替换成空 $str = str_replace(" ", "", $str); // 函数剥去字符串中的 HTML、XML 以及 PHP 的标签,获取纯文本内容 $str = strip_tags($str); $str = str_replace(array("\n", "\r\n", "\r"), ' ', $str); $preg = '//i'; // 剥离JS代码 $str = preg_replace($preg, "", $str, -1); if ($length == 2) { // 返回字符串中的前100字符串长度的字符 $str = mb_substr($str, 0, $length, "utf-8"); } return $str; } } if (!function_exists('sub_str')) { /** * 字符串截取 * @param string $str 需要截取的字符串 * @param int $start 开始位置 * @param int $length 截取长度 * @param bool $suffix 截断显示字符 * @param string $charset 编码格式 * @return string 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function sub_str($str, $start = 0, $length = 10, $suffix = true, $charset = "utf-8") { if (function_exists("mb_substr")) { $slice = mb_substr($str, $start, $length, $charset); } elseif (function_exists('iconv_substr')) { $slice = iconv_substr($str, $start, $length, $charset); } else { $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; preg_match_all($re[$charset], $str, $match); $slice = join("", array_slice($match[0], $start, $length)); } $omit = mb_strlen($str) >= $length ? '...' : ''; return $suffix ? $slice . $omit : $slice; } } if (!function_exists('save_image')) { /** * 保存图片 * @param string $img_url 网络图片地址 * @param string $save_dir 图片保存目录 * @return string 返回路径 * @author laravel开发员 * @date 2019/5/23 */ function save_image($img_url, $save_dir = '/') { if (!$img_url) { return false; } $save_dir = trim($save_dir, "/"); $imgExt = pathinfo($img_url, PATHINFO_EXTENSION); // 是否是本站图片 if (strpos($img_url, IMG_URL) !== false) { // 是否是临时文件 if (strpos($img_url, 'temp') === false) { return str_replace(IMG_URL, "", $img_url); } $new_path = create_image_path($save_dir, $imgExt); $old_path = str_replace(IMG_URL, ATTACHMENT_PATH, $img_url); if (!file_exists($old_path)) { return false; } rename($old_path, ATTACHMENT_PATH . $new_path); $uploadFile = new \App\Services\Common\UploadService(); $uploadFile->save($new_path, $imgExt, \Illuminate\Support\Facades\Config::get('constants.uploadFiles.channel.ADMIN')); return $new_path; } else { // 保存远程图片 $new_path = save_remote_image($img_url, $save_dir); } return $new_path; } } if(!function_exists('save_base64_image')){ /** * 保存base64图片 * @param $base64 * @param string $save_dir * @param string $ext * @return false|string */ function save_base64_image($base64, $save_dir = '', $ext='jpeg') { $content = str_replace('data:image/png;base64,','', urldecode(trim($base64))); $save_path = create_image_path($save_dir, $ext); return file_put_contents(ATTACHMENT_PATH . $save_path, base64_decode($content)) ? $save_path : false; } } if (!function_exists('create_image_path')) { /** * 创建图片存储目录 * @param string $save_dir 存储目录 * @param string $image_ext 图片后缀 * @param string $image_root 图片存储根目录路径 * @return string 返回文件目录 * @author laravel开发员 * @date 2019/5/23 */ function create_image_path($save_dir = "", $image_ext = "", $image_root = IMG_PATH) { $image_dir = date("/Ymd/"); if ($image_dir) { $image_dir = ($save_dir ? "/" : '') . $save_dir . $image_dir; } // 未指定后缀默认使用JPG if (!$image_ext) { $image_ext = "jpg"; } $image_path = $image_root . $image_dir; if (!is_dir($image_path)) { // 创建目录并赋予权限 mkdir($image_path, 0777, true); } $file_name = substr(md5(time() . rand(0, 999999)), 8, 16) . rand(100, 999) . ".{$image_ext}"; $file_path = str_replace(ATTACHMENT_PATH, "", IMG_PATH) . $image_dir . $file_name; return $file_path; } } if (!function_exists('save_remote_image')) { /** * 保存网络图片到本地 * @param string $img_url 网络图片地址 * @param string $save_dir 保存目录 * @return bool|string 图片路径 * @author laravel开发员 * @date 2019/5/23 */ function save_remote_image($img_url, $save_dir = '/') { $content = file_get_contents($img_url); if (!$content) { return false; } if ($content[0] . $content[1] == "\xff\xd8") { $image_ext = 'jpg'; } elseif ($content[0] . $content[1] . $content[2] == "\x47\x49\x46") { $image_ext = 'gif'; } elseif ($content[0] . $content[1] . $content[2] == "\x89\x50\x4e") { $image_ext = 'png'; } else { // 不是有效图片 return false; } $save_path = create_image_path($save_dir, $image_ext); return file_put_contents(ATTACHMENT_PATH . $save_path, $content) ? $save_path : false; } } if (!function_exists('save_image_content')) { /** * 富文本信息处理 * @param string $content 富文本内容 * @param bool $title 标题 * @param string $path 图片存储路径 * @return bool|int 返回结果 * @author laravel开发员 * @date 2020-04-21 */ function save_image_content(&$content, $title = false, $path = 'article') { // 图片处理 preg_match_all("//i", str_ireplace("\\", "", $content), $match); if ($match[1]) { foreach ($match[1] as $id => $val) { $save_image = save_image($val, $path); if ($save_image) { $content = str_replace($val, "[IMG_URL]" . $save_image, $content); } } } // 视频处理 preg_match_all("//i", str_ireplace("\\", "", $content), $match2); if ($match2[1]) { foreach ($match2[1] as $vo) { $save_video = save_image($vo, $path); if ($save_video) { $content = str_replace($vo, "[IMG_URL]" . str_replace(ATTACHMENT_PATH, "", IMG_PATH) . $save_video, $content); } } } // 提示标签替换 if ((strpos($content, 'alt=\"\"') !== false) && $title) { $content = str_replace('alt=\"\"', 'alt=\"' . $title . '\"', $content); } return true; } } if (!function_exists('upload_image')) { /** * 上传图片 * @param $request 网络请求 * @param string $form_name 文件表单名 * @return array 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function upload_image($request, $form_name = 'file', $file_path = '', $userId = 0) { ob_clean(); // 检测请求中是否包含name=$form_name的上传文件 if (!$request->hasFile($form_name)) { return message("请上传文件", false); } // 文件对象 $file = $request->file($form_name); // 判断图片上传是否错误 if (!$file->isValid()) { // 文件上传失败 return message("上传文件验证失败", false); } // 文件原名 $original_name = $file->getClientOriginalName(); // 文件扩展名(文件后缀) $ext = $file->getClientOriginalExtension(); // 临时文件的绝对路径 $real_path = $file->getRealPath(); // 文件类型 $type = $file->getClientMimeType(); // 文件大小 $size = $file->getSize(); // 文件大小校验 if ($size > 5 * 1024 * 1024) { return message("文件大小超过了5M", false); } // 文件后缀校验 $ext = strtolower($ext); if(empty($ext)){ $extData = explode('.', $original_name); $ext = end($extData); } $ext_arr = array('jpg', 'jpeg', 'png', 'gif'); if (!in_array($ext, $ext_arr)) { return message("文件格式不正确:" . $ext, false); } // 文件路径 $file_dir = ($file_path ? ATTACHMENT_PATH . '/images/' . $file_path : UPLOAD_TEMP_PATH) . "/" . date('Ymd'); // 检测文件路径是否存在,不存在则创建 if (!file_exists($file_dir)) { mkdir($file_dir, 0777, true); } // 文件名称 $file_name = ($userId? $userId.'_'.str_replace('=','',base64_encode(date('YmdHis').$userId.$original_name)): str_replace('=','',base64_encode(date('YmdHis').$original_name))); $file_name = $file_name. '.' . $ext; $driver = \App\Services\ConfigService::make()->getConfigByCode('file_upload_driver','local'); if($driver == 'qiniu'){ // 上传云 $file_path = \App\Services\QiniuService::make()->upload($file_name, $file); }else{ // 重命名保存 $path = $file->move($file_dir, $file_name); // 文件临时路径 $file_path = str_replace(ATTACHMENT_PATH, '', $file_dir) . '/' . $file_name; } // 返回结果 $result = [ 'img_original_name' => $original_name, 'img_ext' => $ext, 'img_real_path' => $real_path, 'img_type' => $type, 'img_size' => $size, 'img_name' => $file_name, 'img_path' => $file_path, ]; return message(MESSAGE_OK, true, $result); } } if (!function_exists('upload_file')) { /** * 上传文件 * @param $request 网络请求 * @param string $form_name 文件表单名 * @return array 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function upload_file($request, $form_name = 'file', $file_path = '', $userId = 0) { // 检测请求中是否包含上传的文件 if (!$request->hasFile($form_name)) { return message("请上传文件"); } // 文件对象 $file = $request->file($form_name); // 判断图片上传是否错误 if (!$file->isValid()) { // 文件上传失败 return message("上传文件验证失败"); } // 文件原名 $original_name = $file->getClientOriginalName(); // 文件扩展名(文件后缀) $ext = $file->getClientOriginalExtension(); // 临时文件的绝对路径 $real_path = $file->getRealPath(); // 文件类型 $type = $file->getClientMimeType(); // 文件大小 $size = $file->getSize(); // 文件大小校验(MAX=5M) $file_max_size = 5 * 1024 * 1024; if ($size > $file_max_size) { return message("您上传的文件过大,最大值为" . $file_max_size / 1024 / 1024 . "MB"); } // 允许上传的文件后缀 $ext = strtolower($ext); $file_exts = array('xls', 'xlsx', 'csv'); if (!in_array($ext, $file_exts)) { return message("文件格式不正确:" . $ext); } // 文件路径 $file_dir = ($file_path ? ATTACHMENT_PATH . '/images/' . $file_path : UPLOAD_TEMP_PATH) . "/" . date('Ymd'); // 检测文件路径是否存在,不存在则创建 if (!file_exists($file_dir)) { mkdir($file_dir, 0777, true); } // 文件名称 $file_name = uniqid() . '.' . $ext; // 重命名保存 $path = $file->move($file_dir, $file_name); // 文件临时路径 $file_path = str_replace(IMG_PATH, '', $file_dir) . '/' . $file_name; // 返回结果 $result = [ 'file_original_name' => $original_name, 'file_ext' => $ext, 'file_real_path' => $real_path, 'file_type' => $type, 'file_size' => $size, 'file_name' => $file_name, 'file_path' => $file_path, ]; return message(MESSAGE_OK, true, $result); } } if (!function_exists('upload_video')) { /** * 上传视频文件 * @param $request 网络请求 * @param string $form_name 文件表单名 * @return array 返回结果 * @author laravel开发员 * @date 2019/5/23 */ function upload_video($request, $form_name = 'file', $file_path = '', $userId = 0) { // 检测请求中是否包含上传的文件 if (!$request->hasFile($form_name)) { return message("请上传文件"); } // 文件对象 $file = $request->file($form_name); // 判断图片上传是否错误 if (!$file->isValid()) { // 文件上传失败 return message("上传文件验证失败"); } // 文件原名 $original_name = $file->getClientOriginalName(); // 文件扩展名(文件后缀) $ext = $file->getClientOriginalExtension(); // 临时文件的绝对路径 $real_path = $file->getRealPath(); // 文件类型 $type = $file->getClientMimeType(); // 文件大小 $size = $file->getSize(); // 文件大小校验(MAX=100M) $file_max_size = 100 * 1024 * 1024; if ($size > $file_max_size) { return message("您上传的文件过大,最大值为" . $file_max_size / 1024 / 1024 . "MB"); } // 允许上传的文件后缀 $ext = strtolower($ext); $file_exts = array('mp4', 'wmv', 'mov'); if (!in_array($ext, $file_exts)) { return message("视频文件格式不正确:" . $ext); } // 文件路径 $file_dir = ($file_path ? ATTACHMENT_PATH . '/images/' . $file_path : UPLOAD_TEMP_PATH) . "/" . date('Ymd'); // 检测文件路径是否存在,不存在则创建 if (!file_exists($file_dir)) { mkdir($file_dir, 0777, true); } // 文件名称 $file_name = uniqid() . '.' . $ext; // 重命名保存 $path = $file->move($file_dir, $file_name); // 文件临时路径 $file_path = str_replace(IMG_PATH, '', $file_dir) . '/' . $file_name; // 返回结果 $result = [ 'file_original_name' => $original_name, 'file_ext' => $ext, 'file_real_path' => $real_path, 'file_type' => $type, 'file_size' => $size, 'file_name' => $file_name, 'file_path' => $file_path, ]; return message(MESSAGE_OK, true, $result); } } if (!function_exists('widget')) { /** * 加载系统组件,传入的名字会以目录和类名区别 * 如Home.Common就代表Widget目录下的Home/Common.php这个widget。 * @param $widgetName 组件名称 * @return bool|mixed * @author laravel开发员 * @date 2019/5/23 */ function widget($widgetName) { $widgetNameEx = explode('.', $widgetName); if (!isset($widgetNameEx[1])) { return false; } $widgetClass = 'App\\Widget\\' . $widgetNameEx[0] . '\\' . $widgetNameEx[1]; if (app()->bound($widgetName)) { return app()->make($widgetName); } app()->singleton($widgetName, function () use ($widgetClass) { return new $widgetClass(); }); return app()->make($widgetName); } } if (!function_exists('get_tree')) { function get_tree($datas, $pid = 0, $tempArr = []) { if (empty($datas)) { return false; } foreach ($datas as $key => $v) { $data = []; $id = isset($v['id']) ? $v['id'] : 0; $currentPid = isset($v['parent_id']) ? $v['parent_id'] : 0; $nickname = isset($v['nickname']) ? $v['nickname'] : ''; $username = isset($v['username']) ? $v['username'] : ''; $mobile = isset($v['mobile']) ? $v['mobile'] : ''; $data['id'] = $v['id']; $data['parent_id'] = $v['parent_id']; $data['mobile'] = $mobile; $data['label'] = $nickname . ($mobile ? "({$mobile})" : ""); if ($currentPid && $currentPid == $pid) { $data['children'] = get_tree($datas, $v['id'], []); $tempArr[] = $data; } else if ($currentPid == 0 && $pid == 0) { $data['children'] = get_tree($datas, $v['id'], []); $tempArr[$id] = $data; } } return array_values($tempArr); } } if (!function_exists('getSign')) { function getSign($str, $key = '') { if (empty($str)) { return false; } // 拼接密钥 $str .= '&key=' . ($key ? $key : env('APP_SIGN_KEY', 'app&688')); $str = md5($str); // MD5 运算 $sign = md5($str.substr($str,0,6)); $sign .= substr($str, 2, 4); $sign = strtoupper($sign); return $sign; } } if (!function_exists('arrayToStr')) { function arrayToStr($params) { $string = ''; if (!empty($params)) { ksort($params, SORT_REGULAR); $array = array(); foreach ($params as $key => &$value) { if($key != 'sign'){ // 过滤无法匹配校验的参数类型 if (!is_array($value) && $value !== 'undefined' && strtolower($value) != 'null' && !empty($value) && !preg_match("/^[0-9]{1,9}\.[0-9]{8,}$/", $value)) { $array[] = $key . '=' .trim($value); } } } $string = implode("&", $array); } return $string; } } if (!function_exists('arrayToUrl')) { function arrayToUrl($params) { $string = ''; if (!empty($params)) { ksort($params, SORT_REGULAR); $array = array(); foreach ($params as $key => $value) { if ($value != 'undefined') { $array[] = $key . '=' . (is_array($value) ? json_encode($value,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE) : $value); } } $string = implode("&", $array); } return $string; } } if (!function_exists('httpRequest')) { /** * * 接口请求 * @param $url 接口地址 * @param $data * @param $type * @param int $timeout * @return mixed * @author wesmiler */ function httpRequest($url, $data = '', $type = 'post', $cookie = '', $timeout = 60, $header=[]) { try { set_time_limit($timeout); $data = $data && is_array($data) ? http_build_query($data) : $data; $url = strtolower($type) == 'get' ? $url . (strpos($url, '?') === false ? '?' : '&') . $data : $url; $ch = curl_init($url); if (!empty($cookie)) { curl_setopt($ch, CURLOPT_COOKIE, $cookie); } if ($type == 'post') { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } if ($header) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } else { $header = ['User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1']; curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //禁止 cURL 验证对等证书 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //是否检测服务器的域名与证书上的是否一致 curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $ret = curl_exec($ch); $ret = trim($ret); curl_close($ch); if (!preg_match("/^{/", $ret)) { return ['code' => 'err', 'msg' => $ret]; } $retArr = $ret ? json_decode($ret, true) : ['code' => 'err', 'msg' => 'unknow error']; if (empty($retArr)) { $ret = iconv('gb2312', 'utf-8', $ret); $retArr = json_decode($ret, true); } } catch (\Exception $exception) { $retArr = ['code' => 'error', 'msg' => 'request error']; } return $retArr; } } if (!function_exists('getVersion')) { /** * 获取版本号 * @param $version * @return string|string[] */ function getVersion($version) { return $version ? intval(str_replace('.', '', $version)) : ''; } } if (!function_exists('formatDistance')) { /** * 格式化距离 * @param $distance * @return string */ function formatDistance($distance) { return ($distance > 1000 ? round($distance / 1000, 2) . 'km' : $distance . 'm'); } } if (!function_exists('moneyFormat')) { /** * 金额格式化 * @param $money * @param int $decimal 小数位数,默认2 * @param int $round 是否四舍五入 * @return string */ function moneyFormat($money, $decimal = 2, $round = false, $charset = 'utf-8') { if ($round) { $money = number_format($money, $decimal); } else { $money = round($money, $decimal + 1); $data = explode('.', $money); $money = isset($data[0]) ? $data[0] : 0; $float = isset($data[1]) ? $data[1] : ''; $len = $float ? mb_strlen($float, $charset) : 0; $decimal = $decimal >= 0 ? intval($decimal) : 2; $num1 = isset($data[1]) ? $data[1] : ''; $float = $len >= $decimal ? mb_substr($num1, 0, $decimal, $charset) : $float . str_repeat('0', $decimal - $len); $money = $money . '.' . $float; $money = number_format($money, $decimal, '.', ''); } return $money; } } if(!function_exists('getChatKey')){ /** * 获取聊天窗口KEY * @param $fromUserId * @param $toUserId * @return false|string */ function getChatKey($fromUserId, $toUserId) { if(empty($fromUserId) || empty($toUserId)){ return false; } $ids = [$fromUserId, $toUserId]; asort($ids); return implode('_', $ids); } } if(!function_exists('getDistance')) { /** * 计算地图坐标距离/米 * @param $lat * @param $lng * @param $toLat * @param $toLng * @return float */ function getDistance($lat, $lng, $toLat, $toLng) { return ROUND(6378.138 * 2 * ASIN( SQRT( POW( SIN( ($lat * PI() / 180 - $toLat * PI() / 180 ) / 2 ), 2 ) + COS($lat * PI() / 180) * COS($toLat * PI() / 180) * POW( SIN( ($lng * PI() / 180 - $toLng * PI() / 180 ) / 2 ), 2))) * 1000); } } if(!function_exists('getParents')){ /** * 获取分销上级用户ID * @param $parents * @return array|false */ function getParents($parents, $level=3){ $parents = $parents? explode(',', $parents) : []; $parents = array_filter($parents); if(empty($parents)){ return false; } $parents = array_slice($parents, -$level); return array_reverse($parents); } } if(!function_exists('getMillSecondTime')){ /** * 获取毫秒时间戳 * @return float */ function getMillSecondTime() { list($msec, $sec) = explode(' ', microtime()); return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000); } } if(!function_exists('getPriceData')){ /** * 格式化价格数据 * @param $prices * @return array|false|string[] */ function getPriceData($prices) { $datas = []; $prices = $prices? explode('|', $prices) : []; if($prices){ foreach ($prices as $item){ $data = $item? explode(':',$item) : []; $num = isset($data[0]) && $data[0]? $data[0] : ''; $price = isset($data[1])? $data[1] : 0; if($num && $price){ $datas[] = [ 'distance'=> $num, 'price'=> $price, ]; } } } return $datas; } } if (!function_exists('api_decrypt')) { function api_decrypt($data, $key = '', $type = 'json') { if (empty($data)) { return false; } $key = $key ? $key : env('API_KEY', ''); $iv = substr($key, 0, 14) . 'IV'; $data = openssl_decrypt(hex2bin(strtolower($data)), 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv); return $type == 'json' ? json_decode($data, true) : $data; } } if (!function_exists('format_message')){ /** * 格式化消息内容 * @param $message * @return false|string|string[]|null */ function format_message($message){ if(empty($message)){ return false; } $pattern = "/((https|http|ftp):\/\/((\w+(\-)?\w+(\.)){0,2}\w+\.[a-z]{2,3}(\/[a-zA-Z0-9\_\.]{1,50}(\.php|\.html|\.js|\.htm|\.apk)?){0,5})([\?&]\w+=\w*){0,5}(\s?))/u"; $message = preg_replace($pattern,'$1', $message); return format_content($message); } }