common.php 39 KB

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