functions.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. <?php
  2. use app\service\system\SystemService;
  3. use support\Response;
  4. use Webman\Event\Event;
  5. if (!function_exists("between_time"))
  6. {
  7. /**
  8. * 格式化起止时间(为了兼容前端RangePicker组件)
  9. * 2020-04-01T08:15:08.891Z => 1585670400
  10. * @param array $times
  11. * @param bool $isWithTime 是否包含时间
  12. * @return array
  13. */
  14. function between_time(array $times, bool $isWithTime = false): array
  15. {
  16. foreach ($times as &$time) {
  17. $time = trim($time, '&quot;');
  18. $time = str2date($time, $isWithTime);
  19. }
  20. return ['start_time' => current($times), 'end_time' => next($times)];
  21. }
  22. }
  23. if (!function_exists("str2date"))
  24. {
  25. /**
  26. * 日期转换时间戳
  27. * 例如: 2020-04-01 08:15:08 => 1585670400
  28. * @param string $date
  29. * @param bool $isWithTime 是否包含时间
  30. * @return int
  31. */
  32. function str2date(string $date, bool $isWithTime = false): int
  33. {
  34. if (!$isWithTime) {
  35. $date = date('Y-m-d', strtotime($date));
  36. }
  37. return strtotime($date);
  38. }
  39. }
  40. if (!function_exists("isValidMobile"))
  41. {
  42. /**
  43. * 验证是否为有效的中国大陆手机号码
  44. * @param string $mobile
  45. * @return bool
  46. */
  47. function isValidMobile(string $mobile): bool
  48. {
  49. // 去除空格、换行等
  50. $mobile = trim($mobile);
  51. // 正则:1 开头,第二位 3-9,后面 9 位数字,总共 11 位
  52. $pattern = '/^1[3-9]\d{9}$/';
  53. return preg_match($pattern, $mobile) === 1;
  54. }
  55. }
  56. if(!function_exists("hide_mobile")){
  57. /**
  58. * 手机号码脱敏
  59. * @param string $mobile
  60. * @param int $len 4 末尾4位 6 末尾2位
  61. * @return string
  62. */
  63. function hide_mobile(string $mobile,int $len = 6): string
  64. {
  65. return substr_replace($mobile, ($len==4 ? '****' : '******'), 3, $len);
  66. }
  67. }
  68. if (!function_exists('hide_str')) {
  69. /**
  70. * 将一个字符串部分字符用*替代隐藏
  71. * @param string $string 待转换的字符串
  72. * @param int $begin 起始位置,从0开始计数,当$type=4时,表示左侧保留长度
  73. * @param int $len 需要转换成*的字符个数,当$type=4时,表示右侧保留长度
  74. * @param int $type 转换类型:0,从左向右隐藏;1,从右向左隐藏;2,从指定字符位置分割前由右向左隐藏;3,从指定字符位置分割后由左向右隐藏;4,保留首末指定字符串中间用***代替
  75. * @param string $glue 分割符
  76. * @return string 处理后的字符串
  77. */
  78. function hide_str(string $string, int $begin = 3, int $len = 4, int $type = 0, string $glue = "@"): string
  79. {
  80. $array = array();
  81. if ($type == 0 || $type == 1 || $type == 4) {
  82. $strlen = $length = mb_strlen($string);
  83. while ($strlen) {
  84. $array[] = mb_substr($string, 0, 1, "utf8");
  85. $string = mb_substr($string, 1, $strlen, "utf8");
  86. $strlen = mb_strlen($string);
  87. }
  88. }
  89. if ($type == 0) {
  90. for ($i = $begin; $i < ($begin + $len); $i++) {
  91. if (isset($array[$i])) {
  92. $array[$i] = "*";
  93. }
  94. }
  95. $string = implode("", $array);
  96. } elseif ($type == 1) {
  97. $array = array_reverse($array);
  98. for ($i = $begin; $i < ($begin + $len); $i++) {
  99. if (isset($array[$i])) {
  100. $array[$i] = "*";
  101. }
  102. }
  103. $string = implode("", array_reverse($array));
  104. } elseif ($type == 2) {
  105. $array = explode($glue, $string);
  106. if (isset($array[0])) {
  107. $array[0] = hide_str($array[0], $begin, $len, 1);
  108. }
  109. $string = implode($glue, $array);
  110. } elseif ($type == 3) {
  111. $array = explode($glue, $string);
  112. if (isset($array[1])) {
  113. $array[1] = hide_str($array[1], $begin, $len, 0);
  114. }
  115. $string = implode($glue, $array);
  116. } elseif ($type == 4) {
  117. $left = $begin;
  118. $right = $len;
  119. $tem = array();
  120. for ($i = 0; $i < ($length - $right); $i++) {
  121. if (isset($array[$i])) {
  122. $tem[] = $i >= $left ? "" : $array[$i];
  123. }
  124. }
  125. $tem[] = '*****';
  126. $array = array_chunk(array_reverse($array), $right);
  127. $array = array_reverse($array[0]);
  128. for ($i = 0; $i < $right; $i++) {
  129. if (isset($array[$i])) {
  130. $tem[] = $array[$i];
  131. }
  132. }
  133. $string = implode("", $tem);
  134. }
  135. return $string;
  136. }
  137. }
  138. if (!function_exists('list_sort_by')) {
  139. /**
  140. *----------------------------------------------------------
  141. * 对查询结果集进行排序
  142. *----------------------------------------------------------
  143. * @access public
  144. *----------------------------------------------------------
  145. * @param array $list 查询结果
  146. * @param string $field 排序的字段名
  147. * @param string $sortBy 排序类型
  148. * @switch string asc正向排序 desc逆向排序 nat自然排序
  149. *----------------------------------------------------------
  150. * @return array
  151. *----------------------------------------------------------
  152. */
  153. function list_sort_by(array $list, string $field, string $sortBy = 'asc'): array
  154. {
  155. if (!empty($list)) {
  156. $refer = $resultSet = array();
  157. foreach ($list as $i => $data)
  158. $refer[$i] = &$data[$field];
  159. switch ($sortBy) {
  160. case 'asc': // 正向排序
  161. asort($refer);
  162. break;
  163. case 'desc':// 逆向排序
  164. arsort($refer);
  165. break;
  166. case 'nat': // 自然排序
  167. natcasesort($refer);
  168. break;
  169. }
  170. foreach ($refer as $key => $val)
  171. $resultSet[] = &$list[$key];
  172. return $resultSet;
  173. }
  174. return [];
  175. }
  176. }
  177. if (!function_exists('supplement_id')) {
  178. /**
  179. * 用户ID风格
  180. * @param string $id
  181. * @return string
  182. */
  183. function supplement_id(string $id): string
  184. {
  185. $len = strlen($id);
  186. $buf = '000000';
  187. return $len < 6 ? substr($buf, 0, (6 - $len)) . $id : $id;
  188. }
  189. }
  190. if (!function_exists('createOrderId')) {
  191. /**
  192. * 生成订单号
  193. * @param string $letter
  194. * @param int $length
  195. * @return string
  196. */
  197. function createOrderId(string $letter = '', int $length = 3): string
  198. {
  199. $gradual = 0;
  200. $orderId = date('YmdHis') . mt_rand(10000000, 99999999);
  201. $lengths = strlen($orderId);
  202. // 循环处理随机数
  203. for ($i = 0; $i < $lengths; $i++) {
  204. $gradual += (int)(substr($orderId, $i, 1));
  205. }
  206. if (empty($letter)) {
  207. $letter = get_order_letter($length);
  208. }
  209. $code = (100 - $gradual % 100) % 100;
  210. return $letter . $orderId . str_pad((string)$code, 2, '0', STR_PAD_LEFT);
  211. }
  212. }
  213. if (!function_exists('get_order_letter')) {
  214. /**
  215. * 生成订单短ID
  216. * @param int $length
  217. * @return string
  218. */
  219. function get_order_letter(int $length = 2): string
  220. {
  221. $letter_all = range('A', 'Z');
  222. shuffle($letter_all);
  223. $letter_array = array_diff($letter_all, ['I', 'O']);
  224. $letter = array_rand(array_flip($letter_array), $length);
  225. return implode('', $letter);
  226. }
  227. }
  228. /**
  229. * 过滤emoji表情
  230. * @param string $str
  231. * @return string
  232. */
  233. if (!function_exists('removeEmoji')) {
  234. function removeEmoji(string $str = '') : string
  235. {
  236. $str = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $str);
  237. $str = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $str);
  238. $str = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $str);
  239. $str = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $str);
  240. return preg_replace('/[\x{2700}-\x{27BF}]/u', '', $str);
  241. }
  242. }
  243. if (!function_exists('object_array')) {
  244. /**
  245. * @param $array
  246. * @return array
  247. */
  248. function object_array($array): array
  249. {
  250. if(is_object($array)) {
  251. $array = (array)$array;
  252. }
  253. if(is_array($array)) {
  254. foreach($array as $key=>$value) {
  255. $array[$key] = object_array($value);
  256. }
  257. }
  258. return $array;
  259. }
  260. }
  261. if (!function_exists("getDateFull"))
  262. {
  263. /**
  264. * @param string $format
  265. * @param string $time
  266. * @return string
  267. */
  268. function getDateFull(string $format = "Y-m-d H:i:s",string $time = ""): string
  269. {
  270. if (empty($time)) $time = time();
  271. return date($format??'Y-m-d H:i:s',$time);
  272. }
  273. }
  274. if (!function_exists("events"))
  275. {
  276. /**
  277. * 事件发布
  278. * @param $name
  279. * @param $data
  280. * @return array|mixed|null
  281. */
  282. function events($name,$data): mixed
  283. {
  284. return Event::dispatch($name,$data);
  285. }
  286. }
  287. if (!function_exists("success")) {
  288. /**
  289. * @param string $msg
  290. * @param array $data
  291. * @param int $code
  292. * @return Response
  293. */
  294. function success(string $msg = "", array $data = [], int $code = 1): Response
  295. {
  296. return json(compact('code', 'data', 'msg'));
  297. }
  298. }
  299. if (!function_exists("successTrans")) {
  300. /**
  301. * 消息返回
  302. * @param string $message
  303. * @param array $data
  304. * @param int $code
  305. * @return Response
  306. */
  307. function successTrans(string $message, array $data = [], int $code = 1): Response
  308. {
  309. $msg = trans($message);
  310. return json(compact("msg", "code", "data"));
  311. }
  312. }
  313. if (!function_exists("error")) {
  314. /**
  315. * @param $msg
  316. * @param array $data
  317. * @param int $code
  318. * @return Response
  319. */
  320. function error($msg, array $data = [], int $code = 0): Response
  321. {
  322. return json(compact('code', 'data', 'msg'));
  323. }
  324. }
  325. if (!function_exists("errorTrans")) {
  326. /**
  327. * 消息返回
  328. * @param string $message
  329. * @param array $data
  330. * @param int $code
  331. * @return Response
  332. */
  333. function errorTrans(string $message = "", array $data = [], int $code = 0): Response
  334. {
  335. $msg = trans($message);
  336. return json(compact("msg", "code", "data"));
  337. }
  338. }
  339. if (!function_exists("pageFormat")) {
  340. /**
  341. * @param $data
  342. * @param int $size
  343. * @return array {page:"",pageSize:"",rows:[],total:""}
  344. */
  345. function pageFormat($data, int $size = 10): array
  346. {
  347. if (empty($data)) return [];
  348. return [
  349. 'total' => $data->total(),
  350. 'page' => $data->currentPage(),
  351. 'pageSize' => $size,
  352. 'rows' => $data->items()
  353. ];
  354. }
  355. }
  356. if (!function_exists("pageFormatMsg")) {
  357. /**
  358. * @param $data
  359. * @param int $size
  360. * @return array {page:"",pageSize:"",rows:[],total:""}
  361. */
  362. function pageFormatMsg($data, int $size = 10): array
  363. {
  364. if (empty($data)) return [];
  365. $rowsData = [];
  366. if ($data->total() > 0) {
  367. foreach ($data as $key=>$row) {
  368. $rowsData[$key] = $row->toArray();
  369. }
  370. }
  371. return [
  372. 'total' => $data->total(),
  373. 'page' => $data->currentPage(),
  374. 'pageSize' => $size,
  375. 'rows' => list_sort_by($rowsData,"id","asc")
  376. ];
  377. }
  378. }
  379. if(!function_exists('format_money')){
  380. function format_money($str,$len = '2',$append = ""): string
  381. {
  382. if (empty($str)) {
  383. return "0.00";
  384. }
  385. return number_format($str, $len, ".", $append);
  386. }
  387. }
  388. if (!function_exists('sConf')) {
  389. /**
  390. * 获取或配置系统参数
  391. * @param string $name 参数名称
  392. * @param string|null $value 参数内容
  393. */
  394. function sConf(string $name = '', string $value = null)
  395. {
  396. if (is_null($value) && is_string($name)) {
  397. return SystemService::get($name);
  398. } else {
  399. return SystemService::set($name, $value);
  400. }
  401. }
  402. }
  403. if (!function_exists('sData')) {
  404. /**
  405. * JSON 数据读取与存储
  406. * @param string $name 数据名称
  407. * @param mixed $value 数据内容
  408. */
  409. function sData(string $name,mixed $value = null)
  410. {
  411. if (is_null($value)) {
  412. return SystemService::getData($name);
  413. } else {
  414. return SystemService::setData($name, $value);
  415. }
  416. }
  417. }
  418. if (!function_exists('sOplog')) {
  419. /**
  420. * 写入系统日志
  421. * @param string $action 日志行为
  422. * @param string $content 日志内容
  423. * @param string $userName
  424. * @return boolean
  425. */
  426. function sOplog(string $action, string $content, string $userName): bool
  427. {
  428. return SystemService::setOplog($action, $content,$userName);
  429. }
  430. }
  431. if(!function_exists('store_region')){
  432. /**
  433. * 返回附近司机数据
  434. * @param $latitude
  435. * @param $longitude
  436. * @param $type 1 返回查询影响记录数;2 返回数据数组
  437. */
  438. function store_region($latitude,$longitude,$type = 1,$where = 'status = 1',$field="*"){
  439. $sql = "select ".$field." from(
  440. SELECT id,poi_id,poi_name,status,poi_address,longitude,latitude,
  441. ROUND(6378.138*2*ASIN(SQRT(POW(SIN(({$latitude}*PI()/180-latitude*PI()/180)/2),2)+COS({$latitude}*PI()/180)*COS(latitude*PI()/180)*POW(SIN(({$longitude}*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli
  442. FROM saas_store_shop where ".$where.") as tmp_table_name order by juli asc";
  443. if($type == 1){
  444. return \think\facade\Db::execute($sql);
  445. }
  446. return \think\facade\Db::query($sql);
  447. }
  448. }
  449. if(!function_exists('getHourlyTimeSlots')){
  450. function getHourlyTimeSlots($startHour = 9, $endHour = 22, $format = 'H:i'): array
  451. {
  452. $slots = [];
  453. for ($hour = $startHour; $hour < $endHour; $hour++) {
  454. $startTime = sprintf('%02d:00', $hour);
  455. $endTime = sprintf('%02d:00', $hour + 1);
  456. $slots[] = [
  457. 'start' => $startTime,
  458. 'end' => $endTime,
  459. 'display' => $startTime . ' - ' . $endTime
  460. ];
  461. }
  462. return $slots;
  463. }
  464. }
  465. if (!function_exists("strToUniqueNumberV4"))
  466. {
  467. /**
  468. * 名称加密
  469. * @param string $str
  470. * @param string $salt
  471. * @return string
  472. */
  473. function strToUniqueNumberV4(string $str = "", string $salt = ''): string
  474. {
  475. // 添加盐值增加唯一性
  476. $str = $str . $salt;
  477. // 使用多种哈希组合
  478. $crc = abs(crc32($str));
  479. $md5 = hexdec(substr(md5($str), 0, 8));
  480. $sha1 = hexdec(substr(sha1($str), 0, 8));
  481. // 组合并取模
  482. $number = ($crc + $md5 + $sha1) % 1000000000000;
  483. // 使用时间戳微调确保唯一性(针对同一字符串)
  484. static $lastStr = '';
  485. static $counter = 0;
  486. if ($str === $lastStr) {
  487. $counter++;
  488. $number = ($number + $counter) % 1000000000000;
  489. } else {
  490. $lastStr = $str;
  491. $counter = 0;
  492. }
  493. return str_pad($number, 12, '0', STR_PAD_LEFT);
  494. }
  495. }
  496. if (!function_exists("extractNodesClean"))
  497. {
  498. /**
  499. * 多维数组转N个一维
  500. * @param $data
  501. * @param array $result
  502. * @return array
  503. */
  504. function extractNodesClean($data, array &$result = []): array
  505. {
  506. foreach ($data as $node) {
  507. // 复制节点并删除 sub_tree_infos
  508. $cleanNode = $node;
  509. unset($cleanNode['sub_tree_infos']);
  510. $result[] = $cleanNode;
  511. // 递归处理子节点
  512. if (isset($node['sub_tree_infos']) && is_array($node['sub_tree_infos'])) {
  513. extractNodesClean($node['sub_tree_infos'], $result);
  514. }
  515. }
  516. return $result;
  517. }
  518. }
  519. if (!function_exists("formatTime"))
  520. {
  521. /**
  522. * 格式化时间:今天、昨天、前天、正常日期
  523. * @param string $timestamp 时间戳 或 日期字符串
  524. * @return string
  525. */
  526. function formatTime(string $timestamp): string
  527. {
  528. // 先统一转成时间戳
  529. $time = is_numeric($timestamp) ? $timestamp : strtotime($timestamp);
  530. $today = strtotime('today'); // 今天 00:00
  531. $yesterday = strtotime('yesterday'); // 昨天 00:00
  532. $beforeYesterday = strtotime('-2 days'); // 前天 00:00
  533. if ($time >= $today) {
  534. return '今天';
  535. } elseif ($time >= $yesterday) {
  536. return '昨天';
  537. } elseif ($time >= $beforeYesterday) {
  538. return '前天';
  539. } else {
  540. // 其他时间返回正常格式
  541. return date('Y-m-d', $time);
  542. }
  543. }
  544. }
  545. if(! function_exists ('timeDiff') ) {
  546. function timeDiff($begin_time, $end_time): array
  547. {
  548. if ($begin_time < $end_time) {
  549. return ["day" => 0, "hour" => 0, "min" => 0, "sec" => 0];
  550. } else {
  551. $starttime = $end_time;
  552. $endtime = $begin_time;
  553. }
  554. //计算天数
  555. $timediff = $endtime - $starttime;
  556. $days = intval($timediff / 86400);
  557. //计算小时数
  558. $remain = $timediff % 86400;
  559. $hours = intval($remain / 3600);
  560. //计算分钟数
  561. $remain = $remain % 3600;
  562. $mins = intval($remain / 60);
  563. //计算秒数
  564. $secs = $remain % 60;
  565. return ["day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs];
  566. }
  567. }
  568. if(! function_exists('filterTreeByTargets'))
  569. {
  570. /**
  571. * 过滤树,仅保留包含任何目标 category_id 的节点及其祖先
  572. *
  573. * @param array $tree 原始树
  574. * @param array $targetIds 目标 category_id 列表
  575. * @return array 过滤后的树(保持原结构)
  576. */
  577. function filterTreeByTargets($tree, $targetIds) {
  578. $filtered = [];
  579. foreach ($tree as $node) {
  580. // 检查当前节点或子树中是否包含任一目标 ID
  581. $contains = false;
  582. if (in_array($node['category_id'], $targetIds)) {
  583. $contains = true;
  584. } else {
  585. // 递归检查子节点
  586. $children = [];
  587. if (!empty($node['children']) && is_array($node['children'])) {
  588. $children = filterTreeByTargets($node['children'], $targetIds);
  589. if (!empty($children)) {
  590. $contains = true;
  591. }
  592. }
  593. }
  594. if ($contains) {
  595. // 保留当前节点,并合并过滤后的子节点
  596. $newNode = $node;
  597. if (!empty($node['children']) && is_array($node['children'])) {
  598. $newNode['children'] = filterTreeByTargets($node['children'], $targetIds);
  599. } else {
  600. $newNode['children'] = [];
  601. }
  602. $filtered[] = $newNode;
  603. }
  604. }
  605. return $filtered;
  606. }
  607. }
  608. if(! function_exists('addTypesRecursive'))
  609. {
  610. /**
  611. * 为树中每个节点添加 types 字段
  612. */
  613. function addTypesRecursive(&$nodes, $typeMap) {
  614. foreach ($nodes as &$node) {
  615. $node['types'] = $typeMap[$node['category_id']] ?? '';
  616. if (isset($node['children']) && is_array($node['children'])) {
  617. addTypesRecursive($node['children'], $typeMap);
  618. }
  619. }
  620. }
  621. }
  622. if(! function_exists('emojiToUnicode'))
  623. {
  624. /**
  625. * @param string $str
  626. * @return string
  627. */
  628. function emojiToUnicode(string $str): string
  629. {
  630. return trim(json_encode($str, JSON_UNESCAPED_SLASHES), '"');
  631. }
  632. }
  633. if(! function_exists('unicodeToEmoji'))
  634. {
  635. function unicodeToEmoji(string $str): string
  636. {
  637. return json_decode("\"{$str}\"");
  638. }
  639. }
  640. if(! function_exists('removeEmoji2'))
  641. {
  642. /**
  643. * 清除字符串中所有emoji表情
  644. * @param string $str
  645. * @return string
  646. */
  647. function removeEmoji2(string $str): string
  648. {
  649. // 匹配绝大部分emoji Unicode区间
  650. $pattern = '/[\x{1F600}-\x{1F64F}\x{1F300}-\x{1F5FF}\x{1F680}-\x{1F6FF}\x{1F1E0}-\x{1F1FF}\x{2600}-\x{26FF}\x{2700}-\x{27BF}\xFE00-\xFE0F\x{1F900}-\x{1F9FF}]/u';
  651. return preg_replace($pattern, '', $str);
  652. }
  653. }
  654. if(! function_exists('str_cut_ellipsis'))
  655. {
  656. function str_cut_ellipsis(string $str, int $len = 20, string $dot = '...'): string
  657. {
  658. if (mb_strlen($str, 'UTF-8') <= $len) {
  659. return $str;
  660. }
  661. return mb_substr($str, 0, $len, 'UTF-8') . $dot;
  662. }
  663. }