common.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. <?php
  2. // 公共助手函数
  3. use app\common\exception\UploadException;
  4. use OSS\OssClient;
  5. use think\Env;
  6. use think\exception\HttpResponseException;
  7. use think\Response;
  8. if (!function_exists('__')) {
  9. /**
  10. * 获取语言变量值
  11. * @param string $name 语言变量名
  12. * @param array $vars 动态变量值
  13. * @param string $lang 语言
  14. * @return mixed
  15. */
  16. function __($name, $vars = [], $lang = '')
  17. {
  18. if (is_numeric($name) || !$name) {
  19. return $name;
  20. }
  21. if (!is_array($vars)) {
  22. $vars = func_get_args();
  23. array_shift($vars);
  24. $lang = '';
  25. }
  26. return \think\Lang::get($name, $vars, $lang);
  27. }
  28. }
  29. if (!function_exists('format_bytes')) {
  30. /**
  31. * 将字节转换为可读文本
  32. * @param int $size 大小
  33. * @param string $delimiter 分隔符
  34. * @param int $precision 小数位数
  35. * @return string
  36. */
  37. function format_bytes($size, $delimiter = '', $precision = 2)
  38. {
  39. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  40. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  41. $size /= 1024;
  42. }
  43. return round($size, $precision) . $delimiter . $units[$i];
  44. }
  45. }
  46. if (!function_exists('datetime')) {
  47. /**
  48. * 将时间戳转换为日期时间
  49. * @param int $time 时间戳
  50. * @param string $format 日期时间格式
  51. * @return string
  52. */
  53. function datetime($time, $format = 'Y-m-d H:i:s')
  54. {
  55. $time = is_numeric($time) ? $time : strtotime($time);
  56. return date($format, $time);
  57. }
  58. }
  59. if (!function_exists('human_date')) {
  60. /**
  61. * 获取语义化时间
  62. * @param int $time 时间
  63. * @param int $local 本地时间
  64. * @return string
  65. */
  66. function human_date($time, $local = null)
  67. {
  68. return \fast\Date::human($time, $local);
  69. }
  70. }
  71. if (!function_exists('cdnurl')) {
  72. /**
  73. * 获取上传资源的CDN的地址
  74. * @param string $url 资源相对地址
  75. * @param boolean $domain 是否显示域名 或者直接传入域名
  76. * @return string
  77. */
  78. function cdnurl($url, $domain = false)
  79. {
  80. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  81. $cdnurl = \think\Config::get('upload.cdnurl');
  82. if (is_bool($domain) || stripos($cdnurl, '/') === 0) {
  83. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  84. }
  85. if ($domain && !preg_match($regex, $url)) {
  86. $domain = is_bool($domain) ? request()->domain() : $domain;
  87. $url = $domain . $url;
  88. }
  89. return $url;
  90. }
  91. }
  92. if (!function_exists('is_really_writable')) {
  93. /**
  94. * 判断文件或文件夹是否可写
  95. * @param string $file 文件或目录
  96. * @return bool
  97. */
  98. function is_really_writable($file)
  99. {
  100. if (DIRECTORY_SEPARATOR === '/') {
  101. return is_writable($file);
  102. }
  103. if (is_dir($file)) {
  104. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  105. if (($fp = @fopen($file, 'ab')) === false) {
  106. return false;
  107. }
  108. fclose($fp);
  109. @chmod($file, 0777);
  110. @unlink($file);
  111. return true;
  112. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  113. return false;
  114. }
  115. fclose($fp);
  116. return true;
  117. }
  118. }
  119. if (!function_exists('rmdirs')) {
  120. /**
  121. * 删除文件夹
  122. * @param string $dirname 目录
  123. * @param bool $withself 是否删除自身
  124. * @return boolean
  125. */
  126. function rmdirs($dirname, $withself = true)
  127. {
  128. if (!is_dir($dirname)) {
  129. return false;
  130. }
  131. $files = new RecursiveIteratorIterator(
  132. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  133. RecursiveIteratorIterator::CHILD_FIRST
  134. );
  135. foreach ($files as $fileinfo) {
  136. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  137. $todo($fileinfo->getRealPath());
  138. }
  139. if ($withself) {
  140. @rmdir($dirname);
  141. }
  142. return true;
  143. }
  144. }
  145. if (!function_exists('copydirs')) {
  146. /**
  147. * 复制文件夹
  148. * @param string $source 源文件夹
  149. * @param string $dest 目标文件夹
  150. */
  151. function copydirs($source, $dest)
  152. {
  153. if (!is_dir($dest)) {
  154. mkdir($dest, 0755, true);
  155. }
  156. foreach (
  157. $iterator = new RecursiveIteratorIterator(
  158. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  159. RecursiveIteratorIterator::SELF_FIRST
  160. ) as $item
  161. ) {
  162. if ($item->isDir()) {
  163. $sontDir = $dest . DS . $iterator->getSubPathName();
  164. if (!is_dir($sontDir)) {
  165. mkdir($sontDir, 0755, true);
  166. }
  167. } else {
  168. copy($item, $dest . DS . $iterator->getSubPathName());
  169. }
  170. }
  171. }
  172. }
  173. if (!function_exists('mb_ucfirst')) {
  174. function mb_ucfirst($string)
  175. {
  176. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  177. }
  178. }
  179. if (!function_exists('addtion')) {
  180. /**
  181. * 附加关联字段数据
  182. * @param array $items 数据列表
  183. * @param mixed $fields 渲染的来源字段
  184. * @return array
  185. */
  186. function addtion($items, $fields)
  187. {
  188. if (!$items || !$fields) {
  189. return $items;
  190. }
  191. $fieldsArr = [];
  192. if (!is_array($fields)) {
  193. $arr = explode(',', $fields);
  194. foreach ($arr as $k => $v) {
  195. $fieldsArr[$v] = ['field' => $v];
  196. }
  197. } else {
  198. foreach ($fields as $k => $v) {
  199. if (is_array($v)) {
  200. $v['field'] = $v['field'] ?? $k;
  201. } else {
  202. $v = ['field' => $v];
  203. }
  204. $fieldsArr[$v['field']] = $v;
  205. }
  206. }
  207. foreach ($fieldsArr as $k => &$v) {
  208. $v = is_array($v) ? $v : ['field' => $v];
  209. $v['display'] = $v['display'] ?? str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  210. $v['primary'] = $v['primary'] ?? '';
  211. $v['column'] = $v['column'] ?? 'name';
  212. $v['model'] = $v['model'] ?? '';
  213. $v['table'] = $v['table'] ?? '';
  214. $v['name'] = $v['name'] ?? str_replace(['_ids', '_id'], '', $v['field']);
  215. }
  216. unset($v);
  217. $ids = [];
  218. $fields = array_keys($fieldsArr);
  219. foreach ($items as $k => $v) {
  220. foreach ($fields as $m => $n) {
  221. if (isset($v[$n])) {
  222. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  223. }
  224. }
  225. }
  226. $result = [];
  227. foreach ($fieldsArr as $k => $v) {
  228. if ($v['model']) {
  229. $model = new $v['model'];
  230. } else {
  231. $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
  232. }
  233. $primary = $v['primary'] ? $v['primary'] : $model->getPk();
  234. $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
  235. }
  236. foreach ($items as $k => &$v) {
  237. foreach ($fields as $m => $n) {
  238. if (isset($v[$n])) {
  239. $curr = array_flip(explode(',', $v[$n]));
  240. $linedata = array_intersect_key($result[$n], $curr);
  241. $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
  242. }
  243. }
  244. }
  245. return $items;
  246. }
  247. }
  248. if (!function_exists('var_export_short')) {
  249. /**
  250. * 使用短标签打印或返回数组结构
  251. * @param mixed $data
  252. * @param boolean $return 是否返回数据
  253. * @return string
  254. */
  255. function var_export_short($data, $return = true)
  256. {
  257. return var_export($data, $return);
  258. $replaced = [];
  259. $count = 0;
  260. //判断是否是对象
  261. if (is_resource($data) || is_object($data)) {
  262. return var_export($data, $return);
  263. }
  264. //判断是否有特殊的键名
  265. $specialKey = false;
  266. array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
  267. if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
  268. $specialKey = true;
  269. }
  270. });
  271. if ($specialKey) {
  272. return var_export($data, $return);
  273. }
  274. array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
  275. if (is_object($value) || is_resource($value)) {
  276. $replaced[$count] = var_export($value, true);
  277. $value = "##<{$count}>##";
  278. } else {
  279. if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
  280. $index = array_search($value, $replaced);
  281. if ($index === false) {
  282. $replaced[$count] = var_export($value, true);
  283. $value = "##<{$count}>##";
  284. } else {
  285. $value = "##<{$index}>##";
  286. }
  287. }
  288. }
  289. $count++;
  290. });
  291. $dump = var_export($data, true);
  292. $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
  293. $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
  294. $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
  295. $dump = preg_replace('#\)$#', "]", $dump); //End
  296. if ($replaced) {
  297. $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
  298. return $replaced[$matches[1]] ?? "''";
  299. }, $dump);
  300. }
  301. if ($return === true) {
  302. return $dump;
  303. } else {
  304. echo $dump;
  305. }
  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,}\.){1,}[a-z]{2,8})(?:\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. }
  512. if (!function_exists('ali_oss_upload')) {
  513. /**
  514. * 阿里云OSS上传
  515. * @param string $suffix 后缀
  516. * @param null $background
  517. * @return array
  518. */
  519. function ali_oss_upload(\think\Request $request, $file_path = null, $file_name = '')
  520. {
  521. //$file = $this->request->file('file');
  522. $file = $request->file('file');
  523. try {
  524. $filename = $file->getInfo();
  525. //获取oss实例
  526. $ossClient = new OssClient(Env::get('oss.key_id'), Env::get('oss.key_secret'), Env::get('oss.endpoint'));
  527. $bucket = Env::get('oss.bucket');
  528. $upload_path = Env::get('oss.directory') . "/" . $file_path . "/" . date("Ym") . "/";
  529. //自定义文件名
  530. if(empty($file_name)){
  531. $upload_path .= $file->getInfo();
  532. }else{
  533. $extension = strtolower(pathinfo($file->getInfo('name'), PATHINFO_EXTENSION)); //扩展名
  534. $upload_path .= $file_name . '.' . $extension;
  535. }
  536. $rs = $ossClient->uploadFile($bucket, $upload_path, $file->getRealPath());
  537. } catch (UploadException $e) {
  538. return _error($e->getMessage());
  539. }
  540. return _success(['full_url' => str_replace("http://", "https://", $rs['info']['url'])]);
  541. }
  542. }
  543. if (!function_exists('_success')) {
  544. /**
  545. * 返回成功标记信息
  546. */
  547. function _success($data = [])
  548. {
  549. return ['code' => 1, 'data' => $data];
  550. }
  551. }
  552. if (!function_exists('_error')) {
  553. /**
  554. * 返回错误标记信息
  555. */
  556. function _error($msg = '', $data = [])
  557. {
  558. return ['code' => 0, 'msg' => $msg, 'data' => $data];
  559. }
  560. }
  561. /**
  562. * 生成文件后缀图片
  563. * @param string $unit +-
  564. * @param float $amount 调整金额
  565. * @param float $balance 余额
  566. * @return float
  567. */
  568. function build_amount_compute($unit, $amount, $balance): float
  569. { $res = 0;
  570. switch ($unit) {
  571. case 0:
  572. $res =bcadd($amount, $balance, 6);
  573. break;
  574. default:
  575. // 如果没有匹配的值
  576. if($balance > $amount) $res = bcsub($balance, $amount, 6);
  577. }
  578. return $res;
  579. }