common.php 40 KB

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