Service.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. <?php
  2. namespace App\Service;
  3. use App\Jobs\OperationLog;
  4. use App\Model\Employee;
  5. use Illuminate\Support\Facades\Redis;
  6. use Illuminate\Support\Facades\Storage;
  7. /**
  8. * 公用的公共服务
  9. * @package App\Models
  10. */
  11. class Service
  12. {
  13. public $log;
  14. public $total = 0;
  15. public function __construct()
  16. {
  17. }
  18. //分页共用
  19. public function limit($db, $columns, $request)
  20. {
  21. $per_page = $request['page_size'] ?? 9999;
  22. $page = $request['page_index'] ?? 1;
  23. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  24. $data['total'] = $return['total'];
  25. $data['data'] = $return['data'];
  26. return $data;
  27. }
  28. //分页共用2
  29. public function limitData($db, $columns, $request)
  30. {
  31. $per_page = $request['page_size'] ?? 1000;
  32. $page = $request['page_index'] ?? 1;
  33. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  34. return $return['data'];
  35. }
  36. //抽象一个查询条件,省的每天写很多行
  37. protected function is_exist_db($data, $word, $words, $db, $formula = '=', $type = '')
  38. {
  39. if (isset($data[$word]) && ($data[$word] !== null && $data[$word] !== '' && $data[$word] !== [])) {
  40. switch ($type) {
  41. case 'time':
  42. $data[$word] = ctype_digit($data[$word]) ? $data[$word] : strtotime($data[$word]);
  43. if ($formula == '<'||$formula == '<=') $data[$word] += 86400;
  44. $db = $db->where($words, $formula, $data[$word]);
  45. break;
  46. case 'like':
  47. $db = $db->where($words, $type, '%' . $data[$word] . '%');
  48. break;
  49. case 'in':
  50. if (is_array($data[$word])) {
  51. $db = $db->wherein($words, $data[$word]);
  52. } else {
  53. $db = $db->wherein($words, explode(',', $data[$word]));
  54. }
  55. break;
  56. default:
  57. $db = $db->where($words, $formula, $data[$word]);
  58. break;
  59. }
  60. return $db;
  61. }
  62. return $db;
  63. }
  64. //判断是否为空
  65. protected function isEmpty($data, $word)
  66. {
  67. if (isset($data[$word]) && (!empty($data[$word]) || $data[$word] === '0'|| $data[$word] === 0)) return false;
  68. return true;
  69. }
  70. //递归处理数据成子父级关系
  71. public function makeTree($parentId, &$node)
  72. {
  73. $tree = [];
  74. foreach ($node as $key => $value) {
  75. if ($value['parent_id'] == $parentId) {
  76. $tree[$value['id']] = $value;
  77. unset($node[$key]);
  78. if (isset($tree[$value['id']]['children'])) {
  79. $tree[$value['id']]['children'] = array_merge($tree[$value['id']]['children'], $this->makeTree($value['id'], $node));
  80. } else {
  81. $tree[$value['id']]['children'] = $this->makeTree($value['id'], $node);
  82. }
  83. }
  84. }
  85. return $tree;
  86. }
  87. //进行递归处理数组的排序问题
  88. public function set_sort_circle($data){
  89. foreach ($data as $k=>$v){
  90. // var_dump($v);die;
  91. if(isset($v['children'])&&!empty($v['children'])){
  92. $data[$k]['children'] = $this->set_sort_circle($v['children']);
  93. }
  94. }
  95. $data = array_merge($data);
  96. return $data;
  97. }
  98. //根据编码规则获取每一级的code
  99. public function get_rule_code($code, $rule)
  100. {
  101. $rules = [];
  102. $num = 0;
  103. foreach ($rule as $v) {
  104. $num += $v['num'];
  105. $code = substr($code, 0, $num);
  106. if (strlen($code) != $num) continue;
  107. $rules[] = $code;
  108. }
  109. return $rules;
  110. }
  111. function curlOpen($url, $config = array())
  112. {
  113. $arr = array('post' => false,'referer' => $url,'cookie' => '', 'useragent' => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; customie8)', 'timeout' => 100, 'return' => true, 'proxy' => '', 'userpwd' => '', 'nobody' => false,'header'=>array(),'gzip'=>true,'ssl'=>true,'isupfile'=>false,'returnheader'=>false,'request'=>'post');
  114. $arr = array_merge($arr, $config);
  115. $ch = curl_init();
  116. curl_setopt($ch, CURLOPT_URL, $url);
  117. curl_setopt($ch, CURLOPT_RETURNTRANSFER, $arr['return']);
  118. curl_setopt($ch, CURLOPT_NOBODY, $arr['nobody']);
  119. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  120. curl_setopt($ch, CURLOPT_USERAGENT, $arr['useragent']);
  121. curl_setopt($ch, CURLOPT_REFERER, $arr['referer']);
  122. curl_setopt($ch, CURLOPT_TIMEOUT, $arr['timeout']);
  123. curl_setopt($ch, CURLOPT_HEADER, $arr['returnheader']);//��ȡheader
  124. if($arr['gzip']) curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
  125. if($arr['ssl'])
  126. {
  127. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  128. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  129. }
  130. if(!empty($arr['cookie']))
  131. {
  132. curl_setopt($ch, CURLOPT_COOKIEJAR, $arr['cookie']);
  133. curl_setopt($ch, CURLOPT_COOKIEFILE, $arr['cookie']);
  134. }
  135. if(!empty($arr['proxy']))
  136. {
  137. //curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  138. curl_setopt ($ch, CURLOPT_PROXY, $arr['proxy']);
  139. if(!empty($arr['userpwd']))
  140. {
  141. curl_setopt($ch,CURLOPT_PROXYUSERPWD,$arr['userpwd']);
  142. }
  143. }
  144. //ip�Ƚ����⣬�ü�ֵ��ʾ
  145. if(!empty($arr['header']['ip']))
  146. {
  147. array_push($arr['header'],'X-FORWARDED-FOR:'.$arr['header']['ip'],'CLIENT-IP:'.$arr['header']['ip']);
  148. unset($arr['header']['ip']);
  149. }
  150. $arr['header'] = array_filter($arr['header']);
  151. if(!empty($arr['header']))
  152. {
  153. curl_setopt($ch, CURLOPT_HTTPHEADER, $arr['header']);
  154. }
  155. if($arr['request'] === 'put'){
  156. curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  157. curl_setopt($ch, CURLOPT_POSTFIELDS,$arr['post']);
  158. }elseif($arr['post'] != false)
  159. {
  160. curl_setopt($ch, CURLOPT_POST, true);
  161. if(is_array($arr['post']) && $arr['isupfile'] === false)
  162. {
  163. $post = http_build_query($arr['post']);
  164. }
  165. else
  166. {
  167. $post = $arr['post'];
  168. }
  169. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  170. }
  171. $result = curl_exec($ch);
  172. curl_close($ch);
  173. return $result;
  174. }
  175. function getAllIdsArr($data, $pid = 0, $prefix = '', &$result = []) {
  176. foreach ($data as $node) {
  177. if ($node['parent_id'] == $pid) {
  178. $id = $prefix . $node['id'];
  179. $result[] = $id;
  180. $this->getAllIdsArr($data, $node['id'], $id . ',', $result);
  181. }
  182. }
  183. return $result;
  184. }
  185. function getLongestStr($arr = [], $searchStr){
  186. if(empty($arr) || ! $searchStr) return '';
  187. if(! is_string($searchStr)) $searchStr = (string)$searchStr;
  188. $longest = '';
  189. foreach ($arr as $str) {
  190. if (strpos($str, $searchStr) !== false && strlen($str) > strlen($longest)) {
  191. $longest = $str;
  192. }
  193. }
  194. return $longest;
  195. }
  196. function getAllDescendants($data, $id) {
  197. $result = array(); // 存储结果的数组
  198. foreach ($data as $node) {
  199. if ($node['parent_id'] == $id) { // 如果当前节点的父 ID 等于指定 ID,则将该节点添加到结果中
  200. $result[] = $node['id'];
  201. // 递归查询该节点的所有子孙节点,并将结果合并到结果数组中
  202. $result = array_merge($result, $this->getAllDescendants($data, $node['id']));
  203. }
  204. }
  205. return $result;
  206. }
  207. //后台端 某些需要限制请求频率的接口
  208. //需要主动删除 Redis::del($key)
  209. public function limitingSendRequestBackg($key,$value=0){
  210. $prefix = config('app.name') . ':';
  211. $key = $prefix . $key;
  212. if(! empty($value)) $value = 1;
  213. // 使用Redis Facade设置,当键名不存在时才设置成功
  214. if (Redis::setnx($key, $value)) return [true, ''];
  215. return [false,'操作频繁!'];
  216. }
  217. public function dellimitingSendRequestBackg($key){
  218. $prefix = config('app.name') . ':';
  219. $key = $prefix . $key;
  220. Redis::del($key);
  221. }
  222. //后台端 某些需要限制请求频率的接口 有过期时间
  223. public function limitingSendRequestBackgExpire($key,$ttl = 5){
  224. $prefix = config('app.name') . ':';
  225. $key = $prefix . $key;
  226. if($ttl < 5) $ttl = 5;
  227. // 使用Redis Facade设置,当键名不存在时才设置成功
  228. if (Redis::setnx($key, 1)) {
  229. Redis::expire($key, $ttl); //多少秒后过期
  230. return [true, ''];
  231. }
  232. return [false,'操作频繁, 请在 ' . $ttl . '秒后重试'];
  233. }
  234. //前端传来的时间段 转换为时间戳
  235. //精确到秒
  236. function changeDateToTimeStampAboutRange($time_range){
  237. if(empty($time_range[0]) || empty($time_range[1])) return [];
  238. // 创建一个 DateTime 对象并设置时区为 UTC
  239. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  240. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  241. // 将时区设置为 PRC
  242. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  243. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  244. // 将日期时间格式化为特定格式
  245. $formattedDate = $dateTime->format('Y-m-d');
  246. $formattedDate1 = $dateTime1->format('Y-m-d');
  247. $return = [];
  248. $return[] = strtotime($formattedDate . " 00:00:00");
  249. $return[] = strtotime($formattedDate1 . " 23:59:59");
  250. return $return;
  251. }
  252. //前端传来的时间段 转换为时间戳
  253. //精确到日
  254. function changeDateToNewDate($time_range){
  255. if(empty($time_range[0]) || empty($time_range[1])) return [];
  256. // 创建一个 DateTime 对象并设置时区为 UTC
  257. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  258. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  259. // 将时区设置为 PRC
  260. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  261. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  262. // 将日期时间格式化为特定格式
  263. $formattedDate = $dateTime->format('Y-m-d');
  264. $formattedDate1 = $dateTime1->format('Y-m-d');
  265. $return = [];
  266. $return[] = strtotime($formattedDate);
  267. $return[] = strtotime($formattedDate1);
  268. return $return;
  269. }
  270. function changeDateToNewDate2($time){
  271. if(empty($time_range)) return [];
  272. // 创建一个 DateTime 对象并设置时区为 UTC
  273. $dateTime = new \DateTime($time_range, new \DateTimeZone('UTC'));
  274. // 将时区设置为 PRC
  275. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  276. // 将日期时间格式化为特定格式
  277. $formattedDate = $dateTime->format('Y-m-d 00:00:00');
  278. $formattedDate1 = $dateTime->format('Y-m-d 23:59:59');
  279. $return = [];
  280. $return[] = strtotime($formattedDate);
  281. $return[] = strtotime($formattedDate1);
  282. return $return;
  283. }
  284. //前端传来的时间 转为时间戳
  285. //精确到分
  286. function changeDateToDateMin($time){
  287. if(empty($time)) return '';
  288. // 创建一个 DateTime 对象并设置时区为 UTC
  289. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  290. // 将时区设置为 PRC
  291. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  292. // 将日期时间格式化为特定格式
  293. $formattedDate = $dateTime->format('Y-m-d H:i');
  294. return strtotime($formattedDate);
  295. }
  296. //前端传来的时间 转为时间戳
  297. //精确到日
  298. function changeDateToDate($time){
  299. if(empty($time)) return '';
  300. // 创建一个 DateTime 对象并设置时区为 UTC
  301. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  302. // 将时区设置为 PRC
  303. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  304. // 将日期时间格式化为特定格式
  305. $formattedDate = $dateTime->format('Y-m-d 00:00:00');
  306. return strtotime($formattedDate);
  307. }
  308. /**
  309. * 用于用户行为操作日志记录
  310. * @param $insert
  311. * @return void
  312. */
  313. public function insertLog($insert){
  314. OperationLog::dispatch($insert);
  315. }
  316. public function checkNumber($number, $decimals = 2){
  317. if(! is_numeric($number) || $number < 0) return false;
  318. $formattedNumber = number_format($number, $decimals, '.', '');
  319. if($formattedNumber != $number) return false;
  320. return true;
  321. }
  322. public function getDepart($user){
  323. if(empty($user)) return 0;
  324. return $user['depart_select']['depart_id'];
  325. }
  326. public function getTopId($id, $data) {
  327. foreach ($data as $item) {
  328. if ($item['id'] == $id) {
  329. if ($item['parent_id'] == 0) {
  330. // 找到最顶级的id
  331. return $item['id'];
  332. } else {
  333. // 继续递归查找父级
  334. return $this->getTopId($item['parent_id'], $data);
  335. }
  336. }
  337. }
  338. // 如果没有找到匹配的id,则返回null或者其他你希望的默认值
  339. return 0;
  340. }
  341. // 递归查找所有父级id
  342. public function findParentIds($id, $data) {
  343. $parentIds = [];
  344. foreach ($data as $item) {
  345. if ($item['id'] == $id) {
  346. $parentId = $item['parent_id'];
  347. if ($parentId) {
  348. $parentIds[] = $parentId;
  349. $parentIds = array_merge($parentIds, $this->findParentIds($parentId, $data));
  350. }
  351. break;
  352. }
  353. }
  354. return $parentIds;
  355. }
  356. // 递归查找所有子级id
  357. public function findChildIds($id, $data) {
  358. $childIds = [];
  359. foreach ($data as $item) {
  360. if ($item['parent_id'] == $id) {
  361. $childId = $item['id'];
  362. $childIds[] = $childId;
  363. $childIds = array_merge($childIds, $this->findChildIds($childId, $data));
  364. }
  365. }
  366. return $childIds;
  367. }
  368. public function getDataFile($data){
  369. foreach ($data as $key => $value){
  370. if($key == 'depart_id' || $key == 'top_depart_id') unset($data[$key]);
  371. }
  372. return $data;
  373. }
  374. // 校验域名是否通畅可达
  375. // $domain baidu.com 不要带http这些协议头
  376. // gethostbyname() 函数可能会受到 PHP 配置中的 allow_url_fopen 和 disable_functions 选项的限制
  377. function isDomainAvailable($domain) {
  378. $ip = gethostbyname($domain);
  379. // 如果解析失败或者返回的 IP 地址与输入的域名相同,则说明域名无效
  380. if ($ip === $domain || filter_var($ip, FILTER_VALIDATE_IP) === false) return false;
  381. return true;
  382. }
  383. public function delStorageFile($old, $new = [], $dir = "upload_files/"){
  384. foreach ($old as $value){
  385. if(! in_array($value, $new)){
  386. $filename_rep = "/api/uploadFiles/";
  387. $filename = str_replace($filename_rep, "", $value);
  388. $filePath = $dir . $filename;
  389. if (Storage::disk('public')->exists($filePath)) {
  390. // 文件存在 进行删除操作
  391. Storage::disk('public')->delete($filePath);
  392. }
  393. }
  394. }
  395. }
  396. public function showTimeAgo($time, $time_big){
  397. // 计算时间差(秒)
  398. $diffInSeconds = $time_big - $time;
  399. // 将时间差转换为更易处理的单位
  400. $diffInMinutes = floor($diffInSeconds / 60);
  401. $diffInHours = floor($diffInSeconds / 3600);
  402. $diffInDays = floor($diffInSeconds / (3600 * 24));
  403. // 根据时间差生成描述性文本
  404. if ($diffInSeconds < 60) {
  405. $timeAgo = '刚刚';
  406. } elseif ($diffInMinutes < 60) {
  407. $timeAgo = $diffInMinutes . '分钟前';
  408. } elseif ($diffInHours < 24) {
  409. $timeAgo = $diffInHours . '小时前';
  410. } elseif ($diffInDays < 2) {
  411. $timeAgo = '昨天';
  412. } elseif ($diffInDays < 7) {
  413. $timeAgo = $diffInDays . '天前';
  414. } elseif ($diffInDays < 15) {
  415. $timeAgo = '一周前';
  416. } elseif ($diffInDays < 30) {
  417. $timeAgo = '半个月内';
  418. } else {
  419. // 如果超过半个月,可以使用具体的日期格式
  420. $crtTimeDate = date('Y-m-d', $time);
  421. $timeAgo = '在 ' . $crtTimeDate;
  422. }
  423. return $timeAgo;
  424. }
  425. // 递归函数,用于在数据结构中查找值
  426. function findLabelsByValue($data, $valuesToFind, &$foundLabels) {
  427. foreach ($data as $item) {
  428. if (isset($item['value']) && in_array($item['value'], $valuesToFind)) {
  429. // 如果找到值,则添加其label到结果数组中
  430. $foundLabels[] = $item['label'];
  431. // 移除已找到的值,避免重复查找
  432. $key = array_search($item['value'], $valuesToFind);
  433. if ($key !== false) {
  434. unset($valuesToFind[$key]);
  435. }
  436. }
  437. if (isset($item['children']) && !empty($item['children'])) {
  438. // 递归调用自身来查找子节点
  439. $this->findLabelsByValue($item['children'], $valuesToFind, $foundLabels);
  440. }
  441. // 如果所有值都已找到,则停止递归
  442. if (empty($valuesToFind)) {
  443. break;
  444. }
  445. }
  446. }
  447. public function changeAndReturnDate($date_int){
  448. $int = intval($date_int);
  449. $bool = (string)$int === $date_int;
  450. if(! $bool || $date_int < 0) return [false, '日期不正确'];
  451. $epoch = strtotime("1900-01-01 00:00:00");
  452. $days = $date_int - 1;
  453. $seconds = $days * 86400;
  454. return [true,strtotime(date('Y-m-d 00:00:00', $epoch + $seconds))];
  455. }
  456. function findTopLevelId($data, $id) {
  457. // 遍历数据,查找给定ID的节点
  458. foreach ($data as $item) {
  459. if ($item['id'] == $id) {
  460. // 如果找到了给定ID的节点,并且它的parent_id为null,则它就是最顶层节点
  461. if ($item['parent_id'] === 0) {
  462. return $item['id'];
  463. } else {
  464. // 否则,继续寻找其父节点的最顶层节点
  465. return $this->findTopLevelId($data, $item['parent_id']);
  466. }
  467. }
  468. }
  469. // 如果没有找到给定ID的节点,返回null或抛出异常
  470. return 0;
  471. }
  472. function returnDays($time = [], $is_mirco_time = false){
  473. // 示例时间戳
  474. $timestamp1 = $time[0];
  475. $timestamp2 = $time[1];
  476. // 计算时间差
  477. $difference = abs($timestamp2 - $timestamp1);
  478. // 将时间差转换为天数
  479. $days = floor($difference / (60 * 60 * 24));
  480. if($is_mirco_time) $days = $days / 1000;
  481. return $days;
  482. }
  483. }