common.php 41 KB

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