common.php 18 KB

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