common.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. <?php
  2. // 公共助手函数
  3. use Symfony\Component\VarExporter\VarExporter;
  4. if (!function_exists('__')) {
  5. /**
  6. * 获取语言变量值
  7. * @param string $name 语言变量名
  8. * @param array $vars 动态变量值
  9. * @param string $lang 语言
  10. * @return mixed
  11. */
  12. function __($name, $vars = [], $lang = '')
  13. {
  14. if (is_numeric($name) || !$name) {
  15. return $name;
  16. }
  17. if (!is_array($vars)) {
  18. $vars = func_get_args();
  19. array_shift($vars);
  20. $lang = '';
  21. }
  22. return \think\Lang::get($name, $vars, $lang);
  23. }
  24. }
  25. function p($arr) {
  26. header('content-type:text/html;charset=utf-8');
  27. echo '<pre>';
  28. print_r($arr);
  29. echo '</pre>';
  30. }
  31. if (!function_exists('format_bytes')) {
  32. /**
  33. * 将字节转换为可读文本
  34. * @param int $size 大小
  35. * @param string $delimiter 分隔符
  36. * @param int $precision 小数位数
  37. * @return string
  38. */
  39. function format_bytes($size, $delimiter = '', $precision = 2)
  40. {
  41. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  42. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  43. $size /= 1024;
  44. }
  45. return round($size, $precision) . $delimiter . $units[$i];
  46. }
  47. }
  48. if (!function_exists('datetime')) {
  49. /**
  50. * 将时间戳转换为日期时间
  51. * @param int $time 时间戳
  52. * @param string $format 日期时间格式
  53. * @return string
  54. */
  55. function datetime($time, $format = 'Y-m-d H:i:s')
  56. {
  57. $time = is_numeric($time) ? $time : strtotime($time);
  58. return date($format, $time);
  59. }
  60. }
  61. if (!function_exists('human_date')) {
  62. /**
  63. * 获取语义化时间
  64. * @param int $time 时间
  65. * @param int $local 本地时间
  66. * @return string
  67. */
  68. function human_date($time, $local = null)
  69. {
  70. return \fast\Date::human($time, $local);
  71. }
  72. }
  73. if (!function_exists('cdnurl')) {
  74. /**
  75. * 获取上传资源的CDN的地址
  76. * @param string $url 资源相对地址
  77. * @param boolean $domain 是否显示域名 或者直接传入域名
  78. * @return string
  79. */
  80. function cdnurl($url, $domain = false)
  81. {
  82. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  83. $cdnurl = \think\Config::get('upload.cdnurl');
  84. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  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'] = isset($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'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  210. $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
  211. $v['column'] = isset($v['column']) ? $v['column'] : 'name';
  212. $v['model'] = isset($v['model']) ? $v['model'] : '';
  213. $v['table'] = isset($v['table']) ? $v['table'] : '';
  214. $v['name'] = isset($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("{$primary},{$v['column']}") : [];
  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. $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
  241. }
  242. }
  243. }
  244. return $items;
  245. }
  246. }
  247. if (!function_exists('var_export_short')) {
  248. /**
  249. * 使用短标签打印或返回数组结构
  250. * @param mixed $data
  251. * @param boolean $return 是否返回数据
  252. * @return string
  253. */
  254. function var_export_short($data, $return = true)
  255. {
  256. return var_export($data, $return);
  257. $replaced = [];
  258. $count = 0;
  259. //判断是否是对象
  260. if (is_resource($data) || is_object($data)) {
  261. return var_export($data, $return);
  262. }
  263. //判断是否有特殊的键名
  264. $specialKey = false;
  265. array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
  266. if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
  267. $specialKey = true;
  268. }
  269. });
  270. if ($specialKey) {
  271. return var_export($data, $return);
  272. }
  273. array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
  274. if (is_object($value) || is_resource($value)) {
  275. $replaced[$count] = var_export($value, true);
  276. $value = "##<{$count}>##";
  277. } else {
  278. if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
  279. $index = array_search($value, $replaced);
  280. if ($index === false) {
  281. $replaced[$count] = var_export($value, true);
  282. $value = "##<{$count}>##";
  283. } else {
  284. $value = "##<{$index}>##";
  285. }
  286. }
  287. }
  288. $count++;
  289. });
  290. $dump = var_export($data, true);
  291. $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
  292. $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
  293. $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
  294. $dump = preg_replace('#\)$#', "]", $dump); //End
  295. if ($replaced) {
  296. $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
  297. return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
  298. }, $dump);
  299. }
  300. if ($return === true) {
  301. return $dump;
  302. } else {
  303. echo $dump;
  304. }
  305. }
  306. }
  307. if (!function_exists('letter_avatar')) {
  308. /**
  309. * 首字母头像
  310. * @param $text
  311. * @return string
  312. */
  313. function letter_avatar($text)
  314. {
  315. $total = unpack('L', hash('adler32', $text, true))[1];
  316. $hue = $total % 360;
  317. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  318. $bg = "rgb({$r},{$g},{$b})";
  319. $color = "#ffffff";
  320. $first = mb_strtoupper(mb_substr($text, 0, 1));
  321. $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>');
  322. $value = 'data:image/svg+xml;base64,' . $src;
  323. return $value;
  324. }
  325. }
  326. if (!function_exists('hsv2rgb')) {
  327. function hsv2rgb($h, $s, $v)
  328. {
  329. $r = $g = $b = 0;
  330. $i = floor($h * 6);
  331. $f = $h * 6 - $i;
  332. $p = $v * (1 - $s);
  333. $q = $v * (1 - $f * $s);
  334. $t = $v * (1 - (1 - $f) * $s);
  335. switch ($i % 6) {
  336. case 0:
  337. $r = $v;
  338. $g = $t;
  339. $b = $p;
  340. break;
  341. case 1:
  342. $r = $q;
  343. $g = $v;
  344. $b = $p;
  345. break;
  346. case 2:
  347. $r = $p;
  348. $g = $v;
  349. $b = $t;
  350. break;
  351. case 3:
  352. $r = $p;
  353. $g = $q;
  354. $b = $v;
  355. break;
  356. case 4:
  357. $r = $t;
  358. $g = $p;
  359. $b = $v;
  360. break;
  361. case 5:
  362. $r = $v;
  363. $g = $p;
  364. $b = $q;
  365. break;
  366. }
  367. return [
  368. floor($r * 255),
  369. floor($g * 255),
  370. floor($b * 255)
  371. ];
  372. }
  373. }
  374. if (!function_exists('check_nav_active')) {
  375. /**
  376. * 检测会员中心导航是否高亮
  377. */
  378. function check_nav_active($url, $classname = 'active')
  379. {
  380. $auth = \app\common\library\Auth::instance();
  381. $requestUrl = $auth->getRequestUri();
  382. $url = ltrim($url, '/');
  383. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  384. }
  385. }
  386. if (!function_exists('check_cors_request')) {
  387. /**
  388. * 跨域检测
  389. */
  390. function check_cors_request()
  391. {
  392. if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
  393. $info = parse_url($_SERVER['HTTP_ORIGIN']);
  394. $domainArr = explode(',', config('fastadmin.cors_request_domain'));
  395. $domainArr[] = request()->host(true);
  396. if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  397. header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  398. } else {
  399. header('HTTP/1.1 403 Forbidden');
  400. exit;
  401. }
  402. header('Access-Control-Allow-Credentials: true');
  403. header('Access-Control-Max-Age: 86400');
  404. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  405. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  406. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  407. }
  408. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  409. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  410. }
  411. exit;
  412. }
  413. }
  414. }
  415. }
  416. if (!function_exists('xss_clean')) {
  417. /**
  418. * 清理XSS
  419. */
  420. function xss_clean($content, $is_image = false)
  421. {
  422. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  423. }
  424. }
  425. if (!function_exists('check_ip_allowed')) {
  426. /**
  427. * 检测IP是否允许
  428. * @param string $ip IP地址
  429. */
  430. function check_ip_allowed($ip = null)
  431. {
  432. $ip = is_null($ip) ? request()->ip() : $ip;
  433. $forbiddenipArr = config('site.forbiddenip');
  434. $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
  435. $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
  436. if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
  437. header('HTTP/1.1 403 Forbidden');
  438. exit;
  439. }
  440. }
  441. }