common.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. /**
  13. * 应用公共函数库文件
  14. */
  15. use think\Response;
  16. use think\facade\Env;
  17. use think\facade\Log;
  18. use think\facade\Config;
  19. use think\facade\Request;
  20. use app\common\library\helper;
  21. use app\common\exception\BaseException;
  22. use think\exception\HttpResponseException;
  23. /**
  24. * 打印调试函数
  25. * @param $content
  26. * @param bool $isDie
  27. * @param bool $export
  28. */
  29. function pre($content, bool $isDie = true, bool $export = false)
  30. {
  31. header('Content-type: text/html; charset=utf-8');
  32. $output = $export ? var_export($content, true) : print_r($content, true);
  33. echo "<pre>{$output}</pre>";
  34. $isDie && die;
  35. }
  36. /**
  37. * 规则:生成随机数,最多14位数字
  38. * @return string
  39. */
  40. function random_num($len = 9)
  41. {
  42. return substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 9);
  43. }
  44. /**
  45. * 规则:生成随机字符
  46. * @return string
  47. */
  48. function random_character($len = 8)
  49. {
  50. $arr = array_merge(range(0,9),range('a','z'),range('A','Z'));
  51. $str = '';
  52. for ($i=0;$i<$len;$i++){
  53. $str .= $arr[rand(0,count($arr)-1)];
  54. }
  55. return $str;
  56. }
  57. /**
  58. * 输出错误信息
  59. * @param string $message 报错信息
  60. * @param int|null $status 状态码,默认为配置文件status.error
  61. * @param array $data 附加数据
  62. * @throws BaseException
  63. */
  64. function throwError(string $message, $status = null, array $data = [])
  65. {
  66. is_null($status) && $status = config('status.error');
  67. throw new BaseException(['status' => $status, 'msg' => $message, 'data' => $data]);
  68. }
  69. /**
  70. * 下划线转驼峰
  71. * @param $uncamelized_words
  72. * @param string $separator
  73. * @return string
  74. */
  75. function camelize($uncamelized_words, $separator = '_')
  76. {
  77. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  78. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  79. }
  80. /**
  81. * 驼峰转下划线
  82. * @param $camelCaps
  83. * @param string $separator
  84. * @return string
  85. */
  86. function uncamelize($camelCaps, $separator = '_')
  87. {
  88. return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
  89. }
  90. /**
  91. * 生成密码hash值
  92. * @param $password
  93. * @return string
  94. */
  95. function encryption_hash($password)
  96. {
  97. return password_hash($password, PASSWORD_DEFAULT);
  98. }
  99. /**
  100. * 获取当前域名及根路径
  101. * @return string
  102. */
  103. function base_url()
  104. {
  105. static $baseUrl = '';
  106. if (empty($baseUrl)) {
  107. $request = Request::instance();
  108. // url协议,设置强制https或自动获取
  109. $scheme = Config::get('route')['url_force_https'] ? 'https' : $request->scheme();
  110. // url子目录
  111. $rootUrl = root_url();
  112. // 拼接完整url
  113. $baseUrl = "{$scheme}://" . $request->host() . $rootUrl;
  114. }
  115. return $baseUrl;
  116. }
  117. /**
  118. * 获取当前uploads目录访问地址
  119. * @return string
  120. */
  121. function uploads_url()
  122. {
  123. return base_url() . 'uploads';
  124. }
  125. /**
  126. * 获取当前url的子目录路径
  127. * @return string
  128. */
  129. function root_url()
  130. {
  131. static $rootUrl = '';
  132. if (empty($rootUrl)) {
  133. $request = Request::instance();
  134. $subUrl = str_replace('\\', '/', dirname($request->baseFile()));
  135. $rootUrl = $subUrl . ($subUrl === '/' ? '' : '/');
  136. }
  137. return $rootUrl;
  138. }
  139. /**
  140. * 获取当前的应用名称
  141. * @return mixed
  142. */
  143. function app_name()
  144. {
  145. return app('http')->getName();
  146. }
  147. /**
  148. * 获取web根目录
  149. * @return string
  150. */
  151. function web_path()
  152. {
  153. static $webPath = '';
  154. if (empty($webPath)) {
  155. $request = Request::instance();
  156. $webPath = dirname($request->server('SCRIPT_FILENAME')) . DIRECTORY_SEPARATOR;
  157. }
  158. return $webPath;
  159. }
  160. /**
  161. * 获取runtime根目录路径
  162. * @return string
  163. */
  164. function runtime_root_path()
  165. {
  166. return dirname(runtime_path()) . DIRECTORY_SEPARATOR;
  167. }
  168. /**
  169. * 写入日志 (使用tp自带驱动记录到runtime目录中)
  170. * @param $value
  171. * @param string $type
  172. */
  173. function log_record($value, $type = 'info')
  174. {
  175. $content = is_string($value) ? $value : print_r($value, true);
  176. Log::record($content, $type);
  177. }
  178. /**
  179. * curl请求指定url (post)
  180. * @param $url
  181. * @param array $data
  182. * @return mixed
  183. */
  184. function curl_post($url, $data = [])
  185. {
  186. $ch = curl_init();
  187. curl_setopt($ch, CURLOPT_POST, 1);
  188. curl_setopt($ch, CURLOPT_HEADER, 0);
  189. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  190. curl_setopt($ch, CURLOPT_URL, $url);
  191. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  192. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  193. $result = curl_exec($ch);
  194. curl_close($ch);
  195. return $result;
  196. }
  197. /**
  198. * 多维数组合并
  199. * @param $array1
  200. * @param $array2
  201. * @return array
  202. */
  203. function array_merge_multiple($array1, $array2)
  204. {
  205. $merge = $array1 + $array2;
  206. $data = [];
  207. foreach ($merge as $key => $val) {
  208. if (
  209. isset($array1[$key])
  210. && is_array($array1[$key])
  211. && isset($array2[$key])
  212. && is_array($array2[$key])
  213. ) {
  214. $data[$key] = is_assoc($array1[$key]) ? array_merge_multiple($array1[$key], $array2[$key]) : $array2[$key];
  215. } else {
  216. $data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
  217. }
  218. }
  219. return $data;
  220. }
  221. /**
  222. * 判断是否为自定义索引数组
  223. * @param array $array
  224. * @return bool
  225. */
  226. function is_assoc(array $array)
  227. {
  228. if (empty($array)) return false;
  229. return array_keys($array) !== range(0, count($array) - 1);
  230. }
  231. /**
  232. * 二维数组排序
  233. * @param $arr
  234. * @param $keys
  235. * @param bool $desc
  236. * @return mixed
  237. */
  238. function array_sort($arr, $keys, $desc = false)
  239. {
  240. $key_value = $new_array = array();
  241. foreach ($arr as $k => $v) {
  242. $key_value[$k] = $v[$keys];
  243. }
  244. if ($desc) {
  245. arsort($key_value);
  246. } else {
  247. asort($key_value);
  248. }
  249. reset($key_value);
  250. foreach ($key_value as $k => $v) {
  251. $new_array[$k] = $arr[$k];
  252. }
  253. return $new_array;
  254. }
  255. /**
  256. * 隐藏敏感字符
  257. * @param $value
  258. * @return string
  259. */
  260. function substr_cut($value)
  261. {
  262. $strlen = mb_strlen($value, 'utf-8');
  263. if ($strlen <= 1) return $value;
  264. $firstStr = mb_substr($value, 0, 1, 'utf-8');
  265. $lastStr = mb_substr($value, -1, 1, 'utf-8');
  266. return $strlen == 2 ? $firstStr . str_repeat('*', $strlen - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
  267. }
  268. /**
  269. * 获取当前系统版本号
  270. * @return mixed|null
  271. * @throws Exception
  272. */
  273. function get_version()
  274. {
  275. static $version = [];
  276. if (!empty($version)) {
  277. return $version['version'];
  278. }
  279. // 读取version.json文件
  280. $file = root_path() . '/version.json';
  281. if (!file_exists($file)) {
  282. throw new Exception('version.json not found');
  283. }
  284. // 解析json数据
  285. $version = helper::jsonDecode(file_get_contents($file));
  286. if (!is_array($version)) {
  287. throw new Exception('version cannot be decoded');
  288. }
  289. return $version['version'];
  290. }
  291. /**
  292. * 获取全局唯一标识符
  293. * @param bool $trim
  294. * @return string
  295. */
  296. function get_guid_v4($trim = true)
  297. {
  298. // Windows
  299. if (function_exists('com_create_guid') === true) {
  300. $charid = com_create_guid();
  301. return $trim == true ? trim($charid, '{}') : $charid;
  302. }
  303. // OSX/Linux
  304. if (function_exists('openssl_random_pseudo_bytes') === true) {
  305. $data = openssl_random_pseudo_bytes(16);
  306. $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
  307. $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
  308. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  309. }
  310. // Fallback (PHP 4.2+)
  311. mt_srand(intval((double)microtime() * 10000));
  312. $charid = strtolower(md5(uniqid((string)rand(), true)));
  313. $hyphen = chr(45); // "-"
  314. $lbrace = $trim ? "" : chr(123); // "{"
  315. $rbrace = $trim ? "" : chr(125); // "}"
  316. return $lbrace .
  317. substr($charid, 0, 8) . $hyphen .
  318. substr($charid, 8, 4) . $hyphen .
  319. substr($charid, 12, 4) . $hyphen .
  320. substr($charid, 16, 4) . $hyphen .
  321. substr($charid, 20, 12) .
  322. $rbrace;
  323. }
  324. /**
  325. * 时间戳转换日期
  326. * @param $timeStamp
  327. * @return false|string
  328. */
  329. function format_time($timeStamp)
  330. {
  331. return $timeStamp>0?date('Y-m-d H:i:s', $timeStamp):'';
  332. }
  333. /**
  334. * 左侧填充0
  335. * @param $value
  336. * @param int $padLength
  337. * @return string
  338. */
  339. function pad_left($value, $padLength = 2)
  340. {
  341. return \str_pad($value, $padLength, "0", STR_PAD_LEFT);
  342. }
  343. /**
  344. * 重写trim方法 (解决int类型过滤后后变为string类型)
  345. * @param $str
  346. * @return string
  347. */
  348. function my_trim($str)
  349. {
  350. return is_string($str) ? trim($str) : $str;
  351. }
  352. /**
  353. * 重写htmlspecialchars方法 (解决int类型过滤后后变为string类型)
  354. * @param $string
  355. * @return string
  356. */
  357. function my_htmlspecialchars($string)
  358. {
  359. return is_string($string) ? htmlspecialchars($string) : $string;
  360. }
  361. /**
  362. * 过滤emoji表情
  363. * @param $text
  364. * @return null|string|string[]
  365. */
  366. function filter_emoji($text)
  367. {
  368. if (!is_string($text)) {
  369. return $text;
  370. }
  371. // 此处的preg_replace用于过滤emoji表情
  372. // 如需支持emoji表情, 需将mysql的编码改为utf8mb4
  373. return preg_replace('/[\xf0-\xf7].{3}/', '', $text);
  374. }
  375. /**
  376. * 根据指定长度截取字符串
  377. * @param $str
  378. * @param int $length
  379. * @return bool|string
  380. */
  381. function str_substr($str, $length = 30)
  382. {
  383. if (strlen($str) > $length) {
  384. $str = mb_substr($str, 0, $length);
  385. }
  386. return $str;
  387. }
  388. /**
  389. * 结束执行
  390. */
  391. function app_end()
  392. {
  393. throw new HttpResponseException(Response::create());
  394. }
  395. /**
  396. * 当前是否为调试模式
  397. * @return bool
  398. */
  399. function is_debug()
  400. {
  401. return (bool)Env::instance()->get('APP_DEBUG');
  402. }
  403. /**
  404. * 文本左斜杠转换为右斜杠
  405. * @param $string
  406. * @return mixed
  407. */
  408. function convert_left_slash(string $string)
  409. {
  410. return str_replace('\\', '/', $string);
  411. }
  412. /**
  413. * 隐藏手机号中间四位 13012345678 -> 130****5678
  414. * @param string $mobile 手机号
  415. * @return string
  416. */
  417. function hide_mobile(string $mobile)
  418. {
  419. return substr_replace($mobile, '****', 3, 4);
  420. }
  421. /**
  422. * 隐藏手机号中间四位 42102200201019999 -> 4210************999
  423. * @param string $idcard 手机号
  424. * @return string
  425. */
  426. function hide_id_card(string $idcard)
  427. {
  428. return substr_replace($idcard, '***********', 4, 11);
  429. }
  430. /**
  431. * 生成用户昵称
  432. */
  433. function make_nickname(string $mobile)
  434. {
  435. return '用户' . substr($mobile, -4);
  436. }
  437. /**
  438. * 获取当前登录的商城ID
  439. * @return int $storeId
  440. */
  441. function getStoreId()
  442. {
  443. return 10001;
  444. }
  445. /**
  446. * 获取缩短后的字符串
  447. * @return string
  448. */
  449. function limit_str(string $str,int $limit=6)
  450. {
  451. if(mb_strlen($str)<$limit){
  452. return $str;
  453. }else{
  454. return mb_substr(strip_tags($str),0,$limit,'UTF-8')."...";
  455. }
  456. }
  457. /**
  458. * 获取指定范围的所有日期
  459. *
  460. * @param int $start
  461. * @param int $end
  462. * @param string $format
  463. * @return array
  464. */
  465. function period_date($start, $end, $format = 'Y-m-d')
  466. {
  467. $arr = [];
  468. while ($start <= $end) {
  469. $arr[] = date($format, $start);
  470. $start = strtotime('+1 day', $start);
  471. }
  472. return $arr;
  473. }
  474. /**
  475. * 获取指定范围的所有周
  476. *
  477. * @param int $start
  478. * @param int $end
  479. * @param boolean 是否过滤不满一周的数据
  480. *
  481. * @return array
  482. */
  483. function period_week($start, $end, $filter = false)
  484. {
  485. //开始时间
  486. $startDate = date('Y-m-d', $start);
  487. //结束时间
  488. if (empty($end)) {
  489. $endDate = date('Y-m-d');
  490. } else {
  491. $endDate = date('Y-m-d', $end);
  492. }
  493. //跨越天数
  494. $n = (strtotime($endDate) - strtotime($startDate)) / 86400;
  495. //判断,跨度小于7天,可能是同一周,也可能是两周
  496. $endDate = date("Y-m-d", strtotime("$endDate +1 day"));
  497. if ($n < 7) {
  498. //查开始时间 在 那周 的 位置
  499. $day = date("w", strtotime($startDate)) - 1;
  500. //查开始时间 那周 的 周一
  501. $week_start = date("Y-m-d", strtotime("$startDate -{$day} day"));
  502. //查开始时间 那周 的 周末
  503. $day = 7 - $day;
  504. $week_end = date("Y-m-d", strtotime("$startDate +{$day} day"));
  505. //判断周末时间是否大于时间段的结束时间,如果大于,那就是时间段在同一周,否则时间段跨两周
  506. if ($week_end >= $endDate) {
  507. $weekList[] = array('s' => $startDate, 'e' => date("Y-m-d", strtotime("$endDate -1 day")));
  508. } else {
  509. $weekList[] = array('s' => $startDate, 'e' => date("Y-m-d", strtotime("$week_end -1 day")));
  510. $weekList[] = array('s' => $week_end, 'e' => date("Y-m-d", strtotime("$endDate -1 day")));
  511. }
  512. } else {
  513. //如果跨度大于等于7天,可能是刚好1周或跨2周或跨N周,先找出开始时间 在 那周 的 位置和那周的周末时间
  514. $day = date("w", strtotime($startDate)) - 1;
  515. $week_start = date("Y-m-d", strtotime("$startDate -{$day} day"));
  516. $day = 7 - $day;
  517. $week_end = date("Y-m-d", strtotime("$startDate +{$day} day"));
  518. //先把开始时间那周写入数组
  519. $weekList[] = array('s' => $startDate, 'e' => date("Y-m-d", strtotime("$week_end -1 day")));
  520. //判断周末是否大于等于结束时间,不管大于(2周)还是等于(1周),结束时间都是时间段的结束时间。
  521. if ($week_end >= $endDate) {
  522. $weekList[] = array('s' => $week_end, 'e' => date("Y-m-d", strtotime("$endDate -1 day")));
  523. } else {
  524. //N周的情况用while循环一下,然后写入数组
  525. while ($week_end <= $endDate) {
  526. $start = $week_end;
  527. $week_end = date("Y-m-d", strtotime("$week_end +7 day"));
  528. if ($week_end <= $endDate) {
  529. $weekList[] = array('s' => $start, 'e' => date("Y-m-d", strtotime("$week_end -1 day")));
  530. } else {
  531. // 如果当前时间是每周第一天
  532. if ($start == $endDate) {
  533. $weekList[] = array('s' => $start, 'e' => date("Y-m-d", strtotime("$endDate 0 day")));
  534. } else {
  535. $weekList[] = array('s' => $start, 'e' => date("Y-m-d", strtotime("$endDate -1 day")));
  536. }
  537. }
  538. }
  539. }
  540. }
  541. // 过滤不满一周天数的数据
  542. $firstWeek = current($weekList);
  543. $lastWeek = end($weekList);
  544. $firstWeekDays = (strtotime($firstWeek['e']) - strtotime($firstWeek['s'])) / 86400;
  545. $lastWeekDays = (strtotime($lastWeek['e']) - strtotime($lastWeek['s'])) / 86400;
  546. if ($firstWeekDays < 7 && $filter) {
  547. array_shift($weekList);
  548. }
  549. if ($lastWeekDays < 7 && $filter) {
  550. array_pop($weekList);
  551. }
  552. return $weekList;
  553. }
  554. /**
  555. * 生成从开始月份到结束月份的月份数组
  556. * @param int $start 开始时间戳
  557. * @param int $end 结束时间戳
  558. * @param boolean 是否过滤当前月等于最后一个月的数据
  559. */
  560. function period_month($start, $end, $filter = false)
  561. {
  562. if (!is_numeric($start) || !is_numeric($end) || ($end <= $start)) return '';
  563. $start = date('Y-m', $start);
  564. $end = date('Y-m', $end);
  565. //转为时间戳
  566. $start = strtotime($start . '-01');
  567. $end = strtotime($end . '-01');
  568. $i = 0;
  569. $d = array();
  570. while ($start <= $end) {
  571. //这里累加每个月的的总秒数 计算公式:上一月1号的时间戳秒数减去当前月的时间戳秒数
  572. $d[$i] = trim(date('Y-m', $start), ' ');
  573. $start += strtotime('+1 month', $start) - $start;
  574. $i++;
  575. }
  576. if (end($d) == date('Y-m') && $filter) {
  577. array_pop($d);
  578. }
  579. return $d;
  580. }
  581. function month_first_last($date)
  582. {
  583. $firstday = date('Y-m-01', strtotime($date));
  584. $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
  585. return ['s' => $firstday, 'e'=>$lastday];
  586. }
  587. /**
  588. * 获取上月月份
  589. * @param int $days 默认上个月
  590. * @return false|string
  591. */
  592. function last_month($format = "Y-m", $days = 1, $time = 0)
  593. {
  594. if (!$time) {
  595. $time = time();
  596. }
  597. return date($format, strtotime(date('Y-m-01') . " -{$days} month", $time));
  598. }
  599. function last_week_between_time()
  600. {
  601. $s = mktime(0,0,0,(int)date('m'),(int)(date('d')-date('w')+1-7),(int)date('Y'));
  602. $e = mktime(23,59,59,(int)date('m'),(int)(date('d')-date('w')+7-7),(int)date('Y'));
  603. return ['s' => $s, 'e'=>$e];
  604. }
  605. /*
  606. POST
  607. */
  608. function post_curl($posturl, $params, $method = 'POST', $header = '') {
  609. $curl = curl_init();
  610. curl_setopt($curl, CURLOPT_URL, $posturl);
  611. if ($header)
  612. curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  613. switch ($method) {
  614. case 'GET':
  615. curl_setopt($curl, CURLOPT_HTTPGET, 1);
  616. case 'POST':
  617. curl_setopt($curl, CURLOPT_POST, 1);
  618. break;
  619. case 'PUT':
  620. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
  621. break;
  622. case 'DELETE':
  623. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
  624. break;
  625. }
  626. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, False);
  627. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
  628. curl_setopt($curl, CURLOPT_HEADER, FALSE);
  629. curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
  630. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  631. $retdata = curl_exec($curl);
  632. curl_close($curl);
  633. return $retdata;
  634. }