common.php 16 KB

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