Helpers.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  1. <?php
  2. use GuzzleHttp\Client;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Log;
  5. use Monolog\Handler\StreamHandler;
  6. use Monolog\Logger;
  7. use OSS\OssClient;
  8. use OSS\Core\OssException;
  9. /**
  10. * 截取字符串
  11. *
  12. * @param $string
  13. * @param $length
  14. * @param bool $append
  15. * @return array|string
  16. */
  17. function sysSubStr($string, $length, $append = false)
  18. {
  19. if (strlen($string) <= $length) {
  20. return $string;
  21. }
  22. $i = 0;
  23. $stringLast = [];
  24. while ($i < $length) {
  25. $stringTMP = mb_substr($string, $i, 1);
  26. if (ord($stringTMP) >= 224) {
  27. $stringTMP = mb_substr($string, $i, 3);
  28. $i += 3;
  29. } elseif (ord($stringTMP) >= 192) {
  30. $stringTMP = mb_substr($string, $i, 2);
  31. $i += 2;
  32. } else {
  33. ++$i;
  34. }
  35. $stringLast[] = $stringTMP;
  36. }
  37. $stringLast = implode('', $stringLast);
  38. if ($append) {
  39. $stringLast .= '...';
  40. }
  41. return $stringLast;
  42. }
  43. /**
  44. * 自定义日志
  45. *
  46. * @param $name
  47. * @param string $filename
  48. * @return \Illuminate\Log\Writer
  49. */
  50. function myLog($name, $filename = '')
  51. {
  52. if (!$filename) {
  53. $filename = $name;
  54. }
  55. $filename = $filename . '.log';
  56. $logger = new Logger($name);
  57. $writer = new \Illuminate\Log\Writer($logger);
  58. $writer->useDailyFiles(storage_path('logs/' . $filename));
  59. return $writer;
  60. }
  61. /**
  62. * 业务调试日志
  63. *
  64. * @return Logger
  65. */
  66. function commonLog()
  67. {
  68. $name = 'common';
  69. $filename = $name . '.log';
  70. $logger = new Logger($name);
  71. $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
  72. return $logger;
  73. }
  74. /**
  75. * @param $name
  76. * @return Logger
  77. */
  78. function dLog($name)
  79. {
  80. $filename = $name . '-' . date('Y-m-d') . '.log';
  81. $logger = new Logger($name);
  82. $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
  83. return $logger;
  84. }
  85. /**
  86. * 获取对象或数组的属性值
  87. *
  88. * @param $param
  89. * @param $key
  90. * @param string $default
  91. * @return mixed|string
  92. */
  93. function getProp($param, $key, $default = '')
  94. {
  95. $result = $default;
  96. if (is_object($param) && isset($param->$key)) {
  97. $result = $param->$key;
  98. }
  99. if (is_array($param) && isset($param[$key])) {
  100. $result = $param[$key];
  101. }
  102. return $result;
  103. }
  104. /**
  105. * @param $data
  106. * @param array $trans
  107. * @return array
  108. */
  109. function assetData($data, $trans = []): array
  110. {
  111. $result = [];
  112. if (empty($data)) {
  113. return $result;
  114. }
  115. if (empty($trans)) {
  116. return $data;
  117. }
  118. foreach ($trans as $tran) {
  119. [$originKey, $newKey, $conv, $default] = [$tran['o'], $tran['n'], $tran['conv'], $tran['default']];
  120. if (isset($data[$originKey])) {
  121. $result[$newKey] = $conv(getProp($data, $originKey, $default));
  122. }
  123. }
  124. return $result;
  125. }
  126. /**
  127. * 随机数
  128. *
  129. * @param int $num
  130. * @return string
  131. * @throws Exception
  132. */
  133. function random($num = 16)
  134. {
  135. $bytes = random_bytes($num);
  136. return bin2hex($bytes);
  137. }
  138. /**
  139. * 生成订单
  140. *
  141. * @param string $prefix 订单前缀
  142. * @return string
  143. */
  144. function generateOrderSn($prefix = '')
  145. {
  146. return $prefix . date('YmdHis') . getMillisecond() . rand(1000, 9999);
  147. }
  148. /**
  149. * 分页数据
  150. *
  151. * @param $data
  152. * @return array
  153. */
  154. function getMeta($data)
  155. {
  156. $currentPage = (int)$data->currentPage();
  157. $lastPage = (int)$data->lastPage();
  158. return [
  159. 'current_page' => $currentPage,
  160. 'next_page' => $currentPage >= $lastPage ? $lastPage : ++$currentPage,
  161. 'last_page' => $lastPage,
  162. 'per_page' => (int)$data->perPage(),
  163. 'total' => (int)$data->total(),
  164. 'is_end' => !$data->hasMorePages(),
  165. 'next_page_url' => (string)$data->nextPageUrl(),
  166. 'prev_page_url' => (string)$data->previousPageUrl()
  167. ];
  168. }
  169. /**
  170. * 钉钉通知异常
  171. *
  172. * @param $message
  173. */
  174. function sendNotice($message)
  175. {
  176. $webHook = env('DD_WEB_HOOK');
  177. $data = [
  178. 'msgtype' => 'text',
  179. 'text' => [
  180. 'content' => $message
  181. ],
  182. 'at' => [
  183. 'isAll' => true
  184. ]
  185. ];
  186. // 异步发送
  187. $client = new GuzzleHttp\Client();
  188. $client->post($webHook, ['json' => $data]);
  189. }
  190. /**
  191. * 判断数据是合法的json数据
  192. *
  193. * @param $string
  194. * @return bool
  195. */
  196. function is_json($string)
  197. {
  198. json_decode($string);
  199. return (json_last_error() == JSON_ERROR_NONE);
  200. }
  201. /**
  202. * 获取ip地址
  203. *
  204. * @return mixed|string
  205. */
  206. function getIpAddr()
  207. {
  208. $ipaddress = '';
  209. if (isset($_SERVER['HTTP_CLIENT_IP']))
  210. $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  211. else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  212. $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  213. else if (isset($_SERVER['HTTP_X_FORWARDED']))
  214. $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  215. else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
  216. $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  217. else if (isset($_SERVER['HTTP_FORWARDED']))
  218. $ipaddress = $_SERVER['HTTP_FORWARDED'];
  219. else if (isset($_SERVER['REMOTE_ADDR']))
  220. $ipaddress = $_SERVER['REMOTE_ADDR'];
  221. else
  222. $ipaddress = 'UNKNOWN';
  223. return $ipaddress;
  224. }
  225. /**
  226. * @param int $num
  227. * @return bool|string
  228. * @throws Exception
  229. */
  230. function randStr($num = 5)
  231. {
  232. $str = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm';
  233. return substr(str_shuffle($str), random_int(0, strlen($str) - 11), $num);
  234. }
  235. /**
  236. * 上传文件
  237. *
  238. * @param $prefix 文件夹前缀
  239. * @param $file 文件二进制
  240. * @param $filename 文件名
  241. * @return mixed
  242. */
  243. function uploadFile($prefix, $file, $filename='')
  244. {
  245. // 阿里云主账号
  246. $accessKeyId = env('OSS_ACCESS_ID');
  247. $accessKeySecret = env('OSS_ACCESS_KEY');
  248. $endpoint = env('OSS_END_POINT');
  249. $bucket = env('OSS_BUCKET');
  250. if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  251. // 设置文件名称。
  252. $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
  253. $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
  254. try {
  255. $configs = [
  256. "provider" => $provider,
  257. "endpoint" => $endpoint,
  258. "signatureVersion" => 'v4',
  259. "region" => "cn-hangzhou"
  260. ];
  261. $ossClient = new OssClient($configs);
  262. $uploadRes = $ossClient->uploadFile($bucket, $object, $file->path());
  263. } catch (OssException $e) {
  264. dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
  265. return '';
  266. }
  267. // 替换域名
  268. if (!isset($uploadRes['oss-request-url'])) return '';
  269. $imageUrl = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
  270. return str_ireplace('http://', 'https://', $imageUrl);
  271. }
  272. /**
  273. * 上传文件流
  274. *
  275. * @param $prefix 文件夹前缀
  276. * @param $file 文件二进制
  277. * @param $filename 文件名
  278. * @return mixed
  279. */
  280. function uploadStreamToOss($prefix, $stream, $filename) {
  281. $accessKeyId = env('OSS_ACCESS_ID');
  282. $accessKeySecret = env('OSS_ACCESS_KEY');
  283. $endpoint = env('OSS_END_POINT');
  284. $bucket = env('OSS_BUCKET');
  285. if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  286. // 设置文件名称。
  287. $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
  288. $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
  289. try{
  290. $configs = [
  291. "provider" => $provider,
  292. "endpoint" => $endpoint,
  293. "signatureVersion" => 'v4',
  294. "region"=> "cn-hangzhou"
  295. ];
  296. $ossClient = new OssClient($configs);
  297. $uploadRes = $ossClient->putObject($bucket, $object, $stream);
  298. } catch (OssException $e) {
  299. dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
  300. return '';
  301. }
  302. // 替换域名
  303. if (!isset($uploadRes['oss-request-url'])) return '';
  304. $imageUrl = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
  305. return str_ireplace('http://', 'https://', $imageUrl);
  306. }
  307. /**
  308. * 下载文件到本地
  309. *
  310. * @param $object
  311. * @param $localFile
  312. * @return string
  313. */
  314. function downloadFile($object, $localFile)
  315. {
  316. // 阿里云主账号
  317. $accessKeyId = env('OSS_ACCESS_ID');
  318. $accessKeySecret = env('OSS_ACCESS_KEY');
  319. $endpoint = env('OSS_END_POINT');
  320. $bucket = env('OSS_BUCKET');
  321. try {
  322. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  323. $ossClient->getObject($bucket, $object, [
  324. OssClient::OSS_FILE_DOWNLOAD => $localFile
  325. ]);
  326. } catch (OssException $e) {
  327. printf($e->getMessage());
  328. return '';
  329. }
  330. }
  331. /**
  332. * 上传封面
  333. *
  334. * @param $file
  335. * @return string
  336. * @throws Exception
  337. */
  338. function uploadCoverFile($file)
  339. {
  340. // 阿里云主账号
  341. $accessKeyId = env('OSS_ACCESS_ID');
  342. $accessKeySecret = env('OSS_ACCESS_KEY');
  343. $endpoint = env('OSS_END_POINT');
  344. $bucket = env('OSS_BUCKET');
  345. // 设置文件名称。
  346. $object = 'books/cover/' . randStr(10) . '.' . $file->getClientOriginalExtension();
  347. try {
  348. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  349. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  350. } catch (OssException $e) {
  351. printf($e->getMessage());
  352. return '';
  353. }
  354. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  355. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  356. }
  357. function uploadAgreementFile($file)
  358. {
  359. // 阿里云主账号
  360. $accessKeyId = env('OSS_ACCESS_ID');
  361. $accessKeySecret = env('OSS_ACCESS_KEY');
  362. $endpoint = env('OSS_END_POINT');
  363. $bucket = env('OSS_BUCKET');
  364. $file_name = $file->getClientOriginalName();
  365. $file_name = str_replace('.' . $file->getClientOriginalExtension(), '', $file_name);
  366. // 设置文件名称。
  367. $object = 'books/contract/' . $file_name . '-' . date('YmdHi') . '.' . $file->getClientOriginalExtension();
  368. try {
  369. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  370. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file);
  371. } catch (OssException $e) {
  372. printf($e->getMessage());
  373. return '';
  374. }
  375. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  376. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . urldecode(getProp($urlArr, 'path')) : '';
  377. }
  378. /**
  379. * 上传wap推荐图片
  380. *
  381. * @param $file
  382. * @param $filename
  383. * @return string
  384. * @throws Exception
  385. */
  386. function uploadWapRecommendPic($file, $filename)
  387. {
  388. // 阿里云主账号
  389. $accessKeyId = env('OSS_ACCESS_ID');
  390. $accessKeySecret = env('OSS_ACCESS_KEY');
  391. $endpoint = env('OSS_END_POINT');
  392. $bucket = env('OSS_BUCKET_YCSD');
  393. // 设置文件名称。
  394. $object = 'ycsd_web_3nd/images/homebanners/' . $filename . '.' . $file->getClientOriginalExtension();
  395. try {
  396. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  397. $options = array(
  398. OssClient::OSS_HEADERS => array(
  399. 'Content-Type' => 'image/jpeg',
  400. 'Content-Disposition' => 'inline'
  401. ),
  402. );
  403. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path(), $options);
  404. } catch (OssException $e) {
  405. printf($e->getMessage());
  406. return '';
  407. }
  408. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  409. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  410. }
  411. /**
  412. * @param $path
  413. * @return Generator
  414. */
  415. function readFileContent($path)
  416. {
  417. if ($handle = fopen($path, 'r')) {
  418. while (!feof($handle)) {
  419. yield trim(fgets($handle));
  420. }
  421. fclose($handle);
  422. }
  423. }
  424. function exportFileCsv(array $headers, array $data, string $filename)
  425. {
  426. header("Content-type:application/vnd.ms-excel");
  427. header("Content-Disposition:attachment;filename=" . $filename . ".csv");
  428. $headers = collect($headers)->map(function ($item) {
  429. return "\"" . mb_convert_encoding($item, "GBK", "UTF-8") . "\"";
  430. })->all();
  431. echo implode(",", $headers);
  432. echo "\r\n";
  433. foreach ($data as $item) {
  434. $rows = collect($item)->map(function ($row) {
  435. return "\"" . mb_convert_encoding(is_numeric($row) && strlen($row) > 12 ? "'" . $row : $row, "GBK", "UTF-8") . "\"";
  436. })->all();
  437. echo implode(",", $rows);
  438. echo "\r\n";
  439. }
  440. exit();
  441. }
  442. //function exportFileCsv(array $header, array $data, string $filename) {
  443. // header('Content-Encoding: UTF-8');
  444. // header("Content-type:application/vnd.ms-excel;charset=UTF-8");
  445. // header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
  446. //
  447. // //打开php标准输出流
  448. // $fp = fopen('php://output', 'a');
  449. //
  450. // //添加BOM头,以UTF8编码导出CSV文件,如果文件头未添加BOM头,打开会出现乱码。
  451. // fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
  452. // //添加导出标题
  453. // fputcsv($fp, $header);
  454. //
  455. // foreach ($data as $k => $item) {
  456. // fputcsv($fp, $item);
  457. // if ($k % 5000 == 0) {
  458. // //每1万条数据就刷新缓冲区
  459. // ob_flush();
  460. // flush();
  461. // }
  462. // }
  463. // exit();
  464. //}
  465. //function exportFileCsv(array $header, array $data, string $filename) {
  466. //
  467. // header('Content-Type: application/vnd.ms-excel');
  468. // header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
  469. // header('Cache-Control: max-age=0');
  470. //
  471. // //打开PHP文件句柄,php://output 表示直接输出到浏览器
  472. // $fp = fopen('php://output', 'a');
  473. //
  474. // //输出Excel列名信息
  475. // foreach ($header as $key => $value) {
  476. // //CSV的Excel支持GBK编码,一定要转换,否则乱码
  477. // $header[$key] = iconv('utf-8', 'gbk', $value);
  478. // }
  479. //
  480. // //将数据通过fputcsv写到文件句柄
  481. // fputcsv($fp, $header);
  482. //
  483. // //计数器
  484. // $num = 0;
  485. //
  486. // //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
  487. // $limit = 10000;
  488. //
  489. // //逐行取出数据,不浪费内存
  490. // $count = count($data);
  491. // for ($i = 0; $i < $count; $i++) {
  492. //
  493. // $num++;
  494. //
  495. // //刷新一下输出buffer,防止由于数据过多造成问题
  496. // if ($limit == $num) {
  497. // ob_flush();
  498. // flush();
  499. // $num = 0;
  500. // }
  501. //
  502. // $row = $data[$i];
  503. // foreach ($row as $key => $value) {
  504. // $row[$key] = iconv('utf-8', 'gbk', $value);
  505. // }
  506. //
  507. // fputcsv($fp, $row);
  508. // }
  509. // exit();
  510. //}
  511. // 获取除空格外的字数
  512. function getSize(string $content)
  513. {
  514. $content = preg_replace('/\s+/', '', $content);
  515. return mb_strlen($content, 'utf-8');
  516. }
  517. // 获取word字符数(不计空格)
  518. function getChargeSize(string $content)
  519. {
  520. //判断是否存在替换字符
  521. $is_replace_count = substr_count($content, "龘");
  522. try {
  523. //先将回车换行符做特殊处理
  524. $str = preg_replace('/(\r\n+|\s+| +)/', "龘", $content);
  525. //处理英文字符数字,连续字母、数字、英文符号视为一个单词
  526. $str = preg_replace('/[a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",\'<>~`\?:;|]/', "m", $str);
  527. //合并字符m,连续字母、数字、英文符号视为一个单词
  528. $str = preg_replace('/m+/', "*", $str);
  529. //去掉回车换行符
  530. $str = preg_replace('/龘+/', "", $str);
  531. //返回字数
  532. return mb_strlen($str) + $is_replace_count;
  533. } catch (\Exception $e) {
  534. return 0;
  535. }
  536. }
  537. // 将阿拉伯数字转换成中文
  538. function chineseNum($figure, $capital = false, $mode = true)
  539. {
  540. if ($figure == '0') return '零';
  541. $numberChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  542. $unitChar = ['', '十', '百', '千', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
  543. if ($capital !== false) {
  544. $numberChar = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  545. $unitChar = ['', '拾', '佰', '仟', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
  546. }
  547. $dec = "点";
  548. $target = '';
  549. $matches = [];
  550. if ($mode) {
  551. preg_match("/^0*(\d*)\.?(\d*)/", $figure, $matches);
  552. } else {
  553. preg_match("/(\d*)\.?(\d*)/", $figure, $matches);
  554. }
  555. list(, $number, $point) = $matches;
  556. if ($point) {
  557. $target = $dec . chineseNum($point, $capital, false);
  558. }
  559. if (!$number) {
  560. return $target;
  561. }
  562. $str = strrev($number);
  563. for ($i = 0; $i < strlen($str); $i++) {
  564. $out[$i] = $numberChar[$str[$i]];
  565. if ($mode === false) {
  566. continue;
  567. }
  568. $out[$i] .= $str[$i] != '0' ? $unitChar[$i % 4] : '';
  569. if ($i > 0 && $str[$i] + $str[$i - 1] == 0) {
  570. $out[$i] = '';
  571. }
  572. if ($i % 4 == 0) {
  573. $temp = substr($str, $i, 4);
  574. $out[$i] = str_replace($numberChar[0], '', $out[$i]);
  575. if (strrev($temp) > 0) {
  576. $out[$i] .= $unitChar[4 + floor($i / 4)];
  577. } else {
  578. $out[$i] .= $numberChar[0];
  579. }
  580. }
  581. }
  582. $result = join('', array_reverse($out)) . $target;
  583. return mb_substr($result, 0, 2) == '一十' ? mb_substr($result, 1) : $result;
  584. }
  585. function addPrefix($str)
  586. {
  587. if (!$str) return '';
  588. if (mb_substr($str, 0, 4) == 'http') return $str;
  589. if (mb_substr($str, 0, 5) == 'https') return $str;
  590. if (mb_substr($str, 0, 7) == '/books/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  591. if (mb_substr($str, 0, 6) == '/card/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  592. if (mb_substr($str, 0, 15) == 'uploader/idcard') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com/' . $str;
  593. if (mb_substr($str, 0, 6) == '/cover') return 'https://cdn-newyc.ycsd.cn/ycsd_cover/covermiddle' . mb_substr($str, 6);
  594. if (mb_substr($str, 0, 8) == '/images/') return 'https://cdn-newyc.ycsd.cn/ycsd_cover' . $str;
  595. }
  596. /**
  597. * 章节内容排版
  598. *
  599. * @param $content
  600. * @return string
  601. */
  602. function filterContent($content)
  603. {
  604. if (!$content) return '';
  605. $content = str_replace(
  606. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  607. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  608. $content);
  609. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  610. // 段落首字母前加两个中文空格
  611. $string = explode(PHP_EOL, $content);
  612. foreach ($string as $line => $text) {
  613. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' '], '', $string[$line]);
  614. if (!$string[$line]) {
  615. unset($string[$line]);
  616. } else {
  617. $string[$line] = $string[$line] . PHP_EOL;
  618. // if (mb_substr($string[$line], 0, 1) == ' ') {
  619. // $string[$line] = str_replace(' ', '', $string[$line]); // 去除多个空格
  620. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  621. // }
  622. // if (mb_substr($string[$line], 0, 2) != '  ') {
  623. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  624. // }
  625. // if (mb_substr($string[$line], 0, 2) == '  ' && str_replace(' ', '', $string[$line])) {
  626. // $string[$line] .= PHP_EOL;
  627. // }
  628. }
  629. }
  630. $content = implode(PHP_EOL, $string);
  631. return $content;
  632. }
  633. /**
  634. * 书籍简介排版
  635. *
  636. * @param $content
  637. * @return string
  638. */
  639. function filterContent2($content)
  640. {
  641. if (!$content) return '';
  642. $content = str_replace(
  643. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  644. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  645. $content);
  646. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  647. // 段落首字母前加两个中文空格
  648. $string = explode(PHP_EOL, $content);
  649. $content = '';
  650. foreach ($string as $line => $text) {
  651. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  652. if (!$string[$line]) {
  653. unset($string[$line]);
  654. } else {
  655. $string[$line] = '  ' . $string[$line] . '<br />';
  656. $content .= $string[$line];
  657. }
  658. }
  659. $content = trim($content, '<br />');
  660. return $content;
  661. }
  662. /**
  663. * 书籍简介排版-抖音版
  664. *
  665. * @param $content
  666. * @return string
  667. */
  668. function filterIntro($content)
  669. {
  670. if (!$content) return '';
  671. $content = str_replace(
  672. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  673. [' ', ' ', ' ', ' ', ' ', '', ' ', '“', '”', '...', '‘', '’', '-'],
  674. $content);
  675. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  676. // 段落首字母前加两个中文空格
  677. $string = explode(PHP_EOL, $content);
  678. $content = '';
  679. foreach ($string as $line => $text) {
  680. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  681. if (!$string[$line]) {
  682. unset($string[$line]);
  683. } else {
  684. $content .= $string[$line];
  685. }
  686. }
  687. $content = trim($content, '<br />');
  688. return $content;
  689. }
  690. function sensitiveStr($list, $string)
  691. {
  692. $count = 0; //违规词的个数
  693. $sensitiveWord = ''; //违规词
  694. $stringAfter = $string; //替换后的内容
  695. $total = count($list);
  696. $size = 500;
  697. $last = ceil($total / $size);
  698. $patternList = [];
  699. for ($page = 1; $page <= $last; $page++) {
  700. $arr = array_slice($list, $size * ($page - 1), $size);
  701. $filter = [];
  702. foreach ($arr as $v) {
  703. if (preg_match('/[^a-zA-Z0-9\|\p{Han}\·]/u', $v)) continue;
  704. $filter[] = $v;
  705. // $a = preg_replace('/[^a-zA-Z0-9\|\p{Han}]/u', '', $v);
  706. // if ($a) $filter[] = $a;
  707. }
  708. $pattern = "/" . implode("|", $filter) . "/i"; //定义正则表达式
  709. if (preg_match_all($pattern, $string, $matches)) { //匹配到了结果
  710. $patternList = array_merge($patternList, $matches[0]); //匹配到的数组
  711. }
  712. }
  713. $sensitiveWord = '';
  714. if ($patternList) {
  715. $count = count($patternList);
  716. // $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
  717. $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '*')); //把匹配到的数组进行合并,替换使用
  718. $stringAfter = strtr($string, $replaceArray); //结果替换
  719. // 将敏感词合并
  720. $return_pattern = [];
  721. foreach ($patternList as $v) {
  722. if (!isset($return_pattern[$v])) {
  723. $return_pattern[$v] = [
  724. 'word' => $v,
  725. 'count' => 1,
  726. ];
  727. } else {
  728. $return_pattern[$v]['count'] += 1;
  729. }
  730. }
  731. foreach ($return_pattern as $v) {
  732. $sensitiveWord .= $v['word'] . ',';
  733. }
  734. }
  735. return [
  736. 'count' => $count,
  737. 'sensitive_words' => trim($sensitiveWord, ','),
  738. 'content' => $stringAfter
  739. ];
  740. }
  741. /**
  742. * 转换时间格式
  743. *
  744. * @param $date
  745. * @param string $format
  746. * @return false|string
  747. */
  748. function transDate($date, $format = 'Y-m-d H:i:s')
  749. {
  750. return strtotime($date) > 0 ? date($format, strtotime($date)) : '';
  751. }
  752. /**
  753. * 根据网段获取计算所有IP
  754. *
  755. * @param string $segment 网段 '139.217.0.1/24'
  756. * @return array [网络地址:139.217.0.1 广播地址:139.217.0.255 IP列表: ['139.217.0.2','139.217.0.3'……'139.217.0.254']]
  757. */
  758. function getIpBySegment($segment)
  759. {
  760. $segmentInfo = explode("/", $segment);
  761. $beginIpArray = explode(".", $segmentInfo[0]);
  762. $mask = intval($segmentInfo['1']);
  763. $endIp = array();
  764. foreach ($beginIpArray as $ipKey => $item) {
  765. $beginFlag = 8 * ($ipKey); //0 8 16 24
  766. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  767. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  768. $endIp[] = $mask >= $endFlag ? $item : ($mask > $beginFlag ? bindec(str_pad(substr($decbinItem, 0, $mask - $beginFlag), 8, "1", STR_PAD_RIGHT)) : ($ipKey <= 2 ? pow(2, 8) - 1 : pow(2, 8) - 1));
  769. }
  770. $ipArray = array();
  771. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0]++) {
  772. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1]++) {
  773. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2]++) {
  774. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3]++) {
  775. $ipArray[] = implode(".", $beginIp);
  776. }
  777. }
  778. }
  779. }
  780. $network_ip_addr = $beginIpArray[0] . '.' . $beginIpArray[1] . '.' . $beginIpArray[2] . '.' . '0'; // 网络地址
  781. $broadcast_ip_addr = end($ipArray); // 广播地址
  782. if ($ipArray[0] == $network_ip_addr) { // 如果是网络地址则删掉
  783. unset($ipArray[0]);
  784. }
  785. $last = count($ipArray);
  786. unset($ipArray[$last]);
  787. return [$network_ip_addr, $broadcast_ip_addr, $ipArray];
  788. }
  789. /**
  790. * 在指定网段中分配子网段
  791. *
  792. * @param string $segment 指定网段
  793. * @param int $ipNum 需要的IP数
  794. * @param array $usedIpArray 不可用(已经使用)的IP,默认为空数组
  795. * @return bool|string 成功则返回分配的网段
  796. */
  797. function allocateSegment($segment, $ipNum, $usedIpArray = [])
  798. {
  799. $usedIpArray = empty($usedIpArray) ? [] : array_flip($usedIpArray);
  800. //计算需要多少个IP
  801. $i = 0;
  802. $ipCount = pow(2, $i);
  803. while ($ipCount < $ipNum) {
  804. $i++;
  805. $ipCount = pow(2, $i);
  806. }
  807. $newMask = 32 - $i;
  808. //大网段的开始和结束IP
  809. $segmentInfo = explode("/", $segment); //['139.217.0.1',24]
  810. $beginIpArray = explode(".", $segmentInfo[0]);//[139,217,0,1]
  811. $mask = intval($segmentInfo['1']); //24
  812. if ($newMask < $mask) {
  813. return false;
  814. }
  815. $endIp = array();
  816. $step = [];
  817. foreach ($beginIpArray as $ipKey => $item) {
  818. $beginFlag = 8 * ($ipKey); //0 8 16 24
  819. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  820. $step[$ipKey] = $newMask > $endFlag ? 1 : ($endFlag - $newMask < 8 ? pow(2, $endFlag - $newMask) : pow(2, 8));
  821. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  822. $endIp[] = $mask >= $endFlag ? $item : ($mask > $beginFlag ? bindec(str_pad(substr($decbinItem, 0, $mask - $beginFlag), 8, "1", STR_PAD_RIGHT)) : ($ipKey <= 2 ? pow(2, 8) - 1 : pow(2, 8) - 1));
  823. }
  824. //遍历生成网段
  825. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0] += $step[0]) {
  826. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1] += $step[1]) {
  827. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2] += $step[2]) {
  828. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3] += $step[3]) {
  829. $newSegment = implode('.', $beginIp) . '/' . $newMask;
  830. //获取该网段所有的IP
  831. $ipArray = getIpBySegment($newSegment);
  832. $canUse = true;
  833. //判断该网段是否可用
  834. if (!empty($usedIpArray)) {
  835. foreach ($ipArray as $ip) {
  836. if (isset($usedIpArray[$ip])) {
  837. $canUse = false;
  838. break;
  839. }
  840. }
  841. }
  842. if ($canUse) {
  843. return $newSegment;
  844. }
  845. }
  846. }
  847. }
  848. }
  849. return false;
  850. }
  851. function remove_xss($val)
  852. {
  853. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  854. // this prevents some character re-spacing such as <java\0script>
  855. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
  856. $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
  857. // straight replacements, the user should never need these since they're normal characters
  858. // this prevents like <IMG SRC=@avascript:alert('XSS')>
  859. $search = 'abcdefghijklmnopqrstuvwxyz';
  860. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  861. $search .= '1234567890!@#$%^&*()';
  862. $search .= '~`";:?+/={}[]-_|\'\\';
  863. for ($i = 0; $i < strlen($search); $i++) {
  864. // ;? matches the ;, which is optional
  865. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  866. // @ @ search for the hex values
  867. $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
  868. // @ @ 0{0,7} matches '0' zero to seven times
  869. $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
  870. }
  871. // now the only remaining whitespace attacks are \t, \n, and \r
  872. $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  873. $ra2 = array(
  874. 'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'
  875. );
  876. $ra = array_merge($ra1, $ra2);
  877. $found = true; // keep replacing as long as the previous round replaced something
  878. while ($found == true) {
  879. $val_before = $val;
  880. for ($i = 0; $i < sizeof($ra); $i++) {
  881. $pattern = '/';
  882. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  883. if ($j > 0) {
  884. $pattern .= '(';
  885. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  886. $pattern .= '|';
  887. $pattern .= '|(�{0,8}([9|10|13]);)';
  888. $pattern .= ')*';
  889. }
  890. $pattern .= $ra[$i][$j];
  891. }
  892. $pattern .= '/i';
  893. $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
  894. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  895. if ($val_before == $val) {
  896. // no replacements were made, so exit the loop
  897. $found = false;
  898. }
  899. }
  900. }
  901. return $val;
  902. }
  903. /**
  904. * 计算作者积分等级
  905. *
  906. * @param $score
  907. */
  908. function calcAuthorLevel($score): int
  909. {
  910. switch (true) {
  911. case $score <= 0:
  912. $level = 0;
  913. break;
  914. case $score <= 5000:
  915. $level = 1;
  916. break;
  917. case $score <= 50000:
  918. $level = 2;
  919. break;
  920. case $score <= 100000:
  921. $level = 3;
  922. break;
  923. case $score <= 300000:
  924. $level = 4;
  925. break;
  926. case $score <= 800000:
  927. $level = 5;
  928. break;
  929. case $score <= 1500000:
  930. $level = 6;
  931. break;
  932. case $score <= 2500000:
  933. $level = 7;
  934. break;
  935. case $score <= 5000000:
  936. $level = 8;
  937. break;
  938. case $score <= 10000000:
  939. $level = 9;
  940. break;
  941. default:
  942. $level = 10;
  943. break;
  944. }
  945. return $level;
  946. }
  947. /**
  948. * 运营数据(上传附件)
  949. *
  950. * @param $file
  951. * @return string
  952. * @throws Exception
  953. */
  954. function uploadEnclosureFile($file)
  955. {
  956. // 阿里云主账号
  957. $accessKeyId = env('OSS_ACCESS_ID');
  958. $accessKeySecret = env('OSS_ACCESS_KEY');
  959. $endpoint = env('OSS_END_POINT');
  960. $bucket = env('OSS_BUCKET');
  961. // 设置文件名称。
  962. $object = 'books/enclosure/' . randStr(10) . '--' . $file->getClientOriginalName();
  963. try {
  964. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  965. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  966. } catch (OssException $e) {
  967. printf($e->getMessage());
  968. return '';
  969. }
  970. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  971. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  972. }
  973. // 获取当前域名是http还是https
  974. function getHttpType()
  975. {
  976. return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
  977. }
  978. // 根据id生成唯一邀请码
  979. function enCodeId($user_id)
  980. {
  981. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  982. $num = strlen($key);
  983. $code = ''; // 邀请码
  984. while ($user_id > 0) { // 转进制
  985. $mod = $user_id % $num; // 求模
  986. $user_id = ($user_id - $mod) / $num;
  987. $code = $key[$mod] . $code;
  988. }
  989. $code = str_pad($code, 6, 'A', STR_PAD_LEFT); // 不足用0补充
  990. return $code;
  991. }
  992. // 根据邀请码解密为id
  993. function deCodeId($code)
  994. {
  995. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  996. $num = strlen($key);
  997. if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0') + 1);
  998. $len = strlen($code);
  999. $code = strrev($code);
  1000. $user_id = 0;
  1001. for ($i = 0; $i < $len; $i++) {
  1002. $user_id += strpos($key, $code[$i]) * pow($num, $i);
  1003. }
  1004. return $user_id;
  1005. }
  1006. /**
  1007. * 将二维数组按其中的某个数组排序(此方法适用于将数据库数据按数组取出后自动按ID排序的情况 ps:即未按该数组排序)
  1008. *
  1009. * @param array $array 二维数组
  1010. * @param array $sort 排序数组
  1011. * @param string $field 排序字段(二维数组和排序数组相同的字段)
  1012. * @return array
  1013. */
  1014. function sortByArray(array $array, array $sort, string $field): array
  1015. {
  1016. $data = [];
  1017. if (is_array($array) && is_array($sort)) {
  1018. foreach ($sort as $v) {
  1019. foreach ($array as $key => $val) {
  1020. if ($v == $val[$field]) {
  1021. array_push($data, $array[$key]);
  1022. }
  1023. }
  1024. }
  1025. }
  1026. return $data;
  1027. }
  1028. /**
  1029. * 将二维数组按其中的字段排序(正序或倒序)
  1030. *
  1031. * @param array $array 二维数组
  1032. * @param string $field 排序字段
  1033. * @param mixed $type 排序方式(3倒序,4正序)
  1034. * @return array|mixed
  1035. */
  1036. function sortByField(array $array, string $field, $type): array
  1037. {
  1038. if (is_array($array)) {
  1039. array_multisort(array_column($array, $field), $type, $array);
  1040. }
  1041. return $array;
  1042. }
  1043. // 生成用户邀请码
  1044. function setUserInviteCode($id)
  1045. {
  1046. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->encode($id);
  1047. }
  1048. // 解密用户邀请码
  1049. function decodeUserInviteCode($code)
  1050. {
  1051. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->decode($code);
  1052. }
  1053. function getMillisecond()
  1054. {
  1055. list($microsecond, $time) = explode(' ', microtime());
  1056. return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
  1057. }
  1058. function get_client_ip($type = 0, $adv = false)
  1059. {
  1060. $type = $type ? 1 : 0;
  1061. static $ip = null;
  1062. if (null !== $ip) {
  1063. return $ip[$type];
  1064. }
  1065. if ($adv) {
  1066. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1067. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1068. $pos = array_search('unknown', $arr);
  1069. if (false !== $pos) {
  1070. unset($arr[$pos]);
  1071. }
  1072. $ip = trim($arr[0]);
  1073. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1074. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1075. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1076. $ip = $_SERVER['REMOTE_ADDR'];
  1077. }
  1078. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1079. $ip = $_SERVER['REMOTE_ADDR'];
  1080. }
  1081. // IP地址合法验证
  1082. $long = sprintf("%u", ip2long($ip));
  1083. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  1084. return $ip[$type];
  1085. }
  1086. /**
  1087. * 获取真实IP
  1088. */
  1089. function _getIp()
  1090. {
  1091. if (getenv('HTTP_X_FORWARDED_FOR')) {
  1092. $ip = getenv('HTTP_X_FORWARDED_FOR');
  1093. } else if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  1094. $ip = getenv("HTTP_CLIENT_IP");
  1095. else if (getenv("HTTP_X_FORWARD_FOR") && strcasecmp(getenv("HTTP_X_FORWARD_FOR"), "unknown"))
  1096. $ip = getenv("HTTP_X_FORWARD_FOR");
  1097. else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  1098. $ip = getenv("REMOTE_ADDR");
  1099. else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  1100. $ip = $_SERVER['REMOTE_ADDR'];
  1101. else
  1102. $ip = "unknown";
  1103. return ($ip);
  1104. }
  1105. /**
  1106. * 数组 转 对象
  1107. *
  1108. * @param array $arr 数组
  1109. * @return object
  1110. */
  1111. function array_to_object($arr)
  1112. {
  1113. if (gettype($arr) != 'array') {
  1114. return;
  1115. }
  1116. foreach ($arr as $k => $v) {
  1117. if (gettype($v) == 'array' || getType($v) == 'object') {
  1118. $arr[$k] = (object)array_to_object($v);
  1119. }
  1120. }
  1121. return (object)$arr;
  1122. }
  1123. /**
  1124. * 对象 转 数组
  1125. *
  1126. * @param object $obj 对象
  1127. * @return array
  1128. */
  1129. function object_to_array($obj)
  1130. {
  1131. $obj = (array)$obj;
  1132. foreach ($obj as $k => $v) {
  1133. if (gettype($v) == 'resource') {
  1134. return;
  1135. }
  1136. if (gettype($v) == 'object' || gettype($v) == 'array') {
  1137. $obj[$k] = (array)object_to_array($v);
  1138. }
  1139. }
  1140. return $obj;
  1141. }
  1142. /**
  1143. * 检查是否为手机号码
  1144. */
  1145. function _isPhone($number)
  1146. {
  1147. return preg_match("/^1[34578][0-9]{9}$/", $number);
  1148. }
  1149. /**
  1150. * 判断所传的参数是否缺少,如果缺少返回渠道的字段,正确返回0
  1151. *
  1152. * @param array $param
  1153. * @param array $must
  1154. * @return int|mixed
  1155. */
  1156. function checkParam(array $param, array $must)
  1157. {
  1158. foreach ($must as $item) {
  1159. if (array_key_exists($item, $param) && $param[$item] != '') {
  1160. } else {
  1161. return $item;
  1162. }
  1163. }
  1164. return 0;
  1165. }
  1166. /**
  1167. * 对象 转 数组
  1168. *
  1169. * @param object $obj 对象
  1170. * @return array
  1171. */
  1172. function ignoreKeyInArray($targetArray, $delete_keys = [], $changes = [])
  1173. {
  1174. $change_keys = array_keys($changes);
  1175. foreach ($targetArray as $key => $value) {
  1176. if (in_array($key, $delete_keys) && isset($targetArray[$key])) unset($targetArray[$key]);
  1177. if (in_array($key, $change_keys) && isset($targetArray[$key])) $targetArray[$key] = $changes[$key];
  1178. if (is_array($value)) ignoreKeyInArray($value, $delete_keys, $change_keys);
  1179. }
  1180. return $targetArray;
  1181. }
  1182. function itemTransform($trans, $data)
  1183. {
  1184. if ($data) {
  1185. return $trans->transform($data);
  1186. } else {
  1187. return [];
  1188. }
  1189. }
  1190. function collectionTransform($trans, $data)
  1191. {
  1192. $ret_data = [];
  1193. if ($data) {
  1194. foreach ($data as $item) {
  1195. $ret_data[] = $trans->transform($item);
  1196. }
  1197. }
  1198. return $ret_data;
  1199. }
  1200. function paginationTransform($trans, $paginator)
  1201. {
  1202. $ret = [];
  1203. $ret['list'] = [];
  1204. if ($paginator) {
  1205. foreach ($paginator as $item) {
  1206. $ret['list'][] = $trans->transform($item);
  1207. }
  1208. $ret['meta'] = [
  1209. 'total' => (int)$paginator->total(),
  1210. 'per_page' => (int)$paginator->perPage(),
  1211. 'current_page' => (int)$paginator->currentPage(),
  1212. 'last_page' => (int)$paginator->lastPage(),
  1213. 'next_page_url' => (string)$paginator->nextPageUrl(),
  1214. 'prev_page_url' => (string)$paginator->previousPageUrl()
  1215. ];
  1216. }
  1217. return $ret;
  1218. }
  1219. /**
  1220. * 加密site id
  1221. */
  1222. function encodeDistributionChannelId($id)
  1223. {
  1224. $encrypt_pool = [
  1225. ];
  1226. if (isset($encrypt_pool[$id])) {
  1227. return $encrypt_pool[$id];
  1228. }
  1229. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1230. return $hashids->encode($id);
  1231. }
  1232. /**
  1233. * 解密密site id
  1234. */
  1235. function decodeDistributionChannelId($code)
  1236. {
  1237. $encrypt_pool = [
  1238. ];
  1239. if (isset($encrypt_pool[$code])) {
  1240. return $encrypt_pool[$code];
  1241. }
  1242. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1243. $res = $hashids->decode($code);
  1244. if ($res && isset($res[0])) {
  1245. return $res[0];
  1246. }
  1247. return null;
  1248. }
  1249. //bid加密
  1250. function book_hash_encode($bid)
  1251. {
  1252. return Vinkla\Hashids\Facades\Hashids::encode($bid);
  1253. }
  1254. function decodeBid($encode_bid)
  1255. {
  1256. $bid = 0;
  1257. try {
  1258. $bid_arr = \Hashids::decode($encode_bid);
  1259. if (isset($bid_arr[0])) {
  1260. $bid = $bid_arr[0];
  1261. }
  1262. } catch (\Exception $e) {
  1263. return null;
  1264. }
  1265. return $bid;
  1266. }
  1267. /**
  1268. * 获取当前域名
  1269. */
  1270. function _domain()
  1271. {
  1272. return str_replace('https://', '', str_replace('http://', '', url('/')));
  1273. }
  1274. /**
  1275. * 字符串转*
  1276. *
  1277. * @param $str // 待转的字符串
  1278. * @param $start // 转*起始位置
  1279. * @param int $end // 转*结束位置
  1280. * @param string $dot // 转换的字符(必须是单字符,默认是*)
  1281. * @param string $charset // 编码方式
  1282. * @param string $end_char // 特殊字符(碰到此字符则确定end位置)
  1283. * @return string
  1284. */
  1285. function trans_pass($str, $start, $end = 0, $dot = "*", $charset = "UTF-8", $end_char = '@'): string
  1286. {
  1287. $len = mb_strlen($str, $charset);
  1288. if ($start == 0 || $start > $len) {
  1289. $start = 1;
  1290. }
  1291. if ($end != 0 && $end > $len) {
  1292. $end = $len - 2;
  1293. }
  1294. if (strstr($str, $end_char)) {
  1295. $end = $len - strrpos($str, $end_char);
  1296. }
  1297. $endStart = $len - $end;
  1298. $top = mb_substr($str, 0, $start, $charset);
  1299. $bottom = "";
  1300. if ($endStart > 0) {
  1301. $bottom = mb_substr($str, $endStart, $end, $charset);
  1302. }
  1303. $len -= mb_strlen($top, $charset);
  1304. $len -= mb_strlen($bottom, $charset);
  1305. $newStr = $top;
  1306. for ($i = 0; $i < $len; $i++) {
  1307. $newStr .= $dot;
  1308. }
  1309. $newStr .= $bottom;
  1310. return $newStr;
  1311. }
  1312. /**
  1313. * 格式化章节内容
  1314. *
  1315. * @param $content
  1316. * @return false|string
  1317. */
  1318. function formatContent($content)
  1319. {
  1320. if (!$content) return '';
  1321. $content = str_replace(
  1322. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p >', '&ldquo;', '&rdquo;', '&hellip;'],
  1323. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...'],
  1324. $content);
  1325. $content = str_replace(["&nbsp;", '&ldquo;', '&hellip;', '&rdquo;', '<p>'], '', $content);
  1326. // 段落首字母前加两个中文空格
  1327. $string = explode(PHP_EOL, $content);
  1328. foreach ($string as $line => $text) {
  1329. if (mb_substr($text, 0, 2) != '  ') $string[$line] = '  ' . $text;
  1330. }
  1331. $content = implode(PHP_EOL, $string);
  1332. $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8,GBK,GB2312');
  1333. $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);
  1334. return $content;
  1335. }
  1336. /**
  1337. * 筛选出有效的id集合
  1338. *
  1339. * @param array $ids
  1340. * @return array
  1341. */
  1342. function filterValidIds(array $ids): array
  1343. {
  1344. // 传参
  1345. if (empty($ids)) {
  1346. return [];
  1347. }
  1348. $result = [];
  1349. foreach ($ids as $id) {
  1350. if (in_array($id, $result) || !is_numeric($id) || (int)$id < 1) {
  1351. continue;
  1352. }
  1353. $result[] = (int)$id;
  1354. }
  1355. return $result;
  1356. }
  1357. function arrayToStr($map)
  1358. {
  1359. $isMap = isArrMap($map);
  1360. $result = "";
  1361. if ($isMap) {
  1362. $result = "map[";
  1363. }
  1364. $keyArr = array_keys($map);
  1365. if ($isMap) {
  1366. sort($keyArr);
  1367. }
  1368. $paramsArr = array();
  1369. foreach ($keyArr as $k) {
  1370. $v = $map[$k];
  1371. if ($isMap) {
  1372. if (is_array($v)) {
  1373. $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
  1374. } else {
  1375. $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
  1376. }
  1377. } else {
  1378. if (is_array($v)) {
  1379. $paramsArr[] = arrayToStr($v);
  1380. } else {
  1381. $paramsArr[] = trim(strval($v));
  1382. }
  1383. }
  1384. }
  1385. $result = sprintf("%s%s", $result, join(" ", $paramsArr));
  1386. if (!$isMap) {
  1387. $result = sprintf("[%s]", $result);
  1388. } else {
  1389. $result = sprintf("%s]", $result);
  1390. }
  1391. return $result;
  1392. }
  1393. function isArrMap($map)
  1394. {
  1395. foreach ($map as $k => $v) {
  1396. if (is_string($k)) {
  1397. return true;
  1398. }
  1399. }
  1400. return false;
  1401. }
  1402. /**
  1403. * 随机字符串
  1404. *
  1405. * @param $length
  1406. * @return string
  1407. */
  1408. function makeRandStr($length): string
  1409. {
  1410. // 密码字符集,可任意添加你需要的字符
  1411. $str = [
  1412. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  1413. 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  1414. 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
  1415. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  1416. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  1417. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  1418. ];
  1419. // 在 $str 中随机取 $length 个数组元素键名
  1420. $keys = array_rand($str, $length);
  1421. $password = '';
  1422. for ($i = 0; $i < $length; $i++) {
  1423. // 将 $length 个数组元素连接成字符串
  1424. $password .= $str[$keys[$i]];
  1425. }
  1426. return $password;
  1427. }
  1428. /**
  1429. * 导出数据为excel表格
  1430. *
  1431. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1432. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1433. * @param $filename 下载的文件名
  1434. * @examlpe10
  1435. */
  1436. function exportExcel($data = [], $title = [], $filename = 'report')
  1437. {
  1438. ob_end_clean();
  1439. ob_start();
  1440. header("Content-type:application/octet-stream");
  1441. header("Accept-Ranges:bytes");
  1442. header("Content-type:application/vnd.ms-excel");
  1443. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1444. header("Pragma: no-cache");
  1445. header("Expires: 0");
  1446. //导出xls 开始
  1447. if (!empty($title)) {
  1448. foreach ($title as $k => $v) {
  1449. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1450. }
  1451. $title = implode("\t", $title);
  1452. echo "$title\n";
  1453. }
  1454. if (!empty($data)) {
  1455. foreach ($data as $key => $val) {
  1456. foreach ($val as $ck => $cv) {
  1457. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1458. }
  1459. $data[$key] = implode("\t", $data[$key]);
  1460. }
  1461. echo implode("\n", $data);
  1462. }
  1463. }
  1464. /**
  1465. * 导出csv文件
  1466. * @param string $name
  1467. * @param array $headers
  1468. * @param array $data
  1469. * @return void
  1470. */
  1471. function exportCsv(string $name, array $headers, array $data = [])
  1472. {
  1473. header('Content-Description: File Transfer');
  1474. header('Content-Type: application/csv');
  1475. header("Content-Disposition: attachment; filename=".$name.".csv");
  1476. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  1477. $handle = fopen('php://output', 'w');
  1478. ob_clean();
  1479. fputcsv($handle, $headers);
  1480. if ($data) {
  1481. foreach ($data as $row) {
  1482. fputcsv($handle, $row);
  1483. }
  1484. }
  1485. ob_flush();
  1486. fclose($handle);
  1487. die();
  1488. }
  1489. // 获取文件的md5值
  1490. function getFileContentMD5($filePath){
  1491. //获取文件MD5的128位二进制数组
  1492. $md5Bytes = md5_file($filePath,true);
  1493. //计算文件的Content-MD5
  1494. $contentMD5 = base64_encode($md5Bytes);
  1495. return $contentMD5;
  1496. }
  1497. function getTextTokens($text) {
  1498. // 方法1:按空格分词(西文较准)
  1499. $words = preg_split('/\s+/', $text);
  1500. $wordCount = count($words);
  1501. // 方法2:按字符数估算(中文较准:1个汉字 ≈ 1.5-2 tokens)
  1502. $charCount = mb_strlen($text);
  1503. // 综合估算(根据语言调整权重)
  1504. $tokenCount = $wordCount + $charCount * 0.5; // 示例公式
  1505. // 更简单:直接按字符数 * 系数(中文推荐)
  1506. // $tokenCount = $charCount * 1.8; // 经验系数
  1507. return (int)ceil($tokenCount);
  1508. }
  1509. // 处理小说剧本文本
  1510. function handleScriptWords($text) {
  1511. $text = preg_replace('/[\r\n]+/', PHP_EOL, $text);
  1512. $text_arr = explode(PHP_EOL, $text);
  1513. $roles = [];
  1514. $words = [];
  1515. foreach ($text_arr as $line) {
  1516. $line = trim($line);
  1517. preg_match('/^(.*?)\:(.*?)\{(.*?)\}$/', $line, $matches);
  1518. if (count($matches) == 4) {
  1519. $gender = '0';
  1520. // 角色部分拆分
  1521. preg_match('/^(.*?)\((.*?)\)$/', $matches[1], $matches2);
  1522. if (count($matches2) == 3) {
  1523. $role = $matches2[1];
  1524. $gender_arr = ['男'=>'1', '女'=>'2'];
  1525. $gender = isset($gender_arr[$matches2[2]]) ? $gender_arr[$matches2[2]] : '0';
  1526. }else {
  1527. $role = $matches[1];
  1528. }
  1529. if (!in_array($role, $roles)) $roles[] = $role; // 记录角色
  1530. $words[] = [
  1531. 'role' => $role,
  1532. 'gender' => $gender,
  1533. 'text' => $matches[2],
  1534. 'emotion' => $matches[3],
  1535. ];
  1536. }
  1537. }
  1538. return [
  1539. 'roles' => $roles,
  1540. 'words' => $words,
  1541. ];
  1542. }