common.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. <?php
  2. // 应用公共文件
  3. use app\common\service\FileService;
  4. use think\helper\Str;
  5. /**
  6. * @notes 生成密码加密密钥
  7. * @param string $plaintext
  8. * @param string $salt
  9. * @return string
  10. * @author 段誉
  11. * @date 2021/12/28 18:24
  12. */
  13. function create_password(string $plaintext, string $salt) : string
  14. {
  15. return md5($salt . md5($plaintext . $salt));
  16. }
  17. /**
  18. * @notes 随机生成token值
  19. * @param string $extra
  20. * @return string
  21. * @author 段誉
  22. * @date 2021/12/28 18:24
  23. */
  24. function create_token(string $extra = '') : string
  25. {
  26. $salt = env('project.unique_identification', 'likeadmin');
  27. $encryptSalt = md5( $salt . uniqid());
  28. return md5($salt . $extra . time() . $encryptSalt);
  29. }
  30. /**
  31. * @notes 截取某字符字符串
  32. * @param $str
  33. * @param string $symbol
  34. * @return string
  35. * @author 段誉
  36. * @date 2021/12/28 18:24
  37. */
  38. function substr_symbol_behind($str, $symbol = '.') : string
  39. {
  40. $result = strripos($str, $symbol);
  41. if ($result === false) {
  42. return $str;
  43. }
  44. return substr($str, $result + 1);
  45. }
  46. /**
  47. * @notes 对比php版本
  48. * @param string $version
  49. * @return bool
  50. * @author 段誉
  51. * @date 2021/12/28 18:27
  52. */
  53. function compare_php(string $version) : bool
  54. {
  55. return version_compare(PHP_VERSION, $version) >= 0 ? true : false;
  56. }
  57. /**
  58. * @notes 检查文件是否可写
  59. * @param string $dir
  60. * @return bool
  61. * @author 段誉
  62. * @date 2021/12/28 18:27
  63. */
  64. function check_dir_write(string $dir = '') : bool
  65. {
  66. $route = root_path() . '/' . $dir;
  67. return is_writable($route);
  68. }
  69. /**
  70. * 多级线性结构排序
  71. * 转换前:
  72. * [{"id":1,"pid":0,"name":"a"},{"id":2,"pid":0,"name":"b"},{"id":3,"pid":1,"name":"c"},
  73. * {"id":4,"pid":2,"name":"d"},{"id":5,"pid":4,"name":"e"},{"id":6,"pid":5,"name":"f"},
  74. * {"id":7,"pid":3,"name":"g"}]
  75. * 转换后:
  76. * [{"id":1,"pid":0,"name":"a","level":1},{"id":3,"pid":1,"name":"c","level":2},{"id":7,"pid":3,"name":"g","level":3},
  77. * {"id":2,"pid":0,"name":"b","level":1},{"id":4,"pid":2,"name":"d","level":2},{"id":5,"pid":4,"name":"e","level":3},
  78. * {"id":6,"pid":5,"name":"f","level":4}]
  79. * @param array $data 线性结构数组
  80. * @param string $symbol 名称前面加符号
  81. * @param string $name 名称
  82. * @param string $id_name 数组id名
  83. * @param string $parent_id_name 数组祖先id名
  84. * @param int $level 此值请勿给参数
  85. * @param int $parent_id 此值请勿给参数
  86. * @return array
  87. */
  88. function linear_to_tree($data, $sub_key_name = 'sub', $id_name = 'id', $parent_id_name = 'pid', $parent_id = 0)
  89. {
  90. $tree = [];
  91. foreach ($data as $row) {
  92. if ($row[$parent_id_name] == $parent_id) {
  93. $temp = $row;
  94. $child = linear_to_tree($data, $sub_key_name, $id_name, $parent_id_name, $row[$id_name]);
  95. if ($child) {
  96. $temp[$sub_key_name] = $child;
  97. }
  98. $tree[] = $temp;
  99. }
  100. }
  101. return $tree;
  102. }
  103. /**
  104. * 根据父级ID获取所有子集的值
  105. * @param $data
  106. * @param $pid
  107. * @param $idField
  108. * @param $pidField
  109. * @return array
  110. */
  111. function get_tree_ids($data,$pid = 0, $idField = 'id',$pidField = 'pid')
  112. {
  113. $child = [];
  114. foreach($data as $val){
  115. if ($val[$pidField] == $pid) {
  116. $children = get_tree_ids($data, $val[$idField],$idField,$pidField,);
  117. if ( count($children) > 0) {
  118. $child = array_merge($child,$children);
  119. }
  120. $child[] = $val['id'];
  121. }
  122. }
  123. return $child;
  124. }
  125. function get_top_parent_info($data, $id, $idField = 'id', $pidField = 'pid')
  126. {
  127. foreach ($data as $item) {
  128. if ($item[$idField] == $id) {
  129. if ($item[$pidField] == 0) {
  130. return $item;
  131. } else {
  132. return get_top_parent_info($data, $item[$pidField], $idField, $pidField);
  133. }
  134. }
  135. }
  136. return null;
  137. }
  138. /**
  139. * 根据子集的值获取所有最高父级信息
  140. * @param $data
  141. * @param $pid
  142. * @param $idField
  143. * @param $pidField
  144. * @return array
  145. */
  146. function get_parent_info($data,$ids = [])
  147. {
  148. $res = [];
  149. foreach ($ids as $item) {
  150. $topParentInfo = get_top_parent_info($data, $item);
  151. if ($topParentInfo !== null) {
  152. $res[$topParentInfo['id']] = $topParentInfo;
  153. }
  154. }
  155. return $res;
  156. }
  157. /**
  158. * @notes 删除目标目录
  159. * @param $path
  160. * @param $delDir
  161. * @return bool|void
  162. * @author 段誉
  163. * @date 2022/4/8 16:30
  164. */
  165. function del_target_dir($path, $delDir)
  166. {
  167. //没找到,不处理
  168. if (!file_exists($path)) {
  169. return false;
  170. }
  171. //打开目录句柄
  172. $handle = opendir($path);
  173. if ($handle) {
  174. while (false !== ($item = readdir($handle))) {
  175. if ($item != "." && $item != "..") {
  176. if (is_dir("$path/$item")) {
  177. del_target_dir("$path/$item", $delDir);
  178. } else {
  179. unlink("$path/$item");
  180. }
  181. }
  182. }
  183. closedir($handle);
  184. if ($delDir) {
  185. return rmdir($path);
  186. }
  187. } else {
  188. if (file_exists($path)) {
  189. return unlink($path);
  190. }
  191. return false;
  192. }
  193. }
  194. /**
  195. * @notes 下载文件
  196. * @param $url
  197. * @param $saveDir
  198. * @param $fileName
  199. * @return string
  200. * @author 段誉
  201. * @date 2022/9/16 9:53
  202. */
  203. function download_file($url, $saveDir, $fileName)
  204. {
  205. if (!file_exists($saveDir)) {
  206. mkdir($saveDir, 0775, true);
  207. }
  208. $fileSrc = $saveDir . $fileName;
  209. file_exists($fileSrc) && unlink($fileSrc);
  210. $ch = curl_init();
  211. curl_setopt($ch, CURLOPT_URL, $url);
  212. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  213. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  214. $file = curl_exec($ch);
  215. curl_close($ch);
  216. $resource = fopen($fileSrc, 'a');
  217. fwrite($resource, $file);
  218. fclose($resource);
  219. if (filesize($fileSrc) == 0) {
  220. unlink($fileSrc);
  221. return '';
  222. }
  223. return $fileSrc;
  224. }
  225. /**
  226. * @notes 去除内容图片域名
  227. * @param $content
  228. * @return array|string|string[]
  229. * @author 段誉
  230. * @date 2022/9/26 10:43
  231. */
  232. function clear_file_domain($content)
  233. {
  234. $fileUrl = FileService::getFileUrl();
  235. $pattern = '/<img[^>]*\bsrc=["\']'.preg_quote($fileUrl, '/').'([^"\']+)["\']/i';
  236. return preg_replace($pattern, '<img src="$1"', $content);
  237. }
  238. /**
  239. * @notes 设置内容图片域名
  240. * @param $content
  241. * @return array|string|string[]|null
  242. * @author 段誉
  243. * @date 2024/2/5 16:36
  244. */
  245. function get_file_domain($content)
  246. {
  247. $imgPreg = '/(<img .*?src=")[^https|^http](.*?)(".*?>)/is';
  248. $videoPreg = '/(<video .*?src=")[^https|^http](.*?\.mp4)(".*?>)/is';
  249. $fileUrl = FileService::getFileUrl();
  250. $content = preg_replace($imgPreg, "\${1}$fileUrl\${2}\${3}", $content);
  251. return preg_replace($videoPreg, "\${1}$fileUrl\${2}\${3}", $content);
  252. }
  253. /**
  254. * @notes uri小写
  255. * @param $data
  256. * @return array|string[]
  257. * @author 段誉
  258. * @date 2022/7/19 14:50
  259. */
  260. function lower_uri($data)
  261. {
  262. if (!is_array($data)) {
  263. $data = [$data];
  264. }
  265. return array_map(function ($item) {
  266. return strtolower(Str::camel($item));
  267. }, $data);
  268. }
  269. /**
  270. * @notes 获取无前缀数据表名
  271. * @param $tableName
  272. * @return mixed|string
  273. * @author 段誉
  274. * @date 2022/12/12 15:23
  275. */
  276. function get_no_prefix_table_name($tableName)
  277. {
  278. $tablePrefix = config('database.connections.mysql.prefix');
  279. $prefixIndex = strpos($tableName, $tablePrefix);
  280. if ($prefixIndex !== 0 || $prefixIndex === false) {
  281. return $tableName;
  282. }
  283. $tableName = substr_replace($tableName, '', 0, strlen($tablePrefix));
  284. return trim($tableName);
  285. }
  286. /**
  287. * @notes 生成编码
  288. * @param $table
  289. * @param $field
  290. * @param string $prefix
  291. * @param int $randSuffixLength
  292. * @param array $pool
  293. * @return string
  294. * @author 段誉
  295. * @date 2023/2/23 11:35
  296. */
  297. function generate_sn($table, $field, $prefix = '', $randSuffixLength = 4, $pool = []) : string
  298. {
  299. $suffix = '';
  300. for ($i = 0; $i < $randSuffixLength; $i++) {
  301. if (empty($pool)) {
  302. $suffix .= rand(0, 9);
  303. } else {
  304. $suffix .= $pool[array_rand($pool)];
  305. }
  306. }
  307. $sn = $prefix . date('YmdHis') . $suffix;
  308. if (app()->make($table)->where($field, $sn)->find()) {
  309. return generate_sn($table, $field, $prefix, $randSuffixLength, $pool);
  310. }
  311. return $sn;
  312. }
  313. /**
  314. * @notes 格式化金额
  315. * @param $float
  316. * @return int|mixed|string
  317. * @author 段誉
  318. * @date 2023/2/24 11:20
  319. */
  320. function format_amount($float)
  321. {
  322. if ($float == intval($float)) {
  323. return intval($float);
  324. } elseif ($float == sprintf('%.1f', $float)) {
  325. return sprintf('%.1f', $float);
  326. }
  327. return $float;
  328. }
  329. /**
  330. * curl提交
  331. * @param $str
  332. * @return string
  333. */
  334. function http_request($url , $data = NULL)
  335. {
  336. $ch = curl_init();
  337. curl_setopt($ch, CURLOPT_URL, $url);
  338. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  339. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  340. if (!empty($data)){
  341. curl_setopt($ch, CURLOPT_POST, 1);
  342. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  343. }
  344. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  345. $output = curl_exec($ch);
  346. // 检查是否有错误发生
  347. if(curl_errno($ch))
  348. {
  349. echo 'CURL ERROR CODE: '. curl_errno($ch) . ' , reason : ' . curl_error($ch);
  350. }
  351. curl_close($ch);
  352. $jsoninfo = json_decode($output , true);
  353. return $jsoninfo;
  354. }
  355. /**
  356. * sql语句打印
  357. * 需要打印sql时将record_sql()方法放到sql语句之前,或 config.database.trigger_sql设置为true
  358. */
  359. function record_sql()
  360. {
  361. if(!config("database.connections.mysql.trigger_sql")){
  362. $config = config('database');
  363. $config['connections']['mysql']['trigger_sql'] = true;
  364. app()->config->set($config,'database');
  365. }
  366. \think\facade\Db::listen(function ($sql,$time,$connection) {
  367. if(strpos($sql,'CONNECT') !== false){
  368. return;
  369. }
  370. if(strpos($sql,'SHOW FULL') !== false){
  371. return;
  372. }
  373. \think\facade\Log::debug( '打印sql: '.$sql. ' time:'.$time);
  374. });
  375. }
  376. // 前三后四星号字符
  377. function asteriskString($str) {
  378. if (strlen($str) > 7) {
  379. return substr($str, 0, 3) . '****' . substr($str, -4, 4);
  380. } else {
  381. return $str;
  382. }
  383. }
  384. // 获取随机字符串
  385. function generateRandomString($length = 8,$basic_method = 4) {
  386. $characters = '';
  387. $num = '0123456789';
  388. $lowercase_letters = 'abcdefghijklmnopqrstuvwxyz';
  389. $capital_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  390. switch ($basic_method){
  391. case 1:
  392. $characters = $num;
  393. break;
  394. case 2:
  395. $characters = $lowercase_letters;
  396. break;
  397. case 3:
  398. $characters = $num.$lowercase_letters;
  399. break;
  400. case 4:
  401. $characters = $num.$lowercase_letters.$capital_letters;
  402. break;
  403. }
  404. $charactersLength = strlen($characters);
  405. $randomString = '';
  406. for ($i = 0; $i < $length; $i++) {
  407. $randomString .= $characters[rand(0, $charactersLength - 1)];
  408. }
  409. return $randomString;
  410. }