common.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. <?php
  2. // 应用公共文件
  3. use app\common\model\goods_category\GoodsCategory;
  4. use app\common\model\setting\PostageRegion;
  5. use app\common\service\FileService;
  6. use think\helper\Str;
  7. /**
  8. * 计算两点之间的距离
  9. */
  10. function haversineDistance($lat1, $lon1, $lat2, $lon2) {
  11. // 地球平均半径,单位:千米
  12. $R = 6371;
  13. // 将角度转换为弧度
  14. $lat1 = deg2rad($lat1);
  15. $lon1 = deg2rad($lon1);
  16. $lat2 = deg2rad($lat2);
  17. $lon2 = deg2rad($lon2);
  18. // 计算纬度和经度的差值
  19. $dLat = $lat2 - $lat1;
  20. $dLon = $lon2 - $lon1;
  21. // Haversine 公式的计算步骤
  22. $a = sin($dLat / 2) * sin($dLat / 2) +
  23. cos($lat1) * cos($lat2) * sin($dLon / 2) * sin($dLon / 2);
  24. $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
  25. // 计算距离
  26. $distance = $R * $c;
  27. return $distance;
  28. }
  29. /**
  30. * @notes 生成密码加密密钥
  31. * @param string $plaintext
  32. * @param string $salt
  33. * @return string
  34. * @author 段誉
  35. * @date 2021/12/28 18:24
  36. */
  37. function create_password(string $plaintext, string $salt) : string
  38. {
  39. return md5($salt . md5($plaintext . $salt));
  40. }
  41. /**
  42. * @notes 随机生成token值
  43. * @param string $extra
  44. * @return string
  45. * @author 段誉
  46. * @date 2021/12/28 18:24
  47. */
  48. function create_token(string $extra = '') : string
  49. {
  50. $salt = env('project.unique_identification', 'likeadmin');
  51. $encryptSalt = md5( $salt . uniqid());
  52. return md5($salt . $extra . time() . $encryptSalt);
  53. }
  54. /**
  55. * @notes 截取某字符字符串
  56. * @param $str
  57. * @param string $symbol
  58. * @return string
  59. * @author 段誉
  60. * @date 2021/12/28 18:24
  61. */
  62. function substr_symbol_behind($str, $symbol = '.') : string
  63. {
  64. $result = strripos($str, $symbol);
  65. if ($result === false) {
  66. return $str;
  67. }
  68. return substr($str, $result + 1);
  69. }
  70. /**
  71. * @notes 对比php版本
  72. * @param string $version
  73. * @return bool
  74. * @author 段誉
  75. * @date 2021/12/28 18:27
  76. */
  77. function compare_php(string $version) : bool
  78. {
  79. return version_compare(PHP_VERSION, $version) >= 0 ? true : false;
  80. }
  81. /**
  82. * @notes 检查文件是否可写
  83. * @param string $dir
  84. * @return bool
  85. * @author 段誉
  86. * @date 2021/12/28 18:27
  87. */
  88. function check_dir_write(string $dir = '') : bool
  89. {
  90. $route = root_path() . '/' . $dir;
  91. return is_writable($route);
  92. }
  93. /**
  94. * 多级线性结构排序
  95. * 转换前:
  96. * [{"id":1,"pid":0,"name":"a"},{"id":2,"pid":0,"name":"b"},{"id":3,"pid":1,"name":"c"},
  97. * {"id":4,"pid":2,"name":"d"},{"id":5,"pid":4,"name":"e"},{"id":6,"pid":5,"name":"f"},
  98. * {"id":7,"pid":3,"name":"g"}]
  99. * 转换后:
  100. * [{"id":1,"pid":0,"name":"a","level":1},{"id":3,"pid":1,"name":"c","level":2},{"id":7,"pid":3,"name":"g","level":3},
  101. * {"id":2,"pid":0,"name":"b","level":1},{"id":4,"pid":2,"name":"d","level":2},{"id":5,"pid":4,"name":"e","level":3},
  102. * {"id":6,"pid":5,"name":"f","level":4}]
  103. * @param array $data 线性结构数组
  104. * @param string $symbol 名称前面加符号
  105. * @param string $name 名称
  106. * @param string $id_name 数组id名
  107. * @param string $parent_id_name 数组祖先id名
  108. * @param int $level 此值请勿给参数
  109. * @param int $parent_id 此值请勿给参数
  110. * @return array
  111. */
  112. function linear_to_tree($data, $sub_key_name = 'sub', $id_name = 'id', $parent_id_name = 'pid', $parent_id = 0)
  113. {
  114. $tree = [];
  115. foreach ($data as $row) {
  116. if ($row[$parent_id_name] == $parent_id) {
  117. $temp = $row;
  118. $child = linear_to_tree($data, $sub_key_name, $id_name, $parent_id_name, $row[$id_name]);
  119. if ($child) {
  120. $temp[$sub_key_name] = $child;
  121. }
  122. $tree[] = $temp;
  123. }
  124. }
  125. return $tree;
  126. }
  127. /**
  128. * 根据父级ID获取所有子集的值
  129. * @param $data
  130. * @param $pid
  131. * @param $idField
  132. * @param $pidField
  133. * @return array
  134. */
  135. function get_tree_ids($data,$pid = 0, $idField = 'id',$pidField = 'pid')
  136. {
  137. $child = [];
  138. foreach($data as $val){
  139. if ($val[$pidField] == $pid) {
  140. $children = get_tree_ids($data, $val[$idField],$idField,$pidField,);
  141. if ( count($children) > 0) {
  142. $child = array_merge($child,$children);
  143. }
  144. $child[] = $val['id'];
  145. }
  146. }
  147. return $child;
  148. }
  149. function get_top_parent_info($data, $id, $idField = 'id', $pidField = 'pid' , $parentLevel = 0)
  150. {
  151. foreach ($data as $item) {
  152. if ($item[$idField] == $id) {
  153. if ($item[$pidField] == $parentLevel) {
  154. return $item;
  155. } else {
  156. return get_top_parent_info($data, $item[$pidField], $idField, $pidField);
  157. }
  158. }
  159. }
  160. return null;
  161. }
  162. /**
  163. * 根据子集的值获取所有最高父级信息
  164. * @param $data
  165. * @param $pid
  166. * @param $idField
  167. * @param $pidField
  168. * @return array
  169. */
  170. function get_parent_info($data,$ids = [])
  171. {
  172. $res = [];
  173. foreach ($ids as $item) {
  174. $topParentInfo = get_top_parent_info($data, $item);
  175. if ($topParentInfo !== null) {
  176. $res[$topParentInfo['id']] = $topParentInfo;
  177. }
  178. }
  179. return $res;
  180. }
  181. /**
  182. * @notes 删除目标目录
  183. * @param $path
  184. * @param $delDir
  185. * @return bool|void
  186. * @author 段誉
  187. * @date 2022/4/8 16:30
  188. */
  189. function del_target_dir($path, $delDir)
  190. {
  191. //没找到,不处理
  192. if (!file_exists($path)) {
  193. return false;
  194. }
  195. //打开目录句柄
  196. $handle = opendir($path);
  197. if ($handle) {
  198. while (false !== ($item = readdir($handle))) {
  199. if ($item != "." && $item != "..") {
  200. if (is_dir("$path/$item")) {
  201. del_target_dir("$path/$item", $delDir);
  202. } else {
  203. unlink("$path/$item");
  204. }
  205. }
  206. }
  207. closedir($handle);
  208. if ($delDir) {
  209. return rmdir($path);
  210. }
  211. } else {
  212. if (file_exists($path)) {
  213. return unlink($path);
  214. }
  215. return false;
  216. }
  217. }
  218. /**
  219. * @notes 下载文件
  220. * @param $url
  221. * @param $saveDir
  222. * @param $fileName
  223. * @return string
  224. * @author 段誉
  225. * @date 2022/9/16 9:53
  226. */
  227. function download_file($url, $saveDir, $fileName)
  228. {
  229. if (!file_exists($saveDir)) {
  230. mkdir($saveDir, 0775, true);
  231. }
  232. $fileSrc = $saveDir . $fileName;
  233. file_exists($fileSrc) && unlink($fileSrc);
  234. $ch = curl_init();
  235. curl_setopt($ch, CURLOPT_URL, $url);
  236. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  237. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  238. $file = curl_exec($ch);
  239. curl_close($ch);
  240. $resource = fopen($fileSrc, 'a');
  241. fwrite($resource, $file);
  242. fclose($resource);
  243. if (filesize($fileSrc) == 0) {
  244. unlink($fileSrc);
  245. return '';
  246. }
  247. return $fileSrc;
  248. }
  249. /**
  250. * @notes 去除内容图片域名
  251. * @param $content
  252. * @return array|string|string[]
  253. * @author 段誉
  254. * @date 2022/9/26 10:43
  255. */
  256. function clear_file_domain($content)
  257. {
  258. $fileUrl = FileService::getFileUrl();
  259. $pattern = '/<img[^>]*\bsrc=["\']'.preg_quote($fileUrl, '/').'([^"\']+)["\']/i';
  260. return preg_replace($pattern, '<img src="$1"', $content);
  261. }
  262. /**
  263. * @notes 设置内容图片域名
  264. * @param $content
  265. * @return array|string|string[]|null
  266. * @author 段誉
  267. * @date 2024/2/5 16:36
  268. */
  269. function get_file_domain($content)
  270. {
  271. $imgPreg = '/(<img .*?src=")[^https|^http](.*?)(".*?>)/is';
  272. $videoPreg = '/(<video .*?src=")[^https|^http](.*?\.mp4)(".*?>)/is';
  273. $fileUrl = FileService::getFileUrl();
  274. $content = preg_replace($imgPreg, "\${1}$fileUrl\${2}\${3}", $content);
  275. return preg_replace($videoPreg, "\${1}$fileUrl\${2}\${3}", $content);
  276. }
  277. /**
  278. * @notes uri小写
  279. * @param $data
  280. * @return array|string[]
  281. * @author 段誉
  282. * @date 2022/7/19 14:50
  283. */
  284. function lower_uri($data)
  285. {
  286. if (!is_array($data)) {
  287. $data = [$data];
  288. }
  289. return array_map(function ($item) {
  290. return strtolower(Str::camel($item));
  291. }, $data);
  292. }
  293. /**
  294. * @notes 获取无前缀数据表名
  295. * @param $tableName
  296. * @return mixed|string
  297. * @author 段誉
  298. * @date 2022/12/12 15:23
  299. */
  300. function get_no_prefix_table_name($tableName)
  301. {
  302. $tablePrefix = config('database.connections.mysql.prefix');
  303. $prefixIndex = strpos($tableName, $tablePrefix);
  304. if ($prefixIndex !== 0 || $prefixIndex === false) {
  305. return $tableName;
  306. }
  307. $tableName = substr_replace($tableName, '', 0, strlen($tablePrefix));
  308. return trim($tableName);
  309. }
  310. /**
  311. * @notes 生成编码
  312. * @param $table
  313. * @param $field
  314. * @param string $prefix
  315. * @param int $randSuffixLength
  316. * @param array $pool
  317. * @return string
  318. * @author 段誉
  319. * @date 2023/2/23 11:35
  320. */
  321. function generate_sn($table, $field, $prefix = '', $randSuffixLength = 4, $pool = []) : string
  322. {
  323. $suffix = '';
  324. for ($i = 0; $i < $randSuffixLength; $i++) {
  325. if (empty($pool)) {
  326. $suffix .= rand(0, 9);
  327. } else {
  328. $suffix .= $pool[array_rand($pool)];
  329. }
  330. }
  331. $sn = $prefix . date('YmdHis') . $suffix;
  332. if (app()->make($table)->where($field, $sn)->find()) {
  333. return generate_sn($table, $field, $prefix, $randSuffixLength, $pool);
  334. }
  335. return $sn;
  336. }
  337. /**
  338. * @notes 格式化金额
  339. * @param $float
  340. * @return int|mixed|string
  341. * @author 段誉
  342. * @date 2023/2/24 11:20
  343. */
  344. function format_amount($float)
  345. {
  346. if ($float == intval($float)) {
  347. return intval($float);
  348. } elseif ($float == sprintf('%.1f', $float)) {
  349. return sprintf('%.1f', $float);
  350. }
  351. return $float;
  352. }
  353. /**
  354. * curl提交
  355. * @param $str
  356. * @return string
  357. */
  358. function http_request($url , $data = NULL)
  359. {
  360. $ch = curl_init();
  361. curl_setopt($ch, CURLOPT_URL, $url);
  362. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  363. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  364. if (!empty($data)){
  365. curl_setopt($ch, CURLOPT_POST, 1);
  366. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  367. }
  368. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  369. $output = curl_exec($ch);
  370. // 检查是否有错误发生
  371. if(curl_errno($ch))
  372. {
  373. echo 'CURL ERROR CODE: '. curl_errno($ch) . ' , reason : ' . curl_error($ch);
  374. }
  375. curl_close($ch);
  376. $jsoninfo = json_decode($output , true);
  377. return $jsoninfo;
  378. }
  379. /**
  380. * sql语句打印
  381. * 需要打印sql时将record_sql()方法放到sql语句之前,或 config.database.trigger_sql设置为true
  382. */
  383. function record_sql()
  384. {
  385. if(!config("database.connections.mysql.trigger_sql")){
  386. $config = config('database');
  387. $config['connections']['mysql']['trigger_sql'] = true;
  388. app()->config->set($config,'database');
  389. }
  390. \think\facade\Db::listen(function ($sql,$time,$connection) {
  391. if(strpos($sql,'CONNECT') !== false){
  392. return;
  393. }
  394. if(strpos($sql,'SHOW FULL') !== false){
  395. return;
  396. }
  397. \think\facade\Log::debug( '打印sql: '.$sql. ' time:'.$time);
  398. });
  399. }
  400. // 前三后四星号字符
  401. function asteriskString($str) {
  402. if (strlen($str) > 7) {
  403. return substr($str, 0, 3) . '****' . substr($str, -4, 4);
  404. } else {
  405. return $str;
  406. }
  407. }
  408. function getPostageRegion($ids = []) {
  409. $id_str = '';
  410. if(!empty($ids)){
  411. $id_str = implode(',',$ids);
  412. }
  413. $lists = cache('postageRegion'.$id_str);
  414. if(empty($lists)){
  415. $lists = PostageRegion::field(['*'])->whereIn('id',$ids)->select()->toArray();
  416. cache('postageRegion'.$id_str,$lists);
  417. }
  418. return $lists;
  419. }
  420. // 通过市查询省id
  421. function getProvinceByCityId($city_id) {
  422. $postageRegion = array_column(getPostageRegion([$city_id]), null, 'id');
  423. return $postageRegion[$city_id]['pid'];
  424. }
  425. // 获取随机字符串
  426. function generateRandomString($length = 8,$basic_method = 4) {
  427. $characters = '';
  428. $num = '0123456789';
  429. $lowercase_letters = 'abcdefghijklmnopqrstuvwxyz';
  430. $capital_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  431. switch ($basic_method){
  432. case 1:
  433. $characters = $num;
  434. break;
  435. case 2:
  436. $characters = $lowercase_letters;
  437. break;
  438. case 3:
  439. $characters = $num.$lowercase_letters;
  440. break;
  441. case 4:
  442. $characters = $num.$lowercase_letters.$capital_letters;
  443. break;
  444. }
  445. $charactersLength = strlen($characters);
  446. $randomString = '';
  447. for ($i = 0; $i < $length; $i++) {
  448. $randomString .= $characters[rand(0, $charactersLength - 1)];
  449. }
  450. return $randomString;
  451. }
  452. /**
  453. * 判断点是否在多边形内
  454. * @param $point
  455. * @param $polygon
  456. * @return bool
  457. */
  458. function isPointInPolygon($point, $polygon) {
  459. $x = $point['lng'];
  460. $y = $point['lat'];
  461. $inside = false;
  462. $j = count($polygon) - 1;
  463. for ($i = 0; $i < count($polygon); $i++) {
  464. $xi = $polygon[$i][0];
  465. $yi = $polygon[$i][1];
  466. $xj = $polygon[$j][0];
  467. $yj = $polygon[$j][1];
  468. $intersect = (($yi > $y) != ($yj > $y))
  469. && ($x < ($xj - $xi) * ($y - $yi) / ($yj - $yi) + $xi);
  470. if ($intersect) {
  471. $inside = !$inside;
  472. }
  473. $j = $i;
  474. }
  475. return $inside;
  476. }
  477. /**
  478. * 获取自己和上级id
  479. * @param $point
  480. * @param $polygon
  481. * @return bool
  482. */
  483. function getSuperiorId($all_category,$id,&$all_category_ids)
  484. {
  485. $all_category_ids[] = $id;
  486. $tmp_pid = $all_category[$id];
  487. if($tmp_pid > 0) {
  488. getSuperiorId($all_category,$tmp_pid,$all_category_ids);
  489. }
  490. return $all_category_ids;
  491. }
  492. /**
  493. * 获取子分类上级返回树
  494. * @param $category_ids array 分类id数组
  495. * @return array 分类树结构
  496. */
  497. function getSuperiorCategoryTree($category_ids)
  498. {
  499. $all_category = GoodsCategory::where('status', 1)->column('pid', 'id');
  500. $all_category_ids = [];
  501. foreach ($category_ids as $v) {
  502. getSuperiorId($all_category,$v,$all_category_ids);
  503. }
  504. $tree_data = GoodsCategory::field('id,pid,name')
  505. ->where('status', 1)
  506. ->whereIn('id', array_unique($all_category_ids))
  507. ->select()
  508. ->toArray();
  509. return linear_to_tree($tree_data, 'children');
  510. }