common.php 33 KB

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