common.php 17 KB

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