common.php 20 KB

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