common.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  1. <?php
  2. // 应用公共文件
  3. use SingKa\Sms\SkSms;
  4. use GatewayClient\Gateway;
  5. use \utils\Str;
  6. use think\facade\Queue;
  7. /**
  8. * 框架内部默认ajax返回
  9. * @param string $msg 提示信息
  10. * @param string $redirect 重定向类型 current|parent|''
  11. * @param string $alert 父层弹框信息
  12. * @param bool $close 是否关闭当前层
  13. * @param string $url 重定向地址
  14. * @param string $data 附加数据
  15. * @param int $code 错误码
  16. * @param array $extend 扩展数据
  17. * @param int $count 总数
  18. */
  19. function success($msg, $data = '', $count = 0, $page = 1, $code = 0)
  20. {
  21. return ret($code, $msg, $data, $count, $page);
  22. }
  23. /**
  24. * 返回警告json信息
  25. */
  26. function warning($msg, $data = '', $count = 0, $page = 1 , $code = 400)
  27. {
  28. return success($msg ? : lang('system.fail'), $data, $count, $page, $code);
  29. }
  30. /**
  31. * 返回错误json信息
  32. */
  33. function error($msg, $code = 502)
  34. {
  35. return ret($code, lang('system.error').':'.$msg ? : lang('system.fail'));
  36. }
  37. /**
  38. * 提前终止信息
  39. */
  40. function shutdown($msg, $code = 401)
  41. {
  42. exit(json_encode(['code' => $code, 'msg' => $msg?:lang('system.forbidden'), 'data' => []]));
  43. }
  44. /**
  45. * ajax数据返回,规范格式
  46. * @param array $data 返回的数据,默认空数组
  47. * @param string $msg 信息
  48. * @param int $code 错误码,0-未出现错误|其他出现错误
  49. * @param array $extend 扩展数据
  50. */
  51. function ret($code, $msg = "",$data = [],$count=0, $page=0)
  52. {
  53. $ret = ["code" =>$code, "msg" => $msg,'count'=>$count, "data" => $data,'page'=>$page];
  54. return json($ret);
  55. }
  56. // 执行绑定
  57. function doBindUid($user_id,$client_id,$cid='',$isMobile = false){
  58. // 如果当前ID在线,将其他地方登陆挤兑下线
  59. if(Gateway::isUidOnline($user_id)){
  60. wsSendMsg($user_id,'offline',['id'=>$user_id,'client_id'=>$client_id,'isMobile'=>$isMobile]);
  61. }
  62. Gateway::bindUid($client_id, $user_id);
  63. // 查询团队,如果有团队则加入团队
  64. $group=Group::getMyGroup(['gu.user_id'=>$user_id,'gu.status'=>1]);
  65. if($group){
  66. $group=$group->toArray();
  67. $group_ids=arrayToString($group,'group_id',false);
  68. foreach($group_ids as $v){
  69. Gateway::joinGroup($client_id, $v);
  70. }
  71. }
  72. if($cid){
  73. bindCid($user_id,$cid);
  74. }
  75. wsSendMsg(0,'isOnline',['id'=>$user_id,'is_online'=>1]);
  76. }
  77. function ensureUrl($url)
  78. {
  79. if (!filter_var($url, FILTER_VALIDATE_URL)) {
  80. if (empty($url)) return $url;
  81. $newUrl = config('app.url') . $url;
  82. return filter_var($newUrl, FILTER_VALIDATE_URL) ? $newUrl : $url;
  83. }
  84. return $url;
  85. }
  86. function replacePartInUrl($url)
  87. {
  88. if (filter_var($url, FILTER_VALIDATE_URL)) {
  89. $target = config('app.url');
  90. return str_replace($target, '', $url);
  91. }
  92. return $url;
  93. }
  94. function getSelectData($data, $key_name = 'value', $value_name = 'label')
  95. {
  96. $selectData = [];
  97. foreach ($data as $key => $value) {
  98. $selectData[] = [
  99. $value_name => $value,
  100. $key_name => $key,
  101. ];
  102. }
  103. return $selectData;
  104. }
  105. if (!function_exists('linear_to_tree')) {
  106. function linear_to_tree($data, $sub_key_name = 'children', $id_name = 'id', $parent_id_name = 'parent_id', $parent_id = 0)
  107. {
  108. $tree = [];
  109. foreach ($data as $row) {
  110. if ($row[$parent_id_name] == $parent_id) {
  111. $temp = $row;
  112. $child = linear_to_tree($data, $sub_key_name, $id_name, $parent_id_name, $row[$id_name]);
  113. if ($child) {
  114. $temp[$sub_key_name] = $child;
  115. }
  116. $tree[] = $temp;
  117. }
  118. }
  119. return $tree;
  120. }
  121. }
  122. if (!function_exists('is_valid_date')) {
  123. function is_valid_date($date)
  124. {
  125. // 使用正则表达式匹配 yyyy-mm-dd 格式的日期
  126. return preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) === 1;
  127. }
  128. }
  129. if (!function_exists('getUuid')) {
  130. function getUuid()
  131. {
  132. // Generate 16 bytes (128 bits) of random data or use the data passed into the function.
  133. $data = random_bytes(16);
  134. // Set version to 0100
  135. $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
  136. // Set bits 6-7 to 10
  137. $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
  138. // Output the 36 character UUID.
  139. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  140. }
  141. }
  142. if (!function_exists('generate_random_string')) {
  143. function generate_random_string(int $length = 6): string
  144. {
  145. $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
  146. $randomString = '';
  147. for ($i = 0; $i < $length; $i++) {
  148. $randomString .= $characters[rand(0, strlen($characters) - 1)];
  149. }
  150. return $randomString;
  151. }
  152. }
  153. /**
  154. * 辅助函数:十进制转十六进制(支持大数)
  155. */
  156. function bcdechex($dec)
  157. {
  158. $hex = '';
  159. while (bccomp($dec, 0) > 0) {
  160. $last = bcmod($dec, 16);
  161. $hex = dechex($last) . $hex;
  162. $dec = bcdiv($dec, 16, 0);
  163. }
  164. return $hex ?: '0';
  165. }
  166. function removeZero($str)
  167. {
  168. if (empty($str)) {
  169. return 0;
  170. }
  171. if (!is_numeric($str)) {
  172. return $str;
  173. }
  174. $number = number_format($str, 10, '.', '');
  175. // 使用 rtrim 移除末尾的零和小数点
  176. return rtrim(rtrim($number, '0'), '.');
  177. }
  178. /**
  179. * 唯一订单号
  180. * @return string
  181. */
  182. function createOrderNo(): string
  183. {
  184. $str = microtime(true);
  185. $arr = explode('.', $str);
  186. $decimal = $arr[1];
  187. return date('YmdHis') . $decimal;
  188. }
  189. /**
  190. * 获取精度
  191. * @param $number
  192. * @return int
  193. */
  194. function getScale($number): int
  195. {
  196. if (!is_numeric($number)) {
  197. return 1;
  198. }
  199. $sub = strrchr($number, ".");
  200. if (empty($sub)) {
  201. return 1;
  202. }
  203. $scale = strlen(substr($sub, 1));
  204. if ($scale == 0) {
  205. return 1;
  206. }
  207. return $scale;
  208. }
  209. /**
  210. * 将用户名中间部分字符替换为*号
  211. * @param string $username 原始用户名
  212. * @param int $keepLength 前后保留的字符数量(默认1)
  213. * @return string 处理后的用户名
  214. */
  215. function maskUsername($username, $keepLength = 1) {
  216. // 获取用户名长度
  217. $length = mb_strlen($username, 'UTF-8');
  218. // 短于等于2个字符的不处理
  219. if ($length <= $keepLength) {
  220. return $username;
  221. }
  222. if ($length > 8) {
  223. $keepLength = 3;
  224. }
  225. // 计算需要替换的字符数量
  226. $replaceLength = $length - 2 * $keepLength;
  227. // 获取前后保留的字符
  228. $prefix = mb_substr($username, 0, $keepLength, 'UTF-8');
  229. $suffix = mb_substr($username, -$keepLength, $keepLength, 'UTF-8');
  230. // 生成替换的*号
  231. $stars = str_repeat('*', 3);
  232. // 组合结果
  233. return $prefix . $stars . $suffix;
  234. }
  235. /* @param string $string 原文或者密文
  236. * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
  237. * @param string $key 密钥
  238. * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效
  239. * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
  240. *
  241. * @example
  242. *
  243. * $a = authcode('abc', 'ENCODE', 'key');
  244. * $b = authcode($a, 'DECODE', 'key'); // $b(abc)
  245. *
  246. * $a = authcode('abc', 'ENCODE', 'key', 3600);
  247. * $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内,$b(abc),否则 $b 为空
  248. */
  249. function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) {
  250. $ckey_length = 4;
  251. // 随机密钥长度 取值 0-32;
  252. // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。
  253. // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方
  254. // 当此值为 0 时,则不产生随机密钥
  255. $key = md5($key ? $key : 'default_key'); //这里可以填写默认key值
  256. $keya = md5(substr($key, 0, 16));
  257. $keyb = md5(substr($key, 16, 16));
  258. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
  259. $cryptkey = $keya.md5($keya.$keyc);
  260. $key_length = strlen($cryptkey);
  261. $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
  262. $string_length = strlen($string);
  263. $result = '';
  264. $box = range(0, 255);
  265. $rndkey = array();
  266. for($i = 0; $i <= 255; $i++) {
  267. $rndkey[$i] = ord($cryptkey[$i % $key_length]);
  268. }
  269. for($j = $i = 0; $i < 256; $i++) {
  270. $j = ($j + $box[$i] + $rndkey[$i]) % 256;
  271. $tmp = $box[$i];
  272. $box[$i] = $box[$j];
  273. $box[$j] = $tmp;
  274. }
  275. for($a = $j = $i = 0; $i < $string_length; $i++) {
  276. $a = ($a + 1) % 256;
  277. $j = ($j + $box[$a]) % 256;
  278. $tmp = $box[$a];
  279. $box[$a] = $box[$j];
  280. $box[$j] = $tmp;
  281. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  282. }
  283. if($operation == 'DECODE') {
  284. if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
  285. return substr($result, 26);
  286. } else {
  287. return '';
  288. }
  289. } else {
  290. return $keyc.str_replace('=', '', base64_encode($result));
  291. }
  292. }
  293. function ssoTokenEncode($str,$key='lvzhesso',$expire=0){
  294. $ids=encryptIds($str);
  295. return authcode($ids,"ENCODE",$key,$expire);
  296. }
  297. function ssoTokenDecode($str,$key='lvzhesso'){
  298. $ids=authcode($str,"DECODE",$key);
  299. try{
  300. return decryptIds($ids);
  301. }catch(\Exception $e){
  302. return '';
  303. }
  304. }
  305. //id加密
  306. function encryptIds($str)
  307. {
  308. $hash = config('hashids');
  309. return \Hashids\Hashids::instance($hash['length'], $hash['salt'])->encode($str);
  310. }
  311. //id解密
  312. function decryptIds($str)
  313. {
  314. $hash = config('hashids');
  315. return \Hashids\Hashids::instance($hash['length'], $hash['salt'])->decode($str);
  316. }
  317. /**
  318. * 短信发送示例
  319. *
  320. * @mobile 短信发送对象手机号码
  321. * @action 短信发送场景,会自动传入短信模板
  322. * @parme 短信内容数组
  323. */
  324. function sendSms($mobile, $action, $parme)
  325. {
  326. $config = config('sms');
  327. //$this->SmsDefaultDriver是从数据库中读取的短信默认驱动
  328. $driver = $config['driver'] ?: 'aliyun';
  329. $conf=$config[$driver];
  330. $sms = new SkSms($driver, $conf);//传入短信驱动和配置信息
  331. //判断短信发送驱动,非阿里云和七牛云,需将内容数组主键序号化
  332. if ($driver == 'aliyun') {
  333. $result = $sms->$action($mobile, $parme);
  334. } elseif ($driver == 'qiniu') {
  335. $result = $sms->$action([$mobile], $parme);
  336. } elseif ($driver == 'upyun') {
  337. $result = $sms->$action($mobile, implode('|', restoreArray($parme)));
  338. } else {
  339. $result = $sms->$action($mobile, restoreArray($parme));
  340. }
  341. if ($result['code'] == 200) {
  342. $data['code'] = 200;
  343. $data['msg'] = lang('system.sendOK');
  344. } else {
  345. $data['code'] = $result['code'];
  346. $data['msg'] = $result['msg'];
  347. }
  348. return $data;
  349. }
  350. /**
  351. * 数组主键序号化
  352. *
  353. * @arr 需要转换的数组
  354. */
  355. function restoreArray($arr)
  356. {
  357. if (!is_array($arr)){
  358. return $arr;
  359. }
  360. $c = 0;
  361. $new = [];
  362. foreach ($arr as $key => $value) {
  363. $new[$c] = $value;
  364. $c++;
  365. }
  366. return $new;
  367. }
  368. //密码生成规则
  369. function password_hash_tp($password,$salt)
  370. {
  371. return md5($salt.$password.$salt);
  372. }
  373. // 获取主域名
  374. function getMainHost(){
  375. $host=config('app.app_host','');
  376. if($host){
  377. return $host;
  378. }
  379. $port=request()->port();
  380. $domain=request()->domain();
  381. // halt($domain);
  382. // 判断url是否有端口
  383. if(!hasPort($domain)){
  384. if($port!=80 && $port !=443){
  385. return request()->domain().":".$port;
  386. }
  387. }
  388. return $domain;
  389. }
  390. function hasPort($domainOrIp) {
  391. // 查找冒号的位置
  392. $colonPos = strrpos($domainOrIp, ':');
  393. if ($colonPos!== false) {
  394. // 获取冒号后面的字符串
  395. $portPart = substr($domainOrIp, $colonPos + 1);
  396. // 判断冒号后面的字符串是否为纯数字
  397. return ctype_digit($portPart);
  398. }
  399. return false;
  400. }
  401. // 获取url中的主机名
  402. function getHost($url){
  403. if(!preg_match('/http[s]:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$url)){
  404. return '';
  405. }
  406. $search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~i';
  407. $url = trim($url);
  408. preg_match_all($search, $url ,$rr);
  409. return $rr[4][0];
  410. }
  411. //根据姓名画头像
  412. function circleAvatar($str,$s,$uid=0,$is_save=0,$save_path=''){
  413. //定义输出为图像类型
  414. header("content-type:image/png");
  415. $str =$str?:"A";
  416. $uid =$uid?:rand(0,10);
  417. $text=\utils\Str::getLastName($str,2);
  418. $width = $height = $s?:80;
  419. if($width<40 or $width>120){
  420. $width = $height =80;
  421. }
  422. $colors=['#F56C6C','#E6A23C','#fbbd08','#67C23A','#39b54a','#1cbbb4','#409EFF','#6739b6','#e239ff','#e03997'];
  423. $color=hex2rgb($colors[(int)$uid%10]);
  424. $size=$width/4;
  425. $textLeft=($height/2)-$size-$width/10;
  426. if($width<=80){
  427. $text=\utils\Str::getLastName($str,1);
  428. $size=$width/2;
  429. $textLeft=$size/3;
  430. }
  431. //新建图象
  432. $pic=imagecreate($width,$height);
  433. //定义黑白颜色
  434. $background=imagecolorallocate($pic,$color['r'],$color['g'],$color['b']);
  435. $textColor=imagecolorallocate($pic,255,255,255);
  436. imagefill($pic,0,0,$background);//填充背景色
  437. //定义字体
  438. $font=root_path()."/public/static/fonts/PingFangHeavy.ttf";
  439. //写 TTF 文字到图中
  440. imagettftext($pic,$size,0,$textLeft,($height/2)+$size/2,$textColor,$font,$text);
  441. if($is_save){
  442. $path=$save_path."/".$uid.".png";
  443. $dir = pathinfo($path,PATHINFO_DIRNAME);
  444. if(!is_dir($dir)){
  445. $file_create_res = mkdir($dir,0777,true);
  446. if(!$file_create_res){
  447. imagedestroy($pic);
  448. return false;//没有创建成功
  449. }
  450. }
  451. imagepng($pic,$path);
  452. imagedestroy($pic);
  453. return $path;
  454. }else{
  455. //输出图象
  456. imagepng($pic);
  457. //结束图形,释放内存空间
  458. imagedestroy($pic);
  459. return $pic;
  460. }
  461. }
  462. //头像拼接
  463. function avatarUrl($path, $str = "雨",$uid=0,$s=80,$is_group=0)
  464. {
  465. if ($path) {
  466. // 判断头像路径中是否有http
  467. if (strpos($path, 'http') !== false) {
  468. $url = $path;
  469. } else {
  470. $url = getDiskUrl() .'/'. ltrim($path,'/') ;
  471. }
  472. }else {
  473. if($is_group){
  474. $url=getMainHost()."/static/img/group.png";
  475. }else{
  476. $url=getMainHost()."/static/img/avatar.png";;
  477. }
  478. }
  479. return $url;
  480. // $str = Str::strFilter($str);
  481. // preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str, $matches);
  482. // $str=implode('', $matches[0]);
  483. // if($str==''){
  484. // $str="无";
  485. // }
  486. // if ($path) {
  487. // // 判断头像路径中是否有http
  488. // if (strpos($path, 'http') !== false) {
  489. // $url = $path;
  490. // } else {
  491. // $url = getDiskUrl() .'/'. ltrim($path,'/') ;
  492. // }
  493. // }else {
  494. // if($str){
  495. // $url=getMainHost()."/avatar/".$str.'/'.$s.'/'.$uid;
  496. // }else{
  497. // $url='';
  498. // }
  499. // }
  500. // return $url;
  501. }
  502. // 获取文件的地址
  503. function getFileUrl($path){
  504. if (strpos($path, 'http') !== false) {
  505. return $path;
  506. }
  507. return getDiskUrl() .'/'. ltrim($path,'/') ;
  508. }
  509. /**
  510. * 十六进制 转 RGB
  511. */
  512. function hex2rgb($hexColor)
  513. {
  514. $color = str_replace('#', '', $hexColor);
  515. if (strlen($color) > 3) {
  516. $rgb = array(
  517. 'r' => hexdec(substr($color, 0, 2)),
  518. 'g' => hexdec(substr($color, 2, 2)),
  519. 'b' => hexdec(substr($color, 4, 2))
  520. );
  521. } else {
  522. $color = $hexColor;
  523. $r = substr($color, 0, 1) . substr($color, 0, 1);
  524. $g = substr($color, 1, 1) . substr($color, 1, 1);
  525. $b = substr($color, 2, 1) . substr($color, 2, 1);
  526. $rgb = array(
  527. 'r' => hexdec($r),
  528. 'g' => hexdec($g),
  529. 'b' => hexdec($b)
  530. );
  531. }
  532. return $rgb;
  533. }
  534. /**
  535. * 将数组按字母A-Z排序
  536. * @return [type] [description]
  537. */
  538. function chartSort($array, $field,$isGroup=true,$chart='chart')
  539. {
  540. $newArray = [];
  541. foreach ($array as $k => &$v) {
  542. $v[$chart] = getFirstChart($v[$field]);
  543. $newArray[] = $v;
  544. }
  545. $data = [];
  546. if($isGroup){
  547. foreach ($newArray as $k => $v) {
  548. if (array_key_exists($v[$chart], $data)) {
  549. $data[$v[$chart]][] = $v;
  550. } else {
  551. $data[$v[$chart]] = [];
  552. $data[$v[$chart]][] = $v;
  553. }
  554. }
  555. ksort($data);
  556. }else{
  557. return $newArray;
  558. }
  559. return $data;
  560. }
  561. /**
  562. * 返回取汉字的第一个字的首字母
  563. * @param [type] $str [string]
  564. * @return [type] [strind]
  565. */
  566. function getFirstChart($str)
  567. {
  568. $str = str_replace(' ', '', $str);
  569. // 过滤特殊符号
  570. $str = preg_replace('/[^\x{4e00}-\x{9fa5}A-Za-z0-9]/u', '', $str);
  571. if (empty($str) || is_numeric($str)) {
  572. return '#';
  573. }
  574. $char = ord($str[0]);
  575. if ($char >= ord('A') && $char <= ord('z')) {
  576. return strtoupper($str[0]);
  577. }
  578. $s1 = iconv('UTF-8', 'gb2312//IGNORE', $str);
  579. $s2 = iconv('gb2312', 'UTF-8//IGNORE', $s1);
  580. $s = $s2 == $str ? $s1 : $str;
  581. $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;
  582. if ($asc >= -20319 && $asc <= -20284) return 'A';
  583. if ($asc >= -20283 && $asc <= -19776) return 'B';
  584. if ($asc >= -19775 && $asc <= -19219) return 'C';
  585. if ($asc >= -19218 && $asc <= -18711) return 'D';
  586. if ($asc >= -18710 && $asc <= -18527) return 'E';
  587. if ($asc >= -18526 && $asc <= -18240) return 'F';
  588. if ($asc >= -18239 && $asc <= -17923) return 'G';
  589. if ($asc >= -17922 && $asc <= -17418) return 'H';
  590. if ($asc >= -17417 && $asc <= -16475) return 'J';
  591. if ($asc >= -16474 && $asc <= -16213) return 'K';
  592. if ($asc >= -16212 && $asc <= -15641) return 'L';
  593. if ($asc >= -15640 && $asc <= -15166) return 'M';
  594. if ($asc >= -15165 && $asc <= -14923) return 'N';
  595. if ($asc >= -14922 && $asc <= -14915) return 'O';
  596. if ($asc >= -14914 && $asc <= -14631) return 'P';
  597. if ($asc >= -14630 && $asc <= -14150) return 'Q';
  598. if ($asc >= -14149 && $asc <= -14091) return 'R';
  599. if ($asc >= -14090 && $asc <= -13319) return 'S';
  600. if ($asc >= -13318 && $asc <= -12839) return 'T';
  601. if ($asc >= -12838 && $asc <= -12557) return 'W';
  602. if ($asc >= -12556 && $asc <= -11848) return 'X';
  603. if ($asc >= -11847 && $asc <= -11056) return 'Y';
  604. if ($asc >= -11055 && $asc <= -10247) return 'Z';
  605. return "#";
  606. }
  607. // 拼接聊天对象
  608. function chat_identify($from_user,$to_user){
  609. $identify=[$from_user,$to_user];
  610. sort($identify);
  611. return implode('-',$identify);
  612. }
  613. //数组中获取ID字符串
  614. function arrayToString($array,$field,$isStr=true){
  615. $idArr = [];
  616. foreach ($array as $k => $v) {
  617. if(is_array($field)){
  618. foreach($field as $val){
  619. $idArr[]=$v[$val];
  620. }
  621. }else{
  622. $idArr[] = $v[$field];
  623. }
  624. }
  625. if ($isStr) {
  626. $idStr = implode(',', $idArr);
  627. return $idStr;
  628. } else {
  629. return $idArr;
  630. }
  631. }
  632. // 根据文件后缀进行分类
  633. function getFileType($ext,$rst=false){
  634. $ext=strtolower($ext);
  635. $image=['jpg','jpeg','png','bmp','gif','webp','ico'];
  636. $radio=['mp3','wav','wmv','amr'];
  637. $video=['mp4','3gp','avi','m2v','mkv','mov'];
  638. $doc=['ppt','pptx','doc','docx','xls','xlsx','pdf','txt','md'];
  639. $msgType='file';
  640. if(in_array($ext,$doc)){
  641. $fileType=1;
  642. }elseif(in_array($ext,$image)){
  643. $fileType=2;
  644. $msgType='image';
  645. }elseif(in_array($ext,$radio)){
  646. $fileType=3;
  647. $msgType='voice';
  648. }elseif(in_array($ext,$video)){
  649. $fileType=4;
  650. $msgType='video';
  651. }else{
  652. $fileType=9;
  653. }
  654. if($rst){
  655. return $msgType;
  656. }else{
  657. return $fileType;
  658. }
  659. }
  660. /**
  661. * 二位数组排序
  662. * $array 需要排序的数组
  663. * $sort_key 需要排序的字段
  664. * $sort_order 正序还是倒序
  665. * $sort_type 排序的类型:数字,字母
  666. */
  667. function sortArray($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC)
  668. {
  669. if (is_array($arrays)) {
  670. foreach ($arrays as $array) {
  671. if (is_array($array)) {
  672. $key_arrays[] = $array[$sort_key];
  673. } else {
  674. return false;
  675. }
  676. }
  677. } else {
  678. return false;
  679. }
  680. array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
  681. return $arrays;
  682. }
  683. //gateway向web页面推送消息
  684. function wsSendMsg($user, $type, $data, $isGroup=0)
  685. {
  686. $message = json_encode([
  687. 'type' => $type,
  688. 'time' => time(),
  689. 'data' => $data
  690. ]);
  691. try{
  692. Gateway::$registerAddress = config('gateway.registerAddress');
  693. if (!$user) {
  694. Gateway::sendToAll($message);
  695. } else {
  696. if (!$isGroup) {
  697. $send = 'sendToUid';
  698. // 如果是单聊和语音通话需要使用unipush推送
  699. $event=$data['extends']['event'] ?? '';
  700. if(in_array($type,['simple']) || ($event=='calling' && $type=='webrtc')){
  701. unipush($user,$data);
  702. }
  703. } else {
  704. $send = "sendToGroup";
  705. }
  706. Gateway::$send($user, $message);
  707. }
  708. }catch(\Exception $e){
  709. //忽略错误
  710. }
  711. }
  712. // 绑定unipush的cid
  713. function bindCid($uid,$cid){
  714. $url=env('unipush.url','');
  715. if(!$url){
  716. return false;
  717. }
  718. $data=[
  719. 'type'=>'bindCid',
  720. 'alias'=>[[
  721. 'cid'=>$cid,
  722. 'alias'=>$uid
  723. ]]
  724. ];
  725. try{
  726. $data=json_encode($data);
  727. utils\Curl::curl_post($url,$data,true,["Content-Type: application/json"]);
  728. }catch(\Exception $e){
  729. //忽略错误
  730. }
  731. }
  732. // unipush推送
  733. function unipush($toUser,$data){
  734. $url=env('unipush.url','');
  735. if(!$url){
  736. return false;
  737. }
  738. $content='';
  739. if($data['type']=='text'){
  740. $content=Str::subStr($data['content'],0,50);
  741. }else{
  742. $content=getMsgType($data['type'],$data['extends']['type'] ?? 0);
  743. }
  744. // 这个推送不需要发给发送人
  745. $fromUser=$data['fromUser']['id'] ?? '';
  746. if(is_array($toUser)){
  747. $toUser=array_diff($toUser,[$fromUser]);
  748. }
  749. $is_force=env('unipush.is_force',false);
  750. $data=[
  751. 'type'=>'push',
  752. 'toUser'=>$toUser,
  753. 'title'=>$data['fromUser']['displayName'],
  754. 'content'=>$content,
  755. 'force_notification'=>$is_force,
  756. 'payload'=>$data
  757. ];
  758. try{
  759. $data=json_encode($data);
  760. utils\Curl::curl_post($url,$data,true,["Content-Type: application/json"]);
  761. }catch(\Exception $e){
  762. //忽略错误
  763. }
  764. }
  765. // 预览文件
  766. function previewUrl($url){
  767. $previewUrl=env('preview.own','');
  768. // $preview='';
  769. // $suffix=explode('.',$url);
  770. // $ext=$suffix[count($suffix)-1];
  771. // $media=['jpg','jpeg','png','bmp','gif','pdf','mp3','wav','wmv','amr','mp4','3gp','avi','m2v','mkv','mov','webp'];
  772. // $doc=['ppt','pptx','doc','docx','xls','xlsx','pdf'];
  773. // if(in_array($ext,$media) && $previewConf['own']){
  774. // $preview=$previewConf['own']."view.html?src=".$url;
  775. // }elseif(in_array($ext,$doc) && $previewConf['yzdcs']){
  776. // $preview=$previewConf['yzdcs'].'?k='.$previewConf['keycode'].'&url='.$url;
  777. // }else{
  778. // }
  779. if($previewUrl){
  780. $preview=$previewUrl.$url;
  781. }else{
  782. $preview=getMainHost()."/view.html?src=".$url;
  783. }
  784. return $preview;
  785. }
  786. /**
  787. * 解析sql语句
  788. * @param string $content sql内容
  789. * @param int $limit 如果为1,则只返回一条sql语句,默认返回所有
  790. * @param array $prefix 替换表前缀
  791. * @return array|string 除去注释之后的sql语句数组或一条语句
  792. */
  793. function parse_sql($sql = '', $limit = 0, $prefix = []) {
  794. // 被替换的前缀
  795. $from = '';
  796. // 要替换的前缀
  797. $to = '';
  798. // 替换表前缀
  799. if (!empty($prefix)) {
  800. $to = current($prefix);
  801. $from = current(array_flip($prefix));
  802. }
  803. if ($sql != '') {
  804. // 纯sql内容
  805. $pure_sql = [];
  806. // 多行注释标记
  807. $comment = false;
  808. // 按行分割,兼容多个平台
  809. $sql = str_replace(["\r\n", "\r"], "\n", $sql);
  810. $sql = explode("\n", trim($sql));
  811. // 循环处理每一行
  812. foreach ($sql as $key => $line) {
  813. // 跳过空行
  814. if ($line == '') {
  815. continue;
  816. }
  817. // 跳过以#或者--开头的单行注释
  818. if (preg_match("/^(#|--)/", $line)) {
  819. continue;
  820. }
  821. // 跳过以/**/包裹起来的单行注释
  822. if (preg_match("/^\/\*(.*?)\*\//", $line)) {
  823. continue;
  824. }
  825. // 多行注释开始
  826. if (substr($line, 0, 2) == '/*') {
  827. $comment = true;
  828. continue;
  829. }
  830. // 多行注释结束
  831. if (substr($line, -2) == '*/') {
  832. $comment = false;
  833. continue;
  834. }
  835. // 多行注释没有结束,继续跳过
  836. if ($comment) {
  837. continue;
  838. }
  839. // 替换表前缀
  840. if ($from != '') {
  841. $line = str_replace('`'.$from, '`'.$to, $line);
  842. }
  843. if ($line == 'BEGIN;' || $line =='COMMIT;') {
  844. continue;
  845. }
  846. // sql语句
  847. array_push($pure_sql, $line);
  848. }
  849. // 只返回一条语句
  850. if ($limit == 1) {
  851. return implode("",$pure_sql);
  852. }
  853. // 以数组形式返回sql语句
  854. $pure_sql = implode("\n",$pure_sql);
  855. $pure_sql = explode(";\n", $pure_sql);
  856. return $pure_sql;
  857. } else {
  858. return $limit == 1 ? '' : [];
  859. }
  860. }
  861. /**
  862. * 更新或添加环境变量
  863. *
  864. * @param string $key 环境变量的键
  865. * @param string $value 环境变量的值
  866. * @return bool 成功返回 true,失败返回 false
  867. */
  868. function updateEnv($key, $value)
  869. {
  870. $envFile = app()->getRootPath() . '.env';
  871. if (!file_exists($envFile) || !is_writable($envFile)){
  872. return false;
  873. }
  874. // 读取 .env 文件内容
  875. $envContent = file_get_contents($envFile);
  876. $keyPattern = preg_quote($key, '/');
  877. $pattern = "/^{$keyPattern}=(.*)\$/m";
  878. if (preg_match($pattern, $envContent)) {
  879. // 如果找到了键值对,替换其值
  880. $replacement = "{$key}={$value}";
  881. $newEnvContent = preg_replace($pattern, $replacement, $envContent);
  882. } else {
  883. // 如果没有找到键值对,添加新的键值对
  884. $newEnvContent = $envContent . PHP_EOL . "{$key}={$value}";
  885. }
  886. // 保存更新后的 .env 文件内容
  887. return file_put_contents($envFile, $newEnvContent) !== false;
  888. }
  889. // 获取文件的域名
  890. function getDiskUrl(){
  891. $disk=env('filesystem.driver','local');
  892. $url=getMainHost();
  893. if($disk=='aliyun'){
  894. $url=env('filesystem.aliyun_url','');
  895. }elseif($disk=='qiniu'){
  896. $url=env('filesystem.qiniu_url','');
  897. }elseif($disk=='qcloud'){
  898. $url=env('filesystem.qcloud_cdn','');
  899. }
  900. $url=rtrim($url,'/');
  901. return $url;
  902. }
  903. /**
  904. * 合成图片
  905. * @param array $pic_list [图片列表数组]
  906. * @param boolean $is_save [是否保存,true保存,false输出到浏览器]
  907. * @param string $save_path [保存路径]
  908. * @return boolean|string
  909. */
  910. function getGroupAvatar($pic_list=array(),$is_save=false,$save_path=''){
  911. //验证参数
  912. if(empty($pic_list) || empty($save_path)){
  913. return false;
  914. }
  915. if($is_save){
  916. //如果需要保存,需要传保存地址
  917. if(empty($save_path)){
  918. return false;
  919. }
  920. }
  921. // 只操作前9个图片
  922. $pic_list = array_slice($pic_list, 0, 9);
  923. //设置背景图片宽高
  924. $bg_w = 150; // 背景图片宽度
  925. $bg_h = 150; // 背景图片高度
  926. //新建一个真彩色图像作为背景
  927. $background = imagecreatetruecolor($bg_w,$bg_h);
  928. //为真彩色画布创建白灰色背景,再设置为透明
  929. $color = imagecolorallocate($background, 202, 201, 201);
  930. imagefill($background, 0, 0, $color);
  931. imageColorTransparent($background, $color);
  932. //根据图片个数设置图片位置
  933. $pic_count = count($pic_list);
  934. $lineArr = array();//需要换行的位置
  935. $space_x = 3;
  936. $space_y = 3;
  937. $line_x = 0;
  938. switch($pic_count) {
  939. case 1: // 正中间
  940. $start_x = intval($bg_w/4); // 开始位置X
  941. $start_y = intval($bg_h/4); // 开始位置Y
  942. $pic_w = intval($bg_w/2); // 宽度
  943. $pic_h = intval($bg_h/2); // 高度
  944. break;
  945. case 2: // 中间位置并排
  946. $start_x = 2;
  947. $start_y = intval($bg_h/4) + 3;
  948. $pic_w = intval($bg_w/2) - 5;
  949. $pic_h = intval($bg_h/2) - 5;
  950. $space_x = 5;
  951. break;
  952. case 3:
  953. $start_x = 40; // 开始位置X
  954. $start_y = 5; // 开始位置Y
  955. $pic_w = intval($bg_w/2) - 5; // 宽度
  956. $pic_h = intval($bg_h/2) - 5; // 高度
  957. $lineArr = array(2);
  958. $line_x = 4;
  959. break;
  960. case 4:
  961. $start_x = 4; // 开始位置X
  962. $start_y = 5; // 开始位置Y
  963. $pic_w = intval($bg_w/2) - 5; // 宽度
  964. $pic_h = intval($bg_h/2) - 5; // 高度
  965. $lineArr = array(3);
  966. $line_x = 4;
  967. break;
  968. case 5:
  969. $start_x = 30; // 开始位置X
  970. $start_y = 30; // 开始位置Y
  971. $pic_w = intval($bg_w/3) - 5; // 宽度
  972. $pic_h = intval($bg_h/3) - 5; // 高度
  973. $lineArr = array(3);
  974. $line_x = 5;
  975. break;
  976. case 6:
  977. $start_x = 5; // 开始位置X
  978. $start_y = 30; // 开始位置Y
  979. $pic_w = intval($bg_w/3) - 5; // 宽度
  980. $pic_h = intval($bg_h/3) - 5; // 高度
  981. $lineArr = array(4);
  982. $line_x = 5;
  983. break;
  984. case 7:
  985. $start_x = 53; // 开始位置X
  986. $start_y = 5; // 开始位置Y
  987. $pic_w = intval($bg_w/3) - 5; // 宽度
  988. $pic_h = intval($bg_h/3) - 5; // 高度
  989. $lineArr = array(2,5);
  990. $line_x = 5;
  991. break;
  992. case 8:
  993. $start_x = 30; // 开始位置X
  994. $start_y = 5; // 开始位置Y
  995. $pic_w = intval($bg_w/3) - 5; // 宽度
  996. $pic_h = intval($bg_h/3) - 5; // 高度
  997. $lineArr = array(3,6);
  998. $line_x = 5;
  999. break;
  1000. case 9:
  1001. $start_x = 5; // 开始位置X
  1002. $start_y = 5; // 开始位置Y
  1003. $pic_w = intval($bg_w/3) - 5; // 宽度
  1004. $pic_h = intval($bg_h/3) - 5; // 高度
  1005. $lineArr = array(4,7);
  1006. $line_x = 5;
  1007. break;
  1008. }
  1009. foreach( $pic_list as $k=>$pic_path ) {
  1010. $kk = $k + 1;
  1011. if ( in_array($kk, $lineArr) ) {
  1012. $start_x = $line_x;
  1013. $start_y = $start_y + $pic_h + $space_y;
  1014. }
  1015. //获取图片文件扩展类型和mime类型,判断是否是正常图片文件
  1016. //非正常图片文件,相应位置空着,跳过处理
  1017. $image_mime_info = @getimagesize($pic_path);
  1018. if($image_mime_info && !empty($image_mime_info['mime'])){
  1019. $mime_arr = explode('/',$image_mime_info['mime']);
  1020. if(is_array($mime_arr) && $mime_arr[0] == 'image' && !empty($mime_arr[1])){
  1021. switch($mime_arr[1]) {
  1022. case 'jpg':
  1023. case 'jpeg':
  1024. $imagecreatefromjpeg = 'imagecreatefromjpeg';
  1025. break;
  1026. case 'png':
  1027. $imagecreatefromjpeg = 'imagecreatefrompng';
  1028. break;
  1029. case 'gif':
  1030. default:
  1031. $imagecreatefromjpeg = 'imagecreatefromstring';
  1032. $pic_path = file_get_contents($pic_path);
  1033. break;
  1034. }
  1035. //创建一个新图像
  1036. $resource = $imagecreatefromjpeg($pic_path);
  1037. //将图像中的一块矩形区域拷贝到另一个背景图像中
  1038. // $start_x,$start_y 放置在背景中的起始位置
  1039. // 0,0 裁剪的源头像的起点位置
  1040. // $pic_w,$pic_h copy后的高度和宽度
  1041. imagecopyresized($background,$resource,$start_x,$start_y,0,0,$pic_w,$pic_h,imagesx($resource),imagesy($resource));
  1042. }
  1043. }
  1044. // 最后两个参数为原始图片宽度和高度,倒数两个参数为copy时的图片宽度和高度
  1045. $start_x = $start_x + $pic_w + $space_x;
  1046. }
  1047. if($is_save){
  1048. $dir = pathinfo($save_path,PATHINFO_DIRNAME);
  1049. if(!is_dir($dir)){
  1050. $file_create_res = mkdir($dir,0777,true);
  1051. if(!$file_create_res){
  1052. return false;//没有创建成功
  1053. }
  1054. }
  1055. $res = imagejpeg($background,$save_path);
  1056. imagedestroy($background);
  1057. if($res){
  1058. return true;
  1059. }else{
  1060. return false;
  1061. }
  1062. }else{
  1063. //直接输出
  1064. header("Content-type: image/jpg");
  1065. imagejpeg($background);
  1066. imagedestroy($background);
  1067. }
  1068. }
  1069. /**
  1070. * 获取一个唯一token
  1071. * @return string
  1072. */
  1073. function getOnlyToken()
  1074. {
  1075. return md5(uniqid(md5(microtime(true)), true));
  1076. }
  1077. // 设置排序规则
  1078. function orderBy($field, $type, $prefix = '', $default = 'update_time')
  1079. {
  1080. $type=is_numeric($type)?($type==1?'asc':'desc'):$type;
  1081. if ($field) {
  1082. $order = $prefix . $field . ' ' . $type;
  1083. } else {
  1084. $order = $prefix . $default . ' desc';
  1085. }
  1086. return $order;
  1087. }
  1088. // 获取文件后缀图片
  1089. function getExtUrl($path){
  1090. $ext=explode('.',$path);
  1091. $ext=end($ext);
  1092. // 如果是图片文件,就直接返回图片地址
  1093. $image=['jpg','jpeg','png','bmp','gif','webp'];
  1094. if(in_array($ext,$image)){
  1095. return getFileUrl($path);
  1096. }
  1097. $extUrl='/static/img/ext/'.strtoupper($ext).'.png';
  1098. // 判断文件是否存在
  1099. if(!file_exists(public_path().$extUrl)){
  1100. $extUrl='/static/img/ext/folder.png';
  1101. }
  1102. return getMainHost().$extUrl;
  1103. }
  1104. // 字符串内容加解密函数
  1105. function str_encipher($str,$encode=true,$key=''){
  1106. if($key==''){
  1107. $key=config('app.aes_chat_key');
  1108. }
  1109. if($key=='' || $str==''){
  1110. return $str;
  1111. }
  1112. if($encode){
  1113. $s=\utils\Aes::encrypt($str,$key);
  1114. }else{
  1115. $s=\utils\Aes::decrypt($str,$key) ?:'';
  1116. }
  1117. return $s;
  1118. }
  1119. // 推送时获取消息的类型
  1120. function getMsgType($type,$callVideo=false){
  1121. $msgName=lang('messageType.other');
  1122. switch($type){
  1123. case 'image':
  1124. $msgName=lang('messageType.image');
  1125. break;
  1126. case 'voice':
  1127. $msgName=lang('messageType.voice');
  1128. break;
  1129. case 'emoji':
  1130. $msgName=lang('messageType.emoji');
  1131. break;
  1132. case 'video':
  1133. $msgName=lang('messageType.video');
  1134. break;
  1135. case 'file':
  1136. $msgName=lang('messageType.file');
  1137. break;
  1138. case 'webrtc':
  1139. if($callVideo){
  1140. $msgName=lang('messageType.webrtcAudio');
  1141. }else{
  1142. $msgName=lang('messageType.webrtcVideo');
  1143. }
  1144. break;
  1145. }
  1146. return $msgName;
  1147. }
  1148. // 获取app的下载链接
  1149. function getAppDowmUrl($platform='android'){
  1150. $config=config('version.'.$platform);
  1151. $name=config('version.app_name');
  1152. if($platform=='windows'){
  1153. $packageName=$name."_Setup_".$config['version'].".exe";
  1154. $path="/downloadApp/windows";
  1155. }elseif($platform=='mac'){
  1156. $packageName=$name."_Setup_".$config['version'].".dmg";
  1157. $path="/downloadApp/mac";
  1158. }else{
  1159. $packageName=$name."_Setup_".$config['version'].".apk";
  1160. $path="/downloadApp/android";
  1161. }
  1162. if(is_file(PACKAGE_PATH . $packageName)){
  1163. return getMainHost().$path;
  1164. }else{
  1165. return '';
  1166. }
  1167. }
  1168. // php匹配文本中的所有url
  1169. function getAllUrl($text){
  1170. // 使用正则表达式匹配带有或不带有协议头的URL
  1171. $pattern = '/\b(?:https?:\/\/)?[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/i';
  1172. // 使用preg_replace()函数将URL转换为<a>标签
  1173. $replaced_text = preg_replace_callback($pattern, function($matches) {
  1174. $url = $matches[0];
  1175. if(utils\Regular::is_url($url)){
  1176. $newUrl=$url;
  1177. if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
  1178. $newUrl = "http://" . $url;
  1179. }
  1180. return '<a href="' . $newUrl . '">' . $url . '</a>';
  1181. }else{
  1182. return $url;
  1183. }
  1184. }, $text);
  1185. return $replaced_text;
  1186. }
  1187. // 将链接转成可点击的标签
  1188. function preg_link($text){
  1189. // 判断文本中是否有img标签
  1190. if(preg_match('/<img[^>]+>/i', $text)){
  1191. return $text;
  1192. }
  1193. // 匹配更广泛的 URL 的正则表达式
  1194. $pattern ='/\b(?:https?:\/\/|ftp:\/\/)?([a-z0-9-+&@#\/%?=~_|!:,.;]*\.[a-z]{2,}(?:\/[a-z0-9-+&@#\/%?=~_|!:,.;]*)*)\b/i';
  1195. // 使用preg_replace()函数将URL转换为<a>标签
  1196. $replaced_text = preg_replace_callback($pattern, function($matches) {
  1197. $url = $matches[0];
  1198. $isUrl=preg_match('/\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]|[a-z0-9-+&@#\/%?=~_|!:,.;]*\.[a-z]{2,}\b/i',$url) ? true : false;
  1199. if($isUrl){
  1200. $newUrl=$url;
  1201. if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
  1202. $newUrl = "https://" . $url;
  1203. }
  1204. return '<a href="' . $newUrl . '" target="_blank">' . $url . '</a>';
  1205. }else{
  1206. return $url;
  1207. }
  1208. }, $text);
  1209. return $replaced_text;
  1210. }
  1211. //消息队列think-queue
  1212. function queuePush($data, $delay = 0, $job = "Work", $queue = "im")
  1213. {
  1214. $data['job'] = $data['job'] ?? $job;
  1215. $data['queue'] = $data['queue'] ?? $queue;
  1216. $data['data'] = $data['data'] ?? [];
  1217. try {
  1218. if ($data) {
  1219. if ($delay == 0) {
  1220. Queue::push($job, $data, $queue);
  1221. } else {
  1222. Queue::later($delay, $job, $data, $queue);
  1223. }
  1224. }
  1225. return true;
  1226. } catch (Exception $e) {
  1227. return false;
  1228. }
  1229. }