insert($data); } } if (!function_exists('handleSource')) { /** * 来源转换 * @param $source * @return string */ function handleSource($source) { $name = ''; switch ($source) { case 'wxMiniProgram' : $name = 'minapp'; break; case 'App' : $name = 'app'; break; case 'H5' : $name = 'h5'; break; } return $name; } } if (!function_exists('hideStr')) { /** * 将一个字符串部分字符用$re替代隐藏 * @param string $string 待处理的字符串 * @param int $start 规定在字符串的何处开始, * 正数 - 在字符串的指定位置开始 * 负数 - 在从字符串结尾的指定位置开始 * 0 - 在字符串中的第一个字符处开始 * @param int $length 可选。规定要隐藏的字符串长度。默认是直到字符串的结尾。 * 正数 - 从 start 参数所在的位置隐藏 * 负数 - 从字符串末端隐藏 * @param string $re 替代符 * @return string 处理后的字符串 */ function hideStr($string, $start = 0, $length = 0, $re = '*') { if (empty($string)) return false; $strArr = []; $mbStrLen = mb_strlen($string); while ($mbStrLen) { $strArr[] = mb_substr($string, 0, 1, 'utf8'); $string = mb_substr($string, 1, $mbStrLen, 'utf8'); $mbStrLen = mb_strlen($string); } $strLen = count($strArr); $begin = $start >= 0 ? $start : ($strLen - abs($start)); $end = $last = $strLen - 1; if ($length > 0) { $end = $begin + $length - 1; } elseif ($length < 0) { $end -= abs($length); } for ($i = $begin; $i <= $end; $i++) { $strArr[$i] = $re; } // if ($begin >= $end || $begin >= $last || $end > $last) return false; return implode('', $strArr); } } if (!function_exists('getUserVipPriceSku')) { /** * 获取单独sku里的vip价格 * @param $user * @param $skuPrice * @param bool $isActivity * @param bool $jsonEncode * @return mixed */ function getUserVipPriceSku($user, $skuPrice, $isActivity = false, $jsonEncode = false) { if (empty($user)) { return $skuPrice; } // 查看是否是vip $groupId = Db::name('user_group') ->where(['id' => $user->group_id, 'is_vip' => 1]) ->value('id'); if (empty($groupId)) { return $skuPrice; } // 获取vip价格 $vipList = $jsonEncode ? json_decode($skuPrice['vip'], true) : $skuPrice['vip']; if (empty($vipList)) { return $skuPrice; } $vipPrice = 0; $isVipPrice = false; foreach ($vipList as $v) { if ($v['id'] == $groupId) { $vipPrice = $v['price']; $isVipPrice = true; } } // 如果是促销活动并且有会员等级则需要做价格对比,谁的价格低则使用谁的 if ($isVipPrice && $isActivity && !empty($skuPrice['item_goods_sku_price'])) { if ($vipPrice > $skuPrice['item_goods_sku_price']['price']) { $vipPrice = $skuPrice['item_goods_sku_price']['price']; } } $skuPrice['price'] = !empty($vipPrice) ? bcadd($vipPrice, 0, 2) : $skuPrice['price']; return $skuPrice; } } if (!function_exists('arrayGroupByKey')) { /** * 根据数组中某个值进行分组 * @param $arr * @param $key * @return array */ function arrayGroupByKey($arr, $key) { $groupArr = []; foreach ($arr as $item) { if (array_key_exists($key, $item)) { $groupArr[$item[$key]][] = $item; } } return $groupArr; } } if (!function_exists('arrayValueExists')) { /** * 查询多维数组中是否存在某个值 * @param $arr * @param $field * @param $val * @return bool */ function arrayValueExists($arr, $field, $val) { $flag = false; if (empty($arr)) { return $flag; } foreach ($arr as $v) { if ($v[$field] == $val) { $flag = true; break; } } return $flag; } } if (!function_exists('getUserVipPrice')) { /** * 获取会员价格 * @param $user * @param $goods * @param bool $jsonEncode * @return mixed */ function getUserVipPrice($user, $goods, $jsonEncode = false) { // 只有普通商品和限时促销商品可显示vip价格 if (!empty($goods['activity'])) { if ($goods['activity']['type'] != 'promote') { return $goods; } } if (empty($user)) { return $goods; } // 查看是否是vip $groupId = Db::name('user_group') ->where(['id' => $user->group_id, 'is_vip' => 1]) ->value('id'); if (empty($groupId)) { return $goods; } // 最低价 $price = 0; // 是否有vip价格 $isVipPrice = false; // 多规格 foreach ($goods['sku_price'] as $k => &$val) { if ($val['status'] == 'down') { continue; } // 获取vip价格 $vipList = $jsonEncode ? json_decode($val['vip'], true) : $val['vip']; if (empty($vipList)) { continue; } $vipPrice = 0; foreach ($vipList as $v) { if ($v['id'] == $groupId) { $vipPrice = $v['price']; $isVipPrice = true; } } // 如果是促销活动并且有会员等级则需要做价格对比,谁的价格低则使用谁的 if (!empty($goods['activity']) && $goods['activity']['type'] == 'promote' && $isVipPrice && !empty($val['item_goods_sku_price'])) { if ($vipPrice > $val['item_goods_sku_price']['price']) { $vipPrice = $val['item_goods_sku_price']['price']; } } $val['price'] = !empty($vipPrice) ? bcadd($vipPrice, 0, 2) : $val['price']; // 获取最低的价格 if (empty($price)) { $price = $val['price']; } else { $price = $price > $val['price'] ? $val['price'] : $price; } } // 最低价 if (!empty($isVipPrice)) { $goods['original_price'] = $goods['price']; $goods['price'] = $price; } return $goods; } } if (!function_exists('downImage')) { // 图片下载 function downImage($url = '', $domain = '') { // 防止下载多图的时候超时 set_time_limit(0); if (empty($url)) { return '图片url不能为空'; } if (strrpos($url, 'http://') === false && strrpos($url, 'https://') === false) { return '请您传递正确的图片url地址'; } // 判断后缀是否是图片文件 $ext = trim(strrchr($url, '.')); $extArr = ['.jpg', '.jpeg', '.gif', '.png', '.bmp', '.JPG', '.JPEG', '.GIF', '.PNG', '.BMP']; if (!in_array($ext, $extArr)) { return '图片格式不正确'; } $https = false; if (stripos($url, 'https://') !== false) { $https = true; } // curl远程获取图片 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_REFERER, $domain); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if ($https === true) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } $file = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); var_dump($file); exit; if ($httpCode === 200) { // 文件名 $fName = substr(strrchr($url, '/'), 1); // 创建目录 $path = substr(str_replace($fName, '', $url), 0, -1); $path = preg_replace('/^[a-z]+:\/\/[\w\.\?\=\&]+\/([^>]+)$/', '$1', $path); if (is_dir(ROOT_PATH . 'public' . DS . $path) === false) { $pathArr = explode('/', $path); // 层级创建目录 $currentDir = ''; foreach ($pathArr as $v) { $currentDir .= $v . DS; $dirPath = ROOT_PATH . 'public' . DS . $currentDir; if (is_dir($dirPath) === false) { $w = umask(0); mkdir($dirPath, 0777, true); umask($w); } } } // 保存图片到本地 $fileName = DS . $path . DS . $fName; $filePath = ROOT_PATH . 'public' . $fileName; $fp = fopen($filePath, 'a'); fwrite($fp, $file); fclose($fp); return file_exists($filePath) ? str_replace('\\', '/', $fileName) : 404; } if ($httpCode === 0) { return $url; } return 404; } } if (!function_exists('getVideoUrl')) { /** * 获取播放地址 * @param $domain * @param $streamName * @param null $key * @param null $time * @return string */ function getVideoUrl($domain, $streamName, $key = null, $time = null) { if ($key && $time) { $txTime = strtoupper(base_convert(strtotime($time), 10, 16)); $txSecret = md5($key . $streamName . $txTime); $ext_str = '?' . http_build_query([ 'txSecret' => $txSecret, 'txTime' => $txTime ]); } return "http://" . $domain . "/live/" . $streamName . '.flv' . (isset($ext_str) ? $ext_str : ""); } } if (!function_exists('getPushUrl')) { /** * 获取推流地址 * 如果不传key和过期时间,将返回不含防盗链的url * @param domain 您用来推流的域名 * streamName 您用来区别不同推流地址的唯一流名称 * key 安全密钥 * time 过期时间 sample 2016-11-12 12:00:00 * @return String url */ function getPushUrl($domain, $streamName, $key = null, $time = null) { if ($key && $time) { $txTime = strtoupper(base_convert(strtotime($time), 10, 16)); //txSecret = MD5( KEY + streamName + txTime ) $txSecret = md5($key . $streamName . $txTime); $ext_str = '?' . http_build_query([ 'txSecret' => $txSecret, 'txTime' => $txTime ]); } return "rtmp://" . $domain . "/live/" . $streamName . (isset($ext_str) ? $ext_str : ""); } } if (!function_exists('randomSelectArr')) { /** * 随机获取数组数据 * @param $array * @param $number * @return array */ function randomSelectArr($array, $number) { $length = count($array); $result = []; for ($i = 0; $i < $number; $i++) { $randomIndex = rand(0, $length - 1); $result[] = $array[$randomIndex]; } return $result; } } if (!function_exists('getSn')) { /** * 生成订单号 * @param $user_id * @return string */ function getSn($user_id) { $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999); $order_sn = date('Yhis') . $rand; $id = str_pad($user_id, (24 - strlen($order_sn)), '0', STR_PAD_BOTH); return $order_sn . $id; } } if (!function_exists('__')) { /** * 获取语言变量值 * @param string $name 语言变量名 * @param array $vars 动态变量值 * @param string $lang 语言 * @return mixed */ function __($name, $vars = [], $lang = '') { if (is_numeric($name) || !$name) { return $name; } if (!is_array($vars)) { $vars = func_get_args(); array_shift($vars); $lang = ''; } return \think\Lang::get($name, $vars, $lang); } } if (!function_exists('format_bytes')) { /** * 将字节转换为可读文本 * @param int $size 大小 * @param string $delimiter 分隔符 * @param int $precision 小数位数 * @return string */ function format_bytes($size, $delimiter = '', $precision = 2) { $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); for ($i = 0; $size >= 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 = is_array($url) ? $url[0] : $url; if (is_bool($domain) || stripos($cdnurl, '/') === 0) { $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'] = $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'] = $v['display'] ?? str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']); $v['primary'] = $v['primary'] ?? ''; $v['column'] = $v['column'] ?? 'name'; $v['model'] = $v['model'] ?? ''; $v['table'] = $v['table'] ?? ''; $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 $replaced[$matches[1]] ?? "''"; }, $dump); } if ($return === true) { return $dump; } else { echo $dump; } } } if (!function_exists('getNavArrData')) { function getNavArrData($id) { if (empty($id)) { return $id; } // 是否有上级 $pid = \think\Db::name('attachment_nav') ->where(['id' => $id]) ->value('pid'); return !empty($pid) ? [$pid, $id] : [$id]; } } 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('' . $first . ''); $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'] && config('fastadmin.cors_request_domain')) { $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('url_clean')) { /** * 清理URL */ function url_clean($url) { if (!check_url_allowed($url)) { return ''; } return xss_clean($url); } } 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('check_url_allowed')) { /** * 检测URL是否允许 * @param string $url URL * @return bool */ function check_url_allowed($url = '') { //允许的主机列表 $allowedHostArr = [ strtolower(request()->host()) ]; if (empty($url)) { return true; } //如果是站内相对链接则允许 if (preg_match("/^[\/a-z][a-z0-9][a-z0-9\.\/]+((\?|#).*)?\$/i", $url) && substr($url, 0, 2) !== '//') { return true; } //如果是站外链接则需要判断HOST是否允许 if (preg_match("/((http[s]?:\/\/)+(?>[a-z\-0-9]{2,}\.){1,}[a-z]{2,8})(?:\s|\/)/i", $url)) { $chkHost = parse_url(strtolower($url), PHP_URL_HOST); if ($chkHost && in_array($chkHost, $allowedHostArr)) { return true; } } return false; } } 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; } }