common.php 43 KB

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