common.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // |
  4. // +----------------------------------------------------------------------
  5. // |
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // |
  10. // +----------------------------------------------------------------------
  11. // +----------------------------------------------------------------------
  12. // | 全局函数文件
  13. // +----------------------------------------------------------------------
  14. use think\App;
  15. use think\facade\Config;
  16. use think\facade\Request;
  17. !defined('DS') && define('DS', DIRECTORY_SEPARATOR);
  18. // 运行目录
  19. define('ROOT_URL', Request::rootUrl() . '/');
  20. //模板目录
  21. define('TEMPLATE_PATH', App::getRootPath() . 'templates' . DS);
  22. if (!function_exists('cdnurl')) {
  23. /**
  24. * 获取上传资源的CDN的地址
  25. * @param string $url 资源相对地址
  26. * @param string|bool $domain 是否显示域名 或者直接传入域名
  27. * @return string
  28. */
  29. function cdnurl(string $url, string | bool $domain = false): string
  30. {
  31. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  32. $cdnurl = Config::get('upload.cdnurl');
  33. if (is_bool($domain) || stripos($cdnurl, '/') === 0) {
  34. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  35. }
  36. if ($domain && !preg_match($regex, $url)) {
  37. $domain = is_bool($domain) ? Request::domain() : $domain;
  38. $url = $domain . $url;
  39. }
  40. return $url;
  41. }
  42. }
  43. if (!function_exists('str_cut')) {
  44. /**
  45. * 字符截取
  46. * @param string $sourcestr 需要截取的字符串
  47. * @param int $length 长度
  48. * @param string $dot
  49. * @return string
  50. */
  51. function str_cut($sourcestr, $length, string $dot = '...')
  52. {
  53. $returnstr = '';
  54. $i = 0;
  55. $n = 0;
  56. $str_length = strlen($sourcestr); //字符串的字节数
  57. while (($n < $length) && ($i <= $str_length)) {
  58. $temp_str = substr($sourcestr, $i, 1);
  59. $ascnum = Ord($temp_str); //得到字符串中第$i位字符的ascii码
  60. if ($ascnum >= 224) {
  61. //如果ASCII位高与224,
  62. $returnstr = $returnstr . substr($sourcestr, $i, 3); //根据UTF-8编码规范,将3个连续的字符计为单个字符
  63. $i = $i + 3; //实际Byte计为3
  64. $n++; //字串长度计1
  65. } elseif ($ascnum >= 192) {
  66. //如果ASCII位高与192,
  67. $returnstr = $returnstr . substr($sourcestr, $i, 2); //根据UTF-8编码规范,将2个连续的字符计为单个字符
  68. $i = $i + 2; //实际Byte计为2
  69. $n++; //字串长度计1
  70. } elseif ($ascnum >= 65 && $ascnum <= 90) {
  71. //如果是大写字母,
  72. $returnstr = $returnstr . substr($sourcestr, $i, 1);
  73. $i = $i + 1; //实际的Byte数仍计1个
  74. $n++; //但考虑整体美观,大写字母计成一个高位字符
  75. } else {
  76. //其他情况下,包括小写字母和半角标点符号,
  77. $returnstr = $returnstr . substr($sourcestr, $i, 1);
  78. $i = $i + 1; //实际的Byte数计1个
  79. $n = $n + 0.5; //小写字母和半角标点等与半个高位字符宽...
  80. }
  81. }
  82. if ($str_length > strlen($returnstr)) {
  83. $returnstr = $returnstr . $dot; //超过长度时在尾处加上省略号
  84. }
  85. return $returnstr;
  86. }
  87. }
  88. if (!function_exists('parse_attr')) {
  89. /**
  90. * 解析配置
  91. * @param string $value 配置值
  92. * @return array|string
  93. */
  94. function parse_attr(string $value = '')
  95. {
  96. $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
  97. if (strpos($value, ':')) {
  98. $value = [];
  99. foreach ($array as $val) {
  100. [$k, $v] = explode(':', $val);
  101. $value[$k] = $v;
  102. }
  103. } else {
  104. $value = $array;
  105. }
  106. return $value;
  107. }
  108. }
  109. if (!function_exists('time_format')) {
  110. /**
  111. * 时间戳格式化
  112. * @param int|null $timestamp
  113. * @param int $type
  114. * @return string 完整的时间显示
  115. */
  116. function time_format(?int $timestamp = null, int $type = 0)
  117. {
  118. if ($timestamp == 0) {
  119. return '';
  120. }
  121. $types = ['Y-m-d H:i:s', 'Y-m-d H:i', 'Y-m-d'];
  122. $timestamp = $timestamp === null ? $_SERVER['REQUEST_TIME'] : intval($timestamp);
  123. return date($types[$type], $timestamp);
  124. }
  125. }
  126. if (!function_exists('human_date')) {
  127. /**
  128. * 获取语义化时间
  129. * @param int $time 时间
  130. * @param int $local 本地时间
  131. * @return string
  132. */
  133. function human_date($time, $local = null)
  134. {
  135. return \util\Date::human($time, $local);
  136. }
  137. }
  138. if (!function_exists('format_bytes')) {
  139. /**
  140. * 格式化字节大小
  141. * @param float|int $size 字节数
  142. * @param string $delimiter 数字和单位分隔符
  143. * @return string 格式化后的带单位的大小
  144. */
  145. function format_bytes(float | int $size, string $delimiter = ''): string
  146. {
  147. $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
  148. for ($i = 0; $size >= 1024 && $i < 5; $i++) {
  149. $size /= 1024;
  150. }
  151. return round($size, 2) . $delimiter . $units[$i];
  152. }
  153. }
  154. if (!function_exists('to_guid_string')) {
  155. /**
  156. * 根据PHP各种类型变量生成唯一标识号
  157. * @param mixed $mix 变量
  158. * @return string
  159. */
  160. function to_guid_string(mixed $mix): string
  161. {
  162. if (is_object($mix)) {
  163. return spl_object_hash($mix);
  164. } elseif (is_resource($mix)) {
  165. $mix = get_resource_type($mix) . strval($mix);
  166. } else {
  167. $mix = serialize($mix);
  168. }
  169. return md5($mix);
  170. }
  171. }
  172. if (!function_exists('encrypt_password')) {
  173. /**
  174. * 对用户的密码进行加密
  175. * @param string $password 明文密码
  176. * @param string $encrypt 传入加密串,在修改密码时做认证
  177. * @param string $fun 加密函数
  178. * @return array|mixed
  179. */
  180. function encrypt_password(string $password, string $encrypt = '', string $fun = 'md5'): mixed
  181. {
  182. $pwd = [];
  183. $pwd['encrypt'] = $encrypt ?: genRandomString();
  184. $pwd['password'] = $fun($fun($password) . $pwd['encrypt']);
  185. return $encrypt ? $pwd['password'] : $pwd;
  186. }
  187. }
  188. if (!function_exists('genRandomString')) {
  189. /**
  190. * 产生一个指定长度的随机字符串,并返回给用户
  191. * @param int $len 产生字符串的长度
  192. * @return string 随机字符串
  193. */
  194. function genRandomString(int $len = 6): string
  195. {
  196. $chars = [
  197. "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
  198. "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
  199. "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
  200. "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
  201. "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
  202. "3", "4", "5", "6", "7", "8", "9",
  203. ];
  204. $charsLen = count($chars) - 1;
  205. // 将数组打乱
  206. shuffle($chars);
  207. $output = "";
  208. for ($i = 0; $i < $len; $i++) {
  209. $output .= $chars[mt_rand(0, $charsLen)];
  210. }
  211. return $output;
  212. }
  213. }
  214. if (!function_exists('http_down')) {
  215. /**
  216. * 下载远程文件,默认保存在temp下
  217. * @param string $url 网址
  218. * @param string $filename 保存文件名
  219. * @param integer $timeout 过期时间
  220. * @return string 本地文件名
  221. */
  222. function http_down($url, $filename = "", $timeout = 60)
  223. {
  224. if (empty($filename)) {
  225. $filename = public_path() . 'temp' . DS . pathinfo($url, PATHINFO_BASENAME);
  226. }
  227. $path = dirname($filename);
  228. if (!is_dir($path) && !mkdir($path, 0755, true)) {
  229. return false;
  230. }
  231. $url = str_replace(" ", "%20", $url);
  232. if (function_exists('curl_init')) {
  233. $ch = curl_init();
  234. curl_setopt($ch, CURLOPT_URL, $url);
  235. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  236. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  237. // curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
  238. // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  239. if ('https' == substr($url, 0, 5)) {
  240. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  241. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  242. }
  243. $temp = curl_exec($ch);
  244. if (file_put_contents($filename, $temp) && !curl_error($ch)) {
  245. return $filename;
  246. } else {
  247. return false;
  248. }
  249. } else {
  250. $opts = [
  251. "http" => [
  252. "method" => "GET",
  253. "header" => "",
  254. "timeout" => $timeout,
  255. ],
  256. ];
  257. $context = stream_context_create($opts);
  258. if (@copy($url, $filename, $context)) {
  259. //$http_response_header
  260. return $filename;
  261. } else {
  262. return false;
  263. }
  264. }
  265. }
  266. }
  267. if (!function_exists('safe_replace')) {
  268. /**
  269. * 安全过滤函数
  270. * @param $string
  271. * @return string
  272. */
  273. function safe_replace($string)
  274. {
  275. $string = str_replace('%20', '', $string);
  276. $string = str_replace('%27', '', $string);
  277. $string = str_replace('%2527', '', $string);
  278. $string = str_replace('*', '', $string);
  279. $string = str_replace('"', '&quot;', $string);
  280. $string = str_replace("'", '', $string);
  281. $string = str_replace('"', '', $string);
  282. $string = str_replace(';', '', $string);
  283. $string = str_replace('<', '&lt;', $string);
  284. $string = str_replace('>', '&gt;', $string);
  285. $string = str_replace("{", '', $string);
  286. $string = str_replace('}', '', $string);
  287. $string = str_replace('\\', '', $string);
  288. return $string;
  289. }
  290. }
  291. if (!function_exists('sys_auth')) {
  292. /**
  293. * 字符串加密、解密函数
  294. * @param string $string
  295. * @param string $operation ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
  296. * @param string $key 密钥:数字、字母、下划线
  297. * @param int $expiry 过期时间
  298. * @return string
  299. */
  300. function sys_auth(string $string, string $operation = 'ENCODE', string $key = '', int $expiry = 0): string
  301. {
  302. $ckey_length = 4;
  303. $key = md5($key != '' ? $key : Config::get('yzn.data_auth_key'));
  304. $keya = md5(substr($key, 0, 16));
  305. $keyb = md5(substr($key, 16, 16));
  306. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
  307. $cryptkey = $keya . md5($keya . $keyc);
  308. $key_length = strlen($cryptkey);
  309. $string = $operation == 'DECODE' ? base64_decode(strtr(substr($string, $ckey_length), '-_', '+/')) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
  310. $string_length = strlen($string);
  311. $result = '';
  312. $box = range(0, 255);
  313. $rndkey = [];
  314. for ($i = 0; $i <= 255; $i++) {
  315. $rndkey[$i] = ord($cryptkey[$i % $key_length]);
  316. }
  317. for ($j = $i = 0; $i < 256; $i++) {
  318. $j = ($j + $box[$i] + $rndkey[$i]) % 256;
  319. $tmp = $box[$i];
  320. $box[$i] = $box[$j];
  321. $box[$j] = $tmp;
  322. }
  323. for ($a = $j = $i = 0; $i < $string_length; $i++) {
  324. $a = ($a + 1) % 256;
  325. $j = ($j + $box[$a]) % 256;
  326. $tmp = $box[$a];
  327. $box[$a] = $box[$j];
  328. $box[$j] = $tmp;
  329. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  330. }
  331. if ($operation == 'DECODE') {
  332. if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
  333. return substr($result, 26);
  334. } else {
  335. return '';
  336. }
  337. } else {
  338. return $keyc . rtrim(strtr(base64_encode($result), '+/', '-_'), '=');
  339. }
  340. }
  341. }
  342. if (!function_exists('hsv2rgb')) {
  343. function hsv2rgb($h, $s, $v): array
  344. {
  345. $r = $g = $b = 0;
  346. $i = floor($h * 6);
  347. $f = $h * 6 - $i;
  348. $p = $v * (1 - $s);
  349. $q = $v * (1 - $f * $s);
  350. $t = $v * (1 - (1 - $f) * $s);
  351. switch ($i % 6) {
  352. case 0:
  353. $r = $v;
  354. $g = $t;
  355. $b = $p;
  356. break;
  357. case 1:
  358. $r = $q;
  359. $g = $v;
  360. $b = $p;
  361. break;
  362. case 2:
  363. $r = $p;
  364. $g = $v;
  365. $b = $t;
  366. break;
  367. case 3:
  368. $r = $p;
  369. $g = $q;
  370. $b = $v;
  371. break;
  372. case 4:
  373. $r = $t;
  374. $g = $p;
  375. $b = $v;
  376. break;
  377. case 5:
  378. $r = $v;
  379. $g = $p;
  380. $b = $q;
  381. break;
  382. }
  383. return [
  384. floor($r * 255),
  385. floor($g * 255),
  386. floor($b * 255),
  387. ];
  388. }
  389. }
  390. if (!function_exists('letter_avatar')) {
  391. /**
  392. * 首字母头像
  393. * @param string $text
  394. * @return string
  395. */
  396. function letter_avatar(string $text): string
  397. {
  398. $total = unpack('L', hash('adler32', $text, true))[1];
  399. $hue = $total % 360;
  400. [$r, $g, $b] = hsv2rgb($hue / 360, 0.3, 0.9);
  401. $bg = "rgb({$r},{$g},{$b})";
  402. $color = "#ffffff";
  403. $first = mb_strtoupper(mb_substr($text, 0, 1));
  404. $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>');
  405. return 'data:image/svg+xml;base64,' . $src;
  406. }
  407. }
  408. if (!function_exists('build_suffix_image')) {
  409. /**
  410. * 生成文件后缀图片
  411. * @param string $suffix 后缀
  412. * @param ?string $background 背景颜色
  413. * @return string
  414. */
  415. function build_suffix_image(string $suffix, ?string $background = null): string
  416. {
  417. $suffix = mb_substr(strtoupper($suffix), 0, 4);
  418. $total = unpack('L', hash('adler32', $suffix, true))[1];
  419. $hue = $total % 360;
  420. [$r, $g, $b] = hsv2rgb($hue / 360, 0.3, 0.9);
  421. $background = $background ?: "rgb({$r},{$g},{$b})";
  422. return <<<EOT
  423. <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">
  424. <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"/>
  425. <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
  426. <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
  427. <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"/>
  428. <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
  429. <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>
  430. </svg>
  431. EOT;
  432. }
  433. }
  434. if (!function_exists('xss_clean')) {
  435. /**
  436. * 清理XSS
  437. * @param array|string $content
  438. * @param bool $is_image
  439. * @return bool|string|string[]
  440. */
  441. function xss_clean(array | string $content, bool $is_image = false)
  442. {
  443. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  444. }
  445. }
  446. if (!function_exists('url_clean')) {
  447. /**
  448. * 清理URL
  449. */
  450. function url_clean($url)
  451. {
  452. if (!check_url_allowed($url)) {
  453. return '';
  454. }
  455. return xss_clean($url);
  456. }
  457. }
  458. if (!function_exists('check_url_allowed')) {
  459. /**
  460. * 检测URL是否允许范围内
  461. * @param string $url
  462. * @return bool
  463. */
  464. function check_url_allowed(string $url = ''): bool
  465. {
  466. //允许的主机列表
  467. $allowedHostArr = [
  468. strtolower(request()->host()),
  469. ];
  470. if (empty($url)) {
  471. return true;
  472. }
  473. //如果是站内相对链接则允许
  474. if (preg_match("/^[\/a-z][a-z0-9][a-z0-9\.\/]+((\?|#).*)?\$/i", $url) && substr($url, 0, 2) !== '//') {
  475. return true;
  476. }
  477. //如果是站外链接则需要判断HOST是否允许
  478. if (preg_match("/((http[s]?:\/\/)+(?>[a-z\-0-9]{2,}\.){1,}[a-z]{2,8})(?:\s|\/)/i", $url)) {
  479. $chkHost = parse_url(strtolower($url), PHP_URL_HOST);
  480. if ($chkHost && in_array($chkHost, $allowedHostArr)) {
  481. return true;
  482. }
  483. }
  484. return false;
  485. }
  486. }
  487. if (!function_exists('check_nav_active')) {
  488. /**
  489. * 检测会员中心导航是否高亮
  490. */
  491. function check_nav_active($url, $classname = 'layui-this')
  492. {
  493. $auth = \app\common\library\Auth::instance();
  494. $requestUrl = $auth->getRequestUri();
  495. $url = ltrim($url, '/');
  496. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  497. }
  498. }
  499. if (!function_exists('var_export_short')) {
  500. /**
  501. * 使用短标签打印或返回数组结构
  502. * @param mixed $data
  503. * @param boolean $return 是否返回数据
  504. * @return string
  505. */
  506. function var_export_short($data, $return = true)
  507. {
  508. return var_export($data, $return);
  509. $replaced = [];
  510. $count = 0;
  511. //判断是否是对象
  512. if (is_resource($data) || is_object($data)) {
  513. return var_export($data, $return);
  514. }
  515. //判断是否有特殊的键名
  516. $specialKey = false;
  517. array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
  518. if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
  519. $specialKey = true;
  520. }
  521. });
  522. if ($specialKey) {
  523. return var_export($data, $return);
  524. }
  525. array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
  526. if (is_object($value) || is_resource($value)) {
  527. $replaced[$count] = var_export($value, true);
  528. $value = "##<{$count}>##";
  529. } else {
  530. if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
  531. $index = array_search($value, $replaced);
  532. if ($index === false) {
  533. $replaced[$count] = var_export($value, true);
  534. $value = "##<{$count}>##";
  535. } else {
  536. $value = "##<{$index}>##";
  537. }
  538. }
  539. }
  540. $count++;
  541. });
  542. $dump = var_export($data, true);
  543. $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
  544. $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
  545. $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
  546. $dump = preg_replace('#\)$#', "]", $dump); //End
  547. if ($replaced) {
  548. $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
  549. return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
  550. }, $dump);
  551. }
  552. if ($return === true) {
  553. return $dump;
  554. } else {
  555. echo $dump;
  556. }
  557. }
  558. }