common.php 44 KB

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