common.php 20 KB

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