Helpers.php 54 KB

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