common.php 42 KB

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