common.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. <?php
  2. // 公共助手函数
  3. use think\exception\HttpResponseException;
  4. use think\Response;
  5. use app\common\Service\ShopConfigService;
  6. use app\common\exception\BusinessException;
  7. if (!function_exists('shop_config')) {
  8. /**
  9. * 获取SheepAdmin配置
  10. * @param string $code 配置名
  11. * @return string
  12. */
  13. function shop_config(string $code, $cache = true)
  14. {
  15. return ShopConfigService::getConfigs($code, $cache);
  16. }
  17. }
  18. /**
  19. * 获取前端用户
  20. */
  21. if (!function_exists('auth_user')) {
  22. function auth_user($throwException = false)
  23. {
  24. if (\app\common\library\Auth::instance()->isLogin()) {
  25. return \app\common\library\Auth::instance()->getUser();
  26. }
  27. if ($throwException) {
  28. throw new BusinessException('请登录后操作');
  29. }
  30. return null;
  31. }
  32. }
  33. /**
  34. * 获取管理员信息
  35. */
  36. if (!function_exists('auth_admin')) {
  37. function auth_admin()
  38. {
  39. if (\app\admin\library\Auth::instance()->isLogin()) {
  40. $admin = \app\admin\library\Auth::instance()->getUserInfo(); // 这里获取的是个数组,转为模型
  41. if ($admin) {
  42. return \app\admin\model\Admin::where('id', $admin['id'])->find();
  43. }
  44. }
  45. return null;
  46. }
  47. }
  48. if (!function_exists('string_hide')) {
  49. /**
  50. * 隐藏部分字符串
  51. *
  52. * @param string $string 原始字符串
  53. * @param int $start 开始位置
  54. * @return string
  55. */
  56. function string_hide($string, $start = 2)
  57. {
  58. if (mb_strlen($string) > $start) {
  59. $hide = mb_substr($string, 0, $start) . '***';
  60. } else {
  61. $hide = $string . '***';
  62. }
  63. return $hide;
  64. }
  65. }
  66. if (!function_exists('account_hide')) {
  67. /**
  68. * 隐藏账号部分字符串
  69. *
  70. * @param string $string 原始字符串
  71. * @param int $start 开始位置
  72. * @param int $end 开始位置
  73. * @return string
  74. */
  75. function account_hide($string, $start = 2, $end = 2)
  76. {
  77. $hide = mb_substr($string, 0, $start) . '*****' . mb_substr($string, -$end);
  78. return $hide;
  79. }
  80. }
  81. if (!function_exists('get_sn')) {
  82. /**
  83. * 获取唯一编号
  84. *
  85. * @param mixed $id 唯一标识
  86. * @param string $type 类型
  87. * @return string
  88. */
  89. function get_sn($id, $type = '')
  90. {
  91. $id = (string)$id;
  92. $rand = $id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
  93. $sn = date('Yhis') . $rand;
  94. $id = str_pad($id, (24 - strlen($sn)), '0', STR_PAD_BOTH);
  95. return $type . $sn . $id;
  96. }
  97. }
  98. if (!function_exists('format_log_error')) {
  99. /**
  100. * 格式化记录日志,重要地方使用
  101. *
  102. * @param object $error
  103. * @param string $name
  104. * @param string $message
  105. * @return void
  106. */
  107. function format_log_error($error, $name = 'QUEUE', $message = '')
  108. {
  109. $logInfo = [
  110. "========== $name LOG INFO BEGIN ==========",
  111. '[ Message ] ' . var_export('[' . $error->getCode() . ']' . $error->getMessage() . ' ' . $message, true),
  112. '[ File ] ' . var_export($error->getFile() . ':' . $error->getLine(), true),
  113. '[ Trace ] ' . var_export($error->getTraceAsString(), true),
  114. "============================================= $name LOG INFO ENDED ==========",
  115. ];
  116. $logInfo = implode(PHP_EOL, $logInfo) . PHP_EOL;
  117. \think\Log::error($logInfo);
  118. }
  119. }
  120. if (!function_exists('__')) {
  121. /**
  122. * 获取语言变量值
  123. * @param string $name 语言变量名
  124. * @param string | array $vars 动态变量值
  125. * @param string $lang 语言
  126. * @return mixed
  127. */
  128. function __($name, $vars = [], $lang = '')
  129. {
  130. if (is_numeric($name) || !$name) {
  131. return $name;
  132. }
  133. if (!is_array($vars)) {
  134. $vars = func_get_args();
  135. array_shift($vars);
  136. $lang = '';
  137. }
  138. return \think\Lang::get($name, $vars, $lang);
  139. }
  140. }
  141. if (!function_exists('format_bytes')) {
  142. /**
  143. * 将字节转换为可读文本
  144. * @param int $size 大小
  145. * @param string $delimiter 分隔符
  146. * @param int $precision 小数位数
  147. * @return string
  148. */
  149. function format_bytes($size, $delimiter = '', $precision = 2)
  150. {
  151. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  152. for ($i = 0; $size >= 1024 && $i < 5; $i++) {
  153. $size /= 1024;
  154. }
  155. return round($size, $precision) . $delimiter . $units[$i];
  156. }
  157. }
  158. if (!function_exists('datetime')) {
  159. /**
  160. * 将时间戳转换为日期时间
  161. * @param int $time 时间戳
  162. * @param string $format 日期时间格式
  163. * @return string
  164. */
  165. function datetime($time, $format = 'Y-m-d H:i:s')
  166. {
  167. $time = is_numeric($time) ? $time : strtotime($time);
  168. return date($format, $time);
  169. }
  170. }
  171. if (!function_exists('human_date')) {
  172. /**
  173. * 获取语义化时间
  174. * @param int $time 时间
  175. * @param int $local 本地时间
  176. * @return string
  177. */
  178. function human_date($time, $local = null)
  179. {
  180. return \fast\Date::human($time, $local);
  181. }
  182. }
  183. if (!function_exists('cdnurl')) {
  184. /**
  185. * 获取上传资源的CDN的地址
  186. * @param string $url 资源相对地址
  187. * @param boolean $domain 是否显示域名 或者直接传入域名
  188. * @return string
  189. */
  190. function cdnurl($url, $domain = false)
  191. {
  192. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  193. $cdnurl = \think\Config::get('upload.cdnurl');
  194. if (is_bool($domain) || stripos($cdnurl, '/') === 0) {
  195. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  196. }
  197. if ($domain && !preg_match($regex, $url)) {
  198. $domain = is_bool($domain) ? request()->domain() : $domain;
  199. $url = $domain . $url;
  200. }
  201. return $url;
  202. }
  203. }
  204. if (!function_exists('is_really_writable')) {
  205. /**
  206. * 判断文件或文件夹是否可写
  207. * @param string $file 文件或目录
  208. * @return bool
  209. */
  210. function is_really_writable($file)
  211. {
  212. if (DIRECTORY_SEPARATOR === '/') {
  213. return is_writable($file);
  214. }
  215. if (is_dir($file)) {
  216. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  217. if (($fp = @fopen($file, 'ab')) === false) {
  218. return false;
  219. }
  220. fclose($fp);
  221. @chmod($file, 0777);
  222. @unlink($file);
  223. return true;
  224. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  225. return false;
  226. }
  227. fclose($fp);
  228. return true;
  229. }
  230. }
  231. if (!function_exists('rmdirs')) {
  232. /**
  233. * 删除文件夹
  234. * @param string $dirname 目录
  235. * @param bool $withself 是否删除自身
  236. * @return boolean
  237. */
  238. function rmdirs($dirname, $withself = true)
  239. {
  240. if (!is_dir($dirname)) {
  241. return false;
  242. }
  243. $files = new RecursiveIteratorIterator(
  244. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  245. RecursiveIteratorIterator::CHILD_FIRST
  246. );
  247. foreach ($files as $fileinfo) {
  248. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  249. $todo($fileinfo->getRealPath());
  250. }
  251. if ($withself) {
  252. @rmdir($dirname);
  253. }
  254. return true;
  255. }
  256. }
  257. if (!function_exists('copydirs')) {
  258. /**
  259. * 复制文件夹
  260. * @param string $source 源文件夹
  261. * @param string $dest 目标文件夹
  262. */
  263. function copydirs($source, $dest)
  264. {
  265. if (!is_dir($dest)) {
  266. mkdir($dest, 0755, true);
  267. }
  268. foreach (
  269. $iterator = new RecursiveIteratorIterator(
  270. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  271. RecursiveIteratorIterator::SELF_FIRST
  272. ) as $item
  273. ) {
  274. if ($item->isDir()) {
  275. $sontDir = $dest . DS . $iterator->getSubPathName();
  276. if (!is_dir($sontDir)) {
  277. mkdir($sontDir, 0755, true);
  278. }
  279. } else {
  280. copy($item, $dest . DS . $iterator->getSubPathName());
  281. }
  282. }
  283. }
  284. }
  285. if (!function_exists('mb_ucfirst')) {
  286. function mb_ucfirst($string)
  287. {
  288. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  289. }
  290. }
  291. if (!function_exists('addtion')) {
  292. /**
  293. * 附加关联字段数据
  294. * @param array $items 数据列表
  295. * @param mixed $fields 渲染的来源字段
  296. * @return array
  297. */
  298. function addtion($items, $fields)
  299. {
  300. if (!$items || !$fields) {
  301. return $items;
  302. }
  303. $fieldsArr = [];
  304. if (!is_array($fields)) {
  305. $arr = explode(',', $fields);
  306. foreach ($arr as $k => $v) {
  307. $fieldsArr[$v] = ['field' => $v];
  308. }
  309. } else {
  310. foreach ($fields as $k => $v) {
  311. if (is_array($v)) {
  312. $v['field'] = $v['field'] ?? $k;
  313. } else {
  314. $v = ['field' => $v];
  315. }
  316. $fieldsArr[$v['field']] = $v;
  317. }
  318. }
  319. foreach ($fieldsArr as $k => &$v) {
  320. $v = is_array($v) ? $v : ['field' => $v];
  321. $v['display'] = $v['display'] ?? str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  322. $v['primary'] = $v['primary'] ?? '';
  323. $v['column'] = $v['column'] ?? 'name';
  324. $v['model'] = $v['model'] ?? '';
  325. $v['table'] = $v['table'] ?? '';
  326. $v['name'] = $v['name'] ?? str_replace(['_ids', '_id'], '', $v['field']);
  327. }
  328. unset($v);
  329. $ids = [];
  330. $fields = array_keys($fieldsArr);
  331. foreach ($items as $k => $v) {
  332. foreach ($fields as $m => $n) {
  333. if (isset($v[$n])) {
  334. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  335. }
  336. }
  337. }
  338. $result = [];
  339. foreach ($fieldsArr as $k => $v) {
  340. if ($v['model']) {
  341. $model = new $v['model'];
  342. } else {
  343. // 优先判断使用table的配置
  344. $model = $v['table'] ? \think\Db::table($v['table']) : \think\Db::name($v['name']);
  345. }
  346. $primary = $v['primary'] ?: $model->getPk();
  347. $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
  348. }
  349. foreach ($items as $k => &$v) {
  350. foreach ($fields as $m => $n) {
  351. if (isset($v[$n])) {
  352. $curr = array_flip(explode(',', $v[$n]));
  353. $linedata = array_intersect_key($result[$n], $curr);
  354. $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
  355. }
  356. }
  357. }
  358. return $items;
  359. }
  360. }
  361. if (!function_exists('var_export_short')) {
  362. /**
  363. * 使用短标签打印或返回数组结构
  364. * @param mixed $data
  365. * @param boolean $return 是否返回数据
  366. * @return string
  367. */
  368. function var_export_short($data, $return = true)
  369. {
  370. return var_export($data, $return);
  371. }
  372. }
  373. if (!function_exists('letter_avatar')) {
  374. /**
  375. * 首字母头像
  376. * @param $text
  377. * @return string
  378. */
  379. function letter_avatar($text)
  380. {
  381. $total = unpack('L', hash('adler32', $text, true))[1];
  382. $hue = $total % 360;
  383. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  384. $bg = "rgb({$r},{$g},{$b})";
  385. $color = "#ffffff";
  386. $first = mb_strtoupper(mb_substr($text, 0, 1));
  387. $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" dominant-baseline="central">' . $first . '</text></svg>');
  388. $value = 'data:image/svg+xml;base64,' . $src;
  389. return $value;
  390. }
  391. }
  392. if (!function_exists('hsv2rgb')) {
  393. function hsv2rgb($h, $s, $v)
  394. {
  395. $r = $g = $b = 0;
  396. $i = floor($h * 6);
  397. $f = $h * 6 - $i;
  398. $p = $v * (1 - $s);
  399. $q = $v * (1 - $f * $s);
  400. $t = $v * (1 - (1 - $f) * $s);
  401. switch ($i % 6) {
  402. case 0:
  403. $r = $v;
  404. $g = $t;
  405. $b = $p;
  406. break;
  407. case 1:
  408. $r = $q;
  409. $g = $v;
  410. $b = $p;
  411. break;
  412. case 2:
  413. $r = $p;
  414. $g = $v;
  415. $b = $t;
  416. break;
  417. case 3:
  418. $r = $p;
  419. $g = $q;
  420. $b = $v;
  421. break;
  422. case 4:
  423. $r = $t;
  424. $g = $p;
  425. $b = $v;
  426. break;
  427. case 5:
  428. $r = $v;
  429. $g = $p;
  430. $b = $q;
  431. break;
  432. }
  433. return [
  434. floor($r * 255),
  435. floor($g * 255),
  436. floor($b * 255)
  437. ];
  438. }
  439. }
  440. if (!function_exists('check_nav_active')) {
  441. /**
  442. * 检测会员中心导航是否高亮
  443. */
  444. function check_nav_active($url, $classname = 'active')
  445. {
  446. $auth = \app\common\library\Auth::instance();
  447. $requestUrl = $auth->getRequestUri();
  448. $url = ltrim($url, '/');
  449. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  450. }
  451. }
  452. if (!function_exists('check_cors_request')) {
  453. /**
  454. * 跨域检测
  455. */
  456. function check_cors_request()
  457. {
  458. if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] && config('fastadmin.cors_request_domain')) {
  459. $info = parse_url($_SERVER['HTTP_ORIGIN']);
  460. $domainArr = explode(',', config('fastadmin.cors_request_domain'));
  461. $domainArr[] = request()->host(true);
  462. if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  463. header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  464. } else {
  465. $response = Response::create('跨域检测无效', 'html', 403);
  466. throw new HttpResponseException($response);
  467. }
  468. header('Access-Control-Allow-Credentials: true');
  469. header('Access-Control-Max-Age: 86400');
  470. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  471. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  472. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  473. }
  474. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  475. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  476. }
  477. $response = Response::create('', 'html');
  478. throw new HttpResponseException($response);
  479. }
  480. }
  481. }
  482. }
  483. if (!function_exists('xss_clean')) {
  484. /**
  485. * 清理XSS
  486. */
  487. function xss_clean($content, $is_image = false)
  488. {
  489. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  490. }
  491. }
  492. if (!function_exists('url_clean')) {
  493. /**
  494. * 清理URL
  495. */
  496. function url_clean($url)
  497. {
  498. if (!check_url_allowed($url)) {
  499. return '';
  500. }
  501. return xss_clean($url);
  502. }
  503. }
  504. if (!function_exists('check_ip_allowed')) {
  505. /**
  506. * 检测IP是否允许
  507. * @param string $ip IP地址
  508. */
  509. function check_ip_allowed($ip = null)
  510. {
  511. $ip = is_null($ip) ? request()->ip() : $ip;
  512. $forbiddenipArr = config('site.forbiddenip');
  513. $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
  514. $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
  515. if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
  516. $response = Response::create('请求无权访问', 'html', 403);
  517. throw new HttpResponseException($response);
  518. }
  519. }
  520. }
  521. if (!function_exists('check_url_allowed')) {
  522. /**
  523. * 检测URL是否允许
  524. * @param string $url URL
  525. * @return bool
  526. */
  527. function check_url_allowed($url = '')
  528. {
  529. //允许的主机列表
  530. $allowedHostArr = [
  531. strtolower(request()->host())
  532. ];
  533. if (empty($url)) {
  534. return true;
  535. }
  536. //如果是站内相对链接则允许
  537. if (preg_match("/^[\/a-z][a-z0-9][a-z0-9\.\/]+((\?|#).*)?\$/i", $url) && substr($url, 0, 2) !== '//') {
  538. return true;
  539. }
  540. //如果是站外链接则需要判断HOST是否允许
  541. if (preg_match("/((http[s]?:\/\/)+((?>[a-z\-0-9]{2,}\.)+[a-z]{2,8}|((?>([0-9]{1,3}\.)){3}[0-9]{1,3}))(:[0-9]{1,5})?)(?:\s|\/)/i", $url)) {
  542. $chkHost = parse_url(strtolower($url), PHP_URL_HOST);
  543. if ($chkHost && in_array($chkHost, $allowedHostArr)) {
  544. return true;
  545. }
  546. }
  547. return false;
  548. }
  549. }
  550. if (!function_exists('build_suffix_image')) {
  551. /**
  552. * 生成文件后缀图片
  553. * @param string $suffix 后缀
  554. * @param null $background
  555. * @return string
  556. */
  557. function build_suffix_image($suffix, $background = null)
  558. {
  559. $suffix = mb_substr(strtoupper($suffix), 0, 4);
  560. $total = unpack('L', hash('adler32', $suffix, true))[1];
  561. $hue = $total % 360;
  562. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  563. $background = $background ? $background : "rgb({$r},{$g},{$b})";
  564. $icon = <<<EOT
  565. <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">
  566. <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"/>
  567. <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
  568. <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
  569. <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"/>
  570. <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
  571. <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>
  572. </svg>
  573. EOT;
  574. return $icon;
  575. }
  576. }