common.php 19 KB

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