| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603 |
- <?php
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // +----------------------------------------------------------------------
- // | 全局函数文件
- // +----------------------------------------------------------------------
- use think\App;
- use think\facade\Config;
- use think\facade\Request;
- !defined('DS') && define('DS', DIRECTORY_SEPARATOR);
- // 运行目录
- define('ROOT_URL', Request::rootUrl() . '/');
- //模板目录
- define('TEMPLATE_PATH', App::getRootPath() . 'templates' . DS);
- if (!function_exists('cdnurl')) {
- /**
- * 获取上传资源的CDN的地址
- * @param string $url 资源相对地址
- * @param string|bool $domain 是否显示域名 或者直接传入域名
- * @return string
- */
- function cdnurl(string $url, string | bool $domain = false): string
- {
- $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
- $cdnurl = Config::get('upload.cdnurl');
- 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('str_cut')) {
- /**
- * 字符截取
- * @param string $sourcestr 需要截取的字符串
- * @param int $length 长度
- * @param string $dot
- * @return string
- */
- function str_cut($sourcestr, $length, string $dot = '...')
- {
- $returnstr = '';
- $i = 0;
- $n = 0;
- $str_length = strlen($sourcestr); //字符串的字节数
- while (($n < $length) && ($i <= $str_length)) {
- $temp_str = substr($sourcestr, $i, 1);
- $ascnum = Ord($temp_str); //得到字符串中第$i位字符的ascii码
- if ($ascnum >= 224) {
- //如果ASCII位高与224,
- $returnstr = $returnstr . substr($sourcestr, $i, 3); //根据UTF-8编码规范,将3个连续的字符计为单个字符
- $i = $i + 3; //实际Byte计为3
- $n++; //字串长度计1
- } elseif ($ascnum >= 192) {
- //如果ASCII位高与192,
- $returnstr = $returnstr . substr($sourcestr, $i, 2); //根据UTF-8编码规范,将2个连续的字符计为单个字符
- $i = $i + 2; //实际Byte计为2
- $n++; //字串长度计1
- } elseif ($ascnum >= 65 && $ascnum <= 90) {
- //如果是大写字母,
- $returnstr = $returnstr . substr($sourcestr, $i, 1);
- $i = $i + 1; //实际的Byte数仍计1个
- $n++; //但考虑整体美观,大写字母计成一个高位字符
- } else {
- //其他情况下,包括小写字母和半角标点符号,
- $returnstr = $returnstr . substr($sourcestr, $i, 1);
- $i = $i + 1; //实际的Byte数计1个
- $n = $n + 0.5; //小写字母和半角标点等与半个高位字符宽...
- }
- }
- if ($str_length > strlen($returnstr)) {
- $returnstr = $returnstr . $dot; //超过长度时在尾处加上省略号
- }
- return $returnstr;
- }
- }
- if (!function_exists('parse_attr')) {
- /**
- * 解析配置
- * @param string $value 配置值
- * @return array|string
- */
- function parse_attr(string $value = '')
- {
- $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
- if (strpos($value, ':')) {
- $value = [];
- foreach ($array as $val) {
- [$k, $v] = explode(':', $val);
- $value[$k] = $v;
- }
- } else {
- $value = $array;
- }
- return $value;
- }
- }
- if (!function_exists('time_format')) {
- /**
- * 时间戳格式化
- * @param int|null $timestamp
- * @param int $type
- * @return string 完整的时间显示
- */
- function time_format(?int $timestamp = null, int $type = 0)
- {
- if ($timestamp == 0) {
- return '';
- }
- $types = ['Y-m-d H:i:s', 'Y-m-d H:i', 'Y-m-d'];
- $timestamp = $timestamp === null ? $_SERVER['REQUEST_TIME'] : intval($timestamp);
- return date($types[$type], $timestamp);
- }
- }
- if (!function_exists('human_date')) {
- /**
- * 获取语义化时间
- * @param int $time 时间
- * @param int $local 本地时间
- * @return string
- */
- function human_date($time, $local = null)
- {
- return \util\Date::human($time, $local);
- }
- }
- if (!function_exists('format_bytes')) {
- /**
- * 格式化字节大小
- * @param float|int $size 字节数
- * @param string $delimiter 数字和单位分隔符
- * @return string 格式化后的带单位的大小
- */
- function format_bytes(float | int $size, string $delimiter = ''): string
- {
- $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
- for ($i = 0; $size >= 1024 && $i < 5; $i++) {
- $size /= 1024;
- }
- return round($size, 2) . $delimiter . $units[$i];
- }
- }
- if (!function_exists('to_guid_string')) {
- /**
- * 根据PHP各种类型变量生成唯一标识号
- * @param mixed $mix 变量
- * @return string
- */
- function to_guid_string(mixed $mix): string
- {
- if (is_object($mix)) {
- return spl_object_hash($mix);
- } elseif (is_resource($mix)) {
- $mix = get_resource_type($mix) . strval($mix);
- } else {
- $mix = serialize($mix);
- }
- return md5($mix);
- }
- }
- if (!function_exists('encrypt_password')) {
- /**
- * 对用户的密码进行加密
- * @param string $password 明文密码
- * @param string $encrypt 传入加密串,在修改密码时做认证
- * @param string $fun 加密函数
- * @return array|mixed
- */
- function encrypt_password(string $password, string $encrypt = '', string $fun = 'md5'): mixed
- {
- $pwd = [];
- $pwd['encrypt'] = $encrypt ?: genRandomString();
- $pwd['password'] = $fun($fun($password) . $pwd['encrypt']);
- return $encrypt ? $pwd['password'] : $pwd;
- }
- }
- if (!function_exists('genRandomString')) {
- /**
- * 产生一个指定长度的随机字符串,并返回给用户
- * @param int $len 产生字符串的长度
- * @return string 随机字符串
- */
- function genRandomString(int $len = 6): string
- {
- $chars = [
- "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
- "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
- "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
- "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
- "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
- "3", "4", "5", "6", "7", "8", "9",
- ];
- $charsLen = count($chars) - 1;
- // 将数组打乱
- shuffle($chars);
- $output = "";
- for ($i = 0; $i < $len; $i++) {
- $output .= $chars[mt_rand(0, $charsLen)];
- }
- return $output;
- }
- }
- if (!function_exists('http_down')) {
- /**
- * 下载远程文件,默认保存在temp下
- * @param string $url 网址
- * @param string $filename 保存文件名
- * @param integer $timeout 过期时间
- * @return string 本地文件名
- */
- function http_down($url, $filename = "", $timeout = 60)
- {
- if (empty($filename)) {
- $filename = public_path() . 'temp' . DS . pathinfo($url, PATHINFO_BASENAME);
- }
- $path = dirname($filename);
- if (!is_dir($path) && !mkdir($path, 0755, true)) {
- return false;
- }
- $url = str_replace(" ", "%20", $url);
- if (function_exists('curl_init')) {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
- // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
- if ('https' == substr($url, 0, 5)) {
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- }
- $temp = curl_exec($ch);
- if (file_put_contents($filename, $temp) && !curl_error($ch)) {
- return $filename;
- } else {
- return false;
- }
- } else {
- $opts = [
- "http" => [
- "method" => "GET",
- "header" => "",
- "timeout" => $timeout,
- ],
- ];
- $context = stream_context_create($opts);
- if (@copy($url, $filename, $context)) {
- //$http_response_header
- return $filename;
- } else {
- return false;
- }
- }
- }
- }
- if (!function_exists('safe_replace')) {
- /**
- * 安全过滤函数
- * @param $string
- * @return string
- */
- function safe_replace($string)
- {
- $string = str_replace('%20', '', $string);
- $string = str_replace('%27', '', $string);
- $string = str_replace('%2527', '', $string);
- $string = str_replace('*', '', $string);
- $string = str_replace('"', '"', $string);
- $string = str_replace("'", '', $string);
- $string = str_replace('"', '', $string);
- $string = str_replace(';', '', $string);
- $string = str_replace('<', '<', $string);
- $string = str_replace('>', '>', $string);
- $string = str_replace("{", '', $string);
- $string = str_replace('}', '', $string);
- $string = str_replace('\\', '', $string);
- return $string;
- }
- }
- if (!function_exists('sys_auth')) {
- /**
- * 字符串加密、解密函数
- * @param string $string
- * @param string $operation ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
- * @param string $key 密钥:数字、字母、下划线
- * @param int $expiry 过期时间
- * @return string
- */
- function sys_auth(string $string, string $operation = 'ENCODE', string $key = '', int $expiry = 0): string
- {
- $ckey_length = 4;
- $key = md5($key != '' ? $key : Config::get('yzn.data_auth_key'));
- $keya = md5(substr($key, 0, 16));
- $keyb = md5(substr($key, 16, 16));
- $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
- $cryptkey = $keya . md5($keya . $keyc);
- $key_length = strlen($cryptkey);
- $string = $operation == 'DECODE' ? base64_decode(strtr(substr($string, $ckey_length), '-_', '+/')) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
- $string_length = strlen($string);
- $result = '';
- $box = range(0, 255);
- $rndkey = [];
- for ($i = 0; $i <= 255; $i++) {
- $rndkey[$i] = ord($cryptkey[$i % $key_length]);
- }
- for ($j = $i = 0; $i < 256; $i++) {
- $j = ($j + $box[$i] + $rndkey[$i]) % 256;
- $tmp = $box[$i];
- $box[$i] = $box[$j];
- $box[$j] = $tmp;
- }
- for ($a = $j = $i = 0; $i < $string_length; $i++) {
- $a = ($a + 1) % 256;
- $j = ($j + $box[$a]) % 256;
- $tmp = $box[$a];
- $box[$a] = $box[$j];
- $box[$j] = $tmp;
- $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
- }
- if ($operation == 'DECODE') {
- if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
- return substr($result, 26);
- } else {
- return '';
- }
- } else {
- return $keyc . rtrim(strtr(base64_encode($result), '+/', '-_'), '=');
- }
- }
- }
- if (!function_exists('hsv2rgb')) {
- function hsv2rgb($h, $s, $v): array
- {
- $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('letter_avatar')) {
- /**
- * 首字母头像
- * @param string $text
- * @return string
- */
- function letter_avatar(string $text): string
- {
- $total = unpack('L', hash('adler32', $text, true))[1];
- $hue = $total % 360;
- [$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('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
- return 'data:image/svg+xml;base64,' . $src;
- }
- }
- if (!function_exists('build_suffix_image')) {
- /**
- * 生成文件后缀图片
- * @param string $suffix 后缀
- * @param ?string $background 背景颜色
- * @return string
- */
- function build_suffix_image(string $suffix, ?string $background = null): string
- {
- $suffix = mb_substr(strtoupper($suffix), 0, 4);
- $total = unpack('L', hash('adler32', $suffix, true))[1];
- $hue = $total % 360;
- [$r, $g, $b] = hsv2rgb($hue / 360, 0.3, 0.9);
- $background = $background ?: "rgb({$r},{$g},{$b})";
- return <<<EOT
- <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
- <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
- <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
- <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
- <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
- <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
- <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
- </svg>
- EOT;
- }
- }
- if (!function_exists('xss_clean')) {
- /**
- * 清理XSS
- * @param array|string $content
- * @param bool $is_image
- * @return bool|string|string[]
- */
- function xss_clean(array | string $content, bool $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_url_allowed')) {
- /**
- * 检测URL是否允许范围内
- * @param string $url
- * @return bool
- */
- function check_url_allowed(string $url = ''): bool
- {
- //允许的主机列表
- $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('check_nav_active')) {
- /**
- * 检测会员中心导航是否高亮
- */
- function check_nav_active($url, $classname = 'layui-this')
- {
- $auth = \app\common\library\Auth::instance();
- $requestUrl = $auth->getRequestUri();
- $url = ltrim($url, '/');
- return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
- }
- }
- 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;
- }
- }
- }
|