common.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. if (!function_exists('format_bytes')) {
  26. /**
  27. * 将字节转换为可读文本
  28. * @param int $size 大小
  29. * @param string $delimiter 分隔符
  30. * @return string
  31. */
  32. function format_bytes($size, $delimiter = '')
  33. {
  34. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  35. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  36. $size /= 1024;
  37. }
  38. return round($size, 2) . $delimiter . $units[$i];
  39. }
  40. }
  41. if (!function_exists('datetime')) {
  42. /**
  43. * 将时间戳转换为日期时间
  44. * @param int $time 时间戳
  45. * @param string $format 日期时间格式
  46. * @return string
  47. */
  48. function datetime($time, $format = 'Y-m-d H:i:s')
  49. {
  50. $time = is_numeric($time) ? $time : strtotime($time);
  51. return date($format, $time);
  52. }
  53. }
  54. if (!function_exists('human_date')) {
  55. /**
  56. * 获取语义化时间
  57. * @param int $time 时间
  58. * @param int $local 本地时间
  59. * @return string
  60. */
  61. function human_date($time, $local = null)
  62. {
  63. return \fast\Date::human($time, $local);
  64. }
  65. }
  66. if (!function_exists('cdnurl')) {
  67. /**
  68. * 获取上传资源的CDN的地址
  69. * @param string $url 资源相对地址
  70. * @param boolean $domain 是否显示域名 或者直接传入域名
  71. * @return string
  72. */
  73. function cdnurl($url, $domain = false)
  74. {
  75. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  76. $cdnurl = \think\Config::get('upload.cdnurl');
  77. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  78. if ($domain && !preg_match($regex, $url)) {
  79. $domain = is_bool($domain) ? request()->domain() : $domain;
  80. $url = $domain . $url;
  81. }
  82. return $url;
  83. }
  84. }
  85. if (!function_exists('is_really_writable')) {
  86. /**
  87. * 判断文件或文件夹是否可写
  88. * @param string $file 文件或目录
  89. * @return bool
  90. */
  91. function is_really_writable($file)
  92. {
  93. if (DIRECTORY_SEPARATOR === '/') {
  94. return is_writable($file);
  95. }
  96. if (is_dir($file)) {
  97. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  98. if (($fp = @fopen($file, 'ab')) === false) {
  99. return false;
  100. }
  101. fclose($fp);
  102. @chmod($file, 0777);
  103. @unlink($file);
  104. return true;
  105. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  106. return false;
  107. }
  108. fclose($fp);
  109. return true;
  110. }
  111. }
  112. if (!function_exists('rmdirs')) {
  113. /**
  114. * 删除文件夹
  115. * @param string $dirname 目录
  116. * @param bool $withself 是否删除自身
  117. * @return boolean
  118. */
  119. function rmdirs($dirname, $withself = true)
  120. {
  121. if (!is_dir($dirname)) {
  122. return false;
  123. }
  124. $files = new RecursiveIteratorIterator(
  125. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  126. RecursiveIteratorIterator::CHILD_FIRST
  127. );
  128. foreach ($files as $fileinfo) {
  129. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  130. $todo($fileinfo->getRealPath());
  131. }
  132. if ($withself) {
  133. @rmdir($dirname);
  134. }
  135. return true;
  136. }
  137. }
  138. if (!function_exists('copydirs')) {
  139. /**
  140. * 复制文件夹
  141. * @param string $source 源文件夹
  142. * @param string $dest 目标文件夹
  143. */
  144. function copydirs($source, $dest)
  145. {
  146. if (!is_dir($dest)) {
  147. mkdir($dest, 0755, true);
  148. }
  149. foreach (
  150. $iterator = new RecursiveIteratorIterator(
  151. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  152. RecursiveIteratorIterator::SELF_FIRST
  153. ) as $item
  154. ) {
  155. if ($item->isDir()) {
  156. $sontDir = $dest . DS . $iterator->getSubPathName();
  157. if (!is_dir($sontDir)) {
  158. mkdir($sontDir, 0755, true);
  159. }
  160. } else {
  161. copy($item, $dest . DS . $iterator->getSubPathName());
  162. }
  163. }
  164. }
  165. }
  166. if (!function_exists('mb_ucfirst')) {
  167. function mb_ucfirst($string)
  168. {
  169. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  170. }
  171. }
  172. if (!function_exists('addtion')) {
  173. /**
  174. * 附加关联字段数据
  175. * @param array $items 数据列表
  176. * @param mixed $fields 渲染的来源字段
  177. * @return array
  178. */
  179. function addtion($items, $fields)
  180. {
  181. if (!$items || !$fields) {
  182. return $items;
  183. }
  184. $fieldsArr = [];
  185. if (!is_array($fields)) {
  186. $arr = explode(',', $fields);
  187. foreach ($arr as $k => $v) {
  188. $fieldsArr[$v] = ['field' => $v];
  189. }
  190. } else {
  191. foreach ($fields as $k => $v) {
  192. if (is_array($v)) {
  193. $v['field'] = isset($v['field']) ? $v['field'] : $k;
  194. } else {
  195. $v = ['field' => $v];
  196. }
  197. $fieldsArr[$v['field']] = $v;
  198. }
  199. }
  200. foreach ($fieldsArr as $k => &$v) {
  201. $v = is_array($v) ? $v : ['field' => $v];
  202. $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  203. $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
  204. $v['column'] = isset($v['column']) ? $v['column'] : 'name';
  205. $v['model'] = isset($v['model']) ? $v['model'] : '';
  206. $v['table'] = isset($v['table']) ? $v['table'] : '';
  207. $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
  208. }
  209. unset($v);
  210. $ids = [];
  211. $fields = array_keys($fieldsArr);
  212. foreach ($items as $k => $v) {
  213. foreach ($fields as $m => $n) {
  214. if (isset($v[$n])) {
  215. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  216. }
  217. }
  218. }
  219. $result = [];
  220. foreach ($fieldsArr as $k => $v) {
  221. if ($v['model']) {
  222. $model = new $v['model'];
  223. } else {
  224. $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
  225. }
  226. $primary = $v['primary'] ? $v['primary'] : $model->getPk();
  227. $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}") : [];
  228. }
  229. foreach ($items as $k => &$v) {
  230. foreach ($fields as $m => $n) {
  231. if (isset($v[$n])) {
  232. $curr = array_flip(explode(',', $v[$n]));
  233. $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
  234. }
  235. }
  236. }
  237. return $items;
  238. }
  239. }
  240. if (!function_exists('var_export_short')) {
  241. /**
  242. * 使用短标签打印或返回数组结构
  243. * @param mixed $data
  244. * @param boolean $return 是否返回数据
  245. * @return string
  246. */
  247. function var_export_short($data, $return = true)
  248. {
  249. return var_export($data, $return);
  250. $replaced = [];
  251. $count = 0;
  252. //判断是否是对象
  253. if (is_resource($data) || is_object($data)) {
  254. return var_export($data, $return);
  255. }
  256. //判断是否有特殊的键名
  257. $specialKey = false;
  258. array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
  259. if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
  260. $specialKey = true;
  261. }
  262. });
  263. if ($specialKey) {
  264. return var_export($data, $return);
  265. }
  266. array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
  267. if (is_object($value) || is_resource($value)) {
  268. $replaced[$count] = var_export($value, true);
  269. $value = "##<{$count}>##";
  270. } else {
  271. if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
  272. $index = array_search($value, $replaced);
  273. if ($index === false) {
  274. $replaced[$count] = var_export($value, true);
  275. $value = "##<{$count}>##";
  276. } else {
  277. $value = "##<{$index}>##";
  278. }
  279. }
  280. }
  281. $count++;
  282. });
  283. $dump = var_export($data, true);
  284. $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
  285. $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
  286. $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
  287. $dump = preg_replace('#\)$#', "]", $dump); //End
  288. if ($replaced) {
  289. $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
  290. return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
  291. }, $dump);
  292. }
  293. if ($return === true) {
  294. return $dump;
  295. } else {
  296. echo $dump;
  297. }
  298. }
  299. }
  300. if (!function_exists('letter_avatar')) {
  301. /**
  302. * 首字母头像
  303. * @param $text
  304. * @return string
  305. */
  306. function letter_avatar($text)
  307. {
  308. $total = unpack('L', hash('adler32', $text, true))[1];
  309. $hue = $total % 360;
  310. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  311. $bg = "rgb({$r},{$g},{$b})";
  312. $color = "#ffffff";
  313. $first = mb_strtoupper(mb_substr($text, 0, 1));
  314. $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>');
  315. $value = 'data:image/svg+xml;base64,' . $src;
  316. return $value;
  317. }
  318. }
  319. if (!function_exists('hsv2rgb')) {
  320. function hsv2rgb($h, $s, $v)
  321. {
  322. $r = $g = $b = 0;
  323. $i = floor($h * 6);
  324. $f = $h * 6 - $i;
  325. $p = $v * (1 - $s);
  326. $q = $v * (1 - $f * $s);
  327. $t = $v * (1 - (1 - $f) * $s);
  328. switch ($i % 6) {
  329. case 0:
  330. $r = $v;
  331. $g = $t;
  332. $b = $p;
  333. break;
  334. case 1:
  335. $r = $q;
  336. $g = $v;
  337. $b = $p;
  338. break;
  339. case 2:
  340. $r = $p;
  341. $g = $v;
  342. $b = $t;
  343. break;
  344. case 3:
  345. $r = $p;
  346. $g = $q;
  347. $b = $v;
  348. break;
  349. case 4:
  350. $r = $t;
  351. $g = $p;
  352. $b = $v;
  353. break;
  354. case 5:
  355. $r = $v;
  356. $g = $p;
  357. $b = $q;
  358. break;
  359. }
  360. return [
  361. floor($r * 255),
  362. floor($g * 255),
  363. floor($b * 255)
  364. ];
  365. }
  366. }
  367. if (!function_exists('check_nav_active')) {
  368. /**
  369. * 检测会员中心导航是否高亮
  370. */
  371. function check_nav_active($url, $classname = 'active')
  372. {
  373. $auth = \app\common\library\Auth::instance();
  374. $requestUrl = $auth->getRequestUri();
  375. $url = ltrim($url, '/');
  376. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  377. }
  378. }
  379. if (!function_exists('check_cors_request')) {
  380. /**
  381. * 跨域检测
  382. */
  383. function check_cors_request()
  384. {
  385. if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
  386. $info = parse_url($_SERVER['HTTP_ORIGIN']);
  387. $domainArr = explode(',', config('fastadmin.cors_request_domain'));
  388. $domainArr[] = request()->host();
  389. if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  390. header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  391. } else {
  392. header('HTTP/1.1 403 Forbidden');
  393. exit;
  394. }
  395. header('Access-Control-Allow-Credentials: true');
  396. header('Access-Control-Max-Age: 86400');
  397. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  398. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  399. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  400. }
  401. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  402. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  403. }
  404. exit;
  405. }
  406. }
  407. }
  408. }
  409. if (!function_exists('xss_clean')) {
  410. /**
  411. * 清理XSS
  412. */
  413. function xss_clean($content, $is_image = false)
  414. {
  415. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  416. }
  417. }