common.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  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. if ($type == 'isOnline' && $data['is_online'] == 0) {
  709. $admin_id = \app\admin\model\User::getAdminId($data['id']);
  710. if ($admin_id) {
  711. \app\admin\model\Admin::setOnline($admin_id, 0);
  712. }
  713. }
  714. }catch(\Exception $e){
  715. //忽略错误
  716. }
  717. }
  718. // 绑定unipush的cid
  719. function bindCid($uid,$cid){
  720. $url=env('unipush.url','');
  721. if(!$url){
  722. return false;
  723. }
  724. $data=[
  725. 'type'=>'bindCid',
  726. 'alias'=>[[
  727. 'cid'=>$cid,
  728. 'alias'=>$uid
  729. ]]
  730. ];
  731. try{
  732. $data=json_encode($data);
  733. utils\Curl::curl_post($url,$data,true,["Content-Type: application/json"]);
  734. }catch(\Exception $e){
  735. //忽略错误
  736. }
  737. }
  738. // unipush推送
  739. function unipush($toUser,$data){
  740. $url=env('unipush.url','');
  741. if(!$url){
  742. return false;
  743. }
  744. $content='';
  745. if($data['type']=='text'){
  746. $content=Str::subStr($data['content'],0,50);
  747. }else{
  748. $content=getMsgType($data['type'],$data['extends']['type'] ?? 0);
  749. }
  750. // 这个推送不需要发给发送人
  751. $fromUser=$data['fromUser']['id'] ?? '';
  752. if(is_array($toUser)){
  753. $toUser=array_diff($toUser,[$fromUser]);
  754. }
  755. $is_force=env('unipush.is_force',false);
  756. $data=[
  757. 'type'=>'push',
  758. 'toUser'=>$toUser,
  759. 'title'=>$data['fromUser']['displayName'],
  760. 'content'=>$content,
  761. 'force_notification'=>$is_force,
  762. 'payload'=>$data
  763. ];
  764. try{
  765. $data=json_encode($data);
  766. utils\Curl::curl_post($url,$data,true,["Content-Type: application/json"]);
  767. }catch(\Exception $e){
  768. //忽略错误
  769. }
  770. }
  771. // 预览文件
  772. function previewUrl($url){
  773. $previewUrl=env('preview.own','');
  774. // $preview='';
  775. // $suffix=explode('.',$url);
  776. // $ext=$suffix[count($suffix)-1];
  777. // $media=['jpg','jpeg','png','bmp','gif','pdf','mp3','wav','wmv','amr','mp4','3gp','avi','m2v','mkv','mov','webp'];
  778. // $doc=['ppt','pptx','doc','docx','xls','xlsx','pdf'];
  779. // if(in_array($ext,$media) && $previewConf['own']){
  780. // $preview=$previewConf['own']."view.html?src=".$url;
  781. // }elseif(in_array($ext,$doc) && $previewConf['yzdcs']){
  782. // $preview=$previewConf['yzdcs'].'?k='.$previewConf['keycode'].'&url='.$url;
  783. // }else{
  784. // }
  785. if($previewUrl){
  786. $preview=$previewUrl.$url;
  787. }else{
  788. $preview=getMainHost()."/view.html?src=".$url;
  789. }
  790. return $preview;
  791. }
  792. /**
  793. * 解析sql语句
  794. * @param string $content sql内容
  795. * @param int $limit 如果为1,则只返回一条sql语句,默认返回所有
  796. * @param array $prefix 替换表前缀
  797. * @return array|string 除去注释之后的sql语句数组或一条语句
  798. */
  799. function parse_sql($sql = '', $limit = 0, $prefix = []) {
  800. // 被替换的前缀
  801. $from = '';
  802. // 要替换的前缀
  803. $to = '';
  804. // 替换表前缀
  805. if (!empty($prefix)) {
  806. $to = current($prefix);
  807. $from = current(array_flip($prefix));
  808. }
  809. if ($sql != '') {
  810. // 纯sql内容
  811. $pure_sql = [];
  812. // 多行注释标记
  813. $comment = false;
  814. // 按行分割,兼容多个平台
  815. $sql = str_replace(["\r\n", "\r"], "\n", $sql);
  816. $sql = explode("\n", trim($sql));
  817. // 循环处理每一行
  818. foreach ($sql as $key => $line) {
  819. // 跳过空行
  820. if ($line == '') {
  821. continue;
  822. }
  823. // 跳过以#或者--开头的单行注释
  824. if (preg_match("/^(#|--)/", $line)) {
  825. continue;
  826. }
  827. // 跳过以/**/包裹起来的单行注释
  828. if (preg_match("/^\/\*(.*?)\*\//", $line)) {
  829. continue;
  830. }
  831. // 多行注释开始
  832. if (substr($line, 0, 2) == '/*') {
  833. $comment = true;
  834. continue;
  835. }
  836. // 多行注释结束
  837. if (substr($line, -2) == '*/') {
  838. $comment = false;
  839. continue;
  840. }
  841. // 多行注释没有结束,继续跳过
  842. if ($comment) {
  843. continue;
  844. }
  845. // 替换表前缀
  846. if ($from != '') {
  847. $line = str_replace('`'.$from, '`'.$to, $line);
  848. }
  849. if ($line == 'BEGIN;' || $line =='COMMIT;') {
  850. continue;
  851. }
  852. // sql语句
  853. array_push($pure_sql, $line);
  854. }
  855. // 只返回一条语句
  856. if ($limit == 1) {
  857. return implode("",$pure_sql);
  858. }
  859. // 以数组形式返回sql语句
  860. $pure_sql = implode("\n",$pure_sql);
  861. $pure_sql = explode(";\n", $pure_sql);
  862. return $pure_sql;
  863. } else {
  864. return $limit == 1 ? '' : [];
  865. }
  866. }
  867. /**
  868. * 更新或添加环境变量
  869. *
  870. * @param string $key 环境变量的键
  871. * @param string $value 环境变量的值
  872. * @return bool 成功返回 true,失败返回 false
  873. */
  874. function updateEnv($key, $value)
  875. {
  876. $envFile = app()->getRootPath() . '.env';
  877. if (!file_exists($envFile) || !is_writable($envFile)){
  878. return false;
  879. }
  880. // 读取 .env 文件内容
  881. $envContent = file_get_contents($envFile);
  882. $keyPattern = preg_quote($key, '/');
  883. $pattern = "/^{$keyPattern}=(.*)\$/m";
  884. if (preg_match($pattern, $envContent)) {
  885. // 如果找到了键值对,替换其值
  886. $replacement = "{$key}={$value}";
  887. $newEnvContent = preg_replace($pattern, $replacement, $envContent);
  888. } else {
  889. // 如果没有找到键值对,添加新的键值对
  890. $newEnvContent = $envContent . PHP_EOL . "{$key}={$value}";
  891. }
  892. // 保存更新后的 .env 文件内容
  893. return file_put_contents($envFile, $newEnvContent) !== false;
  894. }
  895. // 获取文件的域名
  896. function getDiskUrl(){
  897. $disk=env('filesystem.driver','local');
  898. $url=getMainHost();
  899. if($disk=='aliyun'){
  900. $url=env('filesystem.aliyun_url','');
  901. }elseif($disk=='qiniu'){
  902. $url=env('filesystem.qiniu_url','');
  903. }elseif($disk=='qcloud'){
  904. $url=env('filesystem.qcloud_cdn','');
  905. }
  906. $url=rtrim($url,'/');
  907. return $url;
  908. }
  909. /**
  910. * 合成图片
  911. * @param array $pic_list [图片列表数组]
  912. * @param boolean $is_save [是否保存,true保存,false输出到浏览器]
  913. * @param string $save_path [保存路径]
  914. * @return boolean|string
  915. */
  916. function getGroupAvatar($pic_list=array(),$is_save=false,$save_path=''){
  917. //验证参数
  918. if(empty($pic_list) || empty($save_path)){
  919. return false;
  920. }
  921. if($is_save){
  922. //如果需要保存,需要传保存地址
  923. if(empty($save_path)){
  924. return false;
  925. }
  926. }
  927. // 只操作前9个图片
  928. $pic_list = array_slice($pic_list, 0, 9);
  929. //设置背景图片宽高
  930. $bg_w = 150; // 背景图片宽度
  931. $bg_h = 150; // 背景图片高度
  932. //新建一个真彩色图像作为背景
  933. $background = imagecreatetruecolor($bg_w,$bg_h);
  934. //为真彩色画布创建白灰色背景,再设置为透明
  935. $color = imagecolorallocate($background, 202, 201, 201);
  936. imagefill($background, 0, 0, $color);
  937. imageColorTransparent($background, $color);
  938. //根据图片个数设置图片位置
  939. $pic_count = count($pic_list);
  940. $lineArr = array();//需要换行的位置
  941. $space_x = 3;
  942. $space_y = 3;
  943. $line_x = 0;
  944. switch($pic_count) {
  945. case 1: // 正中间
  946. $start_x = intval($bg_w/4); // 开始位置X
  947. $start_y = intval($bg_h/4); // 开始位置Y
  948. $pic_w = intval($bg_w/2); // 宽度
  949. $pic_h = intval($bg_h/2); // 高度
  950. break;
  951. case 2: // 中间位置并排
  952. $start_x = 2;
  953. $start_y = intval($bg_h/4) + 3;
  954. $pic_w = intval($bg_w/2) - 5;
  955. $pic_h = intval($bg_h/2) - 5;
  956. $space_x = 5;
  957. break;
  958. case 3:
  959. $start_x = 40; // 开始位置X
  960. $start_y = 5; // 开始位置Y
  961. $pic_w = intval($bg_w/2) - 5; // 宽度
  962. $pic_h = intval($bg_h/2) - 5; // 高度
  963. $lineArr = array(2);
  964. $line_x = 4;
  965. break;
  966. case 4:
  967. $start_x = 4; // 开始位置X
  968. $start_y = 5; // 开始位置Y
  969. $pic_w = intval($bg_w/2) - 5; // 宽度
  970. $pic_h = intval($bg_h/2) - 5; // 高度
  971. $lineArr = array(3);
  972. $line_x = 4;
  973. break;
  974. case 5:
  975. $start_x = 30; // 开始位置X
  976. $start_y = 30; // 开始位置Y
  977. $pic_w = intval($bg_w/3) - 5; // 宽度
  978. $pic_h = intval($bg_h/3) - 5; // 高度
  979. $lineArr = array(3);
  980. $line_x = 5;
  981. break;
  982. case 6:
  983. $start_x = 5; // 开始位置X
  984. $start_y = 30; // 开始位置Y
  985. $pic_w = intval($bg_w/3) - 5; // 宽度
  986. $pic_h = intval($bg_h/3) - 5; // 高度
  987. $lineArr = array(4);
  988. $line_x = 5;
  989. break;
  990. case 7:
  991. $start_x = 53; // 开始位置X
  992. $start_y = 5; // 开始位置Y
  993. $pic_w = intval($bg_w/3) - 5; // 宽度
  994. $pic_h = intval($bg_h/3) - 5; // 高度
  995. $lineArr = array(2,5);
  996. $line_x = 5;
  997. break;
  998. case 8:
  999. $start_x = 30; // 开始位置X
  1000. $start_y = 5; // 开始位置Y
  1001. $pic_w = intval($bg_w/3) - 5; // 宽度
  1002. $pic_h = intval($bg_h/3) - 5; // 高度
  1003. $lineArr = array(3,6);
  1004. $line_x = 5;
  1005. break;
  1006. case 9:
  1007. $start_x = 5; // 开始位置X
  1008. $start_y = 5; // 开始位置Y
  1009. $pic_w = intval($bg_w/3) - 5; // 宽度
  1010. $pic_h = intval($bg_h/3) - 5; // 高度
  1011. $lineArr = array(4,7);
  1012. $line_x = 5;
  1013. break;
  1014. }
  1015. foreach( $pic_list as $k=>$pic_path ) {
  1016. $kk = $k + 1;
  1017. if ( in_array($kk, $lineArr) ) {
  1018. $start_x = $line_x;
  1019. $start_y = $start_y + $pic_h + $space_y;
  1020. }
  1021. //获取图片文件扩展类型和mime类型,判断是否是正常图片文件
  1022. //非正常图片文件,相应位置空着,跳过处理
  1023. $image_mime_info = @getimagesize($pic_path);
  1024. if($image_mime_info && !empty($image_mime_info['mime'])){
  1025. $mime_arr = explode('/',$image_mime_info['mime']);
  1026. if(is_array($mime_arr) && $mime_arr[0] == 'image' && !empty($mime_arr[1])){
  1027. switch($mime_arr[1]) {
  1028. case 'jpg':
  1029. case 'jpeg':
  1030. $imagecreatefromjpeg = 'imagecreatefromjpeg';
  1031. break;
  1032. case 'png':
  1033. $imagecreatefromjpeg = 'imagecreatefrompng';
  1034. break;
  1035. case 'gif':
  1036. default:
  1037. $imagecreatefromjpeg = 'imagecreatefromstring';
  1038. $pic_path = file_get_contents($pic_path);
  1039. break;
  1040. }
  1041. //创建一个新图像
  1042. $resource = $imagecreatefromjpeg($pic_path);
  1043. //将图像中的一块矩形区域拷贝到另一个背景图像中
  1044. // $start_x,$start_y 放置在背景中的起始位置
  1045. // 0,0 裁剪的源头像的起点位置
  1046. // $pic_w,$pic_h copy后的高度和宽度
  1047. imagecopyresized($background,$resource,$start_x,$start_y,0,0,$pic_w,$pic_h,imagesx($resource),imagesy($resource));
  1048. }
  1049. }
  1050. // 最后两个参数为原始图片宽度和高度,倒数两个参数为copy时的图片宽度和高度
  1051. $start_x = $start_x + $pic_w + $space_x;
  1052. }
  1053. if($is_save){
  1054. $dir = pathinfo($save_path,PATHINFO_DIRNAME);
  1055. if(!is_dir($dir)){
  1056. $file_create_res = mkdir($dir,0777,true);
  1057. if(!$file_create_res){
  1058. return false;//没有创建成功
  1059. }
  1060. }
  1061. $res = imagejpeg($background,$save_path);
  1062. imagedestroy($background);
  1063. if($res){
  1064. return true;
  1065. }else{
  1066. return false;
  1067. }
  1068. }else{
  1069. //直接输出
  1070. header("Content-type: image/jpg");
  1071. imagejpeg($background);
  1072. imagedestroy($background);
  1073. }
  1074. }
  1075. /**
  1076. * 获取一个唯一token
  1077. * @return string
  1078. */
  1079. function getOnlyToken()
  1080. {
  1081. return md5(uniqid(md5(microtime(true)), true));
  1082. }
  1083. // 设置排序规则
  1084. function orderBy($field, $type, $prefix = '', $default = 'update_time')
  1085. {
  1086. $type=is_numeric($type)?($type==1?'asc':'desc'):$type;
  1087. if ($field) {
  1088. $order = $prefix . $field . ' ' . $type;
  1089. } else {
  1090. $order = $prefix . $default . ' desc';
  1091. }
  1092. return $order;
  1093. }
  1094. // 获取文件后缀图片
  1095. function getExtUrl($path){
  1096. $ext=explode('.',$path);
  1097. $ext=end($ext);
  1098. // 如果是图片文件,就直接返回图片地址
  1099. $image=['jpg','jpeg','png','bmp','gif','webp'];
  1100. if(in_array($ext,$image)){
  1101. return getFileUrl($path);
  1102. }
  1103. $extUrl='/static/img/ext/'.strtoupper($ext).'.png';
  1104. // 判断文件是否存在
  1105. if(!file_exists(public_path().$extUrl)){
  1106. $extUrl='/static/img/ext/folder.png';
  1107. }
  1108. return getMainHost().$extUrl;
  1109. }
  1110. // 字符串内容加解密函数
  1111. function str_encipher($str,$encode=true,$key=''){
  1112. if($key==''){
  1113. $key=config('app.aes_chat_key');
  1114. }
  1115. if($key=='' || $str==''){
  1116. return $str;
  1117. }
  1118. if($encode){
  1119. $s=\utils\Aes::encrypt($str,$key);
  1120. }else{
  1121. $s=\utils\Aes::decrypt($str,$key) ?:'';
  1122. }
  1123. return $s;
  1124. }
  1125. // 推送时获取消息的类型
  1126. function getMsgType($type,$callVideo=false){
  1127. $msgName=lang('messageType.other');
  1128. switch($type){
  1129. case 'image':
  1130. $msgName=lang('messageType.image');
  1131. break;
  1132. case 'voice':
  1133. $msgName=lang('messageType.voice');
  1134. break;
  1135. case 'emoji':
  1136. $msgName=lang('messageType.emoji');
  1137. break;
  1138. case 'video':
  1139. $msgName=lang('messageType.video');
  1140. break;
  1141. case 'file':
  1142. $msgName=lang('messageType.file');
  1143. break;
  1144. case 'webrtc':
  1145. if($callVideo){
  1146. $msgName=lang('messageType.webrtcAudio');
  1147. }else{
  1148. $msgName=lang('messageType.webrtcVideo');
  1149. }
  1150. break;
  1151. }
  1152. return $msgName;
  1153. }
  1154. // 获取app的下载链接
  1155. function getAppDowmUrl($platform='android'){
  1156. $config=config('version.'.$platform);
  1157. $name=config('version.app_name');
  1158. if($platform=='windows'){
  1159. $packageName=$name."_Setup_".$config['version'].".exe";
  1160. $path="/downloadApp/windows";
  1161. }elseif($platform=='mac'){
  1162. $packageName=$name."_Setup_".$config['version'].".dmg";
  1163. $path="/downloadApp/mac";
  1164. }else{
  1165. $packageName=$name."_Setup_".$config['version'].".apk";
  1166. $path="/downloadApp/android";
  1167. }
  1168. if(is_file(PACKAGE_PATH . $packageName)){
  1169. return getMainHost().$path;
  1170. }else{
  1171. return '';
  1172. }
  1173. }
  1174. // php匹配文本中的所有url
  1175. function getAllUrl($text){
  1176. // 使用正则表达式匹配带有或不带有协议头的URL
  1177. $pattern = '/\b(?:https?:\/\/)?[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/i';
  1178. // 使用preg_replace()函数将URL转换为<a>标签
  1179. $replaced_text = preg_replace_callback($pattern, function($matches) {
  1180. $url = $matches[0];
  1181. if(utils\Regular::is_url($url)){
  1182. $newUrl=$url;
  1183. if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
  1184. $newUrl = "http://" . $url;
  1185. }
  1186. return '<a href="' . $newUrl . '">' . $url . '</a>';
  1187. }else{
  1188. return $url;
  1189. }
  1190. }, $text);
  1191. return $replaced_text;
  1192. }
  1193. // 将链接转成可点击的标签
  1194. function preg_link($text){
  1195. // 判断文本中是否有img标签
  1196. if(preg_match('/<img[^>]+>/i', $text)){
  1197. return $text;
  1198. }
  1199. // 匹配更广泛的 URL 的正则表达式
  1200. $pattern ='/\b(?:https?:\/\/|ftp:\/\/)?([a-z0-9-+&@#\/%?=~_|!:,.;]*\.[a-z]{2,}(?:\/[a-z0-9-+&@#\/%?=~_|!:,.;]*)*)\b/i';
  1201. // 使用preg_replace()函数将URL转换为<a>标签
  1202. $replaced_text = preg_replace_callback($pattern, function($matches) {
  1203. $url = $matches[0];
  1204. $isUrl=preg_match('/\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]|[a-z0-9-+&@#\/%?=~_|!:,.;]*\.[a-z]{2,}\b/i',$url) ? true : false;
  1205. if($isUrl){
  1206. $newUrl=$url;
  1207. if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
  1208. $newUrl = "https://" . $url;
  1209. }
  1210. return '<a href="' . $newUrl . '" target="_blank">' . $url . '</a>';
  1211. }else{
  1212. return $url;
  1213. }
  1214. }, $text);
  1215. return $replaced_text;
  1216. }
  1217. //消息队列think-queue
  1218. function queuePush($data, $delay = 0, $job = "Work", $queue = "im")
  1219. {
  1220. $data['job'] = $data['job'] ?? $job;
  1221. $data['queue'] = $data['queue'] ?? $queue;
  1222. $data['data'] = $data['data'] ?? [];
  1223. try {
  1224. if ($data) {
  1225. if ($delay == 0) {
  1226. Queue::push($job, $data, $queue);
  1227. } else {
  1228. Queue::later($delay, $job, $data, $queue);
  1229. }
  1230. }
  1231. return true;
  1232. } catch (Exception $e) {
  1233. return false;
  1234. }
  1235. }