common.php 43 KB

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