Helpers.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707
  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, 7) == '/books/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  590. if (mb_substr($str, 0, 6) == '/card/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  591. if (mb_substr($str, 0, 15) == 'uploader/idcard') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com/' . $str;
  592. if (mb_substr($str, 0, 6) == '/cover') return 'https://cdn-newyc.ycsd.cn/ycsd_cover/covermiddle' . mb_substr($str, 6);
  593. if (mb_substr($str, 0, 8) == '/images/') return 'https://cdn-newyc.ycsd.cn/ycsd_cover' . $str;
  594. }
  595. /**
  596. * 章节内容排版
  597. *
  598. * @param $content
  599. * @return string
  600. */
  601. function filterContent($content)
  602. {
  603. if (!$content) return '';
  604. $content = str_replace(
  605. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  606. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  607. $content);
  608. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  609. // 段落首字母前加两个中文空格
  610. $string = explode(PHP_EOL, $content);
  611. foreach ($string as $line => $text) {
  612. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' '], '', $string[$line]);
  613. if (!$string[$line]) {
  614. unset($string[$line]);
  615. } else {
  616. $string[$line] = $string[$line] . PHP_EOL;
  617. // if (mb_substr($string[$line], 0, 1) == ' ') {
  618. // $string[$line] = str_replace(' ', '', $string[$line]); // 去除多个空格
  619. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  620. // }
  621. // if (mb_substr($string[$line], 0, 2) != '  ') {
  622. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  623. // }
  624. // if (mb_substr($string[$line], 0, 2) == '  ' && str_replace(' ', '', $string[$line])) {
  625. // $string[$line] .= PHP_EOL;
  626. // }
  627. }
  628. }
  629. $content = implode(PHP_EOL, $string);
  630. return $content;
  631. }
  632. /**
  633. * 书籍简介排版
  634. *
  635. * @param $content
  636. * @return string
  637. */
  638. function filterContent2($content)
  639. {
  640. if (!$content) return '';
  641. $content = str_replace(
  642. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  643. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  644. $content);
  645. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  646. // 段落首字母前加两个中文空格
  647. $string = explode(PHP_EOL, $content);
  648. $content = '';
  649. foreach ($string as $line => $text) {
  650. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  651. if (!$string[$line]) {
  652. unset($string[$line]);
  653. } else {
  654. $string[$line] = '  ' . $string[$line] . '<br />';
  655. $content .= $string[$line];
  656. }
  657. }
  658. $content = trim($content, '<br />');
  659. return $content;
  660. }
  661. /**
  662. * 书籍简介排版-抖音版
  663. *
  664. * @param $content
  665. * @return string
  666. */
  667. function filterIntro($content)
  668. {
  669. if (!$content) return '';
  670. $content = str_replace(
  671. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  672. [' ', ' ', ' ', ' ', ' ', '', ' ', '“', '”', '...', '‘', '’', '-'],
  673. $content);
  674. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  675. // 段落首字母前加两个中文空格
  676. $string = explode(PHP_EOL, $content);
  677. $content = '';
  678. foreach ($string as $line => $text) {
  679. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  680. if (!$string[$line]) {
  681. unset($string[$line]);
  682. } else {
  683. $content .= $string[$line];
  684. }
  685. }
  686. $content = trim($content, '<br />');
  687. return $content;
  688. }
  689. function sensitiveStr($list, $string)
  690. {
  691. $count = 0; //违规词的个数
  692. $sensitiveWord = ''; //违规词
  693. $stringAfter = $string; //替换后的内容
  694. $total = count($list);
  695. $size = 500;
  696. $last = ceil($total / $size);
  697. $patternList = [];
  698. for ($page = 1; $page <= $last; $page++) {
  699. $arr = array_slice($list, $size * ($page - 1), $size);
  700. $filter = [];
  701. foreach ($arr as $v) {
  702. if (preg_match('/[^a-zA-Z0-9\|\p{Han}\·]/u', $v)) continue;
  703. $filter[] = $v;
  704. // $a = preg_replace('/[^a-zA-Z0-9\|\p{Han}]/u', '', $v);
  705. // if ($a) $filter[] = $a;
  706. }
  707. $pattern = "/" . implode("|", $filter) . "/i"; //定义正则表达式
  708. if (preg_match_all($pattern, $string, $matches)) { //匹配到了结果
  709. $patternList = array_merge($patternList, $matches[0]); //匹配到的数组
  710. }
  711. }
  712. $sensitiveWord = '';
  713. if ($patternList) {
  714. $count = count($patternList);
  715. // $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
  716. $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '*')); //把匹配到的数组进行合并,替换使用
  717. $stringAfter = strtr($string, $replaceArray); //结果替换
  718. // 将敏感词合并
  719. $return_pattern = [];
  720. foreach ($patternList as $v) {
  721. if (!isset($return_pattern[$v])) {
  722. $return_pattern[$v] = [
  723. 'word' => $v,
  724. 'count' => 1,
  725. ];
  726. } else {
  727. $return_pattern[$v]['count'] += 1;
  728. }
  729. }
  730. foreach ($return_pattern as $v) {
  731. $sensitiveWord .= $v['word'] . ',';
  732. }
  733. }
  734. return [
  735. 'count' => $count,
  736. 'sensitive_words' => trim($sensitiveWord, ','),
  737. 'content' => $stringAfter
  738. ];
  739. }
  740. /**
  741. * 转换时间格式
  742. *
  743. * @param $date
  744. * @param string $format
  745. * @return false|string
  746. */
  747. function transDate($date, $format = 'Y-m-d H:i:s')
  748. {
  749. return strtotime($date) > 0 ? date($format, strtotime($date)) : '';
  750. }
  751. /**
  752. * 根据网段获取计算所有IP
  753. *
  754. * @param string $segment 网段 '139.217.0.1/24'
  755. * @return array [网络地址:139.217.0.1 广播地址:139.217.0.255 IP列表: ['139.217.0.2','139.217.0.3'……'139.217.0.254']]
  756. */
  757. function getIpBySegment($segment)
  758. {
  759. $segmentInfo = explode("/", $segment);
  760. $beginIpArray = explode(".", $segmentInfo[0]);
  761. $mask = intval($segmentInfo['1']);
  762. $endIp = array();
  763. foreach ($beginIpArray as $ipKey => $item) {
  764. $beginFlag = 8 * ($ipKey); //0 8 16 24
  765. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  766. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  767. $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));
  768. }
  769. $ipArray = array();
  770. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0]++) {
  771. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1]++) {
  772. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2]++) {
  773. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3]++) {
  774. $ipArray[] = implode(".", $beginIp);
  775. }
  776. }
  777. }
  778. }
  779. $network_ip_addr = $beginIpArray[0] . '.' . $beginIpArray[1] . '.' . $beginIpArray[2] . '.' . '0'; // 网络地址
  780. $broadcast_ip_addr = end($ipArray); // 广播地址
  781. if ($ipArray[0] == $network_ip_addr) { // 如果是网络地址则删掉
  782. unset($ipArray[0]);
  783. }
  784. $last = count($ipArray);
  785. unset($ipArray[$last]);
  786. return [$network_ip_addr, $broadcast_ip_addr, $ipArray];
  787. }
  788. /**
  789. * 在指定网段中分配子网段
  790. *
  791. * @param string $segment 指定网段
  792. * @param int $ipNum 需要的IP数
  793. * @param array $usedIpArray 不可用(已经使用)的IP,默认为空数组
  794. * @return bool|string 成功则返回分配的网段
  795. */
  796. function allocateSegment($segment, $ipNum, $usedIpArray = [])
  797. {
  798. $usedIpArray = empty($usedIpArray) ? [] : array_flip($usedIpArray);
  799. //计算需要多少个IP
  800. $i = 0;
  801. $ipCount = pow(2, $i);
  802. while ($ipCount < $ipNum) {
  803. $i++;
  804. $ipCount = pow(2, $i);
  805. }
  806. $newMask = 32 - $i;
  807. //大网段的开始和结束IP
  808. $segmentInfo = explode("/", $segment); //['139.217.0.1',24]
  809. $beginIpArray = explode(".", $segmentInfo[0]);//[139,217,0,1]
  810. $mask = intval($segmentInfo['1']); //24
  811. if ($newMask < $mask) {
  812. return false;
  813. }
  814. $endIp = array();
  815. $step = [];
  816. foreach ($beginIpArray as $ipKey => $item) {
  817. $beginFlag = 8 * ($ipKey); //0 8 16 24
  818. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  819. $step[$ipKey] = $newMask > $endFlag ? 1 : ($endFlag - $newMask < 8 ? pow(2, $endFlag - $newMask) : pow(2, 8));
  820. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  821. $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));
  822. }
  823. //遍历生成网段
  824. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0] += $step[0]) {
  825. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1] += $step[1]) {
  826. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2] += $step[2]) {
  827. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3] += $step[3]) {
  828. $newSegment = implode('.', $beginIp) . '/' . $newMask;
  829. //获取该网段所有的IP
  830. $ipArray = getIpBySegment($newSegment);
  831. $canUse = true;
  832. //判断该网段是否可用
  833. if (!empty($usedIpArray)) {
  834. foreach ($ipArray as $ip) {
  835. if (isset($usedIpArray[$ip])) {
  836. $canUse = false;
  837. break;
  838. }
  839. }
  840. }
  841. if ($canUse) {
  842. return $newSegment;
  843. }
  844. }
  845. }
  846. }
  847. }
  848. return false;
  849. }
  850. function remove_xss($val)
  851. {
  852. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  853. // this prevents some character re-spacing such as <java\0script>
  854. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
  855. $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
  856. // straight replacements, the user should never need these since they're normal characters
  857. // this prevents like <IMG SRC=@avascript:alert('XSS')>
  858. $search = 'abcdefghijklmnopqrstuvwxyz';
  859. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  860. $search .= '1234567890!@#$%^&*()';
  861. $search .= '~`";:?+/={}[]-_|\'\\';
  862. for ($i = 0; $i < strlen($search); $i++) {
  863. // ;? matches the ;, which is optional
  864. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  865. // @ @ search for the hex values
  866. $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
  867. // @ @ 0{0,7} matches '0' zero to seven times
  868. $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
  869. }
  870. // now the only remaining whitespace attacks are \t, \n, and \r
  871. $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  872. $ra2 = array(
  873. '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'
  874. );
  875. $ra = array_merge($ra1, $ra2);
  876. $found = true; // keep replacing as long as the previous round replaced something
  877. while ($found == true) {
  878. $val_before = $val;
  879. for ($i = 0; $i < sizeof($ra); $i++) {
  880. $pattern = '/';
  881. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  882. if ($j > 0) {
  883. $pattern .= '(';
  884. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  885. $pattern .= '|';
  886. $pattern .= '|(�{0,8}([9|10|13]);)';
  887. $pattern .= ')*';
  888. }
  889. $pattern .= $ra[$i][$j];
  890. }
  891. $pattern .= '/i';
  892. $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
  893. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  894. if ($val_before == $val) {
  895. // no replacements were made, so exit the loop
  896. $found = false;
  897. }
  898. }
  899. }
  900. return $val;
  901. }
  902. /**
  903. * 计算作者积分等级
  904. *
  905. * @param $score
  906. */
  907. function calcAuthorLevel($score): int
  908. {
  909. switch (true) {
  910. case $score <= 0:
  911. $level = 0;
  912. break;
  913. case $score <= 5000:
  914. $level = 1;
  915. break;
  916. case $score <= 50000:
  917. $level = 2;
  918. break;
  919. case $score <= 100000:
  920. $level = 3;
  921. break;
  922. case $score <= 300000:
  923. $level = 4;
  924. break;
  925. case $score <= 800000:
  926. $level = 5;
  927. break;
  928. case $score <= 1500000:
  929. $level = 6;
  930. break;
  931. case $score <= 2500000:
  932. $level = 7;
  933. break;
  934. case $score <= 5000000:
  935. $level = 8;
  936. break;
  937. case $score <= 10000000:
  938. $level = 9;
  939. break;
  940. default:
  941. $level = 10;
  942. break;
  943. }
  944. return $level;
  945. }
  946. /**
  947. * 运营数据(上传附件)
  948. *
  949. * @param $file
  950. * @return string
  951. * @throws Exception
  952. */
  953. function uploadEnclosureFile($file)
  954. {
  955. // 阿里云主账号
  956. $accessKeyId = env('OSS_ACCESS_ID');
  957. $accessKeySecret = env('OSS_ACCESS_KEY');
  958. $endpoint = env('OSS_END_POINT');
  959. $bucket = env('OSS_BUCKET');
  960. // 设置文件名称。
  961. $object = 'books/enclosure/' . randStr(10) . '--' . $file->getClientOriginalName();
  962. try {
  963. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  964. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  965. } catch (OssException $e) {
  966. printf($e->getMessage());
  967. return '';
  968. }
  969. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  970. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  971. }
  972. // 获取当前域名是http还是https
  973. function getHttpType()
  974. {
  975. return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
  976. }
  977. // 根据id生成唯一邀请码
  978. function enCodeId($user_id)
  979. {
  980. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  981. $num = strlen($key);
  982. $code = ''; // 邀请码
  983. while ($user_id > 0) { // 转进制
  984. $mod = $user_id % $num; // 求模
  985. $user_id = ($user_id - $mod) / $num;
  986. $code = $key[$mod] . $code;
  987. }
  988. $code = str_pad($code, 6, 'A', STR_PAD_LEFT); // 不足用0补充
  989. return $code;
  990. }
  991. // 根据邀请码解密为id
  992. function deCodeId($code)
  993. {
  994. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  995. $num = strlen($key);
  996. if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0') + 1);
  997. $len = strlen($code);
  998. $code = strrev($code);
  999. $user_id = 0;
  1000. for ($i = 0; $i < $len; $i++) {
  1001. $user_id += strpos($key, $code[$i]) * pow($num, $i);
  1002. }
  1003. return $user_id;
  1004. }
  1005. /**
  1006. * 将二维数组按其中的某个数组排序(此方法适用于将数据库数据按数组取出后自动按ID排序的情况 ps:即未按该数组排序)
  1007. *
  1008. * @param array $array 二维数组
  1009. * @param array $sort 排序数组
  1010. * @param string $field 排序字段(二维数组和排序数组相同的字段)
  1011. * @return array
  1012. */
  1013. function sortByArray(array $array, array $sort, string $field): array
  1014. {
  1015. $data = [];
  1016. if (is_array($array) && is_array($sort)) {
  1017. foreach ($sort as $v) {
  1018. foreach ($array as $key => $val) {
  1019. if ($v == $val[$field]) {
  1020. array_push($data, $array[$key]);
  1021. }
  1022. }
  1023. }
  1024. }
  1025. return $data;
  1026. }
  1027. /**
  1028. * 将二维数组按其中的字段排序(正序或倒序)
  1029. *
  1030. * @param array $array 二维数组
  1031. * @param string $field 排序字段
  1032. * @param mixed $type 排序方式(3倒序,4正序)
  1033. * @return array|mixed
  1034. */
  1035. function sortByField(array $array, string $field, $type): array
  1036. {
  1037. if (is_array($array)) {
  1038. array_multisort(array_column($array, $field), $type, $array);
  1039. }
  1040. return $array;
  1041. }
  1042. // 生成用户邀请码
  1043. function setUserInviteCode($id)
  1044. {
  1045. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->encode($id);
  1046. }
  1047. // 解密用户邀请码
  1048. function decodeUserInviteCode($code)
  1049. {
  1050. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->decode($code);
  1051. }
  1052. function getMillisecond()
  1053. {
  1054. list($microsecond, $time) = explode(' ', microtime());
  1055. return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
  1056. }
  1057. function get_client_ip($type = 0, $adv = false)
  1058. {
  1059. $type = $type ? 1 : 0;
  1060. static $ip = null;
  1061. if (null !== $ip) {
  1062. return $ip[$type];
  1063. }
  1064. if ($adv) {
  1065. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1066. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1067. $pos = array_search('unknown', $arr);
  1068. if (false !== $pos) {
  1069. unset($arr[$pos]);
  1070. }
  1071. $ip = trim($arr[0]);
  1072. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1073. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1074. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1075. $ip = $_SERVER['REMOTE_ADDR'];
  1076. }
  1077. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1078. $ip = $_SERVER['REMOTE_ADDR'];
  1079. }
  1080. // IP地址合法验证
  1081. $long = sprintf("%u", ip2long($ip));
  1082. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  1083. return $ip[$type];
  1084. }
  1085. /**
  1086. * 获取真实IP
  1087. */
  1088. function _getIp()
  1089. {
  1090. if (getenv('HTTP_X_FORWARDED_FOR')) {
  1091. $ip = getenv('HTTP_X_FORWARDED_FOR');
  1092. } else if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  1093. $ip = getenv("HTTP_CLIENT_IP");
  1094. else if (getenv("HTTP_X_FORWARD_FOR") && strcasecmp(getenv("HTTP_X_FORWARD_FOR"), "unknown"))
  1095. $ip = getenv("HTTP_X_FORWARD_FOR");
  1096. else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  1097. $ip = getenv("REMOTE_ADDR");
  1098. else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  1099. $ip = $_SERVER['REMOTE_ADDR'];
  1100. else
  1101. $ip = "unknown";
  1102. return ($ip);
  1103. }
  1104. /**
  1105. * 数组 转 对象
  1106. *
  1107. * @param array $arr 数组
  1108. * @return object
  1109. */
  1110. function array_to_object($arr)
  1111. {
  1112. if (gettype($arr) != 'array') {
  1113. return;
  1114. }
  1115. foreach ($arr as $k => $v) {
  1116. if (gettype($v) == 'array' || getType($v) == 'object') {
  1117. $arr[$k] = (object)array_to_object($v);
  1118. }
  1119. }
  1120. return (object)$arr;
  1121. }
  1122. /**
  1123. * 对象 转 数组
  1124. *
  1125. * @param object $obj 对象
  1126. * @return array
  1127. */
  1128. function object_to_array($obj)
  1129. {
  1130. $obj = (array)$obj;
  1131. foreach ($obj as $k => $v) {
  1132. if (gettype($v) == 'resource') {
  1133. return;
  1134. }
  1135. if (gettype($v) == 'object' || gettype($v) == 'array') {
  1136. $obj[$k] = (array)object_to_array($v);
  1137. }
  1138. }
  1139. return $obj;
  1140. }
  1141. /**
  1142. * 检查是否为手机号码
  1143. */
  1144. function _isPhone($number)
  1145. {
  1146. return preg_match("/^1[34578][0-9]{9}$/", $number);
  1147. }
  1148. /**
  1149. * 判断所传的参数是否缺少,如果缺少返回渠道的字段,正确返回0
  1150. *
  1151. * @param array $param
  1152. * @param array $must
  1153. * @return int|mixed
  1154. */
  1155. function checkParam(array $param, array $must)
  1156. {
  1157. foreach ($must as $item) {
  1158. if (array_key_exists($item, $param) && $param[$item] != '') {
  1159. } else {
  1160. return $item;
  1161. }
  1162. }
  1163. return 0;
  1164. }
  1165. /**
  1166. * 对象 转 数组
  1167. *
  1168. * @param object $obj 对象
  1169. * @return array
  1170. */
  1171. function ignoreKeyInArray($targetArray, $delete_keys = [], $changes = [])
  1172. {
  1173. $change_keys = array_keys($changes);
  1174. foreach ($targetArray as $key => $value) {
  1175. if (in_array($key, $delete_keys) && isset($targetArray[$key])) unset($targetArray[$key]);
  1176. if (in_array($key, $change_keys) && isset($targetArray[$key])) $targetArray[$key] = $changes[$key];
  1177. if (is_array($value)) ignoreKeyInArray($value, $delete_keys, $change_keys);
  1178. }
  1179. return $targetArray;
  1180. }
  1181. function itemTransform($trans, $data)
  1182. {
  1183. if ($data) {
  1184. return $trans->transform($data);
  1185. } else {
  1186. return [];
  1187. }
  1188. }
  1189. function collectionTransform($trans, $data)
  1190. {
  1191. $ret_data = [];
  1192. if ($data) {
  1193. foreach ($data as $item) {
  1194. $ret_data[] = $trans->transform($item);
  1195. }
  1196. }
  1197. return $ret_data;
  1198. }
  1199. function paginationTransform($trans, $paginator)
  1200. {
  1201. $ret = [];
  1202. $ret['list'] = [];
  1203. if ($paginator) {
  1204. foreach ($paginator as $item) {
  1205. $ret['list'][] = $trans->transform($item);
  1206. }
  1207. $ret['meta'] = [
  1208. 'total' => (int)$paginator->total(),
  1209. 'per_page' => (int)$paginator->perPage(),
  1210. 'current_page' => (int)$paginator->currentPage(),
  1211. 'last_page' => (int)$paginator->lastPage(),
  1212. 'next_page_url' => (string)$paginator->nextPageUrl(),
  1213. 'prev_page_url' => (string)$paginator->previousPageUrl()
  1214. ];
  1215. }
  1216. return $ret;
  1217. }
  1218. /**
  1219. * 加密site id
  1220. */
  1221. function encodeDistributionChannelId($id)
  1222. {
  1223. $encrypt_pool = [
  1224. ];
  1225. if (isset($encrypt_pool[$id])) {
  1226. return $encrypt_pool[$id];
  1227. }
  1228. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1229. return $hashids->encode($id);
  1230. }
  1231. /**
  1232. * 解密密site id
  1233. */
  1234. function decodeDistributionChannelId($code)
  1235. {
  1236. $encrypt_pool = [
  1237. ];
  1238. if (isset($encrypt_pool[$code])) {
  1239. return $encrypt_pool[$code];
  1240. }
  1241. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1242. $res = $hashids->decode($code);
  1243. if ($res && isset($res[0])) {
  1244. return $res[0];
  1245. }
  1246. return null;
  1247. }
  1248. //bid加密
  1249. function book_hash_encode($bid)
  1250. {
  1251. return Vinkla\Hashids\Facades\Hashids::encode($bid);
  1252. }
  1253. function decodeBid($encode_bid)
  1254. {
  1255. $bid = 0;
  1256. try {
  1257. $bid_arr = \Hashids::decode($encode_bid);
  1258. if (isset($bid_arr[0])) {
  1259. $bid = $bid_arr[0];
  1260. }
  1261. } catch (\Exception $e) {
  1262. return null;
  1263. }
  1264. return $bid;
  1265. }
  1266. /**
  1267. * 获取当前域名
  1268. */
  1269. function _domain()
  1270. {
  1271. return str_replace('https://', '', str_replace('http://', '', url('/')));
  1272. }
  1273. /**
  1274. * 字符串转*
  1275. *
  1276. * @param $str // 待转的字符串
  1277. * @param $start // 转*起始位置
  1278. * @param int $end // 转*结束位置
  1279. * @param string $dot // 转换的字符(必须是单字符,默认是*)
  1280. * @param string $charset // 编码方式
  1281. * @param string $end_char // 特殊字符(碰到此字符则确定end位置)
  1282. * @return string
  1283. */
  1284. function trans_pass($str, $start, $end = 0, $dot = "*", $charset = "UTF-8", $end_char = '@'): string
  1285. {
  1286. $len = mb_strlen($str, $charset);
  1287. if ($start == 0 || $start > $len) {
  1288. $start = 1;
  1289. }
  1290. if ($end != 0 && $end > $len) {
  1291. $end = $len - 2;
  1292. }
  1293. if (strstr($str, $end_char)) {
  1294. $end = $len - strrpos($str, $end_char);
  1295. }
  1296. $endStart = $len - $end;
  1297. $top = mb_substr($str, 0, $start, $charset);
  1298. $bottom = "";
  1299. if ($endStart > 0) {
  1300. $bottom = mb_substr($str, $endStart, $end, $charset);
  1301. }
  1302. $len -= mb_strlen($top, $charset);
  1303. $len -= mb_strlen($bottom, $charset);
  1304. $newStr = $top;
  1305. for ($i = 0; $i < $len; $i++) {
  1306. $newStr .= $dot;
  1307. }
  1308. $newStr .= $bottom;
  1309. return $newStr;
  1310. }
  1311. /**
  1312. * 格式化章节内容
  1313. *
  1314. * @param $content
  1315. * @return false|string
  1316. */
  1317. function formatContent($content)
  1318. {
  1319. if (!$content) return '';
  1320. $content = str_replace(
  1321. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p >', '&ldquo;', '&rdquo;', '&hellip;'],
  1322. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...'],
  1323. $content);
  1324. $content = str_replace(["&nbsp;", '&ldquo;', '&hellip;', '&rdquo;', '<p>'], '', $content);
  1325. // 段落首字母前加两个中文空格
  1326. $string = explode(PHP_EOL, $content);
  1327. foreach ($string as $line => $text) {
  1328. if (mb_substr($text, 0, 2) != '  ') $string[$line] = '  ' . $text;
  1329. }
  1330. $content = implode(PHP_EOL, $string);
  1331. $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8,GBK,GB2312');
  1332. $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);
  1333. return $content;
  1334. }
  1335. /**
  1336. * 筛选出有效的id集合
  1337. *
  1338. * @param array $ids
  1339. * @return array
  1340. */
  1341. function filterValidIds(array $ids): array
  1342. {
  1343. // 传参
  1344. if (empty($ids)) {
  1345. return [];
  1346. }
  1347. $result = [];
  1348. foreach ($ids as $id) {
  1349. if (in_array($id, $result) || !is_numeric($id) || (int)$id < 1) {
  1350. continue;
  1351. }
  1352. $result[] = (int)$id;
  1353. }
  1354. return $result;
  1355. }
  1356. function arrayToStr($map)
  1357. {
  1358. $isMap = isArrMap($map);
  1359. $result = "";
  1360. if ($isMap) {
  1361. $result = "map[";
  1362. }
  1363. $keyArr = array_keys($map);
  1364. if ($isMap) {
  1365. sort($keyArr);
  1366. }
  1367. $paramsArr = array();
  1368. foreach ($keyArr as $k) {
  1369. $v = $map[$k];
  1370. if ($isMap) {
  1371. if (is_array($v)) {
  1372. $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
  1373. } else {
  1374. $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
  1375. }
  1376. } else {
  1377. if (is_array($v)) {
  1378. $paramsArr[] = arrayToStr($v);
  1379. } else {
  1380. $paramsArr[] = trim(strval($v));
  1381. }
  1382. }
  1383. }
  1384. $result = sprintf("%s%s", $result, join(" ", $paramsArr));
  1385. if (!$isMap) {
  1386. $result = sprintf("[%s]", $result);
  1387. } else {
  1388. $result = sprintf("%s]", $result);
  1389. }
  1390. return $result;
  1391. }
  1392. function isArrMap($map)
  1393. {
  1394. foreach ($map as $k => $v) {
  1395. if (is_string($k)) {
  1396. return true;
  1397. }
  1398. }
  1399. return false;
  1400. }
  1401. /**
  1402. * 随机字符串
  1403. *
  1404. * @param $length
  1405. * @return string
  1406. */
  1407. function makeRandStr($length): string
  1408. {
  1409. // 密码字符集,可任意添加你需要的字符
  1410. $str = [
  1411. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  1412. 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  1413. 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
  1414. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  1415. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  1416. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  1417. ];
  1418. // 在 $str 中随机取 $length 个数组元素键名
  1419. $keys = array_rand($str, $length);
  1420. $password = '';
  1421. for ($i = 0; $i < $length; $i++) {
  1422. // 将 $length 个数组元素连接成字符串
  1423. $password .= $str[$keys[$i]];
  1424. }
  1425. return $password;
  1426. }
  1427. /**
  1428. * 导出数据为excel表格
  1429. *
  1430. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1431. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1432. * @param $filename 下载的文件名
  1433. * @examlpe10
  1434. */
  1435. function exportExcel($data = [], $title = [], $filename = 'report')
  1436. {
  1437. ob_end_clean();
  1438. ob_start();
  1439. header("Content-type:application/octet-stream");
  1440. header("Accept-Ranges:bytes");
  1441. header("Content-type:application/vnd.ms-excel");
  1442. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1443. header("Pragma: no-cache");
  1444. header("Expires: 0");
  1445. //导出xls 开始
  1446. if (!empty($title)) {
  1447. foreach ($title as $k => $v) {
  1448. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1449. }
  1450. $title = implode("\t", $title);
  1451. echo "$title\n";
  1452. }
  1453. if (!empty($data)) {
  1454. foreach ($data as $key => $val) {
  1455. foreach ($val as $ck => $cv) {
  1456. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1457. }
  1458. $data[$key] = implode("\t", $data[$key]);
  1459. }
  1460. echo implode("\n", $data);
  1461. }
  1462. }
  1463. /**
  1464. * 导出csv文件
  1465. * @param string $name
  1466. * @param array $headers
  1467. * @param array $data
  1468. * @return void
  1469. */
  1470. function exportCsv(string $name, array $headers, array $data = [])
  1471. {
  1472. header('Content-Description: File Transfer');
  1473. header('Content-Type: application/csv');
  1474. header("Content-Disposition: attachment; filename=".$name.".csv");
  1475. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  1476. $handle = fopen('php://output', 'w');
  1477. ob_clean();
  1478. fputcsv($handle, $headers);
  1479. if ($data) {
  1480. foreach ($data as $row) {
  1481. fputcsv($handle, $row);
  1482. }
  1483. }
  1484. ob_flush();
  1485. fclose($handle);
  1486. die();
  1487. }
  1488. // 获取文件的md5值
  1489. function getFileContentMD5($filePath){
  1490. //获取文件MD5的128位二进制数组
  1491. $md5Bytes = md5_file($filePath,true);
  1492. //计算文件的Content-MD5
  1493. $contentMD5 = base64_encode($md5Bytes);
  1494. return $contentMD5;
  1495. }
  1496. function getTextTokens($text) {
  1497. // 方法1:按空格分词(西文较准)
  1498. $words = preg_split('/\s+/', $text);
  1499. $wordCount = count($words);
  1500. // 方法2:按字符数估算(中文较准:1个汉字 ≈ 1.5-2 tokens)
  1501. $charCount = mb_strlen($text);
  1502. // 综合估算(根据语言调整权重)
  1503. $tokenCount = $wordCount + $charCount * 0.5; // 示例公式
  1504. // 更简单:直接按字符数 * 系数(中文推荐)
  1505. // $tokenCount = $charCount * 1.8; // 经验系数
  1506. return (int)ceil($tokenCount);
  1507. }
  1508. // 处理小说剧本文本
  1509. function handleDramaWords($text) {
  1510. $text_arr = explode(PHP_EOL, $text);
  1511. $roles = [];
  1512. $words = [];
  1513. foreach ($text_arr as $line) {
  1514. $line = trim($line);
  1515. preg_match('/^(.*?)\:(.*?)\{(.*?)\}$/', $line, $matches);
  1516. if (count($matches) == 4) {
  1517. $gender = '0';
  1518. // 角色部分拆分
  1519. preg_match('/^(.*?)\((.*?)\)$/', $matches[1], $matches2);
  1520. if (count($matches2) == 3) {
  1521. $role = $matches2[1];
  1522. $gender_arr = ['男'=>'1', '女'=>'2'];
  1523. $gender = isset($gender_arr[$matches2[2]]) ? $gender_arr[$matches2[2]] : '0';
  1524. }else {
  1525. $role = $matches[1];
  1526. }
  1527. if (!in_array($role, $roles)) $roles[] = $role; // 记录角色
  1528. $words[] = [
  1529. 'role' => $role,
  1530. 'gender' => $gender,
  1531. 'text' => $matches[2],
  1532. 'emotion' => $matches[3],
  1533. ];
  1534. }
  1535. }
  1536. return [
  1537. 'roles' => $roles,
  1538. 'words' => $words,
  1539. ];
  1540. }