Service.php 16 KB

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