common.php 20 KB

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