common.php 42 KB

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