Helpers.php 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042
  1. <?php
  2. use App\Consts\BaseConst;
  3. use GuzzleHttp\Client;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Log;
  6. use Monolog\Handler\StreamHandler;
  7. use Monolog\Logger;
  8. use OSS\OssClient;
  9. use OSS\Core\OssException;
  10. use Tos\TosClient;
  11. use Tos\Exception\TosClientException;
  12. use Tos\Exception\TosServerException;
  13. use Tos\Model\PutObjectInput;
  14. // use Imagick;
  15. /**
  16. * 截取字符串
  17. *
  18. * @param $string
  19. * @param $length
  20. * @param bool $append
  21. * @return array|string
  22. */
  23. function sysSubStr($string, $length, $append = false)
  24. {
  25. if (strlen($string) <= $length) {
  26. return $string;
  27. }
  28. $i = 0;
  29. $stringLast = [];
  30. while ($i < $length) {
  31. $stringTMP = mb_substr($string, $i, 1);
  32. if (ord($stringTMP) >= 224) {
  33. $stringTMP = mb_substr($string, $i, 3);
  34. $i += 3;
  35. } elseif (ord($stringTMP) >= 192) {
  36. $stringTMP = mb_substr($string, $i, 2);
  37. $i += 2;
  38. } else {
  39. ++$i;
  40. }
  41. $stringLast[] = $stringTMP;
  42. }
  43. $stringLast = implode('', $stringLast);
  44. if ($append) {
  45. $stringLast .= '...';
  46. }
  47. return $stringLast;
  48. }
  49. /**
  50. * 自定义日志
  51. *
  52. * @param $name
  53. * @param string $filename
  54. * @return \Illuminate\Log\Writer
  55. */
  56. function myLog($name, $filename = '')
  57. {
  58. if (!$filename) {
  59. $filename = $name;
  60. }
  61. $filename = $filename . '.log';
  62. $logger = new Logger($name);
  63. $writer = new \Illuminate\Log\Writer($logger);
  64. $writer->useDailyFiles(storage_path('logs/' . $filename));
  65. return $writer;
  66. }
  67. /**
  68. * 业务调试日志
  69. *
  70. * @return Logger
  71. */
  72. function commonLog()
  73. {
  74. $name = 'common';
  75. $filename = $name . '.log';
  76. $logger = new Logger($name);
  77. $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
  78. return $logger;
  79. }
  80. /**
  81. * @param $name
  82. * @return Logger
  83. */
  84. function dLog($name)
  85. {
  86. $filename = $name . '-' . date('Y-m-d') . '.log';
  87. $logger = new Logger($name);
  88. $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
  89. return $logger;
  90. }
  91. /**
  92. * 获取对象或数组的属性值
  93. *
  94. * @param $param
  95. * @param $key
  96. * @param string $default
  97. * @return mixed|string
  98. */
  99. function getProp($param, $key, $default = '')
  100. {
  101. $result = $default;
  102. if (is_object($param) && isset($param->$key)) {
  103. $result = $param->$key;
  104. }
  105. if (is_array($param) && isset($param[$key])) {
  106. $result = $param[$key];
  107. }
  108. return $result;
  109. }
  110. /**
  111. * @param $data
  112. * @param array $trans
  113. * @return array
  114. */
  115. function assetData($data, $trans = []): array
  116. {
  117. $result = [];
  118. if (empty($data)) {
  119. return $result;
  120. }
  121. if (empty($trans)) {
  122. return $data;
  123. }
  124. foreach ($trans as $tran) {
  125. [$originKey, $newKey, $conv, $default] = [$tran['o'], $tran['n'], $tran['conv'], $tran['default']];
  126. if (isset($data[$originKey])) {
  127. $result[$newKey] = $conv(getProp($data, $originKey, $default));
  128. }
  129. }
  130. return $result;
  131. }
  132. /**
  133. * 随机数
  134. *
  135. * @param int $num
  136. * @return string
  137. * @throws Exception
  138. */
  139. function random($num = 16)
  140. {
  141. $bytes = random_bytes($num);
  142. return bin2hex($bytes);
  143. }
  144. /**
  145. * 生成订单
  146. *
  147. * @param string $prefix 订单前缀
  148. * @return string
  149. */
  150. function generateOrderSn($prefix = '')
  151. {
  152. return $prefix . date('YmdHis') . getMillisecond() . rand(1000, 9999);
  153. }
  154. /**
  155. * 分页数据
  156. *
  157. * @param $data
  158. * @return array
  159. */
  160. function getMeta($data)
  161. {
  162. $currentPage = (int)$data->currentPage();
  163. $lastPage = (int)$data->lastPage();
  164. return [
  165. 'current_page' => $currentPage,
  166. 'next_page' => $currentPage >= $lastPage ? $lastPage : ++$currentPage,
  167. 'last_page' => $lastPage,
  168. 'per_page' => (int)$data->perPage(),
  169. 'total' => (int)$data->total(),
  170. 'is_end' => !$data->hasMorePages(),
  171. 'next_page_url' => (string)$data->nextPageUrl(),
  172. 'prev_page_url' => (string)$data->previousPageUrl()
  173. ];
  174. }
  175. /**
  176. * 钉钉通知异常
  177. *
  178. * @param $message
  179. */
  180. function sendNotice($message)
  181. {
  182. $webHook = env('DD_WEB_HOOK');
  183. $data = [
  184. 'msgtype' => 'text',
  185. 'text' => [
  186. 'content' => $message
  187. ],
  188. 'at' => [
  189. 'isAll' => true
  190. ]
  191. ];
  192. // 异步发送
  193. $client = new GuzzleHttp\Client();
  194. $client->post($webHook, ['json' => $data]);
  195. }
  196. /**
  197. * 判断数据是合法的json数据
  198. *
  199. * @param $string
  200. * @return bool
  201. */
  202. function is_json($string)
  203. {
  204. json_decode($string);
  205. return (json_last_error() == JSON_ERROR_NONE);
  206. }
  207. /**
  208. * 获取ip地址
  209. *
  210. * @return mixed|string
  211. */
  212. function getIpAddr()
  213. {
  214. $ipaddress = '';
  215. if (isset($_SERVER['HTTP_CLIENT_IP']))
  216. $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  217. else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  218. $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  219. else if (isset($_SERVER['HTTP_X_FORWARDED']))
  220. $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  221. else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
  222. $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  223. else if (isset($_SERVER['HTTP_FORWARDED']))
  224. $ipaddress = $_SERVER['HTTP_FORWARDED'];
  225. else if (isset($_SERVER['REMOTE_ADDR']))
  226. $ipaddress = $_SERVER['REMOTE_ADDR'];
  227. else
  228. $ipaddress = 'UNKNOWN';
  229. return $ipaddress;
  230. }
  231. /**
  232. * @param int $num
  233. * @return bool|string
  234. * @throws Exception
  235. */
  236. function randStr($num = 5)
  237. {
  238. $str = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm';
  239. return substr(str_shuffle($str), random_int(0, strlen($str) - 11), $num);
  240. }
  241. /**
  242. * 上传文件(火山云tos)
  243. *
  244. * @param $prefix 文件夹前缀
  245. * @param $file 文件二进制
  246. * @param $filename 文件名(不带后缀)
  247. * @return mixed
  248. */
  249. function uploadFileByTos($prefix, $file, $filename='')
  250. {
  251. if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  252. else $filename = $filename . '.' . $file->getClientOriginalExtension();
  253. try {
  254. $client = new TosClient([
  255. 'region' => env('VOLC_REGION'),
  256. 'endpoint' => env('VOLC_END_POINT'),
  257. 'ak' => env('VOLC_AK'),
  258. 'sk' => env('VOLC_SK'),
  259. ]);
  260. $stream = fopen($file->getRealPath(), 'r');
  261. $input = new PutObjectInput(env('VOLC_BUCKET'), "$prefix/$filename", $stream);
  262. $output = $client->putObject($input);
  263. if ($output->getRequestId()) {
  264. return "https://".env('VOLC_BUCKET').'.'.env('VOLC_END_POINT')."/$prefix/$filename";
  265. }
  266. } catch (TosClientException $ex) {
  267. dLog('exception')->info('saveToTos', [$ex->getMessage()]);
  268. } catch (TosServerException $ex) {
  269. dLog('exception')->info('saveToTos', [$ex->getRequestId(), $ex->getStatusCode(), $ex->getErrorCode()]);
  270. }
  271. return '';
  272. }
  273. /**
  274. * 上传文件流(火山云tos)
  275. *
  276. * @param $prefix 文件夹前缀
  277. * @param $file 文件二进制
  278. * @param $filename 文件名(带后缀)
  279. * @return mixed
  280. */
  281. function uploadStreamByTos($prefix, $stream, $filename)
  282. {
  283. try {
  284. $client = new TosClient([
  285. 'region' => env('VOLC_REGION'),
  286. 'endpoint' => env('VOLC_END_POINT'),
  287. 'ak' => env('VOLC_AK'),
  288. 'sk' => env('VOLC_SK'),
  289. ]);
  290. $input = new PutObjectInput(env('VOLC_BUCKET'), "$prefix/$filename", $stream);
  291. $output = $client->putObject($input);
  292. if ($output->getRequestId()) {
  293. return "https://".env('VOLC_BUCKET').'.'.env('VOLC_END_POINT')."/$prefix/$filename";
  294. }
  295. } catch (TosClientException $ex) {
  296. dLog('exception')->info('saveToTos', [$ex->getMessage()]);
  297. } catch (TosServerException $ex) {
  298. dLog('exception')->info('saveToTos', [$ex->getRequestId(), $ex->getStatusCode(), $ex->getErrorCode()]);
  299. }
  300. return '';
  301. }
  302. // 从图片URL获取图片扩展名
  303. function getImgExtFromUrl(string $url): ?string {
  304. $imageInfo = @getimagesize($url);
  305. if ($imageInfo !== false) {
  306. // 返回MIME类型
  307. return mimeToExt($imageInfo['mime']);
  308. // 或者返回文件扩展名
  309. // return image_type_to_extension($imageInfo[2], false);
  310. }
  311. return null;
  312. }
  313. /**
  314. * 从视频URL获取视频扩展名
  315. * 通过下载文件头部字节来识别真实的视频格式
  316. *
  317. * @param string $url 视频URL
  318. * @return string 返回扩展名(如 .mp4),默认 .mp4
  319. */
  320. function getVideoExtFromUrl(string $url): string {
  321. try {
  322. // 方法1:从URL路径中提取扩展名
  323. $parsedUrl = parse_url($url);
  324. $path = $parsedUrl['path'] ?? '';
  325. $pathInfo = pathinfo($path);
  326. $extension = $pathInfo['extension'] ?? '';
  327. if ($extension) {
  328. // 验证是否为常见视频格式
  329. $validVideoExts = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v', 'mpeg', 'mpg'];
  330. if (in_array(strtolower($extension), $validVideoExts)) {
  331. return '.' . strtolower($extension);
  332. }
  333. }
  334. // 方法2:下载文件头部字节来识别格式
  335. $client = new \GuzzleHttp\Client(['timeout' => 30]);
  336. // 先尝试HEAD请求获取Content-Type
  337. try {
  338. $response = $client->head($url);
  339. $contentType = $response->getHeader('Content-Type')[0] ?? '';
  340. // 根据Content-Type映射扩展名
  341. $mimeMap = [
  342. 'video/mp4' => '.mp4',
  343. 'video/x-msvideo' => '.avi',
  344. 'video/quicktime' => '.mov',
  345. 'video/x-ms-wmv' => '.wmv',
  346. 'video/x-flv' => '.flv',
  347. 'video/x-matroska' => '.mkv',
  348. 'video/webm' => '.webm',
  349. 'video/mpeg' => '.mpeg',
  350. ];
  351. if (isset($mimeMap[$contentType])) {
  352. return $mimeMap[$contentType];
  353. }
  354. } catch (\Exception $e) {
  355. // HEAD请求失败,继续尝试其他方法
  356. }
  357. // 方法3:下载前几个字节分析文件魔数(Magic Number)
  358. $response = $client->get($url, [
  359. 'stream' => true,
  360. 'headers' => [
  361. 'Range' => 'bytes=0-31' // 只下载前32字节
  362. ]
  363. ]);
  364. $header = $response->getBody()->read(32);
  365. // 根据文件魔数判断格式
  366. // MP4/M4V: 以 ftyp 开头(偏移4-8字节)
  367. if (strpos($header, 'ftyp') !== false) {
  368. // 进一步判断是否为 M4V
  369. if (strpos($header, 'M4V') !== false || strpos($header, 'm4v') !== false) {
  370. return '.m4v';
  371. }
  372. return '.mp4';
  373. }
  374. // AVI: 以 RIFF 开头,包含 AVI
  375. if (substr($header, 0, 4) === 'RIFF' && strpos($header, 'AVI') !== false) {
  376. return '.avi';
  377. }
  378. // MOV: 包含 moov 或 mdat
  379. if (strpos($header, 'moov') !== false || strpos($header, 'mdat') !== false) {
  380. return '.mov';
  381. }
  382. // FLV: 以 FLV 开头
  383. if (substr($header, 0, 3) === 'FLV') {
  384. return '.flv';
  385. }
  386. // WebM: 以 0x1A 0x45 0xDF 0xA3 开头
  387. if (ord($header[0]) === 0x1A && ord($header[1]) === 0x45 &&
  388. ord($header[2]) === 0xDF && ord($header[3]) === 0xA3) {
  389. return '.webm';
  390. }
  391. // MKV: 与WebM类似,但包含 matroska
  392. if (strpos($header, 'matroska') !== false) {
  393. return '.mkv';
  394. }
  395. // MPEG: 以 0x00 0x00 0x01 开头
  396. if (ord($header[0]) === 0x00 && ord($header[1]) === 0x00 && ord($header[2]) === 0x01) {
  397. return '.mpeg';
  398. }
  399. // 默认返回 .mp4(最常见的格式)
  400. return '.mp4';
  401. } catch (\Exception $e) {
  402. // 出错时返回默认格式
  403. return '.mp4';
  404. }
  405. }
  406. // 辅助 MIME 映射函数
  407. function mimeToExt(string $mime): ?string {
  408. $map = [
  409. 'audio/wav' => '.wav',
  410. 'audio/x-ms-wma' => '.wma',
  411. 'video/x-ms-wmv' => '.wmv',
  412. 'video/mp4' => '.mp4',
  413. 'audio/mpeg' => '.mp3',
  414. 'audio/amr' => '.amr',
  415. 'application/vnd.rn-realmedia' => '.rm',
  416. 'audio/mid' => '.mid',
  417. 'image/bmp' => '.bmp',
  418. 'image/gif' => '.gif',
  419. 'image/png' => '.png',
  420. 'image/tiff' => '.tiff',
  421. 'image/jpeg' => '.jpg',
  422. 'application/pdf' => '.pdf',
  423. ];
  424. return $map[$mime] ?? null;
  425. }
  426. /**
  427. * 上传文件(阿里云oss)
  428. *
  429. * @param $prefix 文件夹前缀
  430. * @param $file 文件二进制
  431. * @param $filename 文件名(不带后缀)
  432. * @return mixed
  433. */
  434. function uploadFile($prefix, $file, $filename='')
  435. {
  436. // 阿里云主账号
  437. $accessKeyId = env('OSS_ACCESS_ID');
  438. $accessKeySecret = env('OSS_ACCESS_KEY');
  439. $endpoint = env('OSS_END_POINT');
  440. $bucket = env('OSS_BUCKET');
  441. if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  442. else $filename = $filename . '.' . $file->getClientOriginalExtension();
  443. // 设置文件名称。
  444. $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
  445. $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
  446. try {
  447. $configs = [
  448. "provider" => $provider,
  449. "endpoint" => $endpoint,
  450. "signatureVersion" => 'v4',
  451. "region" => "cn-hangzhou"
  452. ];
  453. $ossClient = new OssClient($configs);
  454. $uploadRes = $ossClient->uploadFile($bucket, $object, $file->path());
  455. } catch (OssException $e) {
  456. dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
  457. return '';
  458. }
  459. // 替换域名
  460. if (!isset($uploadRes['oss-request-url'])) return '';
  461. $url = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
  462. $url = urldecode($url);
  463. return str_ireplace('http://', 'https://', $url);
  464. }
  465. /**
  466. * 上传文件流(阿里云oss)
  467. *
  468. * @param $prefix 文件夹前缀
  469. * @param $file 文件二进制
  470. * @param $filename 文件名(带后缀)
  471. * @return mixed
  472. */
  473. function uploadStreamToOss($prefix, $stream, $filename) {
  474. $accessKeyId = env('OSS_ACCESS_ID');
  475. $accessKeySecret = env('OSS_ACCESS_KEY');
  476. $endpoint = env('OSS_END_POINT');
  477. $bucket = env('OSS_BUCKET');
  478. // if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  479. // 设置文件名称。
  480. $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
  481. $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
  482. try{
  483. $configs = [
  484. "provider" => $provider,
  485. "endpoint" => $endpoint,
  486. "signatureVersion" => 'v4',
  487. "region"=> "cn-hangzhou"
  488. ];
  489. $ossClient = new OssClient($configs);
  490. $uploadRes = $ossClient->putObject($bucket, $object, $stream);
  491. } catch (OssException $e) {
  492. dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
  493. return '';
  494. }
  495. // 替换域名
  496. if (!isset($uploadRes['oss-request-url'])) return '';
  497. $url = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
  498. $url = urldecode($url);
  499. return str_ireplace('http://', 'https://', $url);
  500. }
  501. /**
  502. * 下载文件到本地
  503. *
  504. * @param $object
  505. * @param $localFile
  506. * @return string
  507. */
  508. function downloadFile($object, $localFile)
  509. {
  510. // 阿里云主账号
  511. $accessKeyId = env('OSS_ACCESS_ID');
  512. $accessKeySecret = env('OSS_ACCESS_KEY');
  513. $endpoint = env('OSS_END_POINT');
  514. $bucket = env('OSS_BUCKET');
  515. try {
  516. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  517. $ossClient->getObject($bucket, $object, [
  518. OssClient::OSS_FILE_DOWNLOAD => $localFile
  519. ]);
  520. } catch (OssException $e) {
  521. printf($e->getMessage());
  522. return '';
  523. }
  524. }
  525. /**
  526. * 上传封面
  527. *
  528. * @param $file
  529. * @return string
  530. * @throws Exception
  531. */
  532. function uploadCoverFile($file)
  533. {
  534. // 阿里云主账号
  535. $accessKeyId = env('OSS_ACCESS_ID');
  536. $accessKeySecret = env('OSS_ACCESS_KEY');
  537. $endpoint = env('OSS_END_POINT');
  538. $bucket = env('OSS_BUCKET');
  539. // 设置文件名称。
  540. $object = 'books/cover/' . randStr(10) . '.' . $file->getClientOriginalExtension();
  541. try {
  542. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  543. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  544. } catch (OssException $e) {
  545. printf($e->getMessage());
  546. return '';
  547. }
  548. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  549. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  550. }
  551. function uploadAgreementFile($file)
  552. {
  553. // 阿里云主账号
  554. $accessKeyId = env('OSS_ACCESS_ID');
  555. $accessKeySecret = env('OSS_ACCESS_KEY');
  556. $endpoint = env('OSS_END_POINT');
  557. $bucket = env('OSS_BUCKET');
  558. $file_name = $file->getClientOriginalName();
  559. $file_name = str_replace('.' . $file->getClientOriginalExtension(), '', $file_name);
  560. // 设置文件名称。
  561. $object = 'books/contract/' . $file_name . '-' . date('YmdHi') . '.' . $file->getClientOriginalExtension();
  562. try {
  563. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  564. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file);
  565. } catch (OssException $e) {
  566. printf($e->getMessage());
  567. return '';
  568. }
  569. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  570. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . urldecode(getProp($urlArr, 'path')) : '';
  571. }
  572. /**
  573. * 上传wap推荐图片
  574. *
  575. * @param $file
  576. * @param $filename
  577. * @return string
  578. * @throws Exception
  579. */
  580. function uploadWapRecommendPic($file, $filename)
  581. {
  582. // 阿里云主账号
  583. $accessKeyId = env('OSS_ACCESS_ID');
  584. $accessKeySecret = env('OSS_ACCESS_KEY');
  585. $endpoint = env('OSS_END_POINT');
  586. $bucket = env('OSS_BUCKET_YCSD');
  587. // 设置文件名称。
  588. $object = 'ycsd_web_3nd/images/homebanners/' . $filename . '.' . $file->getClientOriginalExtension();
  589. try {
  590. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  591. $options = array(
  592. OssClient::OSS_HEADERS => array(
  593. 'Content-Type' => 'image/jpeg',
  594. 'Content-Disposition' => 'inline'
  595. ),
  596. );
  597. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path(), $options);
  598. } catch (OssException $e) {
  599. printf($e->getMessage());
  600. return '';
  601. }
  602. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  603. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  604. }
  605. /**
  606. * @param $path
  607. * @return Generator
  608. */
  609. function readFileContent($path)
  610. {
  611. if ($handle = fopen($path, 'r')) {
  612. while (!feof($handle)) {
  613. yield trim(fgets($handle));
  614. }
  615. fclose($handle);
  616. }
  617. }
  618. function exportFileCsv(array $headers, array $data, string $filename)
  619. {
  620. header("Content-type:application/vnd.ms-excel");
  621. header("Content-Disposition:attachment;filename=" . $filename . ".csv");
  622. $headers = collect($headers)->map(function ($item) {
  623. return "\"" . mb_convert_encoding($item, "GBK", "UTF-8") . "\"";
  624. })->all();
  625. echo implode(",", $headers);
  626. echo "\r\n";
  627. foreach ($data as $item) {
  628. $rows = collect($item)->map(function ($row) {
  629. return "\"" . mb_convert_encoding(is_numeric($row) && strlen($row) > 12 ? "'" . $row : $row, "GBK", "UTF-8") . "\"";
  630. })->all();
  631. echo implode(",", $rows);
  632. echo "\r\n";
  633. }
  634. exit();
  635. }
  636. //function exportFileCsv(array $header, array $data, string $filename) {
  637. // header('Content-Encoding: UTF-8');
  638. // header("Content-type:application/vnd.ms-excel;charset=UTF-8");
  639. // header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
  640. //
  641. // //打开php标准输出流
  642. // $fp = fopen('php://output', 'a');
  643. //
  644. // //添加BOM头,以UTF8编码导出CSV文件,如果文件头未添加BOM头,打开会出现乱码。
  645. // fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
  646. // //添加导出标题
  647. // fputcsv($fp, $header);
  648. //
  649. // foreach ($data as $k => $item) {
  650. // fputcsv($fp, $item);
  651. // if ($k % 5000 == 0) {
  652. // //每1万条数据就刷新缓冲区
  653. // ob_flush();
  654. // flush();
  655. // }
  656. // }
  657. // exit();
  658. //}
  659. //function exportFileCsv(array $header, array $data, string $filename) {
  660. //
  661. // header('Content-Type: application/vnd.ms-excel');
  662. // header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
  663. // header('Cache-Control: max-age=0');
  664. //
  665. // //打开PHP文件句柄,php://output 表示直接输出到浏览器
  666. // $fp = fopen('php://output', 'a');
  667. //
  668. // //输出Excel列名信息
  669. // foreach ($header as $key => $value) {
  670. // //CSV的Excel支持GBK编码,一定要转换,否则乱码
  671. // $header[$key] = iconv('utf-8', 'gbk', $value);
  672. // }
  673. //
  674. // //将数据通过fputcsv写到文件句柄
  675. // fputcsv($fp, $header);
  676. //
  677. // //计数器
  678. // $num = 0;
  679. //
  680. // //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
  681. // $limit = 10000;
  682. //
  683. // //逐行取出数据,不浪费内存
  684. // $count = count($data);
  685. // for ($i = 0; $i < $count; $i++) {
  686. //
  687. // $num++;
  688. //
  689. // //刷新一下输出buffer,防止由于数据过多造成问题
  690. // if ($limit == $num) {
  691. // ob_flush();
  692. // flush();
  693. // $num = 0;
  694. // }
  695. //
  696. // $row = $data[$i];
  697. // foreach ($row as $key => $value) {
  698. // $row[$key] = iconv('utf-8', 'gbk', $value);
  699. // }
  700. //
  701. // fputcsv($fp, $row);
  702. // }
  703. // exit();
  704. //}
  705. // 获取除空格外的字数
  706. function getSize(string $content)
  707. {
  708. $content = preg_replace('/\s+/', '', $content);
  709. return mb_strlen($content, 'utf-8');
  710. }
  711. // 获取word字符数(不计空格)
  712. function getChargeSize(string $content)
  713. {
  714. //判断是否存在替换字符
  715. $is_replace_count = substr_count($content, "龘");
  716. try {
  717. //先将回车换行符做特殊处理
  718. $str = preg_replace('/(\r\n+|\s+| +)/', "龘", $content);
  719. //处理英文字符数字,连续字母、数字、英文符号视为一个单词
  720. $str = preg_replace('/[a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",\'<>~`\?:;|]/', "m", $str);
  721. //合并字符m,连续字母、数字、英文符号视为一个单词
  722. $str = preg_replace('/m+/', "*", $str);
  723. //去掉回车换行符
  724. $str = preg_replace('/龘+/', "", $str);
  725. //返回字数
  726. return mb_strlen($str) + $is_replace_count;
  727. } catch (\Exception $e) {
  728. return 0;
  729. }
  730. }
  731. // 将阿拉伯数字转换成中文
  732. function chineseNum($figure, $capital = false, $mode = true)
  733. {
  734. if ($figure == '0') return '零';
  735. $numberChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  736. $unitChar = ['', '十', '百', '千', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
  737. if ($capital !== false) {
  738. $numberChar = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  739. $unitChar = ['', '拾', '佰', '仟', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
  740. }
  741. $dec = "点";
  742. $target = '';
  743. $matches = [];
  744. if ($mode) {
  745. preg_match("/^0*(\d*)\.?(\d*)/", $figure, $matches);
  746. } else {
  747. preg_match("/(\d*)\.?(\d*)/", $figure, $matches);
  748. }
  749. list(, $number, $point) = $matches;
  750. if ($point) {
  751. $target = $dec . chineseNum($point, $capital, false);
  752. }
  753. if (!$number) {
  754. return $target;
  755. }
  756. $str = strrev($number);
  757. for ($i = 0; $i < strlen($str); $i++) {
  758. $out[$i] = $numberChar[$str[$i]];
  759. if ($mode === false) {
  760. continue;
  761. }
  762. $out[$i] .= $str[$i] != '0' ? $unitChar[$i % 4] : '';
  763. if ($i > 0 && $str[$i] + $str[$i - 1] == 0) {
  764. $out[$i] = '';
  765. }
  766. if ($i % 4 == 0) {
  767. $temp = substr($str, $i, 4);
  768. $out[$i] = str_replace($numberChar[0], '', $out[$i]);
  769. if (strrev($temp) > 0) {
  770. $out[$i] .= $unitChar[4 + floor($i / 4)];
  771. } else {
  772. $out[$i] .= $numberChar[0];
  773. }
  774. }
  775. }
  776. $result = join('', array_reverse($out)) . $target;
  777. return mb_substr($result, 0, 2) == '一十' ? mb_substr($result, 1) : $result;
  778. }
  779. function addPrefix($str)
  780. {
  781. if (!$str) return '';
  782. if (mb_substr($str, 0, 4) == 'http') return $str;
  783. if (mb_substr($str, 0, 5) == 'https') return $str;
  784. if (mb_substr($str, 0, 7) == '/books/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  785. if (mb_substr($str, 0, 6) == '/card/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  786. if (mb_substr($str, 0, 15) == 'uploader/idcard') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com/' . $str;
  787. if (mb_substr($str, 0, 6) == '/cover') return 'https://cdn-newyc.ycsd.cn/ycsd_cover/covermiddle' . mb_substr($str, 6);
  788. if (mb_substr($str, 0, 8) == '/images/') return 'https://cdn-newyc.ycsd.cn/ycsd_cover' . $str;
  789. }
  790. /**
  791. * 章节内容排版
  792. *
  793. * @param $content
  794. * @return string
  795. */
  796. function filterContent($content)
  797. {
  798. if (!$content) return '';
  799. $content = str_replace(
  800. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  801. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  802. $content);
  803. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  804. // 段落首字母前加两个中文空格
  805. $string = explode(PHP_EOL, $content);
  806. foreach ($string as $line => $text) {
  807. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' '], '', $string[$line]);
  808. if (!$string[$line]) {
  809. unset($string[$line]);
  810. } else {
  811. $string[$line] = $string[$line] . PHP_EOL;
  812. // if (mb_substr($string[$line], 0, 1) == ' ') {
  813. // $string[$line] = str_replace(' ', '', $string[$line]); // 去除多个空格
  814. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  815. // }
  816. // if (mb_substr($string[$line], 0, 2) != '  ') {
  817. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  818. // }
  819. // if (mb_substr($string[$line], 0, 2) == '  ' && str_replace(' ', '', $string[$line])) {
  820. // $string[$line] .= PHP_EOL;
  821. // }
  822. }
  823. }
  824. $content = implode(PHP_EOL, $string);
  825. return $content;
  826. }
  827. /**
  828. * 书籍简介排版
  829. *
  830. * @param $content
  831. * @return string
  832. */
  833. function filterContent2($content)
  834. {
  835. if (!$content) return '';
  836. $content = str_replace(
  837. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  838. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  839. $content);
  840. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  841. // 段落首字母前加两个中文空格
  842. $string = explode(PHP_EOL, $content);
  843. $content = '';
  844. foreach ($string as $line => $text) {
  845. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  846. if (!$string[$line]) {
  847. unset($string[$line]);
  848. } else {
  849. $string[$line] = '  ' . $string[$line] . '<br />';
  850. $content .= $string[$line];
  851. }
  852. }
  853. $content = trim($content, '<br />');
  854. return $content;
  855. }
  856. /**
  857. * 书籍简介排版-抖音版
  858. *
  859. * @param $content
  860. * @return string
  861. */
  862. function filterIntro($content)
  863. {
  864. if (!$content) return '';
  865. $content = str_replace(
  866. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  867. [' ', ' ', ' ', ' ', ' ', '', ' ', '“', '”', '...', '‘', '’', '-'],
  868. $content);
  869. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  870. // 段落首字母前加两个中文空格
  871. $string = explode(PHP_EOL, $content);
  872. $content = '';
  873. foreach ($string as $line => $text) {
  874. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  875. if (!$string[$line]) {
  876. unset($string[$line]);
  877. } else {
  878. $content .= $string[$line];
  879. }
  880. }
  881. $content = trim($content, '<br />');
  882. return $content;
  883. }
  884. function sensitiveStr($list, $string)
  885. {
  886. $count = 0; //违规词的个数
  887. $sensitiveWord = ''; //违规词
  888. $stringAfter = $string; //替换后的内容
  889. $total = count($list);
  890. $size = 500;
  891. $last = ceil($total / $size);
  892. $patternList = [];
  893. for ($page = 1; $page <= $last; $page++) {
  894. $arr = array_slice($list, $size * ($page - 1), $size);
  895. $filter = [];
  896. foreach ($arr as $v) {
  897. if (preg_match('/[^a-zA-Z0-9\|\p{Han}\·]/u', $v)) continue;
  898. $filter[] = $v;
  899. // $a = preg_replace('/[^a-zA-Z0-9\|\p{Han}]/u', '', $v);
  900. // if ($a) $filter[] = $a;
  901. }
  902. $pattern = "/" . implode("|", $filter) . "/i"; //定义正则表达式
  903. if (preg_match_all($pattern, $string, $matches)) { //匹配到了结果
  904. $patternList = array_merge($patternList, $matches[0]); //匹配到的数组
  905. }
  906. }
  907. $sensitiveWord = '';
  908. if ($patternList) {
  909. $count = count($patternList);
  910. // $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
  911. $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '*')); //把匹配到的数组进行合并,替换使用
  912. $stringAfter = strtr($string, $replaceArray); //结果替换
  913. // 将敏感词合并
  914. $return_pattern = [];
  915. foreach ($patternList as $v) {
  916. if (!isset($return_pattern[$v])) {
  917. $return_pattern[$v] = [
  918. 'word' => $v,
  919. 'count' => 1,
  920. ];
  921. } else {
  922. $return_pattern[$v]['count'] += 1;
  923. }
  924. }
  925. foreach ($return_pattern as $v) {
  926. $sensitiveWord .= $v['word'] . ',';
  927. }
  928. }
  929. return [
  930. 'count' => $count,
  931. 'sensitive_words' => trim($sensitiveWord, ','),
  932. 'content' => $stringAfter
  933. ];
  934. }
  935. /**
  936. * 转换时间格式
  937. *
  938. * @param $date
  939. * @param string $format
  940. * @return false|string
  941. */
  942. function transDate($date, $format = 'Y-m-d H:i:s')
  943. {
  944. return strtotime($date) > 0 ? date($format, strtotime($date)) : '';
  945. }
  946. /**
  947. * 根据网段获取计算所有IP
  948. *
  949. * @param string $segment 网段 '139.217.0.1/24'
  950. * @return array [网络地址:139.217.0.1 广播地址:139.217.0.255 IP列表: ['139.217.0.2','139.217.0.3'……'139.217.0.254']]
  951. */
  952. function getIpBySegment($segment)
  953. {
  954. $segmentInfo = explode("/", $segment);
  955. $beginIpArray = explode(".", $segmentInfo[0]);
  956. $mask = intval($segmentInfo['1']);
  957. $endIp = array();
  958. foreach ($beginIpArray as $ipKey => $item) {
  959. $beginFlag = 8 * ($ipKey); //0 8 16 24
  960. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  961. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  962. $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));
  963. }
  964. $ipArray = array();
  965. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0]++) {
  966. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1]++) {
  967. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2]++) {
  968. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3]++) {
  969. $ipArray[] = implode(".", $beginIp);
  970. }
  971. }
  972. }
  973. }
  974. $network_ip_addr = $beginIpArray[0] . '.' . $beginIpArray[1] . '.' . $beginIpArray[2] . '.' . '0'; // 网络地址
  975. $broadcast_ip_addr = end($ipArray); // 广播地址
  976. if ($ipArray[0] == $network_ip_addr) { // 如果是网络地址则删掉
  977. unset($ipArray[0]);
  978. }
  979. $last = count($ipArray);
  980. unset($ipArray[$last]);
  981. return [$network_ip_addr, $broadcast_ip_addr, $ipArray];
  982. }
  983. /**
  984. * 在指定网段中分配子网段
  985. *
  986. * @param string $segment 指定网段
  987. * @param int $ipNum 需要的IP数
  988. * @param array $usedIpArray 不可用(已经使用)的IP,默认为空数组
  989. * @return bool|string 成功则返回分配的网段
  990. */
  991. function allocateSegment($segment, $ipNum, $usedIpArray = [])
  992. {
  993. $usedIpArray = empty($usedIpArray) ? [] : array_flip($usedIpArray);
  994. //计算需要多少个IP
  995. $i = 0;
  996. $ipCount = pow(2, $i);
  997. while ($ipCount < $ipNum) {
  998. $i++;
  999. $ipCount = pow(2, $i);
  1000. }
  1001. $newMask = 32 - $i;
  1002. //大网段的开始和结束IP
  1003. $segmentInfo = explode("/", $segment); //['139.217.0.1',24]
  1004. $beginIpArray = explode(".", $segmentInfo[0]);//[139,217,0,1]
  1005. $mask = intval($segmentInfo['1']); //24
  1006. if ($newMask < $mask) {
  1007. return false;
  1008. }
  1009. $endIp = array();
  1010. $step = [];
  1011. foreach ($beginIpArray as $ipKey => $item) {
  1012. $beginFlag = 8 * ($ipKey); //0 8 16 24
  1013. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  1014. $step[$ipKey] = $newMask > $endFlag ? 1 : ($endFlag - $newMask < 8 ? pow(2, $endFlag - $newMask) : pow(2, 8));
  1015. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  1016. $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));
  1017. }
  1018. //遍历生成网段
  1019. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0] += $step[0]) {
  1020. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1] += $step[1]) {
  1021. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2] += $step[2]) {
  1022. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3] += $step[3]) {
  1023. $newSegment = implode('.', $beginIp) . '/' . $newMask;
  1024. //获取该网段所有的IP
  1025. $ipArray = getIpBySegment($newSegment);
  1026. $canUse = true;
  1027. //判断该网段是否可用
  1028. if (!empty($usedIpArray)) {
  1029. foreach ($ipArray as $ip) {
  1030. if (isset($usedIpArray[$ip])) {
  1031. $canUse = false;
  1032. break;
  1033. }
  1034. }
  1035. }
  1036. if ($canUse) {
  1037. return $newSegment;
  1038. }
  1039. }
  1040. }
  1041. }
  1042. }
  1043. return false;
  1044. }
  1045. function remove_xss($val)
  1046. {
  1047. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  1048. // this prevents some character re-spacing such as <java\0script>
  1049. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
  1050. $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
  1051. // straight replacements, the user should never need these since they're normal characters
  1052. // this prevents like <IMG SRC=@avascript:alert('XSS')>
  1053. $search = 'abcdefghijklmnopqrstuvwxyz';
  1054. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1055. $search .= '1234567890!@#$%^&*()';
  1056. $search .= '~`";:?+/={}[]-_|\'\\';
  1057. for ($i = 0; $i < strlen($search); $i++) {
  1058. // ;? matches the ;, which is optional
  1059. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  1060. // @ @ search for the hex values
  1061. $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
  1062. // @ @ 0{0,7} matches '0' zero to seven times
  1063. $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
  1064. }
  1065. // now the only remaining whitespace attacks are \t, \n, and \r
  1066. $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  1067. $ra2 = array(
  1068. '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'
  1069. );
  1070. $ra = array_merge($ra1, $ra2);
  1071. $found = true; // keep replacing as long as the previous round replaced something
  1072. while ($found == true) {
  1073. $val_before = $val;
  1074. for ($i = 0; $i < sizeof($ra); $i++) {
  1075. $pattern = '/';
  1076. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  1077. if ($j > 0) {
  1078. $pattern .= '(';
  1079. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  1080. $pattern .= '|';
  1081. $pattern .= '|(�{0,8}([9|10|13]);)';
  1082. $pattern .= ')*';
  1083. }
  1084. $pattern .= $ra[$i][$j];
  1085. }
  1086. $pattern .= '/i';
  1087. $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
  1088. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  1089. if ($val_before == $val) {
  1090. // no replacements were made, so exit the loop
  1091. $found = false;
  1092. }
  1093. }
  1094. }
  1095. return $val;
  1096. }
  1097. /**
  1098. * 计算作者积分等级
  1099. *
  1100. * @param $score
  1101. */
  1102. function calcAuthorLevel($score): int
  1103. {
  1104. switch (true) {
  1105. case $score <= 0:
  1106. $level = 0;
  1107. break;
  1108. case $score <= 5000:
  1109. $level = 1;
  1110. break;
  1111. case $score <= 50000:
  1112. $level = 2;
  1113. break;
  1114. case $score <= 100000:
  1115. $level = 3;
  1116. break;
  1117. case $score <= 300000:
  1118. $level = 4;
  1119. break;
  1120. case $score <= 800000:
  1121. $level = 5;
  1122. break;
  1123. case $score <= 1500000:
  1124. $level = 6;
  1125. break;
  1126. case $score <= 2500000:
  1127. $level = 7;
  1128. break;
  1129. case $score <= 5000000:
  1130. $level = 8;
  1131. break;
  1132. case $score <= 10000000:
  1133. $level = 9;
  1134. break;
  1135. default:
  1136. $level = 10;
  1137. break;
  1138. }
  1139. return $level;
  1140. }
  1141. /**
  1142. * 运营数据(上传附件)
  1143. *
  1144. * @param $file
  1145. * @return string
  1146. * @throws Exception
  1147. */
  1148. function uploadEnclosureFile($file)
  1149. {
  1150. // 阿里云主账号
  1151. $accessKeyId = env('OSS_ACCESS_ID');
  1152. $accessKeySecret = env('OSS_ACCESS_KEY');
  1153. $endpoint = env('OSS_END_POINT');
  1154. $bucket = env('OSS_BUCKET');
  1155. // 设置文件名称。
  1156. $object = 'books/enclosure/' . randStr(10) . '--' . $file->getClientOriginalName();
  1157. try {
  1158. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  1159. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  1160. } catch (OssException $e) {
  1161. printf($e->getMessage());
  1162. return '';
  1163. }
  1164. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  1165. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  1166. }
  1167. // 获取当前域名是http还是https
  1168. function getHttpType()
  1169. {
  1170. return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
  1171. }
  1172. // 根据id生成唯一邀请码
  1173. function enCodeId($user_id)
  1174. {
  1175. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1176. $num = strlen($key);
  1177. $code = ''; // 邀请码
  1178. while ($user_id > 0) { // 转进制
  1179. $mod = $user_id % $num; // 求模
  1180. $user_id = ($user_id - $mod) / $num;
  1181. $code = $key[$mod] . $code;
  1182. }
  1183. $code = str_pad($code, 6, 'A', STR_PAD_LEFT); // 不足用0补充
  1184. return $code;
  1185. }
  1186. // 根据邀请码解密为id
  1187. function deCodeId($code)
  1188. {
  1189. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1190. $num = strlen($key);
  1191. if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0') + 1);
  1192. $len = strlen($code);
  1193. $code = strrev($code);
  1194. $user_id = 0;
  1195. for ($i = 0; $i < $len; $i++) {
  1196. $user_id += strpos($key, $code[$i]) * pow($num, $i);
  1197. }
  1198. return $user_id;
  1199. }
  1200. /**
  1201. * 将二维数组按其中的某个数组排序(此方法适用于将数据库数据按数组取出后自动按ID排序的情况 ps:即未按该数组排序)
  1202. *
  1203. * @param array $array 二维数组
  1204. * @param array $sort 排序数组
  1205. * @param string $field 排序字段(二维数组和排序数组相同的字段)
  1206. * @return array
  1207. */
  1208. function sortByArray(array $array, array $sort, string $field): array
  1209. {
  1210. $data = [];
  1211. if (is_array($array) && is_array($sort)) {
  1212. foreach ($sort as $v) {
  1213. foreach ($array as $key => $val) {
  1214. if ($v == $val[$field]) {
  1215. array_push($data, $array[$key]);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. return $data;
  1221. }
  1222. /**
  1223. * 将二维数组按其中的字段排序(正序或倒序)
  1224. *
  1225. * @param array $array 二维数组
  1226. * @param string $field 排序字段
  1227. * @param mixed $type 排序方式(3倒序,4正序)
  1228. * @return array|mixed
  1229. */
  1230. function sortByField(array $array, string $field, $type): array
  1231. {
  1232. if (is_array($array)) {
  1233. array_multisort(array_column($array, $field), $type, $array);
  1234. }
  1235. return $array;
  1236. }
  1237. // 生成用户邀请码
  1238. function setUserInviteCode($id)
  1239. {
  1240. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->encode($id);
  1241. }
  1242. // 解密用户邀请码
  1243. function decodeUserInviteCode($code)
  1244. {
  1245. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->decode($code);
  1246. }
  1247. function getMillisecond()
  1248. {
  1249. list($microsecond, $time) = explode(' ', microtime());
  1250. return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
  1251. }
  1252. function get_client_ip($type = 0, $adv = false)
  1253. {
  1254. $type = $type ? 1 : 0;
  1255. static $ip = null;
  1256. if (null !== $ip) {
  1257. return $ip[$type];
  1258. }
  1259. if ($adv) {
  1260. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1261. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1262. $pos = array_search('unknown', $arr);
  1263. if (false !== $pos) {
  1264. unset($arr[$pos]);
  1265. }
  1266. $ip = trim($arr[0]);
  1267. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1268. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1269. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1270. $ip = $_SERVER['REMOTE_ADDR'];
  1271. }
  1272. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1273. $ip = $_SERVER['REMOTE_ADDR'];
  1274. }
  1275. // IP地址合法验证
  1276. $long = sprintf("%u", ip2long($ip));
  1277. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  1278. return $ip[$type];
  1279. }
  1280. /**
  1281. * 获取真实IP
  1282. */
  1283. function _getIp()
  1284. {
  1285. if (getenv('HTTP_X_FORWARDED_FOR')) {
  1286. $ip = getenv('HTTP_X_FORWARDED_FOR');
  1287. } else if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  1288. $ip = getenv("HTTP_CLIENT_IP");
  1289. else if (getenv("HTTP_X_FORWARD_FOR") && strcasecmp(getenv("HTTP_X_FORWARD_FOR"), "unknown"))
  1290. $ip = getenv("HTTP_X_FORWARD_FOR");
  1291. else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  1292. $ip = getenv("REMOTE_ADDR");
  1293. else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  1294. $ip = $_SERVER['REMOTE_ADDR'];
  1295. else
  1296. $ip = "unknown";
  1297. return ($ip);
  1298. }
  1299. /**
  1300. * 数组 转 对象
  1301. *
  1302. * @param array $arr 数组
  1303. * @return object
  1304. */
  1305. function array_to_object($arr)
  1306. {
  1307. if (gettype($arr) != 'array') {
  1308. return;
  1309. }
  1310. foreach ($arr as $k => $v) {
  1311. if (gettype($v) == 'array' || getType($v) == 'object') {
  1312. $arr[$k] = (object)array_to_object($v);
  1313. }
  1314. }
  1315. return (object)$arr;
  1316. }
  1317. /**
  1318. * 对象 转 数组
  1319. *
  1320. * @param object $obj 对象
  1321. * @return array
  1322. */
  1323. function object_to_array($obj)
  1324. {
  1325. $obj = (array)$obj;
  1326. foreach ($obj as $k => $v) {
  1327. if (gettype($v) == 'resource') {
  1328. return;
  1329. }
  1330. if (gettype($v) == 'object' || gettype($v) == 'array') {
  1331. $obj[$k] = (array)object_to_array($v);
  1332. }
  1333. }
  1334. return $obj;
  1335. }
  1336. /**
  1337. * 检查是否为手机号码
  1338. */
  1339. function _isPhone($number)
  1340. {
  1341. return preg_match("/^1[34578][0-9]{9}$/", $number);
  1342. }
  1343. /**
  1344. * 判断所传的参数是否缺少,如果缺少返回渠道的字段,正确返回0
  1345. *
  1346. * @param array $param
  1347. * @param array $must
  1348. * @return int|mixed
  1349. */
  1350. function checkParam(array $param, array $must)
  1351. {
  1352. foreach ($must as $item) {
  1353. if (array_key_exists($item, $param) && $param[$item] != '') {
  1354. } else {
  1355. return $item;
  1356. }
  1357. }
  1358. return 0;
  1359. }
  1360. /**
  1361. * 对象 转 数组
  1362. *
  1363. * @param object $obj 对象
  1364. * @return array
  1365. */
  1366. function ignoreKeyInArray($targetArray, $delete_keys = [], $changes = [])
  1367. {
  1368. $change_keys = array_keys($changes);
  1369. foreach ($targetArray as $key => $value) {
  1370. if (in_array($key, $delete_keys) && isset($targetArray[$key])) unset($targetArray[$key]);
  1371. if (in_array($key, $change_keys) && isset($targetArray[$key])) $targetArray[$key] = $changes[$key];
  1372. if (is_array($value)) ignoreKeyInArray($value, $delete_keys, $change_keys);
  1373. }
  1374. return $targetArray;
  1375. }
  1376. function itemTransform($trans, $data)
  1377. {
  1378. if ($data) {
  1379. return $trans->transform($data);
  1380. } else {
  1381. return [];
  1382. }
  1383. }
  1384. function collectionTransform($trans, $data)
  1385. {
  1386. $ret_data = [];
  1387. if ($data) {
  1388. foreach ($data as $item) {
  1389. $ret_data[] = $trans->transform($item);
  1390. }
  1391. }
  1392. return $ret_data;
  1393. }
  1394. function paginationTransform($trans, $paginator)
  1395. {
  1396. $ret = [];
  1397. $ret['list'] = [];
  1398. if ($paginator) {
  1399. foreach ($paginator as $item) {
  1400. $ret['list'][] = $trans->transform($item);
  1401. }
  1402. $ret['meta'] = [
  1403. 'total' => (int)$paginator->total(),
  1404. 'per_page' => (int)$paginator->perPage(),
  1405. 'current_page' => (int)$paginator->currentPage(),
  1406. 'last_page' => (int)$paginator->lastPage(),
  1407. 'next_page_url' => (string)$paginator->nextPageUrl(),
  1408. 'prev_page_url' => (string)$paginator->previousPageUrl()
  1409. ];
  1410. }
  1411. return $ret;
  1412. }
  1413. /**
  1414. * 加密site id
  1415. */
  1416. function encodeDistributionChannelId($id)
  1417. {
  1418. $encrypt_pool = [
  1419. ];
  1420. if (isset($encrypt_pool[$id])) {
  1421. return $encrypt_pool[$id];
  1422. }
  1423. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1424. return $hashids->encode($id);
  1425. }
  1426. /**
  1427. * 解密密site id
  1428. */
  1429. function decodeDistributionChannelId($code)
  1430. {
  1431. $encrypt_pool = [
  1432. ];
  1433. if (isset($encrypt_pool[$code])) {
  1434. return $encrypt_pool[$code];
  1435. }
  1436. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1437. $res = $hashids->decode($code);
  1438. if ($res && isset($res[0])) {
  1439. return $res[0];
  1440. }
  1441. return null;
  1442. }
  1443. //bid加密
  1444. function book_hash_encode($bid)
  1445. {
  1446. return Vinkla\Hashids\Facades\Hashids::encode($bid);
  1447. }
  1448. function decodeBid($encode_bid)
  1449. {
  1450. $bid = 0;
  1451. try {
  1452. $bid_arr = \Hashids::decode($encode_bid);
  1453. if (isset($bid_arr[0])) {
  1454. $bid = $bid_arr[0];
  1455. }
  1456. } catch (\Exception $e) {
  1457. return null;
  1458. }
  1459. return $bid;
  1460. }
  1461. /**
  1462. * 获取当前域名
  1463. */
  1464. function _domain()
  1465. {
  1466. return str_replace('https://', '', str_replace('http://', '', url('/')));
  1467. }
  1468. /**
  1469. * 字符串转*
  1470. *
  1471. * @param $str // 待转的字符串
  1472. * @param $start // 转*起始位置
  1473. * @param int $end // 转*结束位置
  1474. * @param string $dot // 转换的字符(必须是单字符,默认是*)
  1475. * @param string $charset // 编码方式
  1476. * @param string $end_char // 特殊字符(碰到此字符则确定end位置)
  1477. * @return string
  1478. */
  1479. function trans_pass($str, $start, $end = 0, $dot = "*", $charset = "UTF-8", $end_char = '@'): string
  1480. {
  1481. $len = mb_strlen($str, $charset);
  1482. if ($start == 0 || $start > $len) {
  1483. $start = 1;
  1484. }
  1485. if ($end != 0 && $end > $len) {
  1486. $end = $len - 2;
  1487. }
  1488. if (strstr($str, $end_char)) {
  1489. $end = $len - strrpos($str, $end_char);
  1490. }
  1491. $endStart = $len - $end;
  1492. $top = mb_substr($str, 0, $start, $charset);
  1493. $bottom = "";
  1494. if ($endStart > 0) {
  1495. $bottom = mb_substr($str, $endStart, $end, $charset);
  1496. }
  1497. $len -= mb_strlen($top, $charset);
  1498. $len -= mb_strlen($bottom, $charset);
  1499. $newStr = $top;
  1500. for ($i = 0; $i < $len; $i++) {
  1501. $newStr .= $dot;
  1502. }
  1503. $newStr .= $bottom;
  1504. return $newStr;
  1505. }
  1506. /**
  1507. * 格式化章节内容
  1508. *
  1509. * @param $content
  1510. * @return false|string
  1511. */
  1512. function formatContent($content)
  1513. {
  1514. if (!$content) return '';
  1515. $content = str_replace(
  1516. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p >', '&ldquo;', '&rdquo;', '&hellip;'],
  1517. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...'],
  1518. $content);
  1519. $content = str_replace(["&nbsp;", '&ldquo;', '&hellip;', '&rdquo;', '<p>'], '', $content);
  1520. // 段落首字母前加两个中文空格
  1521. $string = explode(PHP_EOL, $content);
  1522. foreach ($string as $line => $text) {
  1523. if (mb_substr($text, 0, 2) != '  ') $string[$line] = '  ' . $text;
  1524. }
  1525. $content = implode(PHP_EOL, $string);
  1526. $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8,GBK,GB2312');
  1527. $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);
  1528. return $content;
  1529. }
  1530. /**
  1531. * 筛选出有效的id集合
  1532. *
  1533. * @param array $ids
  1534. * @return array
  1535. */
  1536. function filterValidIds(array $ids): array
  1537. {
  1538. // 传参
  1539. if (empty($ids)) {
  1540. return [];
  1541. }
  1542. $result = [];
  1543. foreach ($ids as $id) {
  1544. if (in_array($id, $result) || !is_numeric($id) || (int)$id < 1) {
  1545. continue;
  1546. }
  1547. $result[] = (int)$id;
  1548. }
  1549. return $result;
  1550. }
  1551. function arrayToStr($map)
  1552. {
  1553. $isMap = isArrMap($map);
  1554. $result = "";
  1555. if ($isMap) {
  1556. $result = "map[";
  1557. }
  1558. $keyArr = array_keys($map);
  1559. if ($isMap) {
  1560. sort($keyArr);
  1561. }
  1562. $paramsArr = array();
  1563. foreach ($keyArr as $k) {
  1564. $v = $map[$k];
  1565. if ($isMap) {
  1566. if (is_array($v)) {
  1567. $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
  1568. } else {
  1569. $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
  1570. }
  1571. } else {
  1572. if (is_array($v)) {
  1573. $paramsArr[] = arrayToStr($v);
  1574. } else {
  1575. $paramsArr[] = trim(strval($v));
  1576. }
  1577. }
  1578. }
  1579. $result = sprintf("%s%s", $result, join(" ", $paramsArr));
  1580. if (!$isMap) {
  1581. $result = sprintf("[%s]", $result);
  1582. } else {
  1583. $result = sprintf("%s]", $result);
  1584. }
  1585. return $result;
  1586. }
  1587. function isArrMap($map)
  1588. {
  1589. foreach ($map as $k => $v) {
  1590. if (is_string($k)) {
  1591. return true;
  1592. }
  1593. }
  1594. return false;
  1595. }
  1596. /**
  1597. * 随机字符串
  1598. *
  1599. * @param $length
  1600. * @return string
  1601. */
  1602. function makeRandStr($length): string
  1603. {
  1604. // 密码字符集,可任意添加你需要的字符
  1605. $str = [
  1606. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  1607. 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  1608. 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
  1609. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  1610. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  1611. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  1612. ];
  1613. // 在 $str 中随机取 $length 个数组元素键名
  1614. $keys = array_rand($str, $length);
  1615. $password = '';
  1616. for ($i = 0; $i < $length; $i++) {
  1617. // 将 $length 个数组元素连接成字符串
  1618. $password .= $str[$keys[$i]];
  1619. }
  1620. return $password;
  1621. }
  1622. /**
  1623. * 导出数据为excel表格
  1624. *
  1625. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1626. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1627. * @param $filename 下载的文件名
  1628. * @examlpe10
  1629. */
  1630. function exportExcel($data = [], $title = [], $filename = 'report')
  1631. {
  1632. ob_end_clean();
  1633. ob_start();
  1634. header("Content-type:application/octet-stream");
  1635. header("Accept-Ranges:bytes");
  1636. header("Content-type:application/vnd.ms-excel");
  1637. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1638. header("Pragma: no-cache");
  1639. header("Expires: 0");
  1640. //导出xls 开始
  1641. if (!empty($title)) {
  1642. foreach ($title as $k => $v) {
  1643. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1644. }
  1645. $title = implode("\t", $title);
  1646. echo "$title\n";
  1647. }
  1648. if (!empty($data)) {
  1649. foreach ($data as $key => $val) {
  1650. foreach ($val as $ck => $cv) {
  1651. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1652. }
  1653. $data[$key] = implode("\t", $data[$key]);
  1654. }
  1655. echo implode("\n", $data);
  1656. }
  1657. }
  1658. /**
  1659. * 导出csv文件
  1660. * @param string $name
  1661. * @param array $headers
  1662. * @param array $data
  1663. * @return void
  1664. */
  1665. function exportCsv(string $name, array $headers, array $data = [])
  1666. {
  1667. header('Content-Description: File Transfer');
  1668. header('Content-Type: application/csv');
  1669. header("Content-Disposition: attachment; filename=".$name.".csv");
  1670. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  1671. $handle = fopen('php://output', 'w');
  1672. ob_clean();
  1673. fputcsv($handle, $headers);
  1674. if ($data) {
  1675. foreach ($data as $row) {
  1676. fputcsv($handle, $row);
  1677. }
  1678. }
  1679. ob_flush();
  1680. fclose($handle);
  1681. die();
  1682. }
  1683. // 树状分类
  1684. function buildCategoryTree($categories, $pid = 0) {
  1685. $tree = [];
  1686. foreach ($categories as $category) {
  1687. if ($category['pid'] == $pid) {
  1688. $children = buildCategoryTree($categories, $category['category_id']);
  1689. if ($children) {
  1690. $category['children'] = $children;
  1691. }
  1692. $tree[] = $category;
  1693. }
  1694. }
  1695. return $tree;
  1696. }
  1697. // 获取文件的md5值
  1698. function getFileContentMD5($filePath){
  1699. //获取文件MD5的128位二进制数组
  1700. $md5Bytes = md5_file($filePath,true);
  1701. //计算文件的Content-MD5
  1702. $contentMD5 = base64_encode($md5Bytes);
  1703. return $contentMD5;
  1704. }
  1705. function getTextTokens($text) {
  1706. // 方法1:按空格分词(西文较准)
  1707. $words = preg_split('/\s+/', $text);
  1708. $wordCount = count($words);
  1709. // 方法2:按字符数估算(中文较准:1个汉字 ≈ 1.5-2 tokens)
  1710. $charCount = mb_strlen($text);
  1711. // 综合估算(根据语言调整权重)
  1712. $tokenCount = $wordCount + $charCount * 0.5; // 示例公式
  1713. // 更简单:直接按字符数 * 系数(中文推荐)
  1714. // $tokenCount = $charCount * 1.8; // 经验系数
  1715. return (int)ceil($tokenCount);
  1716. }
  1717. // 处理小说剧本文本
  1718. function handleScriptWords($text, $enable_emotion=1) {
  1719. $text = preg_replace('/[\r\n]+/', PHP_EOL, $text);
  1720. $text_arr = explode(PHP_EOL, $text);
  1721. $roles = [];
  1722. $words = [];
  1723. $role_gender = [];
  1724. // $sequence = 0;
  1725. foreach ($text_arr as $line) {
  1726. $line = trim($line);
  1727. if ($enable_emotion) {
  1728. $match_rule = '/^(.*?)\:(.*?)\{(.*?)\}$/';
  1729. $count = 4;
  1730. } else {
  1731. $match_rule = '/^(.*?)\:(.*?)$/';
  1732. $count = 3;
  1733. }
  1734. preg_match($match_rule, $line, $matches);
  1735. if (count($matches) == $count) {
  1736. $gender = '0';
  1737. // 角色部分拆分
  1738. preg_match('/^(.*?)\((.*?)\)$/', $matches[1], $matches2);
  1739. if (count($matches2) == 3) {
  1740. $role = $matches2[1];
  1741. $gender_arr = ['男'=>'1', '女'=>'2'];
  1742. $gender = isset($gender_arr[$matches2[2]]) ? $gender_arr[$matches2[2]] : '0';
  1743. }else {
  1744. $role = $matches[1];
  1745. }
  1746. if (!in_array($role, $roles)) {
  1747. $roles[] = $role; // 记录角色
  1748. $role_gender[$role] = $gender;
  1749. }
  1750. $words[] = [
  1751. 'role' => $role,
  1752. 'gender' => $gender,
  1753. 'text' => $matches[2],
  1754. 'emotion' => $enable_emotion ? $matches[3] : '中性',
  1755. ];
  1756. }
  1757. }
  1758. $new_words = [];
  1759. $tmp = '';
  1760. $tmp_arr = [];
  1761. $tmp_text = '';
  1762. // 将words数组按照role和emotion合并相邻的text内容,不相邻则跳过合并
  1763. foreach ($words as $word) {
  1764. if(!$tmp) $tmp = $word['role'].'-'.$word['emotion'];
  1765. if($tmp == $word['role'].'-'.$word['emotion']) {
  1766. $tmp_text .= PHP_EOL.$word['text'];
  1767. $tmp_arr = [
  1768. 'role' => $word['role'],
  1769. 'gender' => $word['gender'],
  1770. 'text' => trim($tmp_text, PHP_EOL),
  1771. 'emotion' => $word['emotion'],
  1772. ];
  1773. }else {
  1774. // $sequence++;
  1775. // $tmp_arr['sequence'] = $sequence;
  1776. $new_words[] = $tmp_arr;
  1777. $tmp = $word['role'].'-'.$word['emotion'];
  1778. $tmp_text = $word['text'];
  1779. $tmp_arr = [
  1780. 'role' => $word['role'],
  1781. 'gender' => $word['gender'],
  1782. 'text' => trim($tmp_text, PHP_EOL),
  1783. 'emotion' => $word['emotion'],
  1784. ];
  1785. }
  1786. }
  1787. if ($tmp_arr) {
  1788. // $sequence++;
  1789. // $tmp_arr['sequence'] = $sequence;
  1790. $new_words[] = $tmp_arr;
  1791. }
  1792. return [
  1793. 'roles' => $roles,
  1794. 'role_gender' => $role_gender,
  1795. 'words' => $new_words,
  1796. ];
  1797. }
  1798. function extractScriptContent($originalContent) {
  1799. if (!$originalContent) return [];
  1800. // 使用更精确的正则表达式分割内容
  1801. $parts = [];
  1802. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  1803. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  1804. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  1805. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  1806. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  1807. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  1808. // 提取剧本亮点(支持多个空格)
  1809. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  1810. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  1811. // 提取人物关系(支持多个空格)
  1812. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  1813. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  1814. // 提取核心矛盾(支持多个空格)
  1815. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  1816. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  1817. // 提取主体列表(支持多个空格)
  1818. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  1819. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  1820. $parts['roles'] = parseRolesFromText($rolesText);
  1821. // 提取美术风格(支持多个空格)
  1822. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  1823. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  1824. // 提取场景列表(支持多个空格)
  1825. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  1826. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  1827. $parts['scenes'] = parseScenesFromText($scenesText);
  1828. // 提取分集详细内容(多剧集模式,支持多个空格)
  1829. preg_match('/###\s*分集剧本\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  1830. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  1831. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  1832. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  1833. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  1834. // 优先使用原文内容,其次使用分集详细内容
  1835. // $parts['content'] = $generatedContent ?: $detailedContent;
  1836. // 解析分集剧本内容
  1837. $episodes = [];
  1838. if ($detailedContent) {
  1839. // 按 ##分集 分割
  1840. preg_match_all('/##\s*分集(\d+)\s*\n(.*?)(?=\n\s*##分集|\z)/s', $detailedContent, $episodeMatches, PREG_SET_ORDER);
  1841. foreach ($episodeMatches as $episodeMatch) {
  1842. $episodeNum = $episodeMatch[1];
  1843. $episodeContent = trim($episodeMatch[2]);
  1844. $episode = [
  1845. 'episode_number' => $episodeNum,
  1846. 'episode_content' => $episodeContent,
  1847. 'episode_name' => '',
  1848. 'scene_description' => '',
  1849. 'camera_movement' => '',
  1850. 'characters' => '',
  1851. 'dialogues' => []
  1852. ];
  1853. // 提取分集名(格式:##分集01第一集: 第一集的标题)
  1854. if (preg_match('/^第.*?集\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $nameMatch)) {
  1855. $episode['episode_name'] = trim($nameMatch[1]);
  1856. }
  1857. // 提取场景描述
  1858. if (preg_match('/场景描述\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $sceneMatch)) {
  1859. $episode['scene_description'] = trim($sceneMatch[1]);
  1860. }
  1861. // 提取运镜
  1862. if (preg_match('/运镜\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $cameraMatch)) {
  1863. $episode['camera_movement'] = trim($cameraMatch[1]);
  1864. }
  1865. // 提取出场角色
  1866. if (preg_match('/出场角色\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $charactersMatch)) {
  1867. $episode['characters'] = trim($charactersMatch[1]);
  1868. }
  1869. // 提取台词内容
  1870. if (preg_match('/台词内容\s*[::]\s*\n(.*?)$/su', $episodeContent, $dialoguesMatch)) {
  1871. $dialoguesText = trim($dialoguesMatch[1]);
  1872. $dialogueLines = explode("\n", $dialoguesText);
  1873. foreach ($dialogueLines as $line) {
  1874. $line = trim($line);
  1875. if (empty($line)) {
  1876. continue;
  1877. }
  1878. // 匹配格式:角色名: 对话内容 或 角色名:对话内容
  1879. if (preg_match('/^(.+?)\s*[::]\s*(.+)$/u', $line, $dialogueMatch)) {
  1880. $episode['dialogues'][] = [
  1881. 'character' => trim($dialogueMatch[1]),
  1882. 'text' => trim($dialogueMatch[2])
  1883. ];
  1884. }
  1885. }
  1886. }
  1887. $episodes[] = $episode;
  1888. }
  1889. }
  1890. $parts['episodes'] = $episodes;
  1891. return $parts;
  1892. }
  1893. /**
  1894. * 处理剧本内容
  1895. */
  1896. function handleScriptContent($originalContent) {
  1897. if (!$originalContent) return [];
  1898. // 使用更精确的正则表达式分割内容
  1899. $parts = [];
  1900. // // 确保内容使用UTF-8编码
  1901. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  1902. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  1903. // }
  1904. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  1905. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  1906. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  1907. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  1908. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  1909. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  1910. // 提取剧本亮点(支持多个空格)
  1911. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  1912. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  1913. // 提取人物关系(支持多个空格)
  1914. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  1915. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  1916. // 提取核心矛盾(支持多个空格)
  1917. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  1918. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  1919. // 提取主体列表(支持多个空格)
  1920. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  1921. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  1922. $parts['roles'] = parseRolesFromText($rolesText);
  1923. // 提取美术风格(支持多个空格)
  1924. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  1925. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  1926. // 提取场景列表(支持多个空格)
  1927. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  1928. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  1929. $parts['scenes'] = parseScenesFromText($scenesText);
  1930. // 提取分集详细内容(多剧集模式,支持多个空格)
  1931. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  1932. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  1933. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  1934. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  1935. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  1936. // 优先使用原文内容,其次使用分集详细内容
  1937. $parts['content'] = $generatedContent ?: $detailedContent;
  1938. $parts['episode_title'] = '';
  1939. $parts['acts'] = [];
  1940. // 单剧集格式:顶层是大纲信息,分镜部分采用 handleEpisodeContent 的结构标准
  1941. $singleStoryboard = '';
  1942. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  1943. $singleStoryboard = trim($singleStoryboardMatch[1]);
  1944. }
  1945. if ($singleStoryboard !== '') {
  1946. $episodeContent = $singleStoryboard;
  1947. if (!preg_match('/第\d+集[::\s]+/u', $episodeContent)) {
  1948. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  1949. $episodeContent = $defaultEpisodeTitle . "\n\n" . $episodeContent;
  1950. }
  1951. $episodeSections = [];
  1952. $episodeSections[] = $episodeContent;
  1953. if ($parts['intro'] !== '') {
  1954. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  1955. }
  1956. if ($parts['art_style'] !== '') {
  1957. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  1958. }
  1959. if ($rolesText !== '') {
  1960. $episodeSections[] = "###主体列表\n" . $rolesText;
  1961. }
  1962. if ($scenesText !== '') {
  1963. $episodeSections[] = "###场景列表\n" . $scenesText;
  1964. }
  1965. if (strpos($episodeContent, '###分镜剧本') === false) {
  1966. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  1967. }
  1968. $episode_arr = handleEpisodeContent(implode("\n\n", $episodeSections));
  1969. if (!empty($episode_arr['acts'])) {
  1970. $parts['episode_title'] = getProp($episode_arr, 'episode_title');
  1971. $parts['acts'] = getProp($episode_arr, 'acts', []);
  1972. if (empty($parts['roles'])) {
  1973. $parts['roles'] = getProp($episode_arr, 'roles', []);
  1974. }
  1975. if (empty($parts['scenes'])) {
  1976. $parts['scenes'] = getProp($episode_arr, 'scenes', []);
  1977. }
  1978. }
  1979. }
  1980. if (empty($parts['acts'])) {
  1981. $fallbackEpisodeArr = handleEpisodeContent($originalContent);
  1982. if (!empty($fallbackEpisodeArr['acts'])) {
  1983. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title');
  1984. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  1985. if (empty($parts['intro'])) {
  1986. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro');
  1987. }
  1988. if (empty($parts['art_style'])) {
  1989. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style');
  1990. }
  1991. if (empty($parts['roles'])) {
  1992. $parts['roles'] = getProp($fallbackEpisodeArr, 'roles', []);
  1993. }
  1994. if (empty($parts['scenes'])) {
  1995. $parts['scenes'] = getProp($fallbackEpisodeArr, 'scenes', []);
  1996. }
  1997. }
  1998. }
  1999. // 多剧集格式:继续兼容旧的分集剧本结构
  2000. $fullScript = '';
  2001. if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2002. $fullScript = trim($storyboardMatch[1]);
  2003. } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2004. $fullScript = trim($storyboardMatch[1]);
  2005. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2006. $fullScript = trim($storyboardMatch[1]);
  2007. }
  2008. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  2009. $fullScript = trim($fallbackMatch[1]);
  2010. }
  2011. $episodes = [];
  2012. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  2013. foreach ($matches as $match) {
  2014. $episodeNumber = (int)trim($match[1]);
  2015. $episodeName = trim($match[2]);
  2016. $episodeContent = trim($match[3]);
  2017. $segments = [];
  2018. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  2019. foreach ($segmentMatches as $segMatch) {
  2020. $segmentNumber = (int)trim($segMatch[1]);
  2021. $segmentContent = trim($segMatch[2]);
  2022. $segments[] = [
  2023. 'segment_number' => $segmentNumber,
  2024. 'segment_content' => $segmentContent,
  2025. ];
  2026. }
  2027. $episodes[] = [
  2028. 'episode_number' => $episodeNumber,
  2029. 'title' => $episodeName,
  2030. 'content' => $episodeContent,
  2031. 'segments' => $segments,
  2032. ];
  2033. }
  2034. if (empty($episodes) && !empty($parts['acts'])) {
  2035. $singleSegments = [];
  2036. foreach ($parts['acts'] as $act) {
  2037. $actSegments = getProp($act, 'segments', []);
  2038. if (!is_array($actSegments)) {
  2039. continue;
  2040. }
  2041. foreach ($actSegments as $segment) {
  2042. $singleSegments[] = [
  2043. 'segment_number' => getProp($segment, 'segment_number'),
  2044. 'segment_content' => getProp($segment, 'segment_content'),
  2045. ];
  2046. }
  2047. }
  2048. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  2049. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  2050. $episodes[] = [
  2051. 'episode_number' => 1,
  2052. 'title' => $episodeName,
  2053. 'content' => $singleStoryboard,
  2054. 'segments' => $singleSegments,
  2055. ];
  2056. }
  2057. $parts['episodes'] = $episodes;
  2058. return $parts;
  2059. }
  2060. function handleEpisodeContent($originalContent) {
  2061. if (!$originalContent) return [];
  2062. // 解析剧集内容
  2063. $result = [
  2064. 'episode_title' => '',
  2065. 'intro' => '',
  2066. 'art_style' => '',
  2067. 'roles' => [],
  2068. 'scenes' => [],
  2069. 'acts' => []
  2070. ];
  2071. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  2072. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  2073. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  2074. }
  2075. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  2076. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  2077. $result['intro'] = trim($summaryMatch[1]);
  2078. }
  2079. // 提取美术风格 - 兼容多种格式
  2080. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  2081. $result['art_style'] = trim($styleMatch[1]);
  2082. }
  2083. // 提取主体列表 - 兼容多种格式
  2084. if (preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  2085. $charactersText = trim($charactersMatch[1]);
  2086. $characterLines = explode("\n", $charactersText);
  2087. foreach ($characterLines as $line) {
  2088. $line = trim($line);
  2089. if (empty($line)) continue;
  2090. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  2091. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2092. $role = trim($charMatch[1]);
  2093. $description = trim($charMatch[2]);
  2094. $timbreName = null;
  2095. // 检查描述末尾是否有{{音色名}}格式
  2096. if (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2097. $description = trim($timbreMatch[1]);
  2098. $timbreName = trim($timbreMatch[2]);
  2099. }
  2100. $roleData = [
  2101. 'role' => $role,
  2102. 'description' => $description
  2103. ];
  2104. // 如果有音色信息,添加到数组中
  2105. if ($timbreName) {
  2106. $timbre = DB::table('mp_timbres')->where('is_enabled', 1)->where('timbre_name', 'like', "%{$timbreName}%")->orderBy('id')->select('timbre_type', 'audio_url')->first();
  2107. if ($timbre) {
  2108. $roleData['voice_name'] = $timbreName;
  2109. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2110. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');;
  2111. }
  2112. }
  2113. $result['roles'][] = $roleData;
  2114. }
  2115. }
  2116. // 加入旁白角色(如果不存在)
  2117. $hasNarrator = false;
  2118. foreach ($result['roles'] as $role) {
  2119. if (isset($role['role']) && $role['role'] === '旁白') {
  2120. $hasNarrator = true;
  2121. break;
  2122. }
  2123. }
  2124. if (!$hasNarrator) {
  2125. $result['roles'][] = [
  2126. 'role' => '旁白',
  2127. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2128. 'voice_name' => '旁白',
  2129. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2130. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2131. ];
  2132. }
  2133. }
  2134. // 提取场景列表 - 兼容多种格式
  2135. if (preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  2136. $scenesText = trim($scenesMatch[1]);
  2137. $sceneLines = explode("\n", $scenesText);
  2138. foreach ($sceneLines as $line) {
  2139. $line = trim($line);
  2140. if (empty($line)) continue;
  2141. // 兼容中文冒号:和英文冒号:
  2142. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  2143. $result['scenes'][] = [
  2144. 'scene' => trim($sceneMatch[1]),
  2145. 'description' => trim($sceneMatch[2])
  2146. ];
  2147. }
  2148. }
  2149. }
  2150. // 提取分镜剧本 - 兼容多种格式
  2151. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $storyboardMatch)) {
  2152. $storyboardText = trim($storyboardMatch[1]);
  2153. // 按幕分割 - 修复第1幕识别和乱码问题
  2154. $acts = [];
  2155. // 先在开头添加换行符,确保第1幕也能被正确分割
  2156. $normalizedText = "\n" . $storyboardText;
  2157. $parts = preg_split('/\n\s*##/', $normalizedText);
  2158. foreach ($parts as $part) {
  2159. $part = trim($part);
  2160. if (empty($part)) continue;
  2161. // 如果不是以"第"开头,跳过
  2162. if (!preg_match('/^第\d+幕/', $part)) {
  2163. continue;
  2164. }
  2165. // 分离标题和内容
  2166. $lines = explode("\n", $part, 2);
  2167. $actTitle = trim($lines[0]);
  2168. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  2169. // 解析幕标题,提取序号和详细信息 - 修复乱码问题
  2170. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  2171. $actNumber = intval($actTitleMatch[1]);
  2172. $actDetails = trim($actTitleMatch[2]);
  2173. // 如果详细信息为空或者就是冒号,使用完整标题
  2174. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  2175. $actDetails = $actTitle;
  2176. }
  2177. } else {
  2178. $actNumber = count($acts) + 1;
  2179. $actDetails = $actTitle;
  2180. }
  2181. // 解析该幕下的分镜
  2182. $segments = [];
  2183. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  2184. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  2185. foreach ($segmentMatches as $segmentMatch) {
  2186. $segmentNumber = intval($segmentMatch[1]);
  2187. $segmentContent = trim($segmentMatch[2]);
  2188. // 解析分镜详细信息
  2189. $segmentData = [
  2190. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT), // 生成唯一ID(后续可在生成任务里查看历史版本)
  2191. 'segment_number' => $segmentNumber,
  2192. 'segment_content' => $segmentContent,
  2193. 'description' => '',
  2194. 'composition' => '',
  2195. 'camera_movement' => '',
  2196. 'voice_actor' => '',
  2197. 'dialogue' => '',
  2198. 'frame_type' => '',
  2199. 'scene' => '', // 新增:场景
  2200. 'characters' => '', // 新增:出镜角色
  2201. 'tail_frame' => '', // 新增:尾帧描述
  2202. // 新增字段
  2203. 'emotion' => '中性', // 新增: 情感
  2204. 'gender' => '0', // 新增: 性别(0未知,1男,2女)
  2205. 'speed_ratio' => 0, // 新增: 语速
  2206. 'loudness_ratio' => 0, // 新增: 音量
  2207. 'emotion_scale' => 4, // 新增: 语调
  2208. 'pitch' => 0, // 新增: 音调
  2209. ];
  2210. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  2211. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  2212. $segmentData['description'] = trim($descMatch[1]);
  2213. }
  2214. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  2215. $segmentData['composition'] = trim($compMatch[1]);
  2216. }
  2217. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  2218. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  2219. }
  2220. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  2221. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  2222. }
  2223. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  2224. $segmentData['dialogue'] = trim($dialogueMatch[1]) == '无' ? '' : trim($dialogueMatch[1]);
  2225. }
  2226. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  2227. $segmentData['frame_type'] = trim($frameMatch[1]);
  2228. }
  2229. // 新增:场景字段
  2230. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  2231. $segmentData['scene'] = trim($sceneMatch[1]);
  2232. }
  2233. // 新增:出镜角色字段
  2234. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  2235. $segmentData['characters'] = trim($charactersMatch[1]);
  2236. }
  2237. // 新增:尾帧描述字段
  2238. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  2239. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  2240. }
  2241. $replaceEmptyArr = [];
  2242. // 新增:情感字段
  2243. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  2244. $replaceEmptyArr[] = trim($emotionMatch[0]);
  2245. $segmentData['emotion'] = trim($emotionMatch[1]);
  2246. }
  2247. // 新增:性别字段
  2248. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  2249. $replaceEmptyArr[] = trim($genderMatch[0]);
  2250. $genderStr = trim($genderMatch[1]);
  2251. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  2252. $segmentData['gender'] = '1';
  2253. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  2254. $segmentData['gender'] = '2';
  2255. } else {
  2256. $segmentData['gender'] = '0';
  2257. }
  2258. }
  2259. // 新增:语速字段
  2260. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  2261. $replaceEmptyArr[] = trim($speedMatch[0]);
  2262. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  2263. }
  2264. // 新增:音量字段
  2265. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  2266. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  2267. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  2268. }
  2269. // 新增:情感强度字段
  2270. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  2271. $replaceEmptyArr[] = trim($scaleMatch[0]);
  2272. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  2273. }
  2274. // 新增:音调字段
  2275. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  2276. $replaceEmptyArr[] = trim($pitchMatch[0]);
  2277. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  2278. }
  2279. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  2280. $segments[] = $segmentData;
  2281. }
  2282. $acts[] = [
  2283. 'act_number' => $actNumber,
  2284. 'act_title' => $actTitle,
  2285. 'act_details' => $actDetails,
  2286. 'segments' => $segments
  2287. ];
  2288. }
  2289. $result['acts'] = $acts;
  2290. }
  2291. return $result;
  2292. }
  2293. /**
  2294. * 远程图片压缩(尽可能保持原图 fidelity,压缩到不超过 maxBytes 字节)
  2295. * 采用有损/无损组合策略:保留原始格式尽量不失真,若需要则通过尺寸缩放和质量调节来降低体积。
  2296. *
  2297. * @param string $url 远程图片 URL
  2298. * @param int $maxBytes 最大字节数,默认 3MB
  2299. * @param string|null $aspectRatio 目标长宽比,如 "16:9"、"4:3"、"1:1" 等,null 则保持原图比例
  2300. * @return string|null 返回压缩后的图片二进制数据,失败时返回 null
  2301. */
  2302. function compressRemoteImageUrlToSize(string $url, int $maxBytes = 3 * 1024 * 1024, ?string $aspectRatio = null): ?string
  2303. {
  2304. // 1) 下载图片数据(使用 Guzzle 以避免 allow_url_fopen 依赖)
  2305. try {
  2306. $client = new Client(['timeout' => 30]);
  2307. $response = $client->get($url, ['stream' => true]);
  2308. if ($response->getStatusCode() !== 200) {
  2309. return null;
  2310. }
  2311. $data = $response->getBody()->getContents();
  2312. } catch (\Exception $e) {
  2313. return null;
  2314. }
  2315. if (!$data) return null;
  2316. // 2) 识别图片类型
  2317. $imgInfo = @getimagesizefromstring($data);
  2318. $mime = $imgInfo['mime'] ?? '';
  2319. if ($mime == 'image/jpeg') return null; // JPEG 不做有损压缩
  2320. // 3) 载入图像对象
  2321. $srcImg = @imagecreatefromstring($data);
  2322. if (!$srcImg) {
  2323. return null;
  2324. }
  2325. $origW = imagesx($srcImg);
  2326. $origH = imagesy($srcImg);
  2327. // 3.2) 计算目标尺寸(根据长宽比调整)
  2328. $targetW = $origW;
  2329. $targetH = $origH;
  2330. if ($aspectRatio !== null) {
  2331. // 解析长宽比,如 "16:9" -> [16, 9]
  2332. $validRatios = array_keys(BaseConst::IMAGE_RATIOS);
  2333. if (in_array($aspectRatio, $validRatios)) {
  2334. list($ratioW, $ratioH) = explode(':', $aspectRatio);
  2335. $ratioW = (float)$ratioW;
  2336. $ratioH = (float)$ratioH;
  2337. $targetRatio = $ratioW / $ratioH;
  2338. $currentRatio = $origW / $origH;
  2339. // 根据目标比例裁剪图片
  2340. if ($currentRatio > $targetRatio) {
  2341. // 原图更宽,需要裁剪宽度
  2342. $targetW = (int)round($origH * $targetRatio);
  2343. $targetH = $origH;
  2344. } else {
  2345. // 原图更高,需要裁剪高度
  2346. $targetW = $origW;
  2347. $targetH = (int)round($origW / $targetRatio);
  2348. }
  2349. }
  2350. }
  2351. // 如果需要裁剪,创建裁剪后的图像
  2352. if ($targetW !== $origW || $targetH !== $origH) {
  2353. $croppedImg = imagecreatetruecolor($targetW, $targetH);
  2354. imagealphablending($croppedImg, false);
  2355. imagesavealpha($croppedImg, true);
  2356. // 处理透明背景
  2357. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  2358. $transparent = imagecolorallocatealpha($croppedImg, 0, 0, 0, 127);
  2359. imagefill($croppedImg, 0, 0, $transparent);
  2360. }
  2361. // 居中裁剪
  2362. $srcX = (int)(($origW - $targetW) / 2);
  2363. $srcY = (int)(($origH - $targetH) / 2);
  2364. imagecopy($croppedImg, $srcImg, 0, 0, $srcX, $srcY, $targetW, $targetH);
  2365. // 替换原图
  2366. safeDestroyImage($srcImg);
  2367. $srcImg = $croppedImg;
  2368. $origW = $targetW;
  2369. $origH = $targetH;
  2370. }
  2371. // 3.1) 内部渲染成不同格式的字符串
  2372. $render = function($srcRes, string $mimeType, int $quality) {
  2373. ob_start();
  2374. switch (strtolower($mimeType)) {
  2375. case 'image/jpeg':
  2376. case 'image/jpg':
  2377. case 'image/pjpeg':
  2378. // 输出 JPEG
  2379. imagejpeg($srcRes, null, $quality);
  2380. break;
  2381. case 'image/png':
  2382. // 将 quality 映射到 PNG 的 compression level (0-9)
  2383. $level = (int)round((100 - $quality) / 11.11);
  2384. if ($level < 0) $level = 0;
  2385. if ($level > 9) $level = 9;
  2386. imagepng($srcRes, null, $level);
  2387. break;
  2388. case 'image/webp':
  2389. if (function_exists('imagewebp')) {
  2390. imagewebp($srcRes, null, $quality);
  2391. } else {
  2392. imagejpeg($srcRes, null, $quality);
  2393. }
  2394. break;
  2395. default:
  2396. imagejpeg($srcRes, null, $quality);
  2397. break;
  2398. }
  2399. $out = ob_get_contents();
  2400. ob_end_clean();
  2401. return $out;
  2402. };
  2403. // 4) 尝试策略:尽量保留原图尺寸,逐步降维/降质量,直到 <= maxBytes
  2404. $tryList = [];
  2405. // 原始尺寸,尽量保留
  2406. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>100];
  2407. // 逐步缩小尺寸
  2408. for ($s = 0.9; $s >= 0.2; $s -= 0.1) {
  2409. $tryList[] = ['scale'=>$s, 'mime'=>$mime, 'quality'=>90];
  2410. }
  2411. // 一系列质量等级(用于 JPEG/WebP)
  2412. $qualityLevels = [95, 90, 85, 75, 60, 50, 40, 30];
  2413. foreach ($qualityLevels as $q) {
  2414. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>$q];
  2415. }
  2416. $bestData = null;
  2417. foreach ($tryList as $cand) {
  2418. $scale = isset($cand['scale']) ? (float)$cand['scale'] : 1.0;
  2419. $mimeT = $cand['mime'] ?? $mime;
  2420. $quality = isset($cand['quality']) ? (int)$cand['quality'] : 90;
  2421. $w = (int)round($origW * $scale);
  2422. $h = (int)round($origH * $scale);
  2423. $src = $srcImg;
  2424. $tempImg = null;
  2425. if ($scale < 1.0) {
  2426. $tempImg = imagecreatetruecolor($w, $h);
  2427. // 处理透明通道
  2428. imagealphablending($tempImg, false);
  2429. imagesavealpha($tempImg, true);
  2430. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  2431. $transparent = imagecolorallocatealpha($tempImg, 0, 0, 0, 127);
  2432. imagefill($tempImg, 0, 0, $transparent);
  2433. }
  2434. // 确保 $srcImg 有效
  2435. if (!$srcImg || (!is_resource($srcImg) && !($srcImg instanceof \GdImage))) {
  2436. safeDestroyImage($tempImg);
  2437. continue;
  2438. }
  2439. imagecopyresampled($tempImg, $srcImg, 0, 0, 0, 0, $w, $h, $origW, $origH);
  2440. $src = $tempImg;
  2441. }
  2442. $imageBytes = $render($src, $mimeT, $quality);
  2443. if ($tempImg !== null) {
  2444. safeDestroyImage($tempImg);
  2445. }
  2446. if ($imageBytes !== false && strlen($imageBytes) <= $maxBytes) {
  2447. $bestData = $imageBytes;
  2448. break;
  2449. }
  2450. }
  2451. // 5) 回退策略:若仍未达到要求,尝试更大幅度降解到一个合理的小尺寸 JPEG
  2452. if ($bestData === null) {
  2453. $tmpW = max(1, (int)round($origW * 0.5));
  2454. $tmpH = max(1, (int)round($origH * 0.5));
  2455. $tmpImg = imagecreatetruecolor($tmpW, $tmpH);
  2456. imagealphablending($tmpImg, false);
  2457. imagesavealpha($tmpImg, true);
  2458. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  2459. $transparent = imagecolorallocatealpha($tmpImg, 0, 0, 0, 127);
  2460. imagefill($tmpImg, 0, 0, $transparent);
  2461. }
  2462. imagecopyresampled($tmpImg, $srcImg, 0, 0, 0, 0, $tmpW, $tmpH, $origW, $origH);
  2463. ob_start();
  2464. if (in_array(strtolower($mime), ['image/jpeg','image/jpg','image/pjpeg'])) {
  2465. imagejpeg($tmpImg, null, 75);
  2466. } elseif (strtolower($mime) === 'image/png') {
  2467. imagepng($tmpImg, null, 6);
  2468. } elseif (function_exists('imagewebp')) {
  2469. imagewebp($tmpImg, null, 75);
  2470. } else {
  2471. imagejpeg($tmpImg, null, 75);
  2472. }
  2473. $tmpBytes = ob_get_contents();
  2474. ob_end_clean();
  2475. safeDestroyImage($tmpImg);
  2476. if ($tmpBytes !== '' && strlen($tmpBytes) <= $maxBytes) {
  2477. $bestData = $tmpBytes;
  2478. }
  2479. }
  2480. // 6) 清理
  2481. safeDestroyImage($srcImg);
  2482. return $bestData;
  2483. }
  2484. /**
  2485. * 安全销毁 GD 图像资源(兼容 PHP7.4+ 的资源管理)
  2486. * 通过引用传递并在销毁后置空变量,避免未定义变量的问题
  2487. *
  2488. * @param resource|\GdImage|null &$img GD 图像资源或对象(PHP7.4 为 resource,PHP8.0+ 为 GdImage)
  2489. */
  2490. function safeDestroyImage(&$img)
  2491. {
  2492. if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
  2493. @imagedestroy($img);
  2494. }
  2495. $img = null;
  2496. }
  2497. // /**
  2498. // * 使用 Imagick 将远程图片压缩至不超过 maxBytes(默认3MB)内
  2499. // * 目标:在尽量保留原始格式和质量的前提下进行压缩,避免内存暴涨
  2500. // * 依赖:Imagick 扩展与 ImageMagick 库,下载使用 Guzzle 获取图片 blob
  2501. // *
  2502. // * @param string $url
  2503. // * @param int $maxBytes 最大字节数,默认 3*1024*1024
  2504. // * @return string|null 经过压缩后的图片 blob,失败返回 null
  2505. // */
  2506. // function compressRemoteImageUrlToSizeImagick(string $url, int $maxBytes = 3 * 1024 * 1024): ?string
  2507. // {
  2508. // // 兼容性检查
  2509. // if (!extension_loaded('imagick') || !class_exists('Imagick')) {
  2510. // return null;
  2511. // }
  2512. // try {
  2513. // $client = new Client(['timeout' => 30]);
  2514. // // 使用流式下载,将数据写入临时文件,避免一次性加载到内存
  2515. // $response = $client->get($url, ['stream' => true]);
  2516. // if ($response->getStatusCode() !== 200) {
  2517. // return null;
  2518. // }
  2519. // $body = $response->getBody();
  2520. // $tmp = tmpfile();
  2521. // if ($tmp === false) {
  2522. // return null;
  2523. // }
  2524. // stream_copy_to_stream($body, $tmp);
  2525. // rewind($tmp);
  2526. // $imagick = new Imagick();
  2527. // $imagick->readImageFile($tmp);
  2528. // $origW = $imagick->getImageWidth();
  2529. // $origH = $imagick->getImageHeight();
  2530. // $format = strtolower($imagick->getImageFormat());
  2531. // // 尝试序列:尺寸缩放 + 质量调节
  2532. // $scales = [1.0, 0.9, 0.8, 0.6, 0.4, 0.25];
  2533. // $qualities = [95, 90, 85, 75, 60, 40, 30, 20];
  2534. // $bestBlob = null;
  2535. // foreach ($scales as $scale) {
  2536. // foreach ($qualities as $q) {
  2537. // $clone = clone $imagick;
  2538. // if ($scale < 1.0) {
  2539. // $w = (int)round($origW * $scale);
  2540. // $h = (int)round($origH * $scale);
  2541. // if ($w < 1 || $h < 1) {
  2542. // $clone->destroy();
  2543. // continue;
  2544. // }
  2545. // $clone->resizeImage($w, $h, Imagick::FILTER_LANCZOS, 1);
  2546. // }
  2547. // $clone->setImageFormat($format);
  2548. // $clone->setImageCompressionQuality($q);
  2549. // $blob = $clone->getImageBlob();
  2550. // $clone->destroy();
  2551. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  2552. // $bestBlob = $blob;
  2553. // break 2;
  2554. // }
  2555. // }
  2556. // }
  2557. // if ($bestBlob !== null) {
  2558. // $imagick->destroy();
  2559. // fclose($tmp);
  2560. // return $bestBlob;
  2561. // }
  2562. // // 回退:尝试强制输出为当前格式的一个中等质量版本
  2563. // $fallback = clone $imagick;
  2564. // $fallback->setImageFormat($format);
  2565. // $fallback->setImageCompressionQuality(75);
  2566. // $blob = $fallback->getImageBlob();
  2567. // $fallback->destroy();
  2568. // $imagick->destroy();
  2569. // fclose($tmp);
  2570. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  2571. // return $blob;
  2572. // }
  2573. // } catch (\Exception $e) {
  2574. // return null;
  2575. // }
  2576. // return null;
  2577. // }
  2578. /**
  2579. * 将主体列表文本拆分为主体数组
  2580. *
  2581. * @param string $rolesText 主体列表文本内容
  2582. * @return array 主体名称数组
  2583. */
  2584. function parseRolesFromText(string $rolesText): array
  2585. {
  2586. if (empty($rolesText)) {
  2587. return [];
  2588. }
  2589. $roles = [];
  2590. // 按行分割文本
  2591. $lines = explode("\n", $rolesText);
  2592. foreach ($lines as $line) {
  2593. $line = trim($line);
  2594. if (empty($line)) {
  2595. continue;
  2596. }
  2597. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2598. $role = trim($charMatch[1]);
  2599. $description = trim($charMatch[2]);
  2600. $timbreName = null;
  2601. if (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2602. $description = trim($timbreMatch[1]);
  2603. $timbreName = trim($timbreMatch[2]);
  2604. }
  2605. $roleData = [
  2606. 'role' => $role,
  2607. 'description' => $description,
  2608. ];
  2609. if ($timbreName) {
  2610. $timbre = DB::table('mp_timbres')
  2611. ->where('is_enabled', 1)
  2612. ->where('timbre_name', 'like', "%{$timbreName}%")
  2613. ->orderBy('id')
  2614. ->select('timbre_type', 'audio_url')
  2615. ->first();
  2616. if ($timbre) {
  2617. $roleData['voice_name'] = $timbreName;
  2618. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2619. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2620. }
  2621. }
  2622. $roles[] = $roleData;
  2623. }
  2624. }
  2625. $hasNarrator = false;
  2626. foreach ($roles as $role) {
  2627. if (getProp($role, 'role') === '旁白') {
  2628. $hasNarrator = true;
  2629. break;
  2630. }
  2631. }
  2632. if (!$hasNarrator) {
  2633. $roles[] = [
  2634. 'role' => '旁白',
  2635. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2636. 'voice_name' => '旁白',
  2637. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2638. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2639. ];
  2640. }
  2641. return $roles;
  2642. }
  2643. /**
  2644. * 将场景列表文本拆分为主体数组
  2645. *
  2646. * @param string $rolesText 场景列表列表文本内容
  2647. * @return array 场景名称数组
  2648. */
  2649. function parseScenesFromText(string $scenesText): array
  2650. {
  2651. if (empty($scenesText)) {
  2652. return [];
  2653. }
  2654. $scenes = [];
  2655. // 按行分割文本
  2656. $lines = explode("\n", $scenesText);
  2657. foreach ($lines as $line) {
  2658. $line = trim($line);
  2659. if (empty($line)) {
  2660. continue;
  2661. }
  2662. $line = str_replace(':', ':', $line);
  2663. if (strstr($line, ':')) {
  2664. $line_arr = explode(':', $line);
  2665. if (count($line_arr) == 2) {
  2666. $scenes[] = [
  2667. 'scene' => $line_arr[0],
  2668. 'description' => $line_arr[1],
  2669. ];
  2670. }
  2671. }
  2672. }
  2673. return $scenes;
  2674. }
  2675. /**
  2676. * 记录日志到数据库
  2677. *
  2678. * @param string $channel 日志频道/目录名
  2679. * @param string $level 日志级别 (info, error, warning, debug)
  2680. * @param string $message 日志信息
  2681. * @param array $context 日志详细数据
  2682. * @return void
  2683. */
  2684. function logDB($channel, $level, $message, $context = []) {
  2685. try {
  2686. // 获取调用堆栈信息
  2687. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  2688. $caller = $trace[1] ?? $trace[0];
  2689. \App\Models\SystemLog::create([
  2690. 'channel' => $channel,
  2691. 'level' => $level,
  2692. 'message' => $message,
  2693. 'context' => $context,
  2694. 'file' => $caller['file'] ?? '',
  2695. 'line' => $caller['line'] ?? 0,
  2696. 'log_time' => date('Y-m-d H:i:s'),
  2697. ]);
  2698. } catch (\Exception $e) {
  2699. // 记录日志失败时不影响主流程
  2700. \Log::error('记录日志到数据库失败: ' . $e->getMessage());
  2701. }
  2702. }