common.php 20 KB

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