common.php 43 KB

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