common.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. <?php
  2. // 公共助手函数
  3. use Symfony\Component\VarExporter\VarExporter;
  4. use Redis as Redis;
  5. if (!function_exists('__')) {
  6. /**
  7. * 获取语言变量值
  8. * @param string $name 语言变量名
  9. * @param array $vars 动态变量值
  10. * @param string $lang 语言
  11. * @return mixed
  12. */
  13. function __($name, $vars = [], $lang = '')
  14. {
  15. if (is_numeric($name) || !$name) {
  16. return $name;
  17. }
  18. if (!is_array($vars)) {
  19. $vars = func_get_args();
  20. array_shift($vars);
  21. $lang = '';
  22. }
  23. return \think\Lang::get($name, $vars, $lang);
  24. }
  25. }
  26. if (!function_exists('format_bytes')) {
  27. /**
  28. * 将字节转换为可读文本
  29. * @param int $size 大小
  30. * @param string $delimiter 分隔符
  31. * @param int $precision 小数位数
  32. * @return string
  33. */
  34. function format_bytes($size, $delimiter = '', $precision = 2)
  35. {
  36. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  37. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  38. $size /= 1024;
  39. }
  40. return round($size, $precision) . $delimiter . $units[$i];
  41. }
  42. }
  43. if (!function_exists('datetime')) {
  44. /**
  45. * 将时间戳转换为日期时间
  46. * @param int $time 时间戳
  47. * @param string $format 日期时间格式
  48. * @return string
  49. */
  50. function datetime($time, $format = 'Y-m-d H:i:s')
  51. {
  52. $time = is_numeric($time) ? $time : strtotime($time);
  53. return date($format, $time);
  54. }
  55. }
  56. if (!function_exists('human_date')) {
  57. /**
  58. * 获取语义化时间
  59. * @param int $time 时间
  60. * @param int $local 本地时间
  61. * @return string
  62. */
  63. function human_date($time, $local = null)
  64. {
  65. return \fast\Date::human($time, $local);
  66. }
  67. }
  68. if (!function_exists('cdnurl')) {
  69. /**
  70. * 获取上传资源的CDN的地址
  71. * @param string $url 资源相对地址
  72. * @param boolean $domain 是否显示域名 或者直接传入域名
  73. * @return string
  74. */
  75. function cdnurl($url, $domain = false)
  76. {
  77. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  78. $cdnurl = \think\Config::get('upload.cdnurl');
  79. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  80. if ($domain && !preg_match($regex, $url)) {
  81. $domain = is_bool($domain) ? request()->domain() : $domain;
  82. $url = $domain . $url;
  83. }
  84. return $url;
  85. }
  86. }
  87. if (!function_exists('is_really_writable')) {
  88. /**
  89. * 判断文件或文件夹是否可写
  90. * @param string $file 文件或目录
  91. * @return bool
  92. */
  93. function is_really_writable($file)
  94. {
  95. if (DIRECTORY_SEPARATOR === '/') {
  96. return is_writable($file);
  97. }
  98. if (is_dir($file)) {
  99. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  100. if (($fp = @fopen($file, 'ab')) === false) {
  101. return false;
  102. }
  103. fclose($fp);
  104. @chmod($file, 0777);
  105. @unlink($file);
  106. return true;
  107. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  108. return false;
  109. }
  110. fclose($fp);
  111. return true;
  112. }
  113. }
  114. if (!function_exists('rmdirs')) {
  115. /**
  116. * 删除文件夹
  117. * @param string $dirname 目录
  118. * @param bool $withself 是否删除自身
  119. * @return boolean
  120. */
  121. function rmdirs($dirname, $withself = true)
  122. {
  123. if (!is_dir($dirname)) {
  124. return false;
  125. }
  126. $files = new RecursiveIteratorIterator(
  127. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  128. RecursiveIteratorIterator::CHILD_FIRST
  129. );
  130. foreach ($files as $fileinfo) {
  131. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  132. $todo($fileinfo->getRealPath());
  133. }
  134. if ($withself) {
  135. @rmdir($dirname);
  136. }
  137. return true;
  138. }
  139. }
  140. if (!function_exists('copydirs')) {
  141. /**
  142. * 复制文件夹
  143. * @param string $source 源文件夹
  144. * @param string $dest 目标文件夹
  145. */
  146. function copydirs($source, $dest)
  147. {
  148. if (!is_dir($dest)) {
  149. mkdir($dest, 0755, true);
  150. }
  151. foreach (
  152. $iterator = new RecursiveIteratorIterator(
  153. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  154. RecursiveIteratorIterator::SELF_FIRST
  155. ) as $item
  156. ) {
  157. if ($item->isDir()) {
  158. $sontDir = $dest . DS . $iterator->getSubPathName();
  159. if (!is_dir($sontDir)) {
  160. mkdir($sontDir, 0755, true);
  161. }
  162. } else {
  163. copy($item, $dest . DS . $iterator->getSubPathName());
  164. }
  165. }
  166. }
  167. }
  168. if (!function_exists('mb_ucfirst')) {
  169. function mb_ucfirst($string)
  170. {
  171. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  172. }
  173. }
  174. if (!function_exists('addtion')) {
  175. /**
  176. * 附加关联字段数据
  177. * @param array $items 数据列表
  178. * @param mixed $fields 渲染的来源字段
  179. * @return array
  180. */
  181. function addtion($items, $fields)
  182. {
  183. if (!$items || !$fields) {
  184. return $items;
  185. }
  186. $fieldsArr = [];
  187. if (!is_array($fields)) {
  188. $arr = explode(',', $fields);
  189. foreach ($arr as $k => $v) {
  190. $fieldsArr[$v] = ['field' => $v];
  191. }
  192. } else {
  193. foreach ($fields as $k => $v) {
  194. if (is_array($v)) {
  195. $v['field'] = isset($v['field']) ? $v['field'] : $k;
  196. } else {
  197. $v = ['field' => $v];
  198. }
  199. $fieldsArr[$v['field']] = $v;
  200. }
  201. }
  202. foreach ($fieldsArr as $k => &$v) {
  203. $v = is_array($v) ? $v : ['field' => $v];
  204. $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  205. $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
  206. $v['column'] = isset($v['column']) ? $v['column'] : 'name';
  207. $v['model'] = isset($v['model']) ? $v['model'] : '';
  208. $v['table'] = isset($v['table']) ? $v['table'] : '';
  209. $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
  210. }
  211. unset($v);
  212. $ids = [];
  213. $fields = array_keys($fieldsArr);
  214. foreach ($items as $k => $v) {
  215. foreach ($fields as $m => $n) {
  216. if (isset($v[$n])) {
  217. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  218. }
  219. }
  220. }
  221. $result = [];
  222. foreach ($fieldsArr as $k => $v) {
  223. if ($v['model']) {
  224. $model = new $v['model'];
  225. } else {
  226. $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
  227. }
  228. $primary = $v['primary'] ? $v['primary'] : $model->getPk();
  229. $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}") : [];
  230. }
  231. foreach ($items as $k => &$v) {
  232. foreach ($fields as $m => $n) {
  233. if (isset($v[$n])) {
  234. $curr = array_flip(explode(',', $v[$n]));
  235. $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
  236. }
  237. }
  238. }
  239. return $items;
  240. }
  241. }
  242. if (!function_exists('var_export_short')) {
  243. /**
  244. * 使用短标签打印或返回数组结构
  245. * @param mixed $data
  246. * @param boolean $return 是否返回数据
  247. * @return string
  248. */
  249. function var_export_short($data, $return = true)
  250. {
  251. return var_export($data, $return);
  252. $replaced = [];
  253. $count = 0;
  254. //判断是否是对象
  255. if (is_resource($data) || is_object($data)) {
  256. return var_export($data, $return);
  257. }
  258. //判断是否有特殊的键名
  259. $specialKey = false;
  260. array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
  261. if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
  262. $specialKey = true;
  263. }
  264. });
  265. if ($specialKey) {
  266. return var_export($data, $return);
  267. }
  268. array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
  269. if (is_object($value) || is_resource($value)) {
  270. $replaced[$count] = var_export($value, true);
  271. $value = "##<{$count}>##";
  272. } else {
  273. if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
  274. $index = array_search($value, $replaced);
  275. if ($index === false) {
  276. $replaced[$count] = var_export($value, true);
  277. $value = "##<{$count}>##";
  278. } else {
  279. $value = "##<{$index}>##";
  280. }
  281. }
  282. }
  283. $count++;
  284. });
  285. $dump = var_export($data, true);
  286. $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
  287. $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
  288. $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
  289. $dump = preg_replace('#\)$#', "]", $dump); //End
  290. if ($replaced) {
  291. $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
  292. return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
  293. }, $dump);
  294. }
  295. if ($return === true) {
  296. return $dump;
  297. } else {
  298. echo $dump;
  299. }
  300. }
  301. }
  302. if (!function_exists('letter_avatar')) {
  303. /**
  304. * 首字母头像
  305. * @param $text
  306. * @return string
  307. */
  308. function letter_avatar($text)
  309. {
  310. $total = unpack('L', hash('adler32', $text, true))[1];
  311. $hue = $total % 360;
  312. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  313. $bg = "rgb({$r},{$g},{$b})";
  314. $color = "#ffffff";
  315. $first = mb_strtoupper(mb_substr($text, 0, 1));
  316. $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>');
  317. $value = 'data:image/svg+xml;base64,' . $src;
  318. return $value;
  319. }
  320. }
  321. if (!function_exists('hsv2rgb')) {
  322. function hsv2rgb($h, $s, $v)
  323. {
  324. $r = $g = $b = 0;
  325. $i = floor($h * 6);
  326. $f = $h * 6 - $i;
  327. $p = $v * (1 - $s);
  328. $q = $v * (1 - $f * $s);
  329. $t = $v * (1 - (1 - $f) * $s);
  330. switch ($i % 6) {
  331. case 0:
  332. $r = $v;
  333. $g = $t;
  334. $b = $p;
  335. break;
  336. case 1:
  337. $r = $q;
  338. $g = $v;
  339. $b = $p;
  340. break;
  341. case 2:
  342. $r = $p;
  343. $g = $v;
  344. $b = $t;
  345. break;
  346. case 3:
  347. $r = $p;
  348. $g = $q;
  349. $b = $v;
  350. break;
  351. case 4:
  352. $r = $t;
  353. $g = $p;
  354. $b = $v;
  355. break;
  356. case 5:
  357. $r = $v;
  358. $g = $p;
  359. $b = $q;
  360. break;
  361. }
  362. return [
  363. floor($r * 255),
  364. floor($g * 255),
  365. floor($b * 255)
  366. ];
  367. }
  368. }
  369. if (!function_exists('check_nav_active')) {
  370. /**
  371. * 检测会员中心导航是否高亮
  372. */
  373. function check_nav_active($url, $classname = 'active')
  374. {
  375. $auth = \app\common\library\Auth::instance();
  376. $requestUrl = $auth->getRequestUri();
  377. $url = ltrim($url, '/');
  378. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  379. }
  380. }
  381. if (!function_exists('check_cors_request')) {
  382. /**
  383. * 跨域检测
  384. */
  385. function check_cors_request()
  386. {
  387. if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
  388. $info = parse_url($_SERVER['HTTP_ORIGIN']);
  389. $domainArr = explode(',', config('fastadmin.cors_request_domain'));
  390. $domainArr[] = request()->host(true);
  391. if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  392. header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  393. } else {
  394. header('HTTP/1.1 403 Forbidden');
  395. exit;
  396. }
  397. header('Access-Control-Allow-Credentials: true');
  398. header('Access-Control-Max-Age: 86400');
  399. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  400. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  401. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  402. }
  403. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  404. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  405. }
  406. exit;
  407. }
  408. }
  409. }
  410. }
  411. if (!function_exists('xss_clean')) {
  412. /**
  413. * 清理XSS
  414. */
  415. function xss_clean($content, $is_image = false)
  416. {
  417. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  418. }
  419. }
  420. if (!function_exists('check_ip_allowed')) {
  421. /**
  422. * 检测IP是否允许
  423. * @param string $ip IP地址
  424. */
  425. function check_ip_allowed($ip = null)
  426. {
  427. $ip = is_null($ip) ? request()->ip() : $ip;
  428. $forbiddenipArr = config('site.forbiddenip');
  429. $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
  430. $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
  431. if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
  432. header('HTTP/1.1 403 Forbidden');
  433. exit;
  434. }
  435. }
  436. }
  437. if (!function_exists('httpurllocal')) {
  438. /**
  439. * 判断当前url是否为全路径,并返回全路径
  440. */
  441. function httpurllocal($path) {
  442. if(!$path) return $path;
  443. $host = $_SERVER["REQUEST_SCHEME"]."://".$_SERVER["HTTP_HOST"];
  444. // 获取当前域名
  445. if(strpos($path,'http://') === false && strpos($path,'https://') === false) {
  446. $url = $host.$path;
  447. } else {
  448. $url = $path;
  449. }
  450. return $url;
  451. }
  452. }
  453. if (!function_exists('httpurl')) {
  454. /**
  455. * 判断当前url是否为全路径,并返回全路径
  456. */
  457. function httpurl($path) {
  458. if(!$path) return $path;
  459. $host = config("oss")['url']?config("oss")['url']:$_SERVER["REQUEST_SCHEME"]."://".$_SERVER["HTTP_HOST"];
  460. // 获取当前域名
  461. if(strpos($path,'http://') === false && strpos($path,'https://') === false) {
  462. $url = $host.$path;
  463. } else {
  464. $url = $path;
  465. }
  466. return $url;
  467. }
  468. }
  469. if (!function_exists('sensitive')) {
  470. /**
  471. * @param array $list 定义敏感词一维数组
  472. * @param string $string 要过滤的内容
  473. * @return string $log 处理结果
  474. * @todo 敏感词过滤,返回结果
  475. */
  476. function sensitive($string) {
  477. $str = ['count'=>0,'sensitiveWord'=>'','stringAfter'=>''];
  478. $list_arr = config('site.sensitiveWords');
  479. $list = explode(',',$list_arr);
  480. if(!$list || !$string) return $str;
  481. $count = 0; //违规词的个数
  482. $sensitiveWord = ''; //违规词
  483. $stringAfter = $string; //替换后的内容
  484. $pattern = "/" . implode("|", $list) . "/i"; //定义正则表达式
  485. if (preg_match_all($pattern, $string, $matches)) { //匹配到了结果
  486. $patternList = $matches[0]; //匹配到的数组
  487. $count = count($patternList);
  488. $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
  489. $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '**')); //把匹配到的数组进行合并,替换使用
  490. $stringAfter = strtr($string, $replaceArray); //结果替换
  491. }
  492. $str['count'] = $count;
  493. $str['sensitiveWord'] = $sensitiveWord;
  494. $str['stringAfter'] = $stringAfter;
  495. return $str;
  496. }
  497. }
  498. if (!function_exists('getVideoCover')) {
  499. function getVideoCover($file, $time, $name)
  500. {
  501. // 视频宽高 -- 开始
  502. $command = sprintf(config('project_path') . '/ffmpeg -i "%s" 2>&1', $file);
  503. ob_start();
  504. passthru($command);
  505. $info = ob_get_contents();
  506. ob_end_clean();
  507. if (preg_match("/Video: (.*?), (.*?), (.*?), (.*?)[,\s]/", $info, $match)) {
  508. $resolution_str = $match[0];
  509. $resolution_arr = explode(" ",$resolution_str);
  510. if($resolution_arr) foreach($resolution_arr as $k => $v) {
  511. if(strpos($v,"x")) {
  512. $resolution = explode(",",$v)[0];
  513. }
  514. }
  515. } else {
  516. $resolution = '251x334';
  517. }
  518. // 视频宽高 -- 结束
  519. if (empty($time)) $time = 0.1;//默认截取第一秒第一帧
  520. $str = config('project_path') . "/ffmpeg -i " . $file . " -y -f mjpeg -ss 3 -t " . $time . " -s ".$resolution." " . $name;
  521. exec($str.' 2>&1',$result);
  522. return $result;
  523. }
  524. }
  525. if (!function_exists('encodeArray')) {
  526. function encodeArray($array) {
  527. if(!is_array($array)) {
  528. return false;
  529. }
  530. if($array) foreach($array as $k => $v) {
  531. if(is_array($v)) {
  532. $array[$k] = json_encode($v);
  533. }
  534. }
  535. return $array;
  536. }
  537. }
  538. if (!function_exists('decodeArray')) {
  539. function decodeArray($array) {
  540. if(!is_array($array)) {
  541. return false;
  542. }
  543. if($array) foreach($array as $k => $v) {
  544. $array[$k] = json_decode($v,true)?:$v;
  545. }
  546. return $array;
  547. }
  548. }
  549. if (!function_exists('delUserInfo')) {
  550. function delUserInfo($user_id) {
  551. return true;
  552. // redis
  553. $redis = new Redis();
  554. $redisconfig = config("redis");
  555. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  556. $redis->del('userInfo_'.$user_id);
  557. }
  558. }
  559. function getVideoInfo($file) {
  560. $command = sprintf(FFMPEG_PATH, $file);
  561. ob_start();
  562. passthru($command);
  563. $info = ob_get_contents();
  564. ob_end_clean();
  565. $data = [];
  566. if (preg_match("/Video: (.*?), (.*?), (.*?)[,\s]/", $info, $match)) {
  567. $arr_resolution = explode('x', $match[3]);
  568. $data['width'] = $arr_resolution[0];
  569. $data['height'] = isset($arr_resolution[1]) ? $arr_resolution[1] : '';
  570. }
  571. return $data;
  572. }
  573. function p($arr) {
  574. header('content-type:text/html;charset=utf-8');
  575. echo '<pre>';
  576. print_r($arr);
  577. echo '</pre>';
  578. }
  579. /**
  580. * 手机格式验证
  581. * @param string $mobile 验证的手机号码
  582. * @return boolean
  583. */
  584. function is_mobile($mobile) {
  585. if (!empty($mobile)) {
  586. return preg_match('/^1[3|4|5|6|7|8|9][0-9]\d{8}$/', $mobile);
  587. }
  588. return false;
  589. }
  590. /**
  591. * [getMillisecond 获取毫秒级时间戳]
  592. * @return [type] [description]
  593. */
  594. function getMillisecond() {
  595. list($t1, $t2) = explode(' ', microtime());
  596. return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
  597. }