common.php 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: 流年 <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. use app\common\model\Setting;
  12. use GuzzleHttp\Client;
  13. use think\Cache;
  14. use think\Config;
  15. use think\Db;
  16. use think\db\exception\DataNotFoundException;
  17. use think\db\exception\ModelNotFoundException;
  18. use think\Env;
  19. use think\Exception;
  20. use think\exception\DbException;
  21. /**
  22. * 取得随机数
  23. *
  24. * @param int $length 生成随机数的长度
  25. * @param int $numeric 是否只产生数字随机数 1是0否
  26. * @return string
  27. */
  28. function random($length, $numeric = 0)
  29. {
  30. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  31. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  32. $hash = '';
  33. $max = strlen($seed) - 1;
  34. for ($i = 0; $i < $length; $i++) {
  35. $hash .= $seed[mt_rand(0, $max)];
  36. }
  37. return $hash;
  38. }
  39. /**
  40. * 二维数组根据字段进行排序
  41. * @params array $array 需要排序的数组
  42. * @params string $field 排序的字段
  43. * @params string $sort 排序顺序标志 SORT_DESC 降序;SORT_ASC 升序
  44. *
  45. */
  46. function arraySequence($array, $field, $sort = 'SORT_DESC')
  47. {
  48. $arrSort = array();
  49. if (empty($array)) {
  50. return $arrSort;
  51. }
  52. foreach ($array as $uniqid => $row) {
  53. foreach ($row as $key => $value) {
  54. $arrSort[$key][$uniqid] = $value;
  55. }
  56. }
  57. array_multisort($arrSort[$field], constant($sort), $array);
  58. return $array;
  59. }
  60. /**
  61. * 因为 < php7.0自带的array_column函数无法作用于对象数组,该函数用于返回对象数组中指定的一列
  62. *
  63. * @param $arr : array 需要取出数组列的二维数组
  64. * @param $column_key :数组的列的键
  65. * @return array :一维数组
  66. *
  67. */
  68. function arrayColumnByObject($arr, $column_key, $index_key = null)
  69. {
  70. $result = array();
  71. if (!empty($arr)) {
  72. foreach ($arr as $value) {
  73. if (!empty($index_key)) {
  74. $result[$value[$index_key]] = $value[$column_key];
  75. } else
  76. $result[] = $value[$column_key];
  77. }
  78. }
  79. return $result;
  80. }
  81. /**
  82. * 转换字符串中的HTML、js等XSS字符
  83. * @param string $value 需要转义的值
  84. *
  85. * @return string
  86. */
  87. function escape($value)
  88. {
  89. if (empty($value)) {
  90. return $value;
  91. }
  92. return htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
  93. }
  94. /**
  95. * HTML过滤XSS字符
  96. * @param mixed $value 需要转义的值
  97. * @return mixed
  98. */
  99. function removeXss($value)
  100. {
  101. if (empty($value)) {
  102. return $value;
  103. }
  104. vendor('htmlpurifier.library.HTMLPurifier#auto');
  105. // 实例化 HTMLPurifier对象
  106. $purifier = new HTMLPurifier();
  107. // 返回过滤后的数据
  108. return $purifier->purify($value);
  109. }
  110. /**
  111. * 生成返回跳转的url
  112. *
  113. * @param string $url 生成的URL地址或路由地址
  114. * @param string|array $params 参数
  115. * @param bool|string $suffix 生成的URL后缀
  116. * @param bool|string $domain 域名
  117. *
  118. * @return string
  119. */
  120. function createRefererUrl($url = null, $params = '', $suffix = true, $domain = false)
  121. {
  122. if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
  123. $url = $_SERVER["HTTP_REFERER"];
  124. } else {
  125. $url = empty($params) ? url($url, '', $suffix, $domain) :
  126. url($url, '', $suffix, $domain) . '?' . http_build_query($params, null, '&');
  127. }
  128. return urlencode($url);
  129. }
  130. /**
  131. * 旧版SDK加密解密函数(来自discuz)
  132. * @param $string string 明文或密文
  133. * @param $operation string DECODE为解密,ENCODE为加密
  134. * @param $key string 密钥
  135. * @param $expiry int 有效期,秒为单位,0为永久
  136. */
  137. function auth_code($string, $operation = 'DECODE', $key = '', $expiry = 0)
  138. {
  139. $ckey_length = 0;
  140. $key = md5($key ? $key : Env::get('auth_key'));
  141. $keya = md5(substr($key, 0, 16));
  142. $keyb = md5(substr($key, 16, 16));
  143. $keyc = $ckey_length ?
  144. ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
  145. $cryptkey = $keya . md5($keya . $keyc);
  146. $key_length = strlen($cryptkey);
  147. $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) :
  148. sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
  149. $string_length = strlen($string);
  150. $result = '';
  151. $box = range(0, 255);
  152. // $box = 100;
  153. $rndkey = array();
  154. for ($i = 0; $i <= 255; $i++) {
  155. $rndkey[$i] = ord($cryptkey[$i % $key_length]);
  156. }
  157. for ($j = $i = 0; $i < 256; $i++) {
  158. $j = ($j + $box[$i] + $rndkey[$i]) % 256;
  159. $tmp = $box[$i];
  160. $box[$i] = $box[$j];
  161. $box[$j] = $tmp;
  162. }
  163. for ($a = $j = $i = 0; $i < $string_length; $i++) {
  164. $a = ($a + 1) % 256;
  165. $j = ($j + $box[$a]) % 256;
  166. $tmp = $box[$a];
  167. $box[$a] = $box[$j];
  168. $box[$j] = $tmp;
  169. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  170. }
  171. if ($operation == 'DECODE') {
  172. if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
  173. return substr($result, 26);
  174. } else {
  175. return '';
  176. }
  177. } else {
  178. return $keyc . str_replace('=', '', base64_encode($result));
  179. }
  180. }
  181. /**
  182. * 字符串模糊处理,中间4位以*代替
  183. * @param string $str 需要模糊处理的字符串
  184. * @param int $startlen 开头明文显示的长度
  185. *
  186. * @return string
  187. */
  188. function stringObfuscation($str, $startlen = 3)
  189. {
  190. if (!$str) {
  191. return '***';
  192. }
  193. $len = mb_strlen($str, 'utf-8');
  194. if ($len <= $startlen) {
  195. return mb_substr($str, 0, 1) . str_repeat('*', $len - 1);
  196. } elseif ($len <= ($startlen + 4)) {
  197. return mb_substr($str, 0, $startlen) . str_repeat('*', $len - $startlen);
  198. } else {
  199. return mb_substr($str, 0, $startlen) . str_repeat('*', 4) . mb_substr($str, $startlen + 4);
  200. }
  201. return $str;
  202. }
  203. /**
  204. * 身份证模糊处理,中间以*代替
  205. * @param string $str
  206. * @return string
  207. */
  208. function idcardObfuscation($str)
  209. {
  210. if (!$str || $str == '-1') {
  211. return $str;
  212. }
  213. $len = mb_strlen($str, 'utf-8');
  214. return mb_substr($str, 0, 4) . str_repeat('*', $len - 8) . mb_substr($str, -4);
  215. }
  216. /**
  217. * 密码模糊处理,中间以*代替
  218. * @param string $str
  219. * @return string
  220. */
  221. function passwordObfuscation($str)
  222. {
  223. if (!$str) {
  224. return '***';
  225. }
  226. $len = mb_strlen($str, 'utf-8');
  227. return mb_substr($str, 0, 3) . str_repeat('*', $len - 6) . mb_substr($str, -3);
  228. }
  229. /**
  230. * 手机号模糊处理,中间4位以*代替
  231. *
  232. * @param string $mobile
  233. * @return string 处理过的手机号
  234. */
  235. function mobileObfuscation($mobile)
  236. {
  237. if (empty($mobile)) {
  238. return null;
  239. }
  240. return substr($mobile, 0, 3) . '****' . substr($mobile, 7);
  241. }
  242. /**
  243. * 用户名模糊处理
  244. * @param $username
  245. * @return string
  246. */
  247. function usernameObfuscation($username)
  248. {
  249. $len = mb_strlen($username, 'utf-8');
  250. if ($len == 2) {
  251. return mb_substr($username, 0, 1) . '*';
  252. } else if ($len > 2) {
  253. return mb_substr($username, 0, 1) . str_repeat('*', $len - 2) . mb_substr($username, -1);
  254. }
  255. return $username;
  256. }
  257. /**
  258. * 邮箱地址模糊处理,显示头两位及@之后的
  259. * @param string $mail
  260. * @return string 处理过的邮箱地址
  261. */
  262. function mailObfuscation($mail)
  263. {
  264. if (empty($mail)) {
  265. return null;
  266. }
  267. return substr($mail, 0, 3) . '****' . strstr($mail, '@');
  268. }
  269. if (!function_exists('filterAndTrimInput')) {
  270. function filterAndTrimInput($val)
  271. {
  272. return escape(trim($val));
  273. }
  274. }
  275. /**
  276. * 根据传来的日期,生成时间戳区间查询条件,日期格式:2016-01-01
  277. * @param string $start_time 开始时间
  278. * @param string $end_time 结束时间
  279. * @return array 时间戳查询条件
  280. */
  281. function makeTimeCondition($start_time = '', $end_time = '')
  282. {
  283. $start_time = !empty($start_time) ? strtotime($start_time) : '';
  284. $end_time = !empty($end_time) ? strtotime($end_time . ' 23:59:59') : '';
  285. $condition = array();
  286. if (!empty($start_time)) {
  287. $condition = array('EGT', $start_time);
  288. }
  289. if (!empty($end_time)) {
  290. $condition = array('ELT', $end_time);
  291. }
  292. if (!empty($start_time) && !empty($end_time)) {
  293. $condition = array(array('EGT', $start_time), array('ELT', $end_time));
  294. }
  295. return $condition;
  296. }
  297. /**
  298. * 写入日志
  299. *
  300. * @param string $path 日志路径
  301. * @param string $level
  302. * log 常规日志,用于记录日志
  303. * error 错误,一般会导致程序的终止
  304. * notice 警告,程序可以运行但是还不够完美的错误
  305. * info 信息,程序输出信息
  306. * debug 调试,用于调试信息
  307. * sql SQL语句,用于SQL记录,只在数据库的调试模式开启时有效
  308. */
  309. function log_message($msg, $level = 'info', $path = LOG_PATH)
  310. {
  311. \think\Log::init([
  312. 'type' => 'File',
  313. 'path' => $path,
  314. 'file_size' => 10485760
  315. ]);
  316. \think\Log::write($msg, $level);
  317. }
  318. /**
  319. * 获得cURL请求数据
  320. *
  321. * @param string $url 请求的URL
  322. * @param array $post_fields “POST”请求的数据
  323. * @return mixed
  324. */
  325. function getCurlContent($url, $post_fields = array())
  326. {
  327. $h_curl = curl_init();
  328. curl_setopt($h_curl, CURLOPT_URL, $url);
  329. curl_setopt($h_curl, CURLOPT_HEADER, false);
  330. curl_setopt($h_curl, CURLOPT_FOLLOWLOCATION, 1);
  331. curl_setopt($h_curl, CURLOPT_RETURNTRANSFER, 1);
  332. curl_setopt($h_curl, CURLOPT_TIMEOUT, 60);
  333. curl_setopt($h_curl, CURLOPT_SSL_VERIFYPEER, false); // 阻止对证书的合法性的检查
  334. curl_setopt($h_curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
  335. if (!empty($post_fields)) {
  336. curl_setopt($h_curl, CURLOPT_POST, 1);
  337. curl_setopt($h_curl, CURLOPT_POSTFIELDS, $post_fields);
  338. if (is_string($post_fields)) {
  339. curl_setopt($h_curl, CURLOPT_HTTPHEADER, array(
  340. 'Content-Type: application/json; charset=utf-8',
  341. 'Content-Length: ' . strlen($post_fields))
  342. );
  343. }
  344. }
  345. $contents = curl_exec($h_curl);
  346. curl_close($h_curl);
  347. return $contents;
  348. }
  349. /**
  350. * 生成订单号,每秒可产生9999个不重复的订单号
  351. * @return string
  352. */
  353. function makeOrderid($head = 'WL')
  354. {
  355. $redis = think\Cache::store('default');
  356. $orderid = (microtime(true) * 10000) . substr(str_pad(mt_rand(), 6, "0", STR_PAD_BOTH), 0, 6);
  357. // 判断是否有同个订单号的请求还没处理完,防止因为网络问题,导致同个订单并发
  358. $cache_key = 'orderid:' . $orderid;
  359. if ($redis->has($cache_key)) {
  360. return makeOrderid();
  361. } else {
  362. $redis->set($cache_key, $orderid, 86400);
  363. return $head . $orderid;
  364. }
  365. }
  366. /**
  367. * 生成平台币订单号
  368. *
  369. */
  370. function makeCoinSn()
  371. {
  372. return 'sn' . makeOrderid();
  373. }
  374. /**
  375. * 获取渠道顶级信息
  376. *
  377. * @param $channelId int 当前渠道ID
  378. *
  379. * @return array 渠道信息
  380. */
  381. function get_top_channel($channelId)
  382. {
  383. $channelModel = \Think\Db::name('nw_channel');
  384. // $channelLevel = get_channel_level($channelId);
  385. $i = 0;
  386. while ($info = $channelModel->where(['id' => $channelId])->find()) {
  387. $i++;
  388. if ($info['level'] == 1 || $info['parent_id'] == $info['id'] || $i > 5) {
  389. return $info;
  390. }
  391. $channelId = $info['parent_id'];
  392. }
  393. }
  394. /**
  395. * 获取渠道联盟信息
  396. *
  397. * @param $channelId int 当前渠道ID
  398. *
  399. * @return array 渠道信息
  400. */
  401. function get_union_channel($channelId)
  402. {
  403. $data = \think\Cache::get('get_union_channel'.$channelId);
  404. if(!empty($data)){
  405. return json_decode($data,true);
  406. }
  407. $channelModel = \Think\Db::name('nw_channel');
  408. // $channelLevel = get_channel_level($channelId);
  409. $i = 0;
  410. while ($info = $channelModel->where(['id' => $channelId])->find()) {
  411. $i++;
  412. if ($info['level'] == 0 || $info['parent_id'] == $info['id'] || $i > 5) {
  413. \think\Cache::set('get_union_channel'.$channelId,json_encode($info),60);
  414. return $info;
  415. }
  416. $channelId = $info['parent_id'];
  417. }
  418. }
  419. /**
  420. * 获取渠道等级
  421. */
  422. function get_channel_level($channelId)
  423. {
  424. $level = 3;
  425. $channelModel = \Think\Db::name('nw_channel');
  426. while ($info = $channelModel->where(['id' => $channelId])->find()) {
  427. return $info['level'];
  428. /*
  429. if ($info['level'] == 1) {
  430. return $level;
  431. }
  432. $channelId = $info['parent_id'];
  433. $level++;
  434. */
  435. }
  436. }
  437. /**
  438. * 获取顶级二级渠道
  439. * 获取渠道信息
  440. */
  441. function get_top_second_channel_name($channelId)
  442. {
  443. $keyName = 'get_top_second_channel_name:'.$channelId;
  444. $data = \think\Cache::get($keyName);
  445. if(!empty($data)){
  446. return json_decode($data,true);
  447. }
  448. $channel = [];
  449. $channelModel = \think\Db::name('nw_channel');
  450. $level = 0;
  451. $newChannelId = $channelId;
  452. while ($info = $channelModel->field('id,name,parent_id,level')->where(['id' => $newChannelId, 'flag' => ['in', '1,2,3']])->find()) {
  453. $channel[$level] = $info['name'];
  454. $level++;
  455. //如果上级是最高级渠道退出循环
  456. if ($info['level'] == 1) {
  457. break;
  458. }
  459. //测试数据存在 多个parent_id = 0的情况 后续不需要去掉
  460. if (!$info['parent_id']) {
  461. break;
  462. }
  463. $newChannelId = $info['parent_id'];
  464. }
  465. //反转数组
  466. $channel = array_reverse($channel);
  467. if (!$level) {
  468. $res = [
  469. 'channel_name' => '',
  470. 'second_name' => '',
  471. 'top_name' => '',
  472. ];
  473. }
  474. //二级渠道情况
  475. if ($level == 2) {
  476. $res = [
  477. 'channel_name' => isset($channel[1]) ? $channel[1] : '',
  478. 'second_name' => '',
  479. 'top_name' => isset($channel[0]) ? $channel[0] : '',
  480. ];
  481. } elseif ($level > 2) { //三级渠道情况
  482. $res = [
  483. 'channel_name' => isset($channel[count($channel) - 1]) ? $channel[count($channel) - 1] : "",
  484. 'second_name' => isset($channel[1]) ? $channel[1] : '',
  485. 'top_name' => isset($channel[0]) ? $channel[0] : '',
  486. ];
  487. } else {
  488. //最高级渠道情况
  489. $res = [
  490. 'channel_name' => isset($channel[0]) ? $channel[0] : '',
  491. 'second_name' => '',
  492. 'top_name' => '',
  493. ];
  494. }
  495. \think\Cache::set($keyName, json_encode($res),60);
  496. return $res;
  497. }
  498. /**
  499. * 获取顶级二级渠道名称 - v2 优化版
  500. *
  501. * 原版问题:while 循环逐级向上查 parent_id,N 级渠道就打 N 次 SQL。
  502. * 优化思路:nw_channel.id_path 已存储完整祖先 ID 链(逗号分隔),
  503. * 只需 1 次查询取出当前渠道的 id_path + level,
  504. * 再用 1 次 IN 查询批量拿到所有祖先名称,合计固定 2 次 SQL。
  505. *
  506. * id_path 格式示例(自身 id 也包含在内):
  507. * level=0(B+): "10"
  508. * level=1(B): "10,20"
  509. * level=2(B-): "10,20,300"
  510. * level=3(推广员): "10,20,300,500"
  511. *
  512. * 返回结构与原版保持一致:
  513. * [
  514. * 'channel_name' => 当前渠道名(最末级),
  515. * 'second_name' => 二级渠道名(level=1,B账号),无则空字符串,
  516. * 'top_name' => 顶级渠道名(level=0,B+账号),
  517. * ]
  518. *
  519. * @param int $channelId
  520. * @return array
  521. */
  522. function get_top_second_channel_name_v2($channelId)
  523. {
  524. // ---------- 0. 空值快速返回 ----------
  525. $emptyRes = ['channel_name' => '', 'second_name' => '', 'top_name' => '', 'union_name' => ''];
  526. if (empty($channelId)) {
  527. return $emptyRes;
  528. }
  529. // ---------- 1. 缓存读取 ----------
  530. $keyName = 'get_top_second_channel_name_v2:' . $channelId;
  531. $cached = \think\Cache::get($keyName);
  532. if (!empty($cached)) {
  533. return json_decode($cached, true);
  534. }
  535. // ---------- 2. 查询当前渠道的 id_path ----------
  536. $self = \think\Db::name('nw_channel')
  537. ->field('id, name, level, id_path')
  538. ->where(['id' => $channelId])
  539. ->find();
  540. if (empty($self)) {
  541. \think\Cache::set($keyName, json_encode($emptyRes), 60);
  542. return $emptyRes;
  543. }
  544. // ---------- 3. 解析 id_path,获取所有上级渠道 ID ----------
  545. // id_path 格式:",10,5213,5214,"
  546. $idPath = trim($self['id_path'], ',');
  547. // 当前渠道名称
  548. $channelName = $self['name'];
  549. $topName = $twoName = $threeName ='';
  550. if (!empty($idPath)) {
  551. // 解析上级 ID 列表
  552. $parentIds = array_filter(array_map('intval', explode(',', $idPath)));
  553. if (!empty($parentIds)) {
  554. // ---------- 4. 批量查询所有上级渠道的 id/name/level ----------
  555. $parents = \think\Db::name('nw_channel')
  556. ->field('id, name, level')
  557. ->where(['id' => ['in', $parentIds]])
  558. ->select();
  559. // 以 level 为键建立映射
  560. $levelMap = [];
  561. foreach ($parents as $row) {
  562. $levelMap[(int)$row['level']] = $row['name'];
  563. }
  564. // 根据层级组装返回
  565. // level: 0=B+(顶级), 1=B(二级), 2=B-(三级), 3=推广员(四级)
  566. $topName = $levelMap[0] ?? ''; // 顶级渠道(B+)
  567. $twoName = $levelMap[1] ?? ''; // 二级渠道(B)
  568. $threeName = $levelMap[2] ?? ''; // 三级渠道(B-)
  569. }
  570. }
  571. // ---------- 5. 组装返回结构 ----------
  572. $res = [
  573. 'channel_name' => $channelName,
  574. 'second_name' => $threeName,
  575. 'top_name' => $twoName,
  576. 'union_name' => $topName,
  577. ];
  578. // ---------- 6. 写缓存并返回 ----------
  579. \think\Cache::set($keyName, json_encode($res), 60);
  580. return $res;
  581. }
  582. /**
  583. * 根据渠道ID,获取四级渠道,并根据渠道等级为键
  584. * 四级渠道=层级:0(B+账号),1(B账号),2(B-账号),3(推广员)
  585. * @param $channelId
  586. *
  587. * @return array
  588. * @throws DataNotFoundException
  589. * @throws ModelNotFoundException
  590. * @throws DbException
  591. */
  592. function get_channel_top_by_aggregate($channelId)
  593. {
  594. $id_path = Db::table('nw_channel')->field('id,name,level,id_path')->where('id', $channelId)->value('id_path');
  595. if(!$id_path) return [];
  596. $id_path = $channelId . ',' . $id_path;
  597. $id_path = array_filter(explode(',', $id_path));
  598. $list = Db::table('nw_channel')->field('id,name,level')->where('id', 'in', $id_path)->select();
  599. if(!$list) return [];
  600. $result = array_column($list, null, 'level');
  601. return $result;
  602. }
  603. /**
  604. * 获取渠道名称
  605. */
  606. function get_channel_name($id)
  607. {
  608. $info = \Think\Db::name('nw_channel')->field('name')->where(['id' => $id])->find();
  609. return $info['name'];
  610. }
  611. /**
  612. * 获取聚合渠道名称
  613. */
  614. function get_complex_channel_name($id)
  615. {
  616. $info = \Think\Db::name('nw_complex_channel')->field('name')->where(['id' => $id])->find();
  617. return $info['name'];
  618. }
  619. /**
  620. * 获取子渠道
  621. *
  622. * @param $channelId integer 当前渠道ID
  623. * @param $deep 层级深度(默认不传值时,取所有子渠道)
  624. *
  625. */
  626. function get_child_channel_arr($channelId, $deep = '')
  627. {
  628. $result = [];
  629. $channelModel = \think\Db::name('nw_channel');
  630. //所有子渠道
  631. if (empty($deep)) {
  632. while ($info = $channelModel->field('id')->whereIn('parent_id', $channelId)->select()) {
  633. $tmp = [];
  634. if (!empty($info)) {
  635. foreach ($info as $v) {
  636. $result[] = $v['id'];
  637. $tmp[] = $v['id'];
  638. }
  639. $channelId = $tmp;
  640. }
  641. }
  642. } //层级深度以内的子渠道
  643. else {
  644. while ($info = $channelModel->field('id')->whereIn('parent_id', $channelId)->select()) {
  645. $deep--;
  646. $tmp = [];
  647. if (!empty($info)) {
  648. foreach ($info as $v) {
  649. $result[] = $v['id'];
  650. $tmp[] = $v['id'];
  651. }
  652. $channelId = $tmp;
  653. }
  654. if ($deep == 0) break;
  655. }
  656. }
  657. return $result;
  658. }
  659. /**
  660. * 获取游戏名称
  661. */
  662. function get_game_name($id)
  663. {
  664. $info = \Think\Db::name('cy_game')->field('name')->where(['id' => $id])->find();
  665. return $info['name'];
  666. }
  667. /**
  668. * 清理游戏名称末尾的平台标识,得到公共游戏组名称。
  669. *
  670. * @param string $name
  671. * @return string
  672. */
  673. function cleanGameName(string $name): string
  674. {
  675. $patterns = [
  676. '/\s*((?:安卓|IOS|ios|H5|h5))\s*$/iu',
  677. '/\s*[-—]?\s*(安卓|IOS|ios|H5|h5)\s*$/iu',
  678. '/\s*\(?(?:安卓|IOS|ios|H5|h5)\)?\s*$/iu',
  679. ];
  680. foreach ($patterns as $pattern) {
  681. $name = preg_replace($pattern, '', $name);
  682. }
  683. return trim($name);
  684. }
  685. /**
  686. * 获取后台管理员名称
  687. */
  688. function get_admin_name($id)
  689. {
  690. $info = \Think\Db::name('cy_admin')->field('id,username')->where(['id' => $id])->find();
  691. return $info['username'];
  692. }
  693. /**
  694. * 后台及推广平台用户密码加密方法
  695. * @param string $pw 要加密的原始密码
  696. * @return string
  697. */
  698. function mg_password($pw)
  699. {
  700. return md5(Env::get('ADMIN_PASS_PRE') . $pw);
  701. }
  702. /**
  703. * 判断游戏母包是否存在,查询结果做10秒缓存,减轻接口的压力
  704. * @param $pinyin string
  705. * @param $platform integer 游戏平台 0:安卓; 1:IOS
  706. * @param $apktype integer 游戏包类型 0:普通包,1:光环包
  707. *
  708. * @return bool | string 返回false或者'False'可判断为母包不存在
  709. */
  710. function isRawGameApkExistBak($pinyin, $platform, $apktype)
  711. {
  712. $cache_key = 'subpackage:apkexist:' . $pinyin . ':apktype:' . $apktype;
  713. $redis = \think\Cache::store('default');
  714. if ($redis->has($cache_key)) {
  715. $redisInfo = $redis->get($cache_key);
  716. //日志记录
  717. if (is_array($redisInfo)) {
  718. log_message('请求母包是否存在redis:' . print_r($redisInfo, true), 'log', LOG_PATH . 'subpackage/');
  719. } else {
  720. log_message('请求母包是否存在redis:' . $redisInfo, 'log', LOG_PATH . 'subpackage/');
  721. }
  722. return $redisInfo;
  723. }
  724. $apk_verify_url = Env::get('mubao.upload_url', 'http://127.0.0.1:9998') . '/apk_exists?gamename=' . $pinyin . '&platform=' . ($platform == 1 ? 'ios' : 'android') . '&apktype=' . $apktype;
  725. try {
  726. $request_result = (new Client(['timeout' => 30]))->get($apk_verify_url);
  727. $response = $request_result->getBody(); //返回的是个对象
  728. } catch (Exception $e) {
  729. log_message('请求母包是否存在接口失败: gamename=' . $pinyin . '; ' . $e->getMessage(). " -- url:". $apk_verify_url, 'error', LOG_PATH . 'subpackage/');
  730. return false;
  731. }
  732. $json = json_decode($response, true);
  733. $error = json_last_error();
  734. //没有json错误时
  735. if (json_last_error() == JSON_ERROR_NONE) {
  736. $result = $json;
  737. } else {
  738. $result = 'False';
  739. }
  740. //日志记录
  741. if (is_array($result)) {
  742. log_message('请求母包是否存在接口: ' . $apk_verify_url . ' data: ' . print_r($result, true), 'log', LOG_PATH . 'subpackage/');
  743. } else {
  744. log_message('请求母包是否存在接口: ' . $apk_verify_url . ' data: ' . $result, 'log', LOG_PATH . 'subpackage/');
  745. }
  746. $redis->set($cache_key, $result, 300);
  747. return $result;
  748. }
  749. // 判断母包是否存在
  750. function isRawGameApkExist($pinyin, $platform, $apktype)
  751. {
  752. $apk_verify_url = Env::get('mubao.upload_url', 'http://127.0.0.1:9998') . '/apk_exists?gamename=' . $pinyin . '&platform=' . ($platform == 1 ? 'ios' : 'android') . '&apktype=' . $apktype;
  753. try {
  754. $request_result = (new Client(['timeout' => 30]))->get($apk_verify_url);
  755. $response = $request_result->getBody(); //返回的是个对象
  756. return $response;
  757. } catch (Exception $e) {
  758. log_message('请求母包是否存在接口失败: gamename=' . $pinyin . '; ' . $e->getMessage() . " -- url:" . $apk_verify_url, 'error', LOG_PATH . 'subpackage/');
  759. return false;
  760. }
  761. }
  762. // 同步分包请求
  763. function gameApkPack($data)
  764. {
  765. $url = Env::get('mubao.upload_url', 'http://127.0.0.1:9998') . '/pack';
  766. try {
  767. // $request_result = (new Client(['timeout' => 60]))->post($url, $data);
  768. // $response = $request_result->getBody(); //返回的是个对象
  769. $response = getHttpPost($url, $data);
  770. return $response;
  771. } catch (Exception $e) {
  772. log_message("同步分包: channel_id={$data['channel_id']}, filename=" . $data['filename'] . '; error=' . $e->getMessage() . " -- url:" . $url, 'error', LOG_PATH . 'subpackage/');
  773. return false;
  774. }
  775. }
  776. /**
  777. * 获取渠道的指定冻结选项的状态
  778. * 此方法除了判断自身渠道的状态, 也将追溯所有层级的父渠道相应的状态
  779. * 如果有被禁止的就会返回被禁止状态
  780. *
  781. * @param <int> $p_depId 渠道ID
  782. * @param <int> $p_gameId 游戏ID
  783. * @param <string> $p_field 选项的数据库字段名
  784. *
  785. * @return <bool> true: 被禁止; false: 未禁止
  786. */
  787. function isFrozenOption($p_depId, $p_gameId, $p_field = 'subpackage')
  788. {
  789. $isFrozen = false;
  790. $depId = (int)$p_depId;
  791. $gameId = (int)$p_gameId;
  792. $field = trim($p_field);
  793. $i = 0;
  794. $findFrozenStatus = true; //循环控制标识
  795. do {
  796. $channelFrozenModel = \think\Db::name('nw_channel_frozen');
  797. $frozenStatus = $channelFrozenModel->cache('common:isFrozenOption:' . $p_field . ':' . $depId . ':' . $gameId, 300)->field($field)->where(['channel_id' => $depId, 'game_id' => $gameId])->find();
  798. if (!empty($frozenStatus) && $frozenStatus[$p_field] == 1) {
  799. $isFrozen = true;
  800. $findFrozenStatus = false;
  801. }
  802. if ($depId == config('TOP_CHANNEL_ID')) {
  803. $findFrozenStatus = false;
  804. }
  805. if ($findFrozenStatus) {
  806. $channelModel = \think\Db::name('nw_channel');
  807. $depId = (int)$channelModel->cache('common:isFrozenOptionChannel:' . $depId, 300)->where(['id' => $depId])->value('parent_id');
  808. if (empty($depId)) {
  809. $findFrozenStatus = false;
  810. }
  811. }
  812. if ($i > 10) {
  813. $findFrozenStatus = false;
  814. }
  815. $i++;
  816. } while ($findFrozenStatus);
  817. return $isFrozen;
  818. }
  819. /**
  820. * 调用钉钉机器人函数
  821. *
  822. */
  823. function curlDD($msg = '', $url, $all = false)
  824. {
  825. // return false;
  826. // 30分钟只提醒一次
  827. $cacheName = md5($msg);
  828. $redis = think\Cache::store('default')->handler();
  829. $cacheKey = "dd:message:".$cacheName;
  830. $cacheNum = $redis->get($cacheKey);
  831. if($cacheNum){
  832. $redis->incr($cacheKey);
  833. if(!in_array($cacheNum, [1,5,10, 30, 50, 100])){
  834. return true;
  835. }
  836. }else{
  837. $cacheNum = 1;
  838. $redis->setex($cacheKey, 1800, 1);
  839. }
  840. $msg .= ' - 循环次数:'.$cacheNum;
  841. if($msg && Env::get('dingtalk.server_name', '')){
  842. $server_name = Env::get('dingtalk.server_name', '');
  843. $msg = "[{$server_name}]: ".$msg;
  844. }
  845. if ($all) {
  846. $postData = [
  847. 'msgtype' => 'text',
  848. 'text' => [
  849. 'content' => mb_convert_encoding($msg, "UTF-8", "auto"),
  850. 'mentioned_list' => array('@all'),
  851. ],
  852. 'at' => [
  853. "atMobiles" => [Config::get('dd_message')['develop']],
  854. ]
  855. ];
  856. } else {
  857. $postData = [
  858. 'msgtype' => 'text',
  859. 'text' => [
  860. 'content' => mb_convert_encoding($msg, "UTF-8", "auto"),
  861. ]
  862. ];
  863. }
  864. $postString = json_encode($postData);
  865. $ch = curl_init();
  866. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
  867. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
  868. curl_setopt($ch, CURLOPT_URL, $url);
  869. curl_setopt($ch, CURLOPT_POST, true);
  870. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  871. curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
  872. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  873. "Content-Type: application/json"
  874. ));
  875. $result = curl_exec($ch);
  876. $HTTP_CODE = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  877. curl_close($ch);
  878. // if($HTTP_CODE<>200){
  879. // $arr=array("state"=>-100);
  880. // echo json_encode($arr);
  881. // exit;
  882. // }elseif($result==""){
  883. // $arr=array("state"=>0,"errMsg"=>"接口返回为空");
  884. // echo json_encode($arr);
  885. // exit;
  886. // }
  887. return $result;
  888. }
  889. /**
  890. * 调用钉钉机器人函数-markdown
  891. *
  892. * @param $msg 消息内容字符串
  893. * @param $url 机器人地址
  894. * @param $devalop 是否@负责人
  895. *
  896. * @return bool|string
  897. */
  898. function curlDDMarkdown($msg, $url, $devalop = false)
  899. {
  900. // 30分钟只提醒一次
  901. $cacheName = md5($msg);
  902. $redis = think\Cache::store('default')->handler();
  903. $cacheKey = "dd:message:".$cacheName;
  904. $cacheNum = $redis->get($cacheKey);
  905. if($cacheNum){
  906. $redis->incr($cacheKey);
  907. if(!in_array($cacheNum, [1,5,10, 30, 50, 100])){
  908. return true;
  909. }
  910. }else{
  911. $cacheNum = 1;
  912. $redis->setex($cacheKey, 1800, 1);
  913. }
  914. $msg .= ' - 循环次数:'.$cacheNum;
  915. $title = config('dd_notice.server_name')??'祁盟';
  916. if($devalop){
  917. $msg = $title." @".config('dd_notice.develop')." \n ". $msg;
  918. $postData = [
  919. 'msgtype' => 'text',
  920. 'text' => [
  921. // 'content' => mb_convert_encoding($msg, "UTF-8", "auto"),
  922. 'content' => $msg,
  923. 'mentioned_list' => array('@all'),
  924. ],
  925. 'at' => [
  926. "atMobiles" => [Config::get('dd_notice')['develop']],
  927. ]
  928. ];
  929. }else{
  930. $postData = [
  931. 'msgtype' => 'markdown',
  932. "markdown" => [
  933. 'title' => $title,
  934. 'text' => $title.' '.$msg,
  935. ],
  936. ];
  937. }
  938. $postString = json_encode($postData);
  939. $ch = curl_init();
  940. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
  941. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
  942. curl_setopt($ch, CURLOPT_URL, $url);
  943. curl_setopt($ch, CURLOPT_POST, true);
  944. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  945. curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
  946. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  947. "Content-Type: application/json"
  948. ));
  949. $result = curl_exec($ch);
  950. $HTTP_CODE = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  951. curl_close($ch);
  952. return $result;
  953. }
  954. /**
  955. * 钉钉markdown通知管理
  956. *
  957. * @param string $notice_type 通知类型: warning/weelfar/notic/operat
  958. * @param string $msg_template 消息模板: 使用默认要为空
  959. * @param string $msg_data 通知数据: 默认=标题、报错说明、相关标识
  960. * @param bool $develop 是否呼叫管理员
  961. *
  962. * @return false|void
  963. */
  964. function ddMsg($notice_type, $msg_template = 'defaults', $msg_data = [], $develop = false){
  965. if(!array_key_exists($notice_type, Config::get('dd_notice.notice_type'))){
  966. return false;
  967. }
  968. $url = Config::get('dd_notice.notice_type')[$notice_type];
  969. if(array_key_exists($msg_template, Config::get('dd_notice.msg_template'))){
  970. // TODO: 不同模板多个 data 判断,未完善。
  971. $warning_msg = sprintf(Config::get('dd_notice')['msg_template'][$msg_template],$msg_data[0], $msg_data[1], $msg_data[2], $msg_data[3], date('Y-m-d H:i:s', time()));
  972. }else{
  973. $warning_msg = sprintf(Config::get('dd_notice')['msg_template']['defaults'],$msg_data[0], $msg_data[1], $msg_data[2], date('Y-m-d H:i:s', time()));
  974. }
  975. if($notice_type == 'warning'){
  976. $develop = true;
  977. }
  978. curlDDMarkdown($warning_msg, $url, $develop);
  979. }
  980. /**
  981. * 发送飞书机器人消息
  982. *
  983. * @param string $webhook 飞书机器人的 Webhook URL
  984. * @param string $content 消息内容
  985. * @param string $msgType 消息类型:text 或 post(富文本,支持格式化)
  986. * @param string $title 富文本标题(msgType=post 时有效)
  987. *
  988. * @return bool|string
  989. *
  990. * 范例:
  991. * **加粗文本**
  992. * ~~删除线~~
  993. * [超链接](https://example.com)
  994. * <at id=user_id></at> @人
  995. *
  996. *
  997. * // 纯文本
  998. * sendFeishuMessage('https://open.feishu.cn/open-apis/bot/v2/hook/你的webhook', '这是一条测试消息');
  999. *
  1000. * // 富文本(支持格式化)
  1001. * $message = "任务执行完成!\n耗时:5.2秒\n状态:成功";
  1002. * sendFeishuMessage('https://open.feishu.cn/...', $message, 'post', '✅❌⚠️ 通知标题');
  1003. *
  1004. */
  1005. function sendFeishuMessage($webhook, $content, $msgType = 'text', $title = '') {
  1006. if (empty($webhook) || empty($content)) {
  1007. return ['success' => false, 'error' => 'webhook or content is empty'];
  1008. }
  1009. $data = [];
  1010. if ($msgType === 'interactive') {
  1011. // 卡片消息 - 支持 Markdown 格式(推荐)
  1012. $data = [
  1013. 'msg_type' => 'interactive',
  1014. 'card' => [
  1015. 'header' => [
  1016. 'title' => [
  1017. 'tag' => 'plain_text',
  1018. 'content' => $title ?: '祈盟-系统通知'
  1019. ],
  1020. 'template' => 'red' // 红色警示
  1021. ],
  1022. 'elements' => [
  1023. [
  1024. 'tag' => 'div',
  1025. 'text' => [
  1026. 'tag' => 'lark_md',
  1027. 'content' => $content
  1028. ]
  1029. ]
  1030. ]
  1031. ]
  1032. ];
  1033. } elseif ($msgType === 'post') {
  1034. // 富文本格式(飞书原生格式,不是 Markdown)
  1035. $data = [
  1036. 'msg_type' => 'post',
  1037. 'content' => [
  1038. 'post' => [
  1039. 'zh_cn' => [
  1040. 'title' => $title ?: '祈盟-系统通知',
  1041. 'content' => [
  1042. [
  1043. [
  1044. 'tag' => 'text',
  1045. 'text' => $content
  1046. ]
  1047. ]
  1048. ]
  1049. ]
  1050. ]
  1051. ]
  1052. ];
  1053. } else {
  1054. // 纯文本
  1055. $data = [
  1056. 'msg_type' => 'text',
  1057. 'content' => [
  1058. 'text' => "祈盟-".$content
  1059. ]
  1060. ];
  1061. }
  1062. $ch = curl_init($webhook);
  1063. curl_setopt($ch, CURLOPT_POST, true);
  1064. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
  1065. curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  1066. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1067. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  1068. // SSL 配置(飞书是 HTTPS)
  1069. if (substr($webhook, 0, 5) == 'https') {
  1070. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1071. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  1072. }
  1073. $result = curl_exec($ch);
  1074. // 检查 curl 是否执行成功
  1075. if ($result === false) {
  1076. $error = curl_error($ch);
  1077. $errno = curl_errno($ch);
  1078. curl_close($ch);
  1079. return ['success' => false, 'error' => "CURL_ERROR [{$errno}]: {$error}"];
  1080. }
  1081. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  1082. curl_close($ch);
  1083. if ($httpCode !== 200) {
  1084. return ['success' => false, 'error' => "HTTP_ERROR: status={$httpCode}, body={$result}"];
  1085. }
  1086. $response = json_decode($result, true);
  1087. if ($response === null) {
  1088. return ['success' => false, 'error' => "JSON_DECODE_ERROR: {$result}"];
  1089. }
  1090. if (isset($response['code']) && $response['code'] == 0) {
  1091. return ['success' => true, 'data' => $response];
  1092. }
  1093. return ['success' => false, 'error' => "FEISHU_ERROR: code=" . ($response['code'] ?? 'unknown') . ", msg=" . ($response['msg'] ?? 'unknown')];
  1094. }
  1095. /**
  1096. * 输出xml字符
  1097. * @param $params array 参数
  1098. *
  1099. * @return string 返回组装的xml
  1100. **/
  1101. function dataToXml($params)
  1102. {
  1103. if (!is_array($params) || count($params) <= 0) {
  1104. return false;
  1105. }
  1106. $xml = "<xml>";
  1107. foreach ($params as $key => $val) {
  1108. if (is_numeric($val)) {
  1109. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  1110. } else {
  1111. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  1112. }
  1113. }
  1114. $xml .= "</xml>";
  1115. return $xml;
  1116. }
  1117. /**
  1118. * 防止重复提交的并发控制
  1119. *
  1120. * @param $cache_key string redis的key
  1121. * @param $time_limit int 限制时间
  1122. *
  1123. * @return boolean true:允许 false:禁止
  1124. */
  1125. function requestDuplicateCheck($cache_key, $time_limit)
  1126. {
  1127. $redis = \think\Cache::store('default')->handler(); //redis的句柄对象
  1128. //redis系统的当前时间
  1129. $redis_time = $redis->time()[0];
  1130. //初步加锁
  1131. $isLock = $redis->setnx($cache_key, $redis_time + $time_limit);
  1132. if ($isLock) {
  1133. $redis->expire($cache_key, $time_limit);
  1134. return true;
  1135. } else {
  1136. //加锁失败的情况下。判断锁是否已经存在,如果锁存在切已经过期,那么删除锁。进行重新加锁
  1137. $val = $redis->get($cache_key);
  1138. if ($val && $val < $redis_time) {
  1139. $redis->del($cache_key);
  1140. }
  1141. $result = $redis->setnx($cache_key, $redis_time + $time_limit);
  1142. if ($result) {
  1143. $redis->expire($cache_key, $time_limit);
  1144. }
  1145. return $result;
  1146. }
  1147. }
  1148. /**
  1149. * 并发解锁
  1150. * @param $cache_key
  1151. */
  1152. function requestDuplicateCheckUnlock($cache_key)
  1153. {
  1154. $redis = \think\Cache::store('default')->handler(); //redis的句柄对象
  1155. $redis->del($cache_key);
  1156. }
  1157. /**
  1158. * 如果是当月7日之前(包括7日),则可以导出上个月和这个月的报表; 如果是7日之后,则只能导出这个月报表
  1159. * @param $start 开始时间戳
  1160. * @param $end 结束时间戳
  1161. * @param int $day 日期分界(例:7号填 7 )
  1162. * @return array
  1163. */
  1164. function judgeReportTime($start, $end, $day = 7)
  1165. {
  1166. $data = ['code' => 0, 'msg' => '违规操作,禁止导出报表'];
  1167. $nowDay = date('d');
  1168. $lastMonth = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month'))); // 上个月1号时间戳
  1169. $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y')); // 这个月的开始时间
  1170. $endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y')); // 这个月的结束时间
  1171. if ($end < $start || $lastMonth > $start || $end > $endThismonth) {
  1172. return $data;
  1173. }
  1174. if ($nowDay <= $day && $lastMonth >= $start) {
  1175. $data['code'] = 1;
  1176. } elseif ($nowDay <= $day && date("Y-m", $start) == date("Y-m", $end)) {
  1177. $data['code'] = 1;
  1178. } elseif ($nowDay > $day && date("Y-m", $start) == date("Y-m", $end) && $start >= $beginThismonth) {
  1179. $data['code'] = 1;
  1180. }
  1181. return $data;
  1182. }
  1183. //以下微信公众号使用
  1184. function apipost($url, $arr = array(), $parse = true, $authentication = false)
  1185. {
  1186. $param = "";
  1187. if ($parse) {
  1188. foreach ($arr as $key => $value) {
  1189. $param = $param . $key . "=" . $value . "&";
  1190. }
  1191. $len = strlen($param) - 1;
  1192. $param = substr($param, 0, $len);
  1193. } else {
  1194. $param = $arr;
  1195. }
  1196. $ch = curl_init();
  1197. curl_setopt($ch, CURLOPT_URL, $url);
  1198. if ($authentication) {
  1199. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  1200. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  1201. }
  1202. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1203. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  1204. curl_setopt($ch, CURLOPT_POST, 1); //启用POST提交
  1205. curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
  1206. $file_contents = curl_exec($ch);
  1207. curl_close($ch);
  1208. return $file_contents;
  1209. }
  1210. function dd()
  1211. {
  1212. echo Db::getLastSql();
  1213. die;
  1214. }
  1215. function priceFormat($number, $decimals = 2, $dec_point = '.', $thousands_sep = '')
  1216. {
  1217. return number_format($number, $decimals, $dec_point, $thousands_sep);
  1218. }
  1219. function getCurl($url, $data = [], $timeout = 30)
  1220. {
  1221. if ($url == "" || $timeout <= 0) {
  1222. return false;
  1223. }
  1224. if ($data) {
  1225. $url = $url . '?' . http_build_query($data);
  1226. }
  1227. $con = curl_init((string)$url);
  1228. curl_setopt($con, CURLOPT_HEADER, false);
  1229. curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
  1230. curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
  1231. return curl_exec($con);
  1232. }
  1233. function opensslEncrypt($data)
  1234. {
  1235. $key = 'ukN3KYVdI2sPtjpL';
  1236. return base64_encode(openssl_encrypt($data, 'AES-128-ECB', $key, 0));
  1237. }
  1238. function opensslDecrypt($data)
  1239. {
  1240. $key = 'ukN3KYVdI2sPtjpL';
  1241. return openssl_decrypt(base64_decode($data), 'AES-128-ECB', $key, 0);
  1242. }
  1243. function curl($url, $params = [], $returnJson = false)
  1244. {
  1245. $curl = curl_init();
  1246. curl_setopt($curl, CURLOPT_URL, $url);
  1247. curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
  1248. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取数据返回
  1249. curl_setopt($curl, CURLOPT_TIMEOUT, 30); //超时时长,单位秒
  1250. if ($params) {
  1251. curl_setopt($curl, CURLOPT_POST, true); // post传输数据
  1252. curl_setopt($curl, CURLOPT_POSTFIELDS, $params); // post传输数据
  1253. }
  1254. // curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 设置请求头
  1255. $result = curl_exec($curl);
  1256. if ($result === false) {
  1257. $result = '接口超时';
  1258. }
  1259. curl_close($curl);
  1260. if ($returnJson) {
  1261. $result = json_decode($result, true);
  1262. }
  1263. return $result;
  1264. }
  1265. function is_mobile_request()
  1266. {
  1267. $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
  1268. $mobile_browser = '0';
  1269. if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
  1270. $mobile_browser++;
  1271. if ((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') !== false))
  1272. $mobile_browser++;
  1273. if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
  1274. $mobile_browser++;
  1275. if (isset($_SERVER['HTTP_PROFILE']))
  1276. $mobile_browser++;
  1277. $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
  1278. $mobile_agents = array(
  1279. 'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
  1280. 'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
  1281. 'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
  1282. 'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
  1283. 'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
  1284. 'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
  1285. 'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
  1286. 'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
  1287. 'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-'
  1288. );
  1289. if (in_array($mobile_ua, $mobile_agents))
  1290. $mobile_browser++;
  1291. if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
  1292. $mobile_browser++;
  1293. // Pre-final check to reset everything if the user is on Windows
  1294. if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
  1295. $mobile_browser = 0;
  1296. // But WP7 is also Windows, with a slightly different characteristic
  1297. if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
  1298. $mobile_browser++;
  1299. if ($mobile_browser > 0)
  1300. return true;
  1301. else
  1302. return false;
  1303. }
  1304. function timingCurl($url)
  1305. {
  1306. $ch = curl_init();
  1307. curl_setopt($ch, CURLOPT_URL, $url);
  1308. curl_setopt($ch, CURLOPT_HEADER, 0);
  1309. curl_exec($ch);
  1310. curl_close($ch);
  1311. }
  1312. function getMonthRange($date, $returnFirstDay = true)
  1313. {
  1314. $timestamp = strtotime($date);
  1315. if ($returnFirstDay) {
  1316. $monthFirstDay = date('Y-m-1 00:00:00', $timestamp);
  1317. return $monthFirstDay;
  1318. } else {
  1319. $mdays = date('t', $timestamp);
  1320. $monthLastDay = date('Y-m-' . $mdays . ' 23:59:59', $timestamp);
  1321. return $monthLastDay;
  1322. }
  1323. }
  1324. /**
  1325. * @return float 获取当前毫秒时间戳
  1326. */
  1327. function getMillisecond()
  1328. {
  1329. list($microsecond, $time) = explode(' ', microtime()); //' '中间是一个空格
  1330. return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
  1331. }
  1332. /**
  1333. * 是否json字符串
  1334. *
  1335. * @param $string
  1336. *
  1337. * @return bool
  1338. */
  1339. function is_json($string)
  1340. {
  1341. if (!is_string($string) || $string === '') {
  1342. return false;
  1343. }
  1344. $decoded = json_decode($string);
  1345. // 检查是否为对象或数组,且没有错误
  1346. return (json_last_error() === JSON_ERROR_NONE) &&
  1347. ($decoded !== null) &&
  1348. (is_object($decoded) || is_array($decoded));
  1349. }
  1350. function curlHeader($url, $params = '', $header = [], $returnJson = false)
  1351. {
  1352. $curl = curl_init();
  1353. curl_setopt($curl, CURLOPT_URL, $url);
  1354. curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
  1355. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取数据返回
  1356. curl_setopt($curl, CURLOPT_TIMEOUT, 30); //超时时长,单位秒
  1357. curl_setopt($curl, CURLOPT_POST, true); // post传输数据
  1358. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  1359. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  1360. if ($params) {
  1361. curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
  1362. }
  1363. if (!empty($header)) {
  1364. curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 设置请求头
  1365. }
  1366. $result = curl_exec($curl);
  1367. if ($result === false) {
  1368. $result = '接口超时';
  1369. }
  1370. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  1371. curl_close($curl);
  1372. if ($returnJson) {
  1373. $result = json_decode($result, true);
  1374. $result['code_qf'] = $code;
  1375. }
  1376. return $result;
  1377. }
  1378. function temporary()
  1379. {
  1380. $time = time();
  1381. $start_time = '1670256000';
  1382. $end_time = '1670342400';
  1383. if($start_time<$time && $end_time>time()){
  1384. return true;
  1385. }else{
  1386. return false;
  1387. }
  1388. }
  1389. /**
  1390. * 生成唯一值
  1391. * @return string
  1392. */
  1393. function makeUniqueid($head = 'FL')
  1394. {
  1395. $redis = think\Cache::store('default');
  1396. $uniqueid = (date('YmdHis').getRandomStr(8, false) . substr(str_pad(mt_rand(), 6, "0", STR_PAD_BOTH), 0, 6));
  1397. // 判断是否有同个唯一值的请求还没处理完,防止因为网络问题,导致同个订单并发
  1398. $cache_key = 'orderid:' . $uniqueid;
  1399. if ($redis->has($cache_key)) {
  1400. return makeUniqueid();
  1401. } else {
  1402. $redis->set($cache_key, $uniqueid, 86400);
  1403. return $head . $uniqueid;
  1404. }
  1405. }
  1406. /**
  1407. * 获得随机字符串
  1408. * @param $len 需要的长度
  1409. * @param $special 是否需要特殊符号
  1410. * @return string 返回随机字符串
  1411. */
  1412. function getRandomStr($len, $special=true){
  1413. $chars = array(
  1414. "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
  1415. "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
  1416. "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
  1417. "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
  1418. "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
  1419. "3", "4", "5", "6", "7", "8", "9"
  1420. );
  1421. if($special){
  1422. $chars = array_merge($chars, array(
  1423. "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
  1424. "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
  1425. "}", "<", ">", "~", "+", "=", ",", "."
  1426. ));
  1427. }
  1428. $charsLen = count($chars) - 1;
  1429. shuffle($chars); //打乱数组顺序
  1430. $str = '';
  1431. for($i=0; $i<$len; $i++){
  1432. $str .= $chars[mt_rand(0, $charsLen)]; //随机取出一位
  1433. }
  1434. return $str;
  1435. }
  1436. function setChannelId($userid,$channelId){
  1437. // \think\Cache::store('default')->set('token:channelId:'.$userid, $channelId, 60 * 60 * 24 * 30);
  1438. }
  1439. function getChannelId($userid, $gameid = ''){
  1440. // $channelId = \think\Cache::store('default')->get('token:channelId:'.$userid);
  1441. // ->cache(true, 86400)
  1442. $channelId = Db::table('nw_subaccount')->where(['member_id' => $userid, 'game_id' => $gameid])->value('channel_id');
  1443. if($channelId > 0){
  1444. return $channelId;
  1445. }else{
  1446. return 0;
  1447. }
  1448. }
  1449. // 获取折扣比例
  1450. function getDiscount($userid = 0,$gameId = 0,$channelId = 0){
  1451. $proportion = \Think\Db::name('cy_game_pay_discount')->where(['game_id' => $gameId])->value('proportion');
  1452. return $proportion??"1";
  1453. }
  1454. /**
  1455. * 金额分转元
  1456. * @param int $fen
  1457. * @return string
  1458. */
  1459. function formatFenToYuan($fen, $long = 2)
  1460. {
  1461. return number_format($fen / 100, $long, '.', '');
  1462. }
  1463. /**
  1464. * 金额元转分
  1465. *
  1466. * @param int $fen
  1467. *
  1468. * @return string
  1469. */
  1470. function formatYuanToFen($yuan, $long = 0)
  1471. {
  1472. return number_format($yuan * 100, $long, '.', '');
  1473. }
  1474. /**
  1475. * 获取渠道游戏支付金额的产品标识
  1476. *
  1477. * @param string $money 获取金额(元)(支付金额最大为9w元)
  1478. * @param string $mark 前缀标识
  1479. *
  1480. * @return string
  1481. */
  1482. function formatComplexProductMark($mark, $game_id, $money)
  1483. {
  1484. $money = formatYuanToFen($money);
  1485. $cpMark = $mark . '_' . str_pad($money, 7, "0", STR_PAD_LEFT); // 拼接标识(0.06 = kdzz_0000006)
  1486. if (!isset(config('config_complex_goods')[$mark][$cpMark])) {
  1487. return false;
  1488. }
  1489. return $cpMark;
  1490. }
  1491. /**
  1492. * 获取游戏所属渠道的标识
  1493. *
  1494. * @param $jh_mark 渠道标识
  1495. * @param $game_id 游戏ID
  1496. *
  1497. * @return array
  1498. */
  1499. function isComplexProduct($jh_mark, $game_id)
  1500. {
  1501. $ids = Env::get('complex.sj_game_ids', '');
  1502. $ids = explode(',', $ids);
  1503. $channelList = [];
  1504. foreach ($ids as $v) {
  1505. $channel = explode('_', $v);
  1506. $channelList[$channel[0]] = $channel[1];
  1507. }
  1508. if(!in_array($game_id, array_keys($channelList))){
  1509. return "";
  1510. }
  1511. return $jh_mark.'_'.$channelList[$game_id];
  1512. }
  1513. function dump($data, $type = true)
  1514. {
  1515. $params = func_get_args();
  1516. if ($type == true) {
  1517. echo "<pre>";
  1518. }
  1519. var_dump(...$params);
  1520. die;
  1521. }
  1522. /**
  1523. * 发起请求提交
  1524. *
  1525. * @param string $type 请求类型 GET/POST
  1526. * @param string $url 请求URL
  1527. * @param array $data POST请求数据
  1528. * @param array $header Header头数据
  1529. *
  1530. * @return
  1531. */
  1532. function getHttp($type = 'GET', $url, $data = [], $header = ['Content-Type: application/json'], $headerStatus = false)
  1533. {
  1534. $curl = curl_init($url);
  1535. // curl_setopt($curl, CURLOPT_URL, $url); // 设置抓取的url
  1536. // curl_setopt($curl, CURLOPT_HEADER, 0); // 设置头文件的信息作为数据流输出
  1537. curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 超时设置,以秒为单位
  1538. // 超时设置,以毫秒为单位
  1539. // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 300);
  1540. if ($header) {
  1541. curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 设置请求头
  1542. }
  1543. //设置获取的信息以文件流的形式返回,而不是直接输出。
  1544. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 执行后不直接打印出来
  1545. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 跳过证书检查
  1546. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
  1547. if ($type == 'POST') {
  1548. // curl_setopt($curl, CURLOPT_POST, 1); // 设置请求方式为post
  1549. curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // post的变量
  1550. // curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // post的变量
  1551. }
  1552. if ($headerStatus == true) {
  1553. $header = curl_getinfo($curl);
  1554. }
  1555. $result = curl_exec($curl); // 执行并获取內容
  1556. curl_close($curl); // 释放curl句柄
  1557. if (!is_json($result)) {
  1558. $result = json_encode($result, true);
  1559. }
  1560. // trace("## common@getHttp: ".$type . " - URL: " . $url . " - Data: " . json_encode($data) . ' - Result: ' . $result, 'common@getHttp.$result');
  1561. log_message("## common@getHttp - ".date("Y-m-d H:i:s", time()).": ".$type . " - URL: " . $url . " - Data: " . json_encode($data) . ' - Result: ' . $result, 'log', LOG_PATH . 'httpLog/'); // ## aplog log
  1562. return $result;
  1563. }
  1564. /**
  1565. * 模拟 GET 请求
  1566. *
  1567. * @param string $url 请求地址
  1568. * @param array $header Header头数据
  1569. *
  1570. * @return
  1571. */
  1572. function getHttpGet(string $url, $query = [], $header = [], $json = true)
  1573. {
  1574. // $res = getHttp('GET', $url . '?' . assemblyByQuery($query), [], $header);
  1575. $query = http_build_query($query);
  1576. if (!empty($query)) {
  1577. $query = "?" . $query;
  1578. }
  1579. return getHttp('GET', $url . $query, [], $header);
  1580. }
  1581. /**
  1582. * 模拟 POST 请求
  1583. *
  1584. * @param string $url 请求地址
  1585. * @param array $data 请求数据
  1586. * @param array $header Header头数据
  1587. * @param array $headerStatus 是否返回请求返回的Header数据
  1588. *
  1589. * @return array
  1590. */
  1591. function getHttpPost(string $url, $data = [], $header = [], $json = true, $headerStatus = false)
  1592. {
  1593. return getHttp('POST', $url, $data, $header, $headerStatus);
  1594. }
  1595. /**
  1596. * GET 数组数据处理为拼接字符串
  1597. *
  1598. * @param array $query 处理的数据数组
  1599. * @param boolean $isUrl 是否是URL参数标识(是的话,返回的字符串前缀加?标识)
  1600. *
  1601. * @return string
  1602. */
  1603. function assemblyByQuery($query, $isUrl = false)
  1604. {
  1605. ksort($query);
  1606. $queryData = '';
  1607. foreach ($query as $key => $value) {
  1608. if (!$queryData) {
  1609. if ($isUrl) {
  1610. $queryData = '?';
  1611. }
  1612. $queryData .= $key . '=' . $value;
  1613. } else {
  1614. $queryData .= '&' . $key . '=' . $value;
  1615. }
  1616. }
  1617. return $queryData;
  1618. }
  1619. //获取真实IP,可以根据实际情况自行获取
  1620. function getUserIp()
  1621. {
  1622. try {
  1623. $info = getCurl('https://myip.ipip.net');
  1624. if (!$info) {
  1625. $info = file_get_contents('http://myip.ipip.net');
  1626. }
  1627. $ipstr = explode(':', $info);
  1628. $ip = explode(' ', $ipstr[1]);
  1629. return $ip[0];
  1630. } catch (Exception $e) {
  1631. return request()->ip();
  1632. }
  1633. }
  1634. /**
  1635. * 为支付方式增加其他附加支付类型
  1636. * conin- = 代金卷
  1637. * mix- = 专属平台币(目前好像没用)
  1638. *
  1639. * @param $list
  1640. *
  1641. * @return array
  1642. */
  1643. function handlePayType($list)
  1644. {
  1645. $newList = [];
  1646. $markList = ['coin-', 'mix-'];
  1647. foreach ($list as $key => $value) {
  1648. $newPayType = [];
  1649. foreach ($value as $value1) {
  1650. $newPayType[] = $value1;
  1651. foreach ($markList as $value2) {
  1652. $newPayType[] = $value2 . $value1;
  1653. }
  1654. }
  1655. $newList[$key] = $newPayType;
  1656. }
  1657. return $newList;
  1658. }
  1659. /**
  1660. * 判断二维数组中是否包含某个字符串
  1661. *
  1662. * @param $arr array 二维数组
  1663. * @param $searchValue string 包含值
  1664. *
  1665. * @return bool
  1666. */
  1667. function isInArrType($arr, $searchValue)
  1668. {
  1669. foreach ($arr as $key => $values) {
  1670. if (in_array($searchValue, $values)) {
  1671. return true;
  1672. }
  1673. }
  1674. return false;
  1675. }
  1676. /**
  1677. * 获取游戏的分包域名地址
  1678. * 配置了则走CDN域名,没有则走默认分包服务器
  1679. *
  1680. * @param $game_id
  1681. *
  1682. * @return string
  1683. */
  1684. function getHandleCdnGamesByIds($game_id)
  1685. {
  1686. $result = (new Setting())->getSetting('handle_cdn_games');
  1687. if ($result) {
  1688. if ($result == 'all') {
  1689. return APK_DOWN_DOMAIN_NEW;
  1690. }
  1691. $res = json_decode($result, true);
  1692. if (in_array($game_id, $res)) {
  1693. return APK_DOWN_DOMAIN_NEW;
  1694. }
  1695. }
  1696. return APK_DOWN_DOMAIN;
  1697. }
  1698. function getChannelH5Url($code, $gameId){
  1699. $h5_url = (new Setting)::getSetting('HTTP_HOST_URL_H5');
  1700. return $h5_url.'/?c='. $code.'&g='.$gameId;
  1701. }
  1702. if (!function_exists('definition_log')) {
  1703. function definition_log($pathType, $message, $level = 'info') {
  1704. $customLogPath = LOG_PATH . "definition/{$pathType}/";
  1705. // dump($customLogPath);
  1706. static $logInited = false;
  1707. if (!$logInited) {
  1708. \think\Log::init([
  1709. // 日志记录方式,内置 file socket 支持扩展
  1710. 'type' => 'File',
  1711. // 日志保存目录
  1712. 'path' => $customLogPath,
  1713. // 日志记录级别
  1714. 'level' => ['log', 'error', 'notice', 'info', 'debug', 'sql'],
  1715. 'max_files' => 30,
  1716. 'realtime_write' => true,
  1717. ]);
  1718. $logInited = true;
  1719. }
  1720. \think\Log::write($message, $level);
  1721. }
  1722. }
  1723. /**
  1724. * 获取游戏绑定的其他端游戏ID
  1725. *
  1726. * @param $gameId
  1727. *
  1728. * @return array|mixed
  1729. * @throws DataNotFoundException
  1730. * @throws DbException
  1731. * @throws ModelNotFoundException
  1732. */
  1733. function getBandGameId($gameId){
  1734. $ameBandList = Db::table('nw_game_band')->select();
  1735. $newBandGameList = [];
  1736. foreach($ameBandList as $v){
  1737. if(!empty($v['android_game_id'])){
  1738. $newBandGameList[$v['android_game_id']] = [$v['ios_game_id'], $v['h5_game_id']];
  1739. }
  1740. if(!empty($v['ios_game_id'])){
  1741. $newBandGameList[$v['ios_game_id']] = [$v['android_game_id'], $v['h5_game_id']];
  1742. }
  1743. if(!empty($v['h5_game_id'])){
  1744. $newBandGameList[$v['h5_game_id']] = [$v['android_game_id'], $v['ios_game_id']];
  1745. }
  1746. }
  1747. if(empty($newBandGameList[$gameId])){
  1748. return [];
  1749. }
  1750. return $newBandGameList[$gameId]; // [20, 30]
  1751. }
  1752. /**
  1753. * 清理金额输入,保留两位小数
  1754. *
  1755. * @param $value
  1756. *
  1757. * @return float
  1758. */
  1759. function cleanAmount($value) {
  1760. /**
  1761. * ¥1,000.00 => 1000.00
  1762. * $2,345.67 => 2345.67
  1763. * 1 234.50元 => 1234.50
  1764. * 3.000,50 => 3000.50
  1765. * abc1234.56def => 1234.56
  1766. */
  1767. // 1. 转为字符串,防止传入非字符串类型
  1768. $value = (string)$value;
  1769. // 2. 去掉所有非数字、小数点、负号
  1770. $value = preg_replace('/[^\d.\-]/', '', $value);
  1771. // 3. 防止多个小数点导致格式错误,只保留第一个
  1772. if (substr_count($value, '.') > 1) {
  1773. $parts = explode('.', $value, 2);
  1774. $value = $parts[0] . '.' . preg_replace('/\./', '', $parts[1]);
  1775. }
  1776. return (float)$value;
  1777. // 4. 转为浮点数并保留两位小数(或根据需求改为字符串)
  1778. // return number_format((float)$value, 2, '.', '');
  1779. }
  1780. // 根据渠道ID获取渠道所属的上级渠道ID
  1781. function getChannel($channel_id)
  1782. {
  1783. // 进程级静态缓存,一次请求只读一次文件
  1784. static $channelList = null;
  1785. if ($channelList === null) {
  1786. $channelList = Cache::store('File')->get('cache_retaine_channel_list');
  1787. if (!$channelList) {
  1788. $channelList = model('common/Channel')->column('id,name,id_path,level', 'id');
  1789. Cache::store('File')->set('cache_retaine_channel_list', $channelList, 3600);
  1790. }
  1791. }
  1792. if (!isset($channelList[$channel_id])) {
  1793. return [];
  1794. }
  1795. $data = [];
  1796. $id_path = explode(',', $channelList[$channel_id]['id_path']);
  1797. foreach ($id_path as $vv) {
  1798. if ($vv == $channel_id || !isset($channelList[$vv])) {
  1799. continue;
  1800. }
  1801. $ch = $channelList[$vv];
  1802. if ($ch['level'] == 0) {
  1803. $data['s_channel_id'] = $ch['id'];
  1804. } elseif ($ch['level'] == 1) {
  1805. $data['b_channel_id'] = $ch['id'];
  1806. } elseif ($ch['level'] == 2) {
  1807. $data['bz_channel_id'] = $ch['id'];
  1808. }
  1809. }
  1810. return $data;
  1811. }
  1812. /**
  1813. * 解析 URL 参数,保留 + 号不转换成空格
  1814. * PHP 的 parse_str() 和 $_POST 会自动把 + 转成空格,导致签名验证失败
  1815. *
  1816. * @param string $queryString 原始查询字符串
  1817. * @return array 解析后的参数数组
  1818. */
  1819. function parseParamsKeepPlus($queryString)
  1820. {
  1821. $params = [];
  1822. if (empty($queryString)) {
  1823. return $params;
  1824. }
  1825. $pairs = explode('&', $queryString);
  1826. foreach ($pairs as $pair) {
  1827. $parts = explode('=', $pair, 2);
  1828. if (count($parts) === 2) {
  1829. // 只解码 %XX 格式的编码,保留 + 号
  1830. $key = rawurldecode($parts[0]);
  1831. $value = rawurldecode($parts[1]);
  1832. $params[$key] = $value;
  1833. }
  1834. }
  1835. return $params;
  1836. }