common.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. <?php
  2. // 公共助手函数
  3. use think\exception\HttpResponseException;
  4. use think\Response;
  5. use fast\Random;
  6. if (!function_exists('__')) {
  7. /**
  8. * 获取语言变量值
  9. * @param string $name 语言变量名
  10. * @param string | 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 < 5; $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. if (empty($url)) return '';
  79. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  80. $cdnurl = \think\Config::get('upload.cdnurl');
  81. if (is_bool($domain) || stripos($cdnurl, '/') === 0) {
  82. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  83. }
  84. if ($domain && !preg_match($regex, $url)) {
  85. $domain = is_bool($domain) ? request()->domain() : $domain;
  86. $url = $domain . $url;
  87. }
  88. return $url;
  89. }
  90. }
  91. /**
  92. * 自动拼im id前缀
  93. * @param $user_id
  94. * @return mixed
  95. */
  96. if (!function_exists('im_prefix')) {
  97. function im_prefix($user_id)
  98. {
  99. return config('tencent_im.chat_prefix').$user_id;
  100. }
  101. }
  102. if (!function_exists('is_really_writable')) {
  103. /**
  104. * 判断文件或文件夹是否可写
  105. * @param string $file 文件或目录
  106. * @return bool
  107. */
  108. function is_really_writable($file)
  109. {
  110. if (DIRECTORY_SEPARATOR === '/') {
  111. return is_writable($file);
  112. }
  113. if (is_dir($file)) {
  114. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  115. if (($fp = @fopen($file, 'ab')) === false) {
  116. return false;
  117. }
  118. fclose($fp);
  119. @chmod($file, 0777);
  120. @unlink($file);
  121. return true;
  122. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  123. return false;
  124. }
  125. fclose($fp);
  126. return true;
  127. }
  128. }
  129. if (!function_exists('rmdirs')) {
  130. /**
  131. * 删除文件夹
  132. * @param string $dirname 目录
  133. * @param bool $withself 是否删除自身
  134. * @return boolean
  135. */
  136. function rmdirs($dirname, $withself = true)
  137. {
  138. if (!is_dir($dirname)) {
  139. return false;
  140. }
  141. $files = new RecursiveIteratorIterator(
  142. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  143. RecursiveIteratorIterator::CHILD_FIRST
  144. );
  145. foreach ($files as $fileinfo) {
  146. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  147. $todo($fileinfo->getRealPath());
  148. }
  149. if ($withself) {
  150. @rmdir($dirname);
  151. }
  152. return true;
  153. }
  154. }
  155. if (!function_exists('copydirs')) {
  156. /**
  157. * 复制文件夹
  158. * @param string $source 源文件夹
  159. * @param string $dest 目标文件夹
  160. */
  161. function copydirs($source, $dest)
  162. {
  163. if (!is_dir($dest)) {
  164. mkdir($dest, 0755, true);
  165. }
  166. foreach (
  167. $iterator = new RecursiveIteratorIterator(
  168. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  169. RecursiveIteratorIterator::SELF_FIRST
  170. ) as $item
  171. ) {
  172. if ($item->isDir()) {
  173. $sontDir = $dest . DS . $iterator->getSubPathName();
  174. if (!is_dir($sontDir)) {
  175. mkdir($sontDir, 0755, true);
  176. }
  177. } else {
  178. copy($item, $dest . DS . $iterator->getSubPathName());
  179. }
  180. }
  181. }
  182. }
  183. if (!function_exists('mb_ucfirst')) {
  184. function mb_ucfirst($string)
  185. {
  186. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  187. }
  188. }
  189. if (!function_exists('addtion')) {
  190. /**
  191. * 附加关联字段数据
  192. * @param array $items 数据列表
  193. * @param mixed $fields 渲染的来源字段
  194. * @return array
  195. */
  196. function addtion($items, $fields)
  197. {
  198. if (!$items || !$fields) {
  199. return $items;
  200. }
  201. $fieldsArr = [];
  202. if (!is_array($fields)) {
  203. $arr = explode(',', $fields);
  204. foreach ($arr as $k => $v) {
  205. $fieldsArr[$v] = ['field' => $v];
  206. }
  207. } else {
  208. foreach ($fields as $k => $v) {
  209. if (is_array($v)) {
  210. $v['field'] = $v['field'] ?? $k;
  211. } else {
  212. $v = ['field' => $v];
  213. }
  214. $fieldsArr[$v['field']] = $v;
  215. }
  216. }
  217. foreach ($fieldsArr as $k => &$v) {
  218. $v = is_array($v) ? $v : ['field' => $v];
  219. $v['display'] = $v['display'] ?? str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  220. $v['primary'] = $v['primary'] ?? '';
  221. $v['column'] = $v['column'] ?? 'name';
  222. $v['model'] = $v['model'] ?? '';
  223. $v['table'] = $v['table'] ?? '';
  224. $v['name'] = $v['name'] ?? str_replace(['_ids', '_id'], '', $v['field']);
  225. }
  226. unset($v);
  227. $ids = [];
  228. $fields = array_keys($fieldsArr);
  229. foreach ($items as $k => $v) {
  230. foreach ($fields as $m => $n) {
  231. if (isset($v[$n])) {
  232. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  233. }
  234. }
  235. }
  236. $result = [];
  237. foreach ($fieldsArr as $k => $v) {
  238. if ($v['model']) {
  239. $model = new $v['model'];
  240. } else {
  241. // 优先判断使用table的配置
  242. $model = $v['table'] ? \think\Db::table($v['table']) : \think\Db::name($v['name']);
  243. }
  244. $primary = $v['primary'] ?: $model->getPk();
  245. $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
  246. }
  247. foreach ($items as $k => &$v) {
  248. foreach ($fields as $m => $n) {
  249. if (isset($v[$n])) {
  250. $curr = array_flip(explode(',', $v[$n]));
  251. $linedata = array_intersect_key($result[$n], $curr);
  252. $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
  253. }
  254. }
  255. }
  256. return $items;
  257. }
  258. }
  259. if (!function_exists('var_export_short')) {
  260. /**
  261. * 使用短标签打印或返回数组结构
  262. * @param mixed $data
  263. * @param boolean $return 是否返回数据
  264. * @return string
  265. */
  266. function var_export_short($data, $return = true)
  267. {
  268. return var_export($data, $return);
  269. }
  270. }
  271. if (!function_exists('letter_avatar')) {
  272. /**
  273. * 首字母头像
  274. * @param $text
  275. * @return string
  276. */
  277. function letter_avatar($text)
  278. {
  279. $total = unpack('L', hash('adler32', $text, true))[1];
  280. $hue = $total % 360;
  281. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  282. $bg = "rgb({$r},{$g},{$b})";
  283. $color = "#ffffff";
  284. $first = mb_strtoupper(mb_substr($text, 0, 1));
  285. $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>');
  286. $value = 'data:image/svg+xml;base64,' . $src;
  287. return $value;
  288. }
  289. }
  290. if (!function_exists('hsv2rgb')) {
  291. function hsv2rgb($h, $s, $v)
  292. {
  293. $r = $g = $b = 0;
  294. $i = floor($h * 6);
  295. $f = $h * 6 - $i;
  296. $p = $v * (1 - $s);
  297. $q = $v * (1 - $f * $s);
  298. $t = $v * (1 - (1 - $f) * $s);
  299. switch ($i % 6) {
  300. case 0:
  301. $r = $v;
  302. $g = $t;
  303. $b = $p;
  304. break;
  305. case 1:
  306. $r = $q;
  307. $g = $v;
  308. $b = $p;
  309. break;
  310. case 2:
  311. $r = $p;
  312. $g = $v;
  313. $b = $t;
  314. break;
  315. case 3:
  316. $r = $p;
  317. $g = $q;
  318. $b = $v;
  319. break;
  320. case 4:
  321. $r = $t;
  322. $g = $p;
  323. $b = $v;
  324. break;
  325. case 5:
  326. $r = $v;
  327. $g = $p;
  328. $b = $q;
  329. break;
  330. }
  331. return [
  332. floor($r * 255),
  333. floor($g * 255),
  334. floor($b * 255)
  335. ];
  336. }
  337. }
  338. if (!function_exists('check_nav_active')) {
  339. /**
  340. * 检测会员中心导航是否高亮
  341. */
  342. function check_nav_active($url, $classname = 'active')
  343. {
  344. $auth = \app\common\library\Auth::instance();
  345. $requestUrl = $auth->getRequestUri();
  346. $url = ltrim($url, '/');
  347. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  348. }
  349. }
  350. if (!function_exists('check_cors_request')) {
  351. /**
  352. * 跨域检测
  353. */
  354. function check_cors_request()
  355. {
  356. if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] && config('fastadmin.cors_request_domain')) {
  357. $info = parse_url($_SERVER['HTTP_ORIGIN']);
  358. $domainArr = explode(',', config('fastadmin.cors_request_domain'));
  359. $domainArr[] = request()->host(true);
  360. if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  361. header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  362. } else {
  363. $response = Response::create('跨域检测无效', 'html', 403);
  364. throw new HttpResponseException($response);
  365. }
  366. header('Access-Control-Allow-Credentials: true');
  367. header('Access-Control-Max-Age: 86400');
  368. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  369. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  370. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  371. }
  372. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  373. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  374. }
  375. $response = Response::create('', 'html');
  376. throw new HttpResponseException($response);
  377. }
  378. }
  379. }
  380. }
  381. if (!function_exists('xss_clean')) {
  382. /**
  383. * 清理XSS
  384. */
  385. function xss_clean($content, $is_image = false)
  386. {
  387. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  388. }
  389. }
  390. if (!function_exists('url_clean')) {
  391. /**
  392. * 清理URL
  393. */
  394. function url_clean($url)
  395. {
  396. if (!check_url_allowed($url)) {
  397. return '';
  398. }
  399. return xss_clean($url);
  400. }
  401. }
  402. if (!function_exists('check_ip_allowed')) {
  403. /**
  404. * 检测IP是否允许
  405. * @param string $ip IP地址
  406. */
  407. function check_ip_allowed($ip = null)
  408. {
  409. $ip = is_null($ip) ? request()->ip() : $ip;
  410. $forbiddenipArr = config('site.forbiddenip');
  411. $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
  412. $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
  413. if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
  414. $response = Response::create('请求无权访问', 'html', 403);
  415. throw new HttpResponseException($response);
  416. }
  417. }
  418. }
  419. if (!function_exists('check_url_allowed')) {
  420. /**
  421. * 检测URL是否允许
  422. * @param string $url URL
  423. * @return bool
  424. */
  425. function check_url_allowed($url = '')
  426. {
  427. //允许的主机列表
  428. $allowedHostArr = [
  429. strtolower(request()->host())
  430. ];
  431. if (empty($url)) {
  432. return true;
  433. }
  434. //如果是站内相对链接则允许
  435. if (preg_match("/^[\/a-z][a-z0-9][a-z0-9\.\/]+((\?|#).*)?\$/i", $url) && substr($url, 0, 2) !== '//') {
  436. return true;
  437. }
  438. //如果是站外链接则需要判断HOST是否允许
  439. if (preg_match("/((http[s]?:\/\/)+((?>[a-z\-0-9]{2,}\.)+[a-z]{2,8}|((?>([0-9]{1,3}\.)){3}[0-9]{1,3}))(:[0-9]{1,5})?)(?:\s|\/)/i", $url)) {
  440. $chkHost = parse_url(strtolower($url), PHP_URL_HOST);
  441. if ($chkHost && in_array($chkHost, $allowedHostArr)) {
  442. return true;
  443. }
  444. }
  445. return false;
  446. }
  447. }
  448. if (!function_exists('build_suffix_image')) {
  449. /**
  450. * 生成文件后缀图片
  451. * @param string $suffix 后缀
  452. * @param null $background
  453. * @return string
  454. */
  455. function build_suffix_image($suffix, $background = null)
  456. {
  457. $suffix = mb_substr(strtoupper($suffix), 0, 4);
  458. $total = unpack('L', hash('adler32', $suffix, true))[1];
  459. $hue = $total % 360;
  460. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  461. $background = $background ? $background : "rgb({$r},{$g},{$b})";
  462. $icon = <<<EOT
  463. <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">
  464. <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"/>
  465. <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
  466. <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
  467. <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"/>
  468. <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
  469. <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>
  470. </svg>
  471. EOT;
  472. return $icon;
  473. }
  474. }
  475. //////////////自定义///////////////////////////
  476. if (!function_exists('list_domain_image')) {
  477. //结果集信息里,多个字段需要增加domain_cdnurl
  478. function list_domain_image($list, $field)
  479. {
  480. if (!$list || empty($list)) {
  481. return $list;
  482. }
  483. foreach ($list as $vo => $info) {
  484. $list[$vo] = info_domain_image($info, $field);
  485. }
  486. return $list;
  487. }
  488. }
  489. if (!function_exists('info_domain_image')) {
  490. //单条信息里,多个字段需要增加domain_cdnurl
  491. //支持image,images
  492. function info_domain_image($data, $field)
  493. {
  494. if (!$data || empty($data)) {
  495. return $data;
  496. }
  497. foreach ($data as $key => $val) {
  498. if (in_array($key, $field)) {
  499. $data[$key] = one_domain_image($val);
  500. }
  501. }
  502. return $data;
  503. }
  504. }
  505. if (!function_exists('one_domain_image')) {
  506. //支持单个字段,需要增加domain_cdnurl
  507. //支持image,images
  508. function one_domain_image($one)
  509. {
  510. if (!$one) {
  511. return $one;
  512. }
  513. if (strpos($one, ',')){
  514. //逗号隔开的多个图片
  515. $one = explode(',', $one);
  516. foreach ($one as $k => $v) {
  517. $one[$k] = localpath_to_netpath($v);
  518. }
  519. $one = implode(',',$one);
  520. } else {
  521. $one = localpath_to_netpath($one);
  522. }
  523. return $one;
  524. }
  525. }
  526. if (!function_exists('array_domain_image')) {
  527. //支持单个字段,需要增加domain_cdnurl
  528. //支持image,images
  529. function array_domain_image($one)
  530. {
  531. if(!empty($one)){
  532. foreach ($one as $key => $val) {
  533. $one[$key] = localpath_to_netpath($val);
  534. }
  535. }
  536. return $one;
  537. }
  538. }
  539. if (!function_exists('localpath_to_netpath')) {
  540. //本地地址转换为网络地址
  541. function localpath_to_netpath($path)
  542. {
  543. if (empty($path)) {
  544. return '';
  545. } elseif (strrpos($path, 'http') !== false) {
  546. return $path;
  547. } else {
  548. // return config('pay_notify_url') . str_replace("\\", "/", $path);
  549. return config('upload.cdnurl') . str_replace("\\", "/", $path);
  550. }
  551. }
  552. }
  553. if (!function_exists('request_post_hub')) {
  554. //post接收参数中心,只接非必须
  555. function request_post_hub($field_array = [],$required = [],$noempty = []){
  556. if(empty($field_array)){
  557. return [];
  558. }
  559. $data = [];
  560. foreach($field_array as $key => $field){
  561. //接收
  562. if(!request()->has($field,'post')){
  563. continue;
  564. }
  565. $newone = request()->post($field);
  566. //追加
  567. $data[$field] = $newone;
  568. }
  569. //必传
  570. if(!empty($required)){
  571. foreach($required as $k => $mustone){
  572. if(!isset($data[$mustone])){
  573. return $mustone.' required';
  574. }
  575. }
  576. }
  577. //必传,且不能空
  578. if(!empty($noempty)){
  579. foreach($noempty as $havekey => $haveone){
  580. if(!isset($data[$havekey]) || empty($data[$havekey])){
  581. return $haveone.' 必填';
  582. }
  583. }
  584. }
  585. return $data;
  586. }
  587. }
  588. /**
  589. * 时间转换
  590. * @param null $time
  591. * @return false|string
  592. */
  593. if (!function_exists('get_last_time')) {
  594. function get_last_time($time = NULL) {
  595. $text = '';
  596. $nowtime = time();
  597. $time = ($time === NULL || empty($time) || $time > $nowtime) ? $nowtime : intval($time);
  598. $t = $nowtime - $time; //时间差 (秒)
  599. $y = date('Y', $time)-date('Y', $nowtime);//是否跨年
  600. switch($t){
  601. case $t == 0:
  602. $text = '刚刚';
  603. break;
  604. case $t < 60:
  605. $text = $t . '秒前'; // 一分钟内
  606. break;
  607. case $t < 60 * 60:
  608. $text = floor($t / 60) . '分钟前'; //一小时内
  609. break;
  610. case $t < 60 * 60 * 24:
  611. $text = floor($t / (60 * 60)) . '小时前'; // 一天内
  612. break;
  613. case $t < 60 * 60 * 24 * 3:
  614. $text = floor($time/(60*60*24)) ==1 ?'昨天 ' . date('H:i', $time) : '前天 ' . date('H:i', $time) ; //昨天和前天
  615. break;
  616. case $t < 60 * 60 * 24 * 30:
  617. $text = date('m月d日 H:i', $time); //一个月内
  618. break;
  619. case $t < 60 * 60 * 24 * 365&&$y==0:
  620. $text = date('m月d日', $time); //一年内
  621. break;
  622. default:
  623. $text = date('Y年m月d日', $time); //一年以前
  624. break;
  625. }
  626. return $text;
  627. }
  628. }
  629. if (!function_exists('get_rand_nick_name')) {
  630. function get_rand_nick_name()
  631. {
  632. $nicheng_tou = array('快乐的', '冷静的', '醉熏的', '潇洒的', '糊涂的', '积极的', '冷酷的', '深情的', '粗暴的', '温柔的', '可爱的', '愉快的', '义气的', '认真的', '威武的', '帅气的', '传统的', '潇洒的', '漂亮的', '自然的', '专一的', '听话的', '昏睡的', '狂野的', '等待的', '搞怪的', '幽默的', '魁梧的', '活泼的', '开心的', '高兴的', '超帅的', '留胡子的', '坦率的', '直率的', '轻松的', '痴情的', '完美的', '精明的', '无聊的', '有魅力的', '丰富的', '繁荣的', '饱满的', '炙热的', '暴躁的', '碧蓝的', '俊逸的', '英勇的', '健忘的', '故意的', '无心的', '土豪的', '朴实的', '兴奋的', '幸福的', '淡定的', '不安的', '阔达的', '孤独的', '独特的', '疯狂的', '时尚的', '落后的', '风趣的', '忧伤的', '大胆的', '爱笑的', '矮小的', '健康的', '合适的', '玩命的', '沉默的', '斯文的', '香蕉', '苹果', '鲤鱼', '鳗鱼', '任性的', '细心的', '粗心的', '大意的', '甜甜的', '酷酷的', '健壮的', '英俊的', '霸气的', '阳光的', '默默的', '大力的', '孝顺的', '忧虑的', '着急的', '紧张的', '善良的', '凶狠的', '害怕的', '重要的', '危机的', '欢喜的', '欣慰的', '满意的', '跳跃的', '诚心的', '称心的', '如意的', '怡然的', '娇气的', '无奈的', '无语的', '激动的', '愤怒的', '美好的', '感动的', '激情的', '激昂的', '震动的', '虚拟的', '超级的', '寒冷的', '精明的', '明理的', '犹豫的', '忧郁的', '寂寞的', '奋斗的', '勤奋的', '现代的', '过时的', '稳重的', '热情的', '含蓄的', '开放的', '无辜的', '多情的', '纯真的', '拉长的', '热心的', '从容的', '体贴的', '风中的', '曾经的', '追寻的', '儒雅的', '优雅的', '开朗的', '外向的', '内向的', '清爽的', '文艺的', '长情的', '平常的', '单身的', '伶俐的', '高大的', '懦弱的', '柔弱的', '爱笑的', '乐观的', '耍酷的', '酷炫的', '神勇的', '年轻的', '唠叨的', '瘦瘦的', '无情的', '包容的', '顺心的', '畅快的', '舒适的', '靓丽的', '负责的', '背后的', '简单的', '谦让的', '彩色的', '缥缈的', '欢呼的', '生动的', '复杂的', '慈祥的', '仁爱的', '魔幻的', '虚幻的', '淡然的', '受伤的', '雪白的', '高高的', '糟糕的', '顺利的', '闪闪的', '羞涩的', '缓慢的', '迅速的', '优秀的', '聪明的', '含糊的', '俏皮的', '淡淡的', '坚强的', '平淡的', '欣喜的', '能干的', '灵巧的', '友好的', '机智的', '机灵的', '正直的', '谨慎的', '俭朴的', '殷勤的', '虚心的', '辛勤的', '自觉的', '无私的', '无限的', '踏实的', '老实的', '现实的', '可靠的', '务实的', '拼搏的', '个性的', '粗犷的', '活力的', '成就的', '勤劳的', '单纯的', '落寞的', '朴素的', '悲凉的', '忧心的', '洁净的', '清秀的', '自由的', '小巧的', '单薄的', '贪玩的', '刻苦的', '干净的', '壮观的', '和谐的', '文静的', '调皮的', '害羞的', '安详的', '自信的', '端庄的', '坚定的', '美满的', '舒心的', '温暖的', '专注的', '勤恳的', '美丽的', '腼腆的', '优美的', '甜美的', '甜蜜的', '整齐的', '动人的', '典雅的', '尊敬的', '舒服的', '妩媚的', '秀丽的', '喜悦的', '甜美的', '彪壮的', '强健的', '大方的', '俊秀的', '聪慧的', '迷人的', '陶醉的', '悦耳的', '动听的', '明亮的', '结实的', '魁梧的', '标致的', '清脆的', '敏感的', '光亮的', '大气的', '老迟到的', '知性的', '冷傲的', '呆萌的', '野性的', '隐形的', '笑点低的', '微笑的', '笨笨的', '难过的', '沉静的', '火星上的', '失眠的', '安静的', '纯情的', '要减肥的', '迷路的', '烂漫的', '哭泣的', '贤惠的', '苗条的', '温婉的', '发嗲的', '会撒娇的', '贪玩的', '执着的', '眯眯眼的', '花痴的', '想人陪的', '眼睛大的', '高贵的', '傲娇的', '心灵美的', '爱撒娇的', '细腻的', '天真的', '怕黑的', '感性的', '飘逸的', '怕孤独的', '忐忑的', '高挑的', '傻傻的', '冷艳的', '爱听歌的', '还单身的', '怕孤单的', '懵懂的');
  633. $nicheng_wei = array('嚓茶', '凉面', '便当', '毛豆', '花生', '可乐', '灯泡', '哈密瓜', '野狼', '背包', '眼神', '缘分', '雪碧', '人生', '牛排', '蚂蚁', '飞鸟', '灰狼', '斑马', '汉堡', '悟空', '巨人', '绿茶', '自行车', '保温杯', '大碗', '墨镜', '魔镜', '煎饼', '月饼', '月亮', '星星', '芝麻', '啤酒', '玫瑰', '大叔', '小伙', '哈密瓜,数据线', '太阳', '树叶', '芹菜', '黄蜂', '蜜粉', '蜜蜂', '信封', '西装', '外套', '裙子', '大象', '猫咪', '母鸡', '路灯', '蓝天', '白云', '星月', '彩虹', '微笑', '摩托', '板栗', '高山', '大地', '大树', '电灯胆', '砖头', '楼房', '水池', '鸡翅', '蜻蜓', '红牛', '咖啡', '机器猫', '枕头', '大船', '诺言', '钢笔', '刺猬', '天空', '飞机', '大炮', '冬天', '洋葱', '春天', '夏天', '秋天', '冬日', '航空', '毛衣', '豌豆', '黑米', '玉米', '眼睛', '老鼠', '白羊', '帅哥', '美女', '季节', '鲜花', '服饰', '裙子', '白开水', '秀发', '大山', '火车', '汽车', '歌曲', '舞蹈', '老师', '导师', '方盒', '大米', '麦片', '水杯', '水壶', '手套', '鞋子', '自行车', '鼠标', '手机', '电脑', '书本', '奇迹', '身影', '香烟', '夕阳', '台灯', '宝贝', '未来', '皮带', '钥匙', '心锁', '故事', '花瓣', '滑板', '画笔', '画板', '学姐', '店员', '电源', '饼干', '宝马', '过客', '大白', '时光', '石头', '钻石', '河马', '犀牛', '西牛', '绿草', '抽屉', '柜子', '往事', '寒风', '路人', '橘子', '耳机', '鸵鸟', '朋友', '苗条', '铅笔', '钢笔', '硬币', '热狗', '大侠', '御姐', '萝莉', '毛巾', '期待', '盼望', '白昼', '黑夜', '大门', '黑裤', '钢铁侠', '哑铃', '板凳', '枫叶', '荷花', '乌龟', '仙人掌', '衬衫', '大神', '草丛', '早晨', '心情', '茉莉', '流沙', '蜗牛', '战斗机', '冥王星', '猎豹', '棒球', '篮球', '乐曲', '电话', '网络', '世界', '中心', '鱼', '鸡', '狗', '老虎', '鸭子', '雨', '羽毛', '翅膀', '外套', '火', '丝袜', '书包', '钢笔', '冷风', '八宝粥', '烤鸡', '大雁', '音响', '招牌', '胡萝卜', '冰棍', '帽子', '菠萝', '蛋挞', '香水', '泥猴桃', '吐司', '溪流', '黄豆', '樱桃', '小鸽子', '小蝴蝶', '爆米花', '花卷', '小鸭子', '小海豚', '日记本', '小熊猫', '小懒猪', '小懒虫', '荔枝', '镜子', '曲奇', '金针菇', '小松鼠', '小虾米', '酒窝', '紫菜', '金鱼', '柚子', '果汁', '百褶裙', '项链', '帆布鞋', '火龙果', '奇异果', '煎蛋', '唇彩', '小土豆', '高跟鞋', '戒指', '雪糕', '睫毛', '铃铛', '手链', '香氛', '红酒', '月光', '酸奶', '银耳汤', '咖啡豆', '小蜜蜂', '小蚂蚁', '蜡烛', '棉花糖', '向日葵', '水蜜桃', '小蝴蝶', '小刺猬', '小丸子', '指甲油', '康乃馨', '糖豆', '薯片', '口红', '超短裙', '乌冬面', '冰淇淋', '棒棒糖', '长颈鹿', '豆芽', '发箍', '发卡', '发夹', '发带', '铃铛', '小馒头', '小笼包', '小甜瓜', '冬瓜', '香菇', '小兔子', '含羞草', '短靴', '睫毛膏', '小蘑菇', '跳跳糖', '小白菜', '草莓', '柠檬', '月饼', '百合', '纸鹤', '小天鹅', '云朵', '芒果', '面包', '海燕', '小猫咪', '龙猫', '唇膏', '鞋垫', '羊', '黑猫', '白猫', '万宝路', '金毛', '山水', '音响');
  634. $nicheng = $nicheng_tou[array_rand($nicheng_tou, 1)] . $nicheng_wei[array_rand($nicheng_wei, 1)];
  635. return $nicheng; //输出生成的昵称
  636. }
  637. }
  638. if (!function_exists('createUniqueNo')) {
  639. //创建订单号
  640. function createUniqueNo($prifix = 'P',$id = 0)
  641. {
  642. $s = 0;
  643. $ms = 0;
  644. list($ms, $s) = explode(' ', microtime());
  645. $ms = substr($ms, 2, 6); //获取微妙
  646. $rt = $prifix.date('YmdHis', $s).$ms.rand(10, 99).$id; //年月日时分秒.用户id对10取余.微秒
  647. return $rt;
  648. }
  649. }
  650. if (!function_exists('getUinqueId')) {
  651. /**
  652. * 生成不重复的随机数字
  653. */
  654. function getUinqueId($length = 8, $ids = [])
  655. {
  656. $newid = Random::build("nozero", $length);
  657. if (in_array($newid, $ids)) {
  658. $newid = getUinqueId($length, $ids);
  659. }
  660. return $newid;
  661. }
  662. }
  663. if (!function_exists('curl_post')) {
  664. /**
  665. * 发起HTTPS请求
  666. */
  667. function curl_post($url, $data, $header = '', $timeOut = 0)
  668. {
  669. //初始化curl
  670. $ch = curl_init();
  671. //参数设置
  672. curl_setopt($ch, CURLOPT_URL, $url);
  673. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  674. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  675. curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
  676. curl_setopt($ch, CURLOPT_HEADER, 0);
  677. curl_setopt($ch, CURLOPT_POST, 1);
  678. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  679. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  680. if ($header != '') {
  681. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  682. }
  683. $result = curl_exec($ch);
  684. //连接失败
  685. if ($result == FALSE) {
  686. //\think\Log::record('[ CURL ] ERROR ' . curl_error($ch)."\n".var_export(debug_backtrace(), true)."\n", 'error');
  687. }
  688. curl_close($ch);
  689. return $result;
  690. }
  691. }
  692. if (!function_exists('curl_get')) {
  693. /**
  694. * 发起HTTP GET请求
  695. */
  696. function curl_get($url,$header = '')
  697. {
  698. $oCurl = curl_init();
  699. if (stripos($url, "https://") !== FALSE) {
  700. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  701. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  702. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  703. }
  704. curl_setopt($oCurl, CURLOPT_TIMEOUT, 3);
  705. curl_setopt($oCurl, CURLOPT_URL, $url);
  706. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
  707. if($header){
  708. curl_setopt($oCurl, CURLOPT_HTTPHEADER, $header);
  709. }
  710. curl_setopt($oCurl, CURLOPT_HEADER, 0);
  711. $sContent = curl_exec($oCurl);
  712. $aStatus = curl_getinfo($oCurl);
  713. $error = curl_error($oCurl);
  714. curl_close($oCurl);
  715. if ($error) {
  716. $sContent = file_get_contents($url);
  717. return $sContent;
  718. }
  719. if (intval($aStatus["http_code"]) == 200) {
  720. return $sContent;
  721. } else {
  722. return false;
  723. }
  724. }
  725. }
  726. if (!function_exists('day_now')) {
  727. //返回今天的开始时间和结束时间
  728. function day_now()
  729. {
  730. $arr = [
  731. mktime(0, 0, 0, date('m'), date('d'), date('Y')),
  732. mktime(23, 59, 59, date('m'), date('d'), date('Y')),
  733. ];
  734. return $arr;
  735. }
  736. }
  737. if (!function_exists('day_yesterday')) {
  738. //返回昨天开始结束时间 改造上边的方法
  739. function day_yesterday()
  740. {
  741. $yesterday = date('d') - 1;
  742. $arr = [
  743. mktime(0, 0, 0, date('m'), $yesterday, date('Y')),
  744. mktime(23, 59, 59, date('m'), $yesterday, date('Y')),
  745. ];
  746. return $arr;
  747. }
  748. }
  749. if (!function_exists('week_now')) {
  750. //获取当前时间的本周开始结束时间
  751. function week_now()
  752. {
  753. $arr = [
  754. strtotime(date('Y-m-d', strtotime("+0 week Monday", time()))),
  755. strtotime(date('Y-m-d', strtotime("+0 week Sunday", time())))
  756. ];
  757. return $arr;
  758. }
  759. }
  760. if (!function_exists('last_week')) {
  761. //返回上周开始和结束的时间戳
  762. function last_week()
  763. {
  764. $arr = [
  765. strtotime('last week Monday', time()),
  766. strtotime('last week Sunday +1 days -1 seconds', time())
  767. ];
  768. return $arr;
  769. }
  770. }
  771. if (!function_exists('changeW')) {
  772. /**
  773. * 数字转化
  774. */
  775. function changeW($val) {
  776. return $val > 10000 ? round($val/10000,4)."w" : $val.'';
  777. }
  778. }
  779. if(!function_exists('mk_dir')) {
  780. /**
  781. * 新建目录
  782. */
  783. function mk_dir($dir, $mode = 0770, $tmp = true)
  784. {
  785. $mode = 0770;
  786. if(is_file($dir)) {
  787. //有同名文件
  788. return false;
  789. } else {
  790. if(!is_dir($dir)) { //目录不存在
  791. $dir_up = dirname($dir); //上级目录
  792. if(!is_dir($dir_up)) {
  793. //上级不存在
  794. $rs = @mk_dir($dir_up);
  795. if(!$rs) return false;
  796. }
  797. $rs = @mkdir($dir, $mode); //新建
  798. if(!$rs) return false;
  799. $rs = @chmod($dir, $mode); //改权限
  800. if(!$rs) return false;
  801. }
  802. return true;
  803. }
  804. }
  805. }
  806. if(!function_exists('filePut')) {
  807. /**
  808. * 在线支付日志
  809. */
  810. function filePut($info,$text='notify.txt'){
  811. if(is_array($info)) {
  812. $info = json_encode($info, JSON_UNESCAPED_UNICODE);
  813. }
  814. if(!file_exist(RUNTIME_PATH.'paylog/')) {
  815. mk_dir(RUNTIME_PATH.'paylog/');
  816. }
  817. $file = RUNTIME_PATH.'paylog/'.$text;
  818. touch_file($file);
  819. if(filesize($file)>5242880)//大于5M自动切换
  820. {
  821. rename($file, $file.'notify_'.date('Y_m_d_H_i_s').'.txt');
  822. }
  823. touch_file($file);
  824. file_put_contents($file, "\r\n".date('Y-m-d H:i:s').' '.$info, FILE_APPEND);
  825. }
  826. }
  827. if(!function_exists('touch_file')) {
  828. /**
  829. * 新建文件
  830. */
  831. function touch_file($file = '')
  832. {
  833. if($file) {
  834. if(!file_exists($file)) {
  835. @touch($file);
  836. @chmod($file, 0770);
  837. }
  838. }
  839. }
  840. }
  841. if(!function_exists('file_exist')) {
  842. /**
  843. * 检测文件是否存在
  844. * @param $file
  845. * @return string
  846. */
  847. function file_exist($file)
  848. {
  849. if(false === strpos($file, 'http')) { //本地文件
  850. if(0 === strpos($file, '/upload')) {
  851. $file = '.'.$file;
  852. }
  853. return file_exists($file);
  854. } else { //网络文件
  855. $ch = curl_init();
  856. curl_setopt($ch, CURLOPT_URL, $file);
  857. curl_setopt($ch, CURLOPT_TIMEOUT, 2);
  858. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  859. curl_exec($ch);
  860. $status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
  861. curl_close($ch);
  862. if(in_array(substr($status, 0, 1), [2, 3])) {
  863. return true;
  864. } else {
  865. return false;
  866. }
  867. }
  868. }
  869. }
  870. if(!function_exists('list_birthday_age')) {
  871. //结果集信息里,生日转换年龄
  872. function list_birthday_age($list){
  873. if(!$list || empty($list)){
  874. return $list;
  875. }
  876. foreach($list as $vo => $info){
  877. $list[$vo]['age'] = birthtime_to_age($info['birthday']);
  878. }
  879. return $list;
  880. }
  881. }
  882. if(!function_exists('Sec2Time')) {
  883. //秒 转换 日月分
  884. function Sec2Time($time){
  885. if(is_numeric($time)){
  886. $value = array(
  887. 'years' => 0, 'days' => 0, 'hours' => 0,
  888. 'minutes' => 0, 'seconds' => 0,
  889. );
  890. /*if($time >= 31556926){
  891. $value['years'] = floor($time/31556926);
  892. $time = ($time%31556926);
  893. }*/
  894. if($time >= 86400){
  895. $value['days'] = floor($time/86400);
  896. $time = ($time%86400);
  897. }
  898. if($time >= 3600){
  899. $value['hours'] = floor($time/3600);
  900. $time = ($time%3600);
  901. }
  902. if($time >= 60){
  903. $value['minutes'] = floor($time/60);
  904. $time = ($time%60);
  905. }
  906. $value['seconds'] = floor($time);
  907. //return (array) $value;
  908. //$t=$value['years'] .'年'. $value['days'] .'天'.' '. $value['hours'] .'小时'. $value['minutes'] .'分'.$value['seconds'].'秒';
  909. $t = $value['days'] .'天' . $value['hours'] .'小时'. $value['minutes'] .'分';
  910. return $t;
  911. }else{
  912. return '0天';
  913. }
  914. }
  915. }
  916. if(!function_exists('birthtime_to_age')) {
  917. //生日转年龄
  918. function birthtime_to_age($birthtime){
  919. // $birthtime = strtotime('1990-11-06');
  920. if(!$birthtime){
  921. return 0;
  922. }
  923. list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthtime));
  924. list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
  925. $age = $y2 - $y1;
  926. if((int)($m2.$d2) < (int)($m1.$d1))
  927. {$age -= 1;}
  928. if($age < 0){
  929. $age = 0;
  930. }
  931. return $age;
  932. }
  933. }
  934. if (!function_exists('unix_time')) {
  935. /**
  936. * 格式化
  937. * @param $time
  938. * @return string
  939. */
  940. function unix_time($time): string
  941. {
  942. //获取今天凌晨的时间戳
  943. $day = strtotime(date('Y-m-d', time()));
  944. //获取昨天凌晨的时间戳
  945. $pday = strtotime(date('Y-m-d', strtotime('-1 day')));
  946. //获取现在的时间戳
  947. $nowtime = time();
  948. $t = $nowtime - $time;
  949. if ($time < $pday) {
  950. $str = date('m-d', $time);
  951. } elseif ($time < $day && $time > $pday) {
  952. $str = "昨天";
  953. } elseif ($t > 60 * 60) {
  954. $str = floor($t / (60 * 60)) . "小时前";
  955. } elseif ($t > 60) {
  956. $str = floor($t / 60) . "分钟前";
  957. } else {
  958. $str = "刚刚";
  959. }
  960. return $str;
  961. }
  962. }
  963. /**
  964. * 多行输入框回车换行
  965. * @param string $str
  966. * @return string mixed
  967. */
  968. if (!function_exists('line_feed')) {
  969. function line_feed(string $str): string
  970. {
  971. return str_replace("\n", "<br />", $str ?? '');
  972. }
  973. }
  974. if (!function_exists('str_limit')){
  975. /**
  976. * 超出字符省略
  977. * @param $value
  978. * @param int $limit
  979. * @param string $end
  980. * @return mixed|string
  981. */
  982. function str_limit($value, int $limit = 100, string $end = '...') {
  983. if (mb_strwidth($value, 'UTF-8') <= $limit) {
  984. return $value;
  985. }
  986. return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')) . $end;
  987. }
  988. }
  989. if (!function_exists('distance_ext')) {
  990. function distance_ext(float $distance = 0){
  991. if ($distance < 0) return '';
  992. // 计算距离
  993. if ($distance >= 1000) {
  994. $distance = round(($distance / 1000), 2) . 'km';
  995. } else {
  996. $distance = round($distance, 1) . 'm';
  997. }
  998. return $distance;
  999. }
  1000. }
  1001. if (!function_exists('dd')) {
  1002. function dd(...$vars){
  1003. foreach ($vars as $v) {
  1004. dump($v);
  1005. }
  1006. exit();
  1007. }
  1008. }