common.php 44 KB

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