common.php 18 KB

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