common.php 17 KB

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