Helpers.php 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290
  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. /**
  885. * 压缩视频文件
  886. * 压缩策略:3秒视频约1M~1.5M
  887. *
  888. * @param string $videoUrl 视频URL地址
  889. * @param string $prefix 上传文件夹前缀(如:'videos')
  890. * @return string 返回压缩后的视频URL,失败返回空字符串
  891. */
  892. function compressVideo($videoUrl, $prefix = 'videos')
  893. {
  894. if (env('APP_ENV') == 'local') return $videoUrl;
  895. try {
  896. // 创建临时目录
  897. $tempDir = storage_path('app/temp/videos');
  898. if (!is_dir($tempDir)) {
  899. mkdir($tempDir, 0775, true);
  900. // 确保目录权限正确
  901. chmod($tempDir, 0775);
  902. }
  903. // 生成唯一文件名(不包含点号)
  904. $uniqueId = uniqid('video_') . bin2hex(random_bytes(4));
  905. $videoExt = getVideoExtFromUrl($videoUrl);
  906. $inputFile = $tempDir . '/' . $uniqueId . '_input' . $videoExt;
  907. $outputFile = $tempDir . '/' . $uniqueId . '_output.mp4';
  908. // 下载视频到本地
  909. dLog('video_compress')->info('开始下载视频', ['url' => $videoUrl]);
  910. $client = new \GuzzleHttp\Client(['timeout' => 300]);
  911. $response = $client->get($videoUrl);
  912. // 使用更安全的方式写入文件
  913. $fileContent = $response->getBody()->getContents();
  914. if (file_put_contents($inputFile, $fileContent) === false) {
  915. dLog('video_compress')->error('视频文件写入失败', [
  916. 'url' => $videoUrl,
  917. 'file' => $inputFile,
  918. 'dir_writable' => is_writable($tempDir)
  919. ]);
  920. return '';
  921. }
  922. // 设置文件权限
  923. chmod($inputFile, 0664);
  924. if (!file_exists($inputFile)) {
  925. dLog('video_compress')->error('视频下载失败', ['url' => $videoUrl]);
  926. return '';
  927. }
  928. $inputFileSize = filesize($inputFile);
  929. dLog('video_compress')->info('视频下载成功', [
  930. 'url' => $videoUrl,
  931. 'size' => $inputFileSize,
  932. 'size_mb' => round($inputFileSize / 1024 / 1024, 2) . 'MB'
  933. ]);
  934. // 获取视频时长(秒)
  935. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  936. $durationCmd = "$ffprobePath -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 \"$inputFile\"";
  937. $duration = (float)trim(shell_exec($durationCmd));
  938. if ($duration <= 0) {
  939. dLog('video_compress')->error('无法获取视频时长', ['file' => $inputFile]);
  940. @unlink($inputFile);
  941. return '';
  942. }
  943. // 计算目标码率
  944. // 目标:3秒视频 = 1~1.5MB,即每秒约 0.33~0.5MB = 2730~4096 kbps
  945. // 使用中间值:3500 kbps
  946. $targetBitrate = 3500; // kbps
  947. // 根据视频时长动态调整码率,确保文件大小合理
  948. // 目标文件大小 = duration * 0.4MB/s = duration * 400KB/s
  949. $targetFileSizeKB = $duration * 400; // KB
  950. $targetBitrateCalculated = (int)(($targetFileSizeKB * 8) / $duration); // kbps
  951. // 使用计算出的码率,但不低于1500kbps,不高于5000kbps
  952. $targetBitrate = max(1500, min(5000, $targetBitrateCalculated));
  953. dLog('video_compress')->info('视频信息', [
  954. 'duration' => $duration . 's',
  955. 'target_bitrate' => $targetBitrate . 'kbps',
  956. 'estimated_size' => round($targetFileSizeKB / 1024, 2) . 'MB'
  957. ]);
  958. // 使用FFmpeg压缩视频
  959. // -c:v libx264: 使用H.264编码器
  960. // -b:v: 视频码率
  961. // -c:a aac: 音频编码器
  962. // -b:a 128k: 音频码率
  963. // -movflags +faststart: 优化网络播放
  964. // -preset medium: 编码速度与质量平衡
  965. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  966. $ffmpegCmd = "$ffmpegPath -i \"$inputFile\" -c:v libx264 -b:v {$targetBitrate}k -c:a aac -b:a 128k -movflags +faststart -preset medium -y \"$outputFile\" 2>&1";
  967. dLog('video_compress')->info('开始压缩视频', ['command' => $ffmpegCmd]);
  968. $output = shell_exec($ffmpegCmd);
  969. if (!file_exists($outputFile)) {
  970. dLog('video_compress')->error('视频压缩失败', [
  971. 'input' => $inputFile,
  972. 'output' => $output
  973. ]);
  974. @unlink($inputFile);
  975. return '';
  976. }
  977. // 设置输出文件权限
  978. chmod($outputFile, 0664);
  979. $outputFileSize = filesize($outputFile);
  980. $compressionRatio = round((1 - $outputFileSize / $inputFileSize) * 100, 2);
  981. dLog('video_compress')->info('视频压缩成功', [
  982. 'input_size' => round($inputFileSize / 1024 / 1024, 2) . 'MB',
  983. 'output_size' => round($outputFileSize / 1024 / 1024, 2) . 'MB',
  984. 'compression_ratio' => $compressionRatio . '%',
  985. 'duration' => $duration . 's',
  986. 'size_per_second' => round($outputFileSize / $duration / 1024 / 1024, 2) . 'MB/s'
  987. ]);
  988. // 上传压缩后的视频到云存储
  989. $stream = fopen($outputFile, 'r');
  990. if (!$stream) {
  991. dLog('video_compress')->error('无法打开压缩后的视频文件', ['file' => $outputFile]);
  992. @unlink($inputFile);
  993. @unlink($outputFile);
  994. return '';
  995. }
  996. $filename = $uniqueId . '.mp4';
  997. // 根据环境变量选择上传方式
  998. $uploadMethod = env('VIDEO_UPLOAD_METHOD', 'tos'); // 默认使用火山云
  999. if ($uploadMethod === 'oss') {
  1000. $compressedUrl = uploadStreamToOss($prefix, $stream, $filename);
  1001. } else {
  1002. $compressedUrl = uploadStreamByTos($prefix, $stream, $filename);
  1003. }
  1004. // 安全关闭文件流
  1005. if (is_resource($stream)) {
  1006. fclose($stream);
  1007. }
  1008. // 清理临时文件
  1009. @unlink($inputFile);
  1010. @unlink($outputFile);
  1011. if (!$compressedUrl) {
  1012. dLog('video_compress')->error('压缩视频上传失败');
  1013. return '';
  1014. }
  1015. dLog('video_compress')->info('压缩视频上传成功', [
  1016. 'original_url' => $videoUrl,
  1017. 'compressed_url' => $compressedUrl
  1018. ]);
  1019. return $compressedUrl;
  1020. } catch (\Exception $e) {
  1021. dLog('video_compress')->error('视频压缩异常', [
  1022. 'url' => $videoUrl,
  1023. 'error' => $e->getMessage(),
  1024. 'trace' => $e->getTraceAsString()
  1025. ]);
  1026. // 安全关闭文件流(如果存在)
  1027. if (isset($stream) && is_resource($stream)) {
  1028. @fclose($stream);
  1029. }
  1030. // 清理可能存在的临时文件
  1031. if (isset($inputFile) && file_exists($inputFile)) {
  1032. @unlink($inputFile);
  1033. }
  1034. if (isset($outputFile) && file_exists($outputFile)) {
  1035. @unlink($outputFile);
  1036. }
  1037. return ''; // 出错时返回空字符串
  1038. }
  1039. }
  1040. function sensitiveStr($list, $string)
  1041. {
  1042. $count = 0; //违规词的个数
  1043. $sensitiveWord = ''; //违规词
  1044. $stringAfter = $string; //替换后的内容
  1045. $total = count($list);
  1046. $size = 500;
  1047. $last = ceil($total / $size);
  1048. $patternList = [];
  1049. for ($page = 1; $page <= $last; $page++) {
  1050. $arr = array_slice($list, $size * ($page - 1), $size);
  1051. $filter = [];
  1052. foreach ($arr as $v) {
  1053. if (preg_match('/[^a-zA-Z0-9\|\p{Han}\·]/u', $v)) continue;
  1054. $filter[] = $v;
  1055. // $a = preg_replace('/[^a-zA-Z0-9\|\p{Han}]/u', '', $v);
  1056. // if ($a) $filter[] = $a;
  1057. }
  1058. $pattern = "/" . implode("|", $filter) . "/i"; //定义正则表达式
  1059. if (preg_match_all($pattern, $string, $matches)) { //匹配到了结果
  1060. $patternList = array_merge($patternList, $matches[0]); //匹配到的数组
  1061. }
  1062. }
  1063. $sensitiveWord = '';
  1064. if ($patternList) {
  1065. $count = count($patternList);
  1066. // $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
  1067. $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '*')); //把匹配到的数组进行合并,替换使用
  1068. $stringAfter = strtr($string, $replaceArray); //结果替换
  1069. // 将敏感词合并
  1070. $return_pattern = [];
  1071. foreach ($patternList as $v) {
  1072. if (!isset($return_pattern[$v])) {
  1073. $return_pattern[$v] = [
  1074. 'word' => $v,
  1075. 'count' => 1,
  1076. ];
  1077. } else {
  1078. $return_pattern[$v]['count'] += 1;
  1079. }
  1080. }
  1081. foreach ($return_pattern as $v) {
  1082. $sensitiveWord .= $v['word'] . ',';
  1083. }
  1084. }
  1085. return [
  1086. 'count' => $count,
  1087. 'sensitive_words' => trim($sensitiveWord, ','),
  1088. 'content' => $stringAfter
  1089. ];
  1090. }
  1091. /**
  1092. * 转换时间格式
  1093. *
  1094. * @param $date
  1095. * @param string $format
  1096. * @return false|string
  1097. */
  1098. function transDate($date, $format = 'Y-m-d H:i:s')
  1099. {
  1100. return strtotime($date) > 0 ? date($format, strtotime($date)) : '';
  1101. }
  1102. /**
  1103. * 根据网段获取计算所有IP
  1104. *
  1105. * @param string $segment 网段 '139.217.0.1/24'
  1106. * @return array [网络地址:139.217.0.1 广播地址:139.217.0.255 IP列表: ['139.217.0.2','139.217.0.3'……'139.217.0.254']]
  1107. */
  1108. function getIpBySegment($segment)
  1109. {
  1110. $segmentInfo = explode("/", $segment);
  1111. $beginIpArray = explode(".", $segmentInfo[0]);
  1112. $mask = intval($segmentInfo['1']);
  1113. $endIp = array();
  1114. foreach ($beginIpArray as $ipKey => $item) {
  1115. $beginFlag = 8 * ($ipKey); //0 8 16 24
  1116. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  1117. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  1118. $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));
  1119. }
  1120. $ipArray = array();
  1121. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0]++) {
  1122. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1]++) {
  1123. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2]++) {
  1124. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3]++) {
  1125. $ipArray[] = implode(".", $beginIp);
  1126. }
  1127. }
  1128. }
  1129. }
  1130. $network_ip_addr = $beginIpArray[0] . '.' . $beginIpArray[1] . '.' . $beginIpArray[2] . '.' . '0'; // 网络地址
  1131. $broadcast_ip_addr = end($ipArray); // 广播地址
  1132. if ($ipArray[0] == $network_ip_addr) { // 如果是网络地址则删掉
  1133. unset($ipArray[0]);
  1134. }
  1135. $last = count($ipArray);
  1136. unset($ipArray[$last]);
  1137. return [$network_ip_addr, $broadcast_ip_addr, $ipArray];
  1138. }
  1139. /**
  1140. * 在指定网段中分配子网段
  1141. *
  1142. * @param string $segment 指定网段
  1143. * @param int $ipNum 需要的IP数
  1144. * @param array $usedIpArray 不可用(已经使用)的IP,默认为空数组
  1145. * @return bool|string 成功则返回分配的网段
  1146. */
  1147. function allocateSegment($segment, $ipNum, $usedIpArray = [])
  1148. {
  1149. $usedIpArray = empty($usedIpArray) ? [] : array_flip($usedIpArray);
  1150. //计算需要多少个IP
  1151. $i = 0;
  1152. $ipCount = pow(2, $i);
  1153. while ($ipCount < $ipNum) {
  1154. $i++;
  1155. $ipCount = pow(2, $i);
  1156. }
  1157. $newMask = 32 - $i;
  1158. //大网段的开始和结束IP
  1159. $segmentInfo = explode("/", $segment); //['139.217.0.1',24]
  1160. $beginIpArray = explode(".", $segmentInfo[0]);//[139,217,0,1]
  1161. $mask = intval($segmentInfo['1']); //24
  1162. if ($newMask < $mask) {
  1163. return false;
  1164. }
  1165. $endIp = array();
  1166. $step = [];
  1167. foreach ($beginIpArray as $ipKey => $item) {
  1168. $beginFlag = 8 * ($ipKey); //0 8 16 24
  1169. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  1170. $step[$ipKey] = $newMask > $endFlag ? 1 : ($endFlag - $newMask < 8 ? pow(2, $endFlag - $newMask) : pow(2, 8));
  1171. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  1172. $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));
  1173. }
  1174. //遍历生成网段
  1175. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0] += $step[0]) {
  1176. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1] += $step[1]) {
  1177. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2] += $step[2]) {
  1178. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3] += $step[3]) {
  1179. $newSegment = implode('.', $beginIp) . '/' . $newMask;
  1180. //获取该网段所有的IP
  1181. $ipArray = getIpBySegment($newSegment);
  1182. $canUse = true;
  1183. //判断该网段是否可用
  1184. if (!empty($usedIpArray)) {
  1185. foreach ($ipArray as $ip) {
  1186. if (isset($usedIpArray[$ip])) {
  1187. $canUse = false;
  1188. break;
  1189. }
  1190. }
  1191. }
  1192. if ($canUse) {
  1193. return $newSegment;
  1194. }
  1195. }
  1196. }
  1197. }
  1198. }
  1199. return false;
  1200. }
  1201. function remove_xss($val)
  1202. {
  1203. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  1204. // this prevents some character re-spacing such as <java\0script>
  1205. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
  1206. $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
  1207. // straight replacements, the user should never need these since they're normal characters
  1208. // this prevents like <IMG SRC=@avascript:alert('XSS')>
  1209. $search = 'abcdefghijklmnopqrstuvwxyz';
  1210. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1211. $search .= '1234567890!@#$%^&*()';
  1212. $search .= '~`";:?+/={}[]-_|\'\\';
  1213. for ($i = 0; $i < strlen($search); $i++) {
  1214. // ;? matches the ;, which is optional
  1215. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  1216. // @ @ search for the hex values
  1217. $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
  1218. // @ @ 0{0,7} matches '0' zero to seven times
  1219. $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
  1220. }
  1221. // now the only remaining whitespace attacks are \t, \n, and \r
  1222. $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  1223. $ra2 = array(
  1224. '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'
  1225. );
  1226. $ra = array_merge($ra1, $ra2);
  1227. $found = true; // keep replacing as long as the previous round replaced something
  1228. while ($found == true) {
  1229. $val_before = $val;
  1230. for ($i = 0; $i < sizeof($ra); $i++) {
  1231. $pattern = '/';
  1232. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  1233. if ($j > 0) {
  1234. $pattern .= '(';
  1235. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  1236. $pattern .= '|';
  1237. $pattern .= '|(�{0,8}([9|10|13]);)';
  1238. $pattern .= ')*';
  1239. }
  1240. $pattern .= $ra[$i][$j];
  1241. }
  1242. $pattern .= '/i';
  1243. $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
  1244. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  1245. if ($val_before == $val) {
  1246. // no replacements were made, so exit the loop
  1247. $found = false;
  1248. }
  1249. }
  1250. }
  1251. return $val;
  1252. }
  1253. /**
  1254. * 计算作者积分等级
  1255. *
  1256. * @param $score
  1257. */
  1258. function calcAuthorLevel($score): int
  1259. {
  1260. switch (true) {
  1261. case $score <= 0:
  1262. $level = 0;
  1263. break;
  1264. case $score <= 5000:
  1265. $level = 1;
  1266. break;
  1267. case $score <= 50000:
  1268. $level = 2;
  1269. break;
  1270. case $score <= 100000:
  1271. $level = 3;
  1272. break;
  1273. case $score <= 300000:
  1274. $level = 4;
  1275. break;
  1276. case $score <= 800000:
  1277. $level = 5;
  1278. break;
  1279. case $score <= 1500000:
  1280. $level = 6;
  1281. break;
  1282. case $score <= 2500000:
  1283. $level = 7;
  1284. break;
  1285. case $score <= 5000000:
  1286. $level = 8;
  1287. break;
  1288. case $score <= 10000000:
  1289. $level = 9;
  1290. break;
  1291. default:
  1292. $level = 10;
  1293. break;
  1294. }
  1295. return $level;
  1296. }
  1297. /**
  1298. * 运营数据(上传附件)
  1299. *
  1300. * @param $file
  1301. * @return string
  1302. * @throws Exception
  1303. */
  1304. function uploadEnclosureFile($file)
  1305. {
  1306. // 阿里云主账号
  1307. $accessKeyId = env('OSS_ACCESS_ID');
  1308. $accessKeySecret = env('OSS_ACCESS_KEY');
  1309. $endpoint = env('OSS_END_POINT');
  1310. $bucket = env('OSS_BUCKET');
  1311. // 设置文件名称。
  1312. $object = 'books/enclosure/' . randStr(10) . '--' . $file->getClientOriginalName();
  1313. try {
  1314. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  1315. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  1316. } catch (OssException $e) {
  1317. printf($e->getMessage());
  1318. return '';
  1319. }
  1320. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  1321. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  1322. }
  1323. // 获取当前域名是http还是https
  1324. function getHttpType()
  1325. {
  1326. return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
  1327. }
  1328. // 根据id生成唯一邀请码
  1329. function enCodeId($user_id)
  1330. {
  1331. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1332. $num = strlen($key);
  1333. $code = ''; // 邀请码
  1334. while ($user_id > 0) { // 转进制
  1335. $mod = $user_id % $num; // 求模
  1336. $user_id = ($user_id - $mod) / $num;
  1337. $code = $key[$mod] . $code;
  1338. }
  1339. $code = str_pad($code, 6, 'A', STR_PAD_LEFT); // 不足用0补充
  1340. return $code;
  1341. }
  1342. // 根据邀请码解密为id
  1343. function deCodeId($code)
  1344. {
  1345. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1346. $num = strlen($key);
  1347. if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0') + 1);
  1348. $len = strlen($code);
  1349. $code = strrev($code);
  1350. $user_id = 0;
  1351. for ($i = 0; $i < $len; $i++) {
  1352. $user_id += strpos($key, $code[$i]) * pow($num, $i);
  1353. }
  1354. return $user_id;
  1355. }
  1356. /**
  1357. * 将二维数组按其中的某个数组排序(此方法适用于将数据库数据按数组取出后自动按ID排序的情况 ps:即未按该数组排序)
  1358. *
  1359. * @param array $array 二维数组
  1360. * @param array $sort 排序数组
  1361. * @param string $field 排序字段(二维数组和排序数组相同的字段)
  1362. * @return array
  1363. */
  1364. function sortByArray(array $array, array $sort, string $field): array
  1365. {
  1366. $data = [];
  1367. if (is_array($array) && is_array($sort)) {
  1368. foreach ($sort as $v) {
  1369. foreach ($array as $key => $val) {
  1370. if ($v == $val[$field]) {
  1371. array_push($data, $array[$key]);
  1372. }
  1373. }
  1374. }
  1375. }
  1376. return $data;
  1377. }
  1378. /**
  1379. * 将二维数组按其中的字段排序(正序或倒序)
  1380. *
  1381. * @param array $array 二维数组
  1382. * @param string $field 排序字段
  1383. * @param mixed $type 排序方式(3倒序,4正序)
  1384. * @return array|mixed
  1385. */
  1386. function sortByField(array $array, string $field, $type): array
  1387. {
  1388. if (is_array($array)) {
  1389. array_multisort(array_column($array, $field), $type, $array);
  1390. }
  1391. return $array;
  1392. }
  1393. // 生成用户邀请码
  1394. function setUserInviteCode($id)
  1395. {
  1396. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->encode($id);
  1397. }
  1398. // 解密用户邀请码
  1399. function decodeUserInviteCode($code)
  1400. {
  1401. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->decode($code);
  1402. }
  1403. function getMillisecond()
  1404. {
  1405. list($microsecond, $time) = explode(' ', microtime());
  1406. return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
  1407. }
  1408. function get_client_ip($type = 0, $adv = false)
  1409. {
  1410. $type = $type ? 1 : 0;
  1411. static $ip = null;
  1412. if (null !== $ip) {
  1413. return $ip[$type];
  1414. }
  1415. if ($adv) {
  1416. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1417. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1418. $pos = array_search('unknown', $arr);
  1419. if (false !== $pos) {
  1420. unset($arr[$pos]);
  1421. }
  1422. $ip = trim($arr[0]);
  1423. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1424. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1425. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1426. $ip = $_SERVER['REMOTE_ADDR'];
  1427. }
  1428. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1429. $ip = $_SERVER['REMOTE_ADDR'];
  1430. }
  1431. // IP地址合法验证
  1432. $long = sprintf("%u", ip2long($ip));
  1433. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  1434. return $ip[$type];
  1435. }
  1436. /**
  1437. * 获取真实IP
  1438. */
  1439. function _getIp()
  1440. {
  1441. if (getenv('HTTP_X_FORWARDED_FOR')) {
  1442. $ip = getenv('HTTP_X_FORWARDED_FOR');
  1443. } else if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  1444. $ip = getenv("HTTP_CLIENT_IP");
  1445. else if (getenv("HTTP_X_FORWARD_FOR") && strcasecmp(getenv("HTTP_X_FORWARD_FOR"), "unknown"))
  1446. $ip = getenv("HTTP_X_FORWARD_FOR");
  1447. else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  1448. $ip = getenv("REMOTE_ADDR");
  1449. else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  1450. $ip = $_SERVER['REMOTE_ADDR'];
  1451. else
  1452. $ip = "unknown";
  1453. return ($ip);
  1454. }
  1455. /**
  1456. * 数组 转 对象
  1457. *
  1458. * @param array $arr 数组
  1459. * @return object
  1460. */
  1461. function array_to_object($arr)
  1462. {
  1463. if (gettype($arr) != 'array') {
  1464. return;
  1465. }
  1466. foreach ($arr as $k => $v) {
  1467. if (gettype($v) == 'array' || getType($v) == 'object') {
  1468. $arr[$k] = (object)array_to_object($v);
  1469. }
  1470. }
  1471. return (object)$arr;
  1472. }
  1473. /**
  1474. * 对象 转 数组
  1475. *
  1476. * @param object $obj 对象
  1477. * @return array
  1478. */
  1479. function object_to_array($obj)
  1480. {
  1481. $obj = (array)$obj;
  1482. foreach ($obj as $k => $v) {
  1483. if (gettype($v) == 'resource') {
  1484. return;
  1485. }
  1486. if (gettype($v) == 'object' || gettype($v) == 'array') {
  1487. $obj[$k] = (array)object_to_array($v);
  1488. }
  1489. }
  1490. return $obj;
  1491. }
  1492. /**
  1493. * 检查是否为手机号码
  1494. */
  1495. function _isPhone($number)
  1496. {
  1497. return preg_match("/^1[34578][0-9]{9}$/", $number);
  1498. }
  1499. /**
  1500. * 判断所传的参数是否缺少,如果缺少返回渠道的字段,正确返回0
  1501. *
  1502. * @param array $param
  1503. * @param array $must
  1504. * @return int|mixed
  1505. */
  1506. function checkParam(array $param, array $must)
  1507. {
  1508. foreach ($must as $item) {
  1509. if (array_key_exists($item, $param) && $param[$item] != '') {
  1510. } else {
  1511. return $item;
  1512. }
  1513. }
  1514. return 0;
  1515. }
  1516. /**
  1517. * 对象 转 数组
  1518. *
  1519. * @param object $obj 对象
  1520. * @return array
  1521. */
  1522. function ignoreKeyInArray($targetArray, $delete_keys = [], $changes = [])
  1523. {
  1524. $change_keys = array_keys($changes);
  1525. foreach ($targetArray as $key => $value) {
  1526. if (in_array($key, $delete_keys) && isset($targetArray[$key])) unset($targetArray[$key]);
  1527. if (in_array($key, $change_keys) && isset($targetArray[$key])) $targetArray[$key] = $changes[$key];
  1528. if (is_array($value)) ignoreKeyInArray($value, $delete_keys, $change_keys);
  1529. }
  1530. return $targetArray;
  1531. }
  1532. function itemTransform($trans, $data)
  1533. {
  1534. if ($data) {
  1535. return $trans->transform($data);
  1536. } else {
  1537. return [];
  1538. }
  1539. }
  1540. function collectionTransform($trans, $data)
  1541. {
  1542. $ret_data = [];
  1543. if ($data) {
  1544. foreach ($data as $item) {
  1545. $ret_data[] = $trans->transform($item);
  1546. }
  1547. }
  1548. return $ret_data;
  1549. }
  1550. function paginationTransform($trans, $paginator)
  1551. {
  1552. $ret = [];
  1553. $ret['list'] = [];
  1554. if ($paginator) {
  1555. foreach ($paginator as $item) {
  1556. $ret['list'][] = $trans->transform($item);
  1557. }
  1558. $ret['meta'] = [
  1559. 'total' => (int)$paginator->total(),
  1560. 'per_page' => (int)$paginator->perPage(),
  1561. 'current_page' => (int)$paginator->currentPage(),
  1562. 'last_page' => (int)$paginator->lastPage(),
  1563. 'next_page_url' => (string)$paginator->nextPageUrl(),
  1564. 'prev_page_url' => (string)$paginator->previousPageUrl()
  1565. ];
  1566. }
  1567. return $ret;
  1568. }
  1569. /**
  1570. * 加密site id
  1571. */
  1572. function encodeDistributionChannelId($id)
  1573. {
  1574. $encrypt_pool = [
  1575. ];
  1576. if (isset($encrypt_pool[$id])) {
  1577. return $encrypt_pool[$id];
  1578. }
  1579. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1580. return $hashids->encode($id);
  1581. }
  1582. /**
  1583. * 解密密site id
  1584. */
  1585. function decodeDistributionChannelId($code)
  1586. {
  1587. $encrypt_pool = [
  1588. ];
  1589. if (isset($encrypt_pool[$code])) {
  1590. return $encrypt_pool[$code];
  1591. }
  1592. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1593. $res = $hashids->decode($code);
  1594. if ($res && isset($res[0])) {
  1595. return $res[0];
  1596. }
  1597. return null;
  1598. }
  1599. //bid加密
  1600. function book_hash_encode($bid)
  1601. {
  1602. return Vinkla\Hashids\Facades\Hashids::encode($bid);
  1603. }
  1604. function decodeBid($encode_bid)
  1605. {
  1606. $bid = 0;
  1607. try {
  1608. $bid_arr = \Hashids::decode($encode_bid);
  1609. if (isset($bid_arr[0])) {
  1610. $bid = $bid_arr[0];
  1611. }
  1612. } catch (\Exception $e) {
  1613. return null;
  1614. }
  1615. return $bid;
  1616. }
  1617. /**
  1618. * 获取当前域名
  1619. */
  1620. function _domain()
  1621. {
  1622. return str_replace('https://', '', str_replace('http://', '', url('/')));
  1623. }
  1624. /**
  1625. * 字符串转*
  1626. *
  1627. * @param $str // 待转的字符串
  1628. * @param $start // 转*起始位置
  1629. * @param int $end // 转*结束位置
  1630. * @param string $dot // 转换的字符(必须是单字符,默认是*)
  1631. * @param string $charset // 编码方式
  1632. * @param string $end_char // 特殊字符(碰到此字符则确定end位置)
  1633. * @return string
  1634. */
  1635. function trans_pass($str, $start, $end = 0, $dot = "*", $charset = "UTF-8", $end_char = '@'): string
  1636. {
  1637. $len = mb_strlen($str, $charset);
  1638. if ($start == 0 || $start > $len) {
  1639. $start = 1;
  1640. }
  1641. if ($end != 0 && $end > $len) {
  1642. $end = $len - 2;
  1643. }
  1644. if (strstr($str, $end_char)) {
  1645. $end = $len - strrpos($str, $end_char);
  1646. }
  1647. $endStart = $len - $end;
  1648. $top = mb_substr($str, 0, $start, $charset);
  1649. $bottom = "";
  1650. if ($endStart > 0) {
  1651. $bottom = mb_substr($str, $endStart, $end, $charset);
  1652. }
  1653. $len -= mb_strlen($top, $charset);
  1654. $len -= mb_strlen($bottom, $charset);
  1655. $newStr = $top;
  1656. for ($i = 0; $i < $len; $i++) {
  1657. $newStr .= $dot;
  1658. }
  1659. $newStr .= $bottom;
  1660. return $newStr;
  1661. }
  1662. /**
  1663. * 格式化章节内容
  1664. *
  1665. * @param $content
  1666. * @return false|string
  1667. */
  1668. function formatContent($content)
  1669. {
  1670. if (!$content) return '';
  1671. $content = str_replace(
  1672. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p >', '&ldquo;', '&rdquo;', '&hellip;'],
  1673. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...'],
  1674. $content);
  1675. $content = str_replace(["&nbsp;", '&ldquo;', '&hellip;', '&rdquo;', '<p>'], '', $content);
  1676. // 段落首字母前加两个中文空格
  1677. $string = explode(PHP_EOL, $content);
  1678. foreach ($string as $line => $text) {
  1679. if (mb_substr($text, 0, 2) != '  ') $string[$line] = '  ' . $text;
  1680. }
  1681. $content = implode(PHP_EOL, $string);
  1682. $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8,GBK,GB2312');
  1683. $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);
  1684. return $content;
  1685. }
  1686. /**
  1687. * 筛选出有效的id集合
  1688. *
  1689. * @param array $ids
  1690. * @return array
  1691. */
  1692. function filterValidIds(array $ids): array
  1693. {
  1694. // 传参
  1695. if (empty($ids)) {
  1696. return [];
  1697. }
  1698. $result = [];
  1699. foreach ($ids as $id) {
  1700. if (in_array($id, $result) || !is_numeric($id) || (int)$id < 1) {
  1701. continue;
  1702. }
  1703. $result[] = (int)$id;
  1704. }
  1705. return $result;
  1706. }
  1707. function arrayToStr($map)
  1708. {
  1709. $isMap = isArrMap($map);
  1710. $result = "";
  1711. if ($isMap) {
  1712. $result = "map[";
  1713. }
  1714. $keyArr = array_keys($map);
  1715. if ($isMap) {
  1716. sort($keyArr);
  1717. }
  1718. $paramsArr = array();
  1719. foreach ($keyArr as $k) {
  1720. $v = $map[$k];
  1721. if ($isMap) {
  1722. if (is_array($v)) {
  1723. $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
  1724. } else {
  1725. $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
  1726. }
  1727. } else {
  1728. if (is_array($v)) {
  1729. $paramsArr[] = arrayToStr($v);
  1730. } else {
  1731. $paramsArr[] = trim(strval($v));
  1732. }
  1733. }
  1734. }
  1735. $result = sprintf("%s%s", $result, join(" ", $paramsArr));
  1736. if (!$isMap) {
  1737. $result = sprintf("[%s]", $result);
  1738. } else {
  1739. $result = sprintf("%s]", $result);
  1740. }
  1741. return $result;
  1742. }
  1743. function isArrMap($map)
  1744. {
  1745. foreach ($map as $k => $v) {
  1746. if (is_string($k)) {
  1747. return true;
  1748. }
  1749. }
  1750. return false;
  1751. }
  1752. /**
  1753. * 随机字符串
  1754. *
  1755. * @param $length
  1756. * @return string
  1757. */
  1758. function makeRandStr($length): string
  1759. {
  1760. // 密码字符集,可任意添加你需要的字符
  1761. $str = [
  1762. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  1763. 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  1764. 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
  1765. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  1766. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  1767. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  1768. ];
  1769. // 在 $str 中随机取 $length 个数组元素键名
  1770. $keys = array_rand($str, $length);
  1771. $password = '';
  1772. for ($i = 0; $i < $length; $i++) {
  1773. // 将 $length 个数组元素连接成字符串
  1774. $password .= $str[$keys[$i]];
  1775. }
  1776. return $password;
  1777. }
  1778. /**
  1779. * 导出数据为excel表格
  1780. *
  1781. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1782. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1783. * @param $filename 下载的文件名
  1784. * @examlpe10
  1785. */
  1786. function exportExcel($data = [], $title = [], $filename = 'report')
  1787. {
  1788. ob_end_clean();
  1789. ob_start();
  1790. header("Content-type:application/octet-stream");
  1791. header("Accept-Ranges:bytes");
  1792. header("Content-type:application/vnd.ms-excel");
  1793. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1794. header("Pragma: no-cache");
  1795. header("Expires: 0");
  1796. //导出xls 开始
  1797. if (!empty($title)) {
  1798. foreach ($title as $k => $v) {
  1799. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1800. }
  1801. $title = implode("\t", $title);
  1802. echo "$title\n";
  1803. }
  1804. if (!empty($data)) {
  1805. foreach ($data as $key => $val) {
  1806. foreach ($val as $ck => $cv) {
  1807. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1808. }
  1809. $data[$key] = implode("\t", $data[$key]);
  1810. }
  1811. echo implode("\n", $data);
  1812. }
  1813. }
  1814. /**
  1815. * 导出csv文件
  1816. * @param string $name
  1817. * @param array $headers
  1818. * @param array $data
  1819. * @return void
  1820. */
  1821. function exportCsv(string $name, array $headers, array $data = [])
  1822. {
  1823. header('Content-Description: File Transfer');
  1824. header('Content-Type: application/csv');
  1825. header("Content-Disposition: attachment; filename=".$name.".csv");
  1826. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  1827. $handle = fopen('php://output', 'w');
  1828. ob_clean();
  1829. fputcsv($handle, $headers);
  1830. if ($data) {
  1831. foreach ($data as $row) {
  1832. fputcsv($handle, $row);
  1833. }
  1834. }
  1835. ob_flush();
  1836. fclose($handle);
  1837. die();
  1838. }
  1839. // 树状分类
  1840. function buildCategoryTree($categories, $pid = 0) {
  1841. $tree = [];
  1842. foreach ($categories as $category) {
  1843. if ($category['pid'] == $pid) {
  1844. $children = buildCategoryTree($categories, $category['category_id']);
  1845. if ($children) {
  1846. $category['children'] = $children;
  1847. }
  1848. $tree[] = $category;
  1849. }
  1850. }
  1851. return $tree;
  1852. }
  1853. // 获取文件的md5值
  1854. function getFileContentMD5($filePath){
  1855. //获取文件MD5的128位二进制数组
  1856. $md5Bytes = md5_file($filePath,true);
  1857. //计算文件的Content-MD5
  1858. $contentMD5 = base64_encode($md5Bytes);
  1859. return $contentMD5;
  1860. }
  1861. function getTextTokens($text) {
  1862. // 方法1:按空格分词(西文较准)
  1863. $words = preg_split('/\s+/', $text);
  1864. $wordCount = count($words);
  1865. // 方法2:按字符数估算(中文较准:1个汉字 ≈ 1.5-2 tokens)
  1866. $charCount = mb_strlen($text);
  1867. // 综合估算(根据语言调整权重)
  1868. $tokenCount = $wordCount + $charCount * 0.5; // 示例公式
  1869. // 更简单:直接按字符数 * 系数(中文推荐)
  1870. // $tokenCount = $charCount * 1.8; // 经验系数
  1871. return (int)ceil($tokenCount);
  1872. }
  1873. // 处理小说剧本文本
  1874. function handleScriptWords($text, $enable_emotion=1) {
  1875. $text = preg_replace('/[\r\n]+/', PHP_EOL, $text);
  1876. $text_arr = explode(PHP_EOL, $text);
  1877. $roles = [];
  1878. $words = [];
  1879. $role_gender = [];
  1880. // $sequence = 0;
  1881. foreach ($text_arr as $line) {
  1882. $line = trim($line);
  1883. if ($enable_emotion) {
  1884. $match_rule = '/^(.*?)\:(.*?)\{(.*?)\}$/';
  1885. $count = 4;
  1886. } else {
  1887. $match_rule = '/^(.*?)\:(.*?)$/';
  1888. $count = 3;
  1889. }
  1890. preg_match($match_rule, $line, $matches);
  1891. if (count($matches) == $count) {
  1892. $gender = '0';
  1893. // 角色部分拆分
  1894. preg_match('/^(.*?)\((.*?)\)$/', $matches[1], $matches2);
  1895. if (count($matches2) == 3) {
  1896. $role = $matches2[1];
  1897. $gender_arr = ['男'=>'1', '女'=>'2'];
  1898. $gender = isset($gender_arr[$matches2[2]]) ? $gender_arr[$matches2[2]] : '0';
  1899. }else {
  1900. $role = $matches[1];
  1901. }
  1902. if (!in_array($role, $roles)) {
  1903. $roles[] = $role; // 记录角色
  1904. $role_gender[$role] = $gender;
  1905. }
  1906. $words[] = [
  1907. 'role' => $role,
  1908. 'gender' => $gender,
  1909. 'text' => $matches[2],
  1910. 'emotion' => $enable_emotion ? $matches[3] : '中性',
  1911. ];
  1912. }
  1913. }
  1914. $new_words = [];
  1915. $tmp = '';
  1916. $tmp_arr = [];
  1917. $tmp_text = '';
  1918. // 将words数组按照role和emotion合并相邻的text内容,不相邻则跳过合并
  1919. foreach ($words as $word) {
  1920. if(!$tmp) $tmp = $word['role'].'-'.$word['emotion'];
  1921. if($tmp == $word['role'].'-'.$word['emotion']) {
  1922. $tmp_text .= PHP_EOL.$word['text'];
  1923. $tmp_arr = [
  1924. 'role' => $word['role'],
  1925. 'gender' => $word['gender'],
  1926. 'text' => trim($tmp_text, PHP_EOL),
  1927. 'emotion' => $word['emotion'],
  1928. ];
  1929. }else {
  1930. // $sequence++;
  1931. // $tmp_arr['sequence'] = $sequence;
  1932. $new_words[] = $tmp_arr;
  1933. $tmp = $word['role'].'-'.$word['emotion'];
  1934. $tmp_text = $word['text'];
  1935. $tmp_arr = [
  1936. 'role' => $word['role'],
  1937. 'gender' => $word['gender'],
  1938. 'text' => trim($tmp_text, PHP_EOL),
  1939. 'emotion' => $word['emotion'],
  1940. ];
  1941. }
  1942. }
  1943. if ($tmp_arr) {
  1944. // $sequence++;
  1945. // $tmp_arr['sequence'] = $sequence;
  1946. $new_words[] = $tmp_arr;
  1947. }
  1948. return [
  1949. 'roles' => $roles,
  1950. 'role_gender' => $role_gender,
  1951. 'words' => $new_words,
  1952. ];
  1953. }
  1954. function extractScriptContent($originalContent) {
  1955. if (!$originalContent) return [];
  1956. // 使用更精确的正则表达式分割内容
  1957. $parts = [];
  1958. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  1959. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  1960. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  1961. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  1962. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  1963. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  1964. // 提取剧本亮点(支持多个空格)
  1965. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  1966. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  1967. // 提取人物关系(支持多个空格)
  1968. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  1969. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  1970. // 提取核心矛盾(支持多个空格)
  1971. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  1972. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  1973. // 提取主体列表(支持多个空格)
  1974. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  1975. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  1976. $parts['roles'] = parseRolesFromText($rolesText);
  1977. // 提取美术风格(支持多个空格)
  1978. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  1979. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  1980. // 提取场景列表(支持多个空格)
  1981. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  1982. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  1983. $parts['scenes'] = parseScenesFromText($scenesText);
  1984. // 提取分集详细内容(多剧集模式,支持多个空格)
  1985. preg_match('/###\s*分集剧本\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  1986. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  1987. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  1988. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  1989. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  1990. // 优先使用原文内容,其次使用分集详细内容
  1991. // $parts['content'] = $generatedContent ?: $detailedContent;
  1992. // 解析分集剧本内容
  1993. $episodes = [];
  1994. if ($detailedContent) {
  1995. // 按 ##分集 分割
  1996. preg_match_all('/##\s*分集(\d+)\s*\n(.*?)(?=\n\s*##分集|\z)/s', $detailedContent, $episodeMatches, PREG_SET_ORDER);
  1997. foreach ($episodeMatches as $episodeMatch) {
  1998. $episodeNum = $episodeMatch[1];
  1999. $episodeContent = trim($episodeMatch[2]);
  2000. $episode = [
  2001. 'episode_number' => $episodeNum,
  2002. 'episode_content' => $episodeContent,
  2003. 'episode_name' => '',
  2004. 'scene_description' => '',
  2005. 'camera_movement' => '',
  2006. 'characters' => '',
  2007. 'dialogues' => []
  2008. ];
  2009. // 提取分集名(格式:##分集01第一集: 第一集的标题)
  2010. if (preg_match('/^第.*?集\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $nameMatch)) {
  2011. $episode['episode_name'] = trim($nameMatch[1]);
  2012. }
  2013. // 提取场景描述
  2014. if (preg_match('/场景描述\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $sceneMatch)) {
  2015. $episode['scene_description'] = trim($sceneMatch[1]);
  2016. }
  2017. // 提取运镜
  2018. if (preg_match('/运镜\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $cameraMatch)) {
  2019. $episode['camera_movement'] = trim($cameraMatch[1]);
  2020. }
  2021. // 提取出场角色
  2022. if (preg_match('/出场角色\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $charactersMatch)) {
  2023. $episode['characters'] = trim($charactersMatch[1]);
  2024. }
  2025. // 提取台词内容
  2026. if (preg_match('/台词内容\s*[::]\s*\n(.*?)$/su', $episodeContent, $dialoguesMatch)) {
  2027. $dialoguesText = trim($dialoguesMatch[1]);
  2028. $dialogueLines = explode("\n", $dialoguesText);
  2029. foreach ($dialogueLines as $line) {
  2030. $line = trim($line);
  2031. if (empty($line)) {
  2032. continue;
  2033. }
  2034. // 匹配格式:角色名: 对话内容 或 角色名:对话内容
  2035. if (preg_match('/^(.+?)\s*[::]\s*(.+)$/u', $line, $dialogueMatch)) {
  2036. $episode['dialogues'][] = [
  2037. 'character' => trim($dialogueMatch[1]),
  2038. 'text' => trim($dialogueMatch[2])
  2039. ];
  2040. }
  2041. }
  2042. }
  2043. $episodes[] = $episode;
  2044. }
  2045. }
  2046. $parts['episodes'] = $episodes;
  2047. return $parts;
  2048. }
  2049. /**
  2050. * 处理剧本内容
  2051. */
  2052. function handleScriptContent($originalContent) {
  2053. if (!$originalContent) return [];
  2054. // 使用更精确的正则表达式分割内容
  2055. $parts = [];
  2056. // // 确保内容使用UTF-8编码
  2057. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  2058. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  2059. // }
  2060. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2061. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2062. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2063. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2064. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2065. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2066. // 提取剧本亮点(支持多个空格)
  2067. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2068. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2069. // 提取人物关系(支持多个空格)
  2070. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2071. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2072. // 提取核心矛盾(支持多个空格)
  2073. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2074. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2075. // 提取主体列表(支持多个空格)
  2076. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2077. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2078. $parts['roles'] = parseRolesFromText($rolesText);
  2079. // 提取美术风格(支持多个空格)
  2080. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2081. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2082. // 提取场景列表(支持多个空格)
  2083. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2084. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2085. $parts['scenes'] = parseScenesFromText($scenesText);
  2086. // 提取分集详细内容(多剧集模式,支持多个空格)
  2087. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2088. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2089. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2090. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2091. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2092. // 优先使用原文内容,其次使用分集详细内容
  2093. $parts['content'] = $generatedContent ?: $detailedContent;
  2094. $parts['episode_title'] = '';
  2095. $parts['acts'] = [];
  2096. // 单剧集格式:顶层是大纲信息,分镜部分采用 handleEpisodeContent 的结构标准
  2097. $singleStoryboard = '';
  2098. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2099. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2100. }
  2101. if ($singleStoryboard !== '') {
  2102. $episodeContent = $singleStoryboard;
  2103. if (!preg_match('/第\d+集[::\s]+/u', $episodeContent)) {
  2104. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  2105. $episodeContent = $defaultEpisodeTitle . "\n\n" . $episodeContent;
  2106. }
  2107. $episodeSections = [];
  2108. $episodeSections[] = $episodeContent;
  2109. if ($parts['intro'] !== '') {
  2110. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  2111. }
  2112. if ($parts['art_style'] !== '') {
  2113. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  2114. }
  2115. if ($rolesText !== '') {
  2116. $episodeSections[] = "###主体列表\n" . $rolesText;
  2117. }
  2118. if ($scenesText !== '') {
  2119. $episodeSections[] = "###场景列表\n" . $scenesText;
  2120. }
  2121. if (strpos($episodeContent, '###分镜剧本') === false) {
  2122. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  2123. }
  2124. $episode_arr = handleEpisodeContent(implode("\n\n", $episodeSections));
  2125. if (!empty($episode_arr['acts'])) {
  2126. $parts['episode_title'] = getProp($episode_arr, 'episode_title');
  2127. $parts['acts'] = getProp($episode_arr, 'acts', []);
  2128. if (empty($parts['roles'])) {
  2129. $parts['roles'] = getProp($episode_arr, 'roles', []);
  2130. }
  2131. if (empty($parts['scenes'])) {
  2132. $parts['scenes'] = getProp($episode_arr, 'scenes', []);
  2133. }
  2134. }
  2135. }
  2136. if (empty($parts['acts'])) {
  2137. $fallbackEpisodeArr = handleEpisodeContent($originalContent);
  2138. if (!empty($fallbackEpisodeArr['acts'])) {
  2139. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title');
  2140. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  2141. if (empty($parts['intro'])) {
  2142. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro');
  2143. }
  2144. if (empty($parts['art_style'])) {
  2145. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style');
  2146. }
  2147. if (empty($parts['roles'])) {
  2148. $parts['roles'] = getProp($fallbackEpisodeArr, 'roles', []);
  2149. }
  2150. if (empty($parts['scenes'])) {
  2151. $parts['scenes'] = getProp($fallbackEpisodeArr, 'scenes', []);
  2152. }
  2153. }
  2154. }
  2155. // 多剧集格式:继续兼容旧的分集剧本结构
  2156. $fullScript = '';
  2157. if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2158. $fullScript = trim($storyboardMatch[1]);
  2159. } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2160. $fullScript = trim($storyboardMatch[1]);
  2161. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2162. $fullScript = trim($storyboardMatch[1]);
  2163. }
  2164. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  2165. $fullScript = trim($fallbackMatch[1]);
  2166. }
  2167. $episodes = [];
  2168. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  2169. foreach ($matches as $match) {
  2170. $episodeNumber = (int)trim($match[1]);
  2171. $episodeName = trim($match[2]);
  2172. $episodeContent = trim($match[3]);
  2173. $segments = [];
  2174. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  2175. foreach ($segmentMatches as $segMatch) {
  2176. $segmentNumber = (int)trim($segMatch[1]);
  2177. $segmentContent = trim($segMatch[2]);
  2178. $segments[] = [
  2179. 'segment_number' => $segmentNumber,
  2180. 'segment_content' => $segmentContent,
  2181. ];
  2182. }
  2183. $episodes[] = [
  2184. 'episode_number' => $episodeNumber,
  2185. 'title' => $episodeName,
  2186. 'content' => $episodeContent,
  2187. 'segments' => $segments,
  2188. ];
  2189. }
  2190. if (empty($episodes) && !empty($parts['acts'])) {
  2191. $singleSegments = [];
  2192. foreach ($parts['acts'] as $act) {
  2193. $actSegments = getProp($act, 'segments', []);
  2194. if (!is_array($actSegments)) {
  2195. continue;
  2196. }
  2197. foreach ($actSegments as $segment) {
  2198. $singleSegments[] = [
  2199. 'segment_number' => getProp($segment, 'segment_number'),
  2200. 'segment_content' => getProp($segment, 'segment_content'),
  2201. ];
  2202. }
  2203. }
  2204. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  2205. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  2206. $episodes[] = [
  2207. 'episode_number' => 1,
  2208. 'title' => $episodeName,
  2209. 'content' => $singleStoryboard,
  2210. 'segments' => $singleSegments,
  2211. ];
  2212. }
  2213. $parts['episodes'] = $episodes;
  2214. return $parts;
  2215. }
  2216. function handleEpisodeContent($originalContent) {
  2217. if (!$originalContent) return [];
  2218. // 解析剧集内容
  2219. $result = [
  2220. 'episode_title' => '',
  2221. 'intro' => '',
  2222. 'art_style' => '',
  2223. 'roles' => [],
  2224. 'scenes' => [],
  2225. 'acts' => []
  2226. ];
  2227. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  2228. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  2229. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  2230. }
  2231. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  2232. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  2233. $result['intro'] = trim($summaryMatch[1]);
  2234. }
  2235. // 提取美术风格 - 兼容多种格式
  2236. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  2237. $result['art_style'] = trim($styleMatch[1]);
  2238. }
  2239. // 提取主体列表 - 兼容多种格式
  2240. if (preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  2241. $charactersText = trim($charactersMatch[1]);
  2242. $characterLines = explode("\n", $charactersText);
  2243. foreach ($characterLines as $line) {
  2244. $line = trim($line);
  2245. if (empty($line)) continue;
  2246. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  2247. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2248. $role = trim($charMatch[1]);
  2249. $description = trim($charMatch[2]);
  2250. $timbreName = null;
  2251. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  2252. $picPrompt = null;
  2253. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  2254. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  2255. $description = trim($fullMatch[1]);
  2256. $picPrompt = trim($fullMatch[2]);
  2257. $timbreName = trim($fullMatch[3]);
  2258. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2259. // 兼容旧格式:主体描述{{音色名}}
  2260. $description = trim($timbreMatch[1]);
  2261. $timbreName = trim($timbreMatch[2]);
  2262. }
  2263. $roleData = [
  2264. 'role' => $role,
  2265. 'description' => $description
  2266. ];
  2267. // 如果有主体图片提示词,添加到数组中
  2268. if ($picPrompt) {
  2269. // 检查开头是否有"全景,正面拍摄。"
  2270. $prefix = '全景,正面拍摄。';
  2271. $prefixParts = ['全景', '正面拍摄'];
  2272. // 检查是否包含完整前缀
  2273. if (strpos($picPrompt, $prefix) !== 0) {
  2274. // 检查是否包含部分前缀词汇(不论位置)
  2275. $hasAnyPrefix = false;
  2276. foreach ($prefixParts as $part) {
  2277. if (mb_strpos($picPrompt, $part) !== false) {
  2278. $hasAnyPrefix = true;
  2279. break;
  2280. }
  2281. }
  2282. if ($hasAnyPrefix) {
  2283. // 移除所有"全景"和"正面拍摄"词汇(包括它们后面的标点)
  2284. $picPrompt = preg_replace('/全景[,,、。. ]*/u', '', $picPrompt);
  2285. $picPrompt = preg_replace('/正面拍摄[,,、。. ]*/u', '', $picPrompt);
  2286. // 清理开头和结尾的标点符号和空格
  2287. $picPrompt = preg_replace('/^[。,,、 ]+|[。,,、 ]+$/u', '', $picPrompt);
  2288. }
  2289. // 在开头添加完整前缀
  2290. $picPrompt = $prefix . $picPrompt;
  2291. }
  2292. // 检查是否包含"姿态:"或"姿态:"
  2293. if (preg_match('/姿态[::]/u', $picPrompt)) {
  2294. // 如果有姿态描述,统一替换为"姿态:站立"
  2295. $picPrompt = preg_replace('/姿态[::][^.。\n]+/u', '姿态:站立', $picPrompt);
  2296. } else {
  2297. // 如果没有姿态描述,在末尾添加"姿态:站立"
  2298. $picPrompt = preg_replace('/[。,, ]+$/u', '', $picPrompt) . '。姿态:站立。';
  2299. }
  2300. $roleData['pic_prompt'] = $picPrompt;
  2301. }
  2302. // 如果有音色信息,添加到数组中
  2303. if ($timbreName) {
  2304. $timbre = DB::table('mp_timbres')->where('is_enabled', 1)->where('timbre_name', 'like', "%{$timbreName}%")->orderBy('id')->select('timbre_type', 'audio_url')->first();
  2305. if ($timbre) {
  2306. $roleData['voice_name'] = $timbreName;
  2307. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2308. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');;
  2309. }
  2310. }else {
  2311. // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  2312. if ($picPrompt) {
  2313. if (strstr($picPrompt, '男')) {
  2314. $roleData['voice_name'] = '阳光青年';
  2315. }elseif (strstr($picPrompt, '女')) {
  2316. $roleData['voice_name'] = '爽快思思';
  2317. }else {
  2318. if ($description) {
  2319. if (strstr($description, '男')) {
  2320. $roleData['voice_name'] = '阳光青年';
  2321. }elseif (strstr($description, '女')) {
  2322. $roleData['voice_name'] = '爽快思思';
  2323. }else {
  2324. $roleData['voice_name'] = '旁白';
  2325. }
  2326. }
  2327. }
  2328. }
  2329. if (!empty($roleData['voice_name'])) {
  2330. if ($roleData['voice_name'] == '旁白') {
  2331. $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  2332. $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  2333. }else {
  2334. $timbre = DB::table('mp_timbres')
  2335. ->where('is_enabled', 1)
  2336. ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  2337. ->orderBy('id')
  2338. ->select('timbre_type', 'audio_url')
  2339. ->first();
  2340. if ($timbre) {
  2341. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2342. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2343. }
  2344. }
  2345. }
  2346. }
  2347. $result['roles'][] = $roleData;
  2348. }
  2349. }
  2350. // 加入旁白角色(如果不存在)
  2351. $hasNarrator = false;
  2352. foreach ($result['roles'] as $role) {
  2353. if (isset($role['role']) && $role['role'] === '旁白') {
  2354. $hasNarrator = true;
  2355. break;
  2356. }
  2357. }
  2358. if (!$hasNarrator) {
  2359. $result['roles'][] = [
  2360. 'role' => '旁白',
  2361. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2362. 'pic_prompt' => '',
  2363. 'voice_name' => '旁白',
  2364. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2365. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2366. ];
  2367. }
  2368. }
  2369. // 提取场景列表 - 兼容多种格式
  2370. if (preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  2371. $scenesText = trim($scenesMatch[1]);
  2372. $sceneLines = explode("\n", $scenesText);
  2373. foreach ($sceneLines as $line) {
  2374. $line = trim($line);
  2375. if (empty($line)) continue;
  2376. // 兼容中文冒号:和英文冒号:
  2377. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  2378. $scene = trim($sceneMatch[1]);
  2379. $description = trim($sceneMatch[2]);
  2380. $picPrompt = null;
  2381. // 检查描述末尾是否有{场景图片提示词}格式
  2382. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  2383. // 匹配格式:场景描述{场景图片提示词}
  2384. $description = trim($promptMatch[1]);
  2385. $picPrompt = trim($promptMatch[2]);
  2386. }
  2387. $sceneData = [
  2388. 'scene' => $scene,
  2389. 'description' => $description
  2390. ];
  2391. // 如果有场景图片提示词,添加到数组中
  2392. if ($picPrompt) {
  2393. $sceneData['pic_prompt'] = $picPrompt;
  2394. }
  2395. $result['scenes'][] = $sceneData;
  2396. }
  2397. }
  2398. }
  2399. // 提取分镜剧本 - 兼容多种格式
  2400. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $storyboardMatch)) {
  2401. $storyboardText = trim($storyboardMatch[1]);
  2402. // 按幕分割 - 修复第1幕识别和乱码问题
  2403. $acts = [];
  2404. // 先在开头添加换行符,确保第1幕也能被正确分割
  2405. $normalizedText = "\n" . $storyboardText;
  2406. $parts = preg_split('/\n\s*##/', $normalizedText);
  2407. foreach ($parts as $part) {
  2408. $part = trim($part);
  2409. if (empty($part)) continue;
  2410. // 如果不是以"第"开头,跳过
  2411. if (!preg_match('/^第\d+幕/', $part)) {
  2412. continue;
  2413. }
  2414. // 分离标题和内容
  2415. $lines = explode("\n", $part, 2);
  2416. $actTitle = trim($lines[0]);
  2417. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  2418. // 解析幕标题,提取序号和详细信息 - 修复乱码问题
  2419. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  2420. $actNumber = intval($actTitleMatch[1]);
  2421. $actDetails = trim($actTitleMatch[2]);
  2422. // 如果详细信息为空或者就是冒号,使用完整标题
  2423. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  2424. $actDetails = $actTitle;
  2425. }
  2426. } else {
  2427. $actNumber = count($acts) + 1;
  2428. $actDetails = $actTitle;
  2429. }
  2430. // 解析该幕下的分镜
  2431. $segments = [];
  2432. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  2433. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  2434. foreach ($segmentMatches as $segmentMatch) {
  2435. $segmentNumber = intval($segmentMatch[1]);
  2436. $segmentContent = trim($segmentMatch[2]);
  2437. // 解析分镜详细信息
  2438. $segmentData = [
  2439. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT), // 生成唯一ID(后续可在生成任务里查看历史版本)
  2440. 'segment_number' => $segmentNumber,
  2441. 'segment_content' => $segmentContent,
  2442. 'description' => '',
  2443. 'composition' => '',
  2444. 'camera_movement' => '',
  2445. 'voice_actor' => '',
  2446. 'dialogue' => '',
  2447. 'frame_type' => '',
  2448. 'scene' => '', // 新增:场景
  2449. 'characters' => '', // 新增:出镜角色
  2450. 'tail_frame' => '', // 新增:尾帧描述
  2451. // 新增字段
  2452. 'emotion' => '中性', // 新增: 情感
  2453. 'gender' => '0', // 新增: 性别(0未知,1男,2女)
  2454. 'speed_ratio' => 0, // 新增: 语速
  2455. 'loudness_ratio' => 0, // 新增: 音量
  2456. 'emotion_scale' => 4, // 新增: 语调
  2457. 'pitch' => 0, // 新增: 音调
  2458. ];
  2459. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  2460. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  2461. $segmentData['description'] = trim($descMatch[1]);
  2462. }
  2463. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  2464. $segmentData['composition'] = trim($compMatch[1]);
  2465. }
  2466. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  2467. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  2468. }
  2469. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  2470. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  2471. }
  2472. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  2473. $dialogue = trim($dialogueMatch[1]) == '无' ? '' : trim($dialogueMatch[1]);
  2474. // 确保台词使用中文左右双引号
  2475. if (!empty($dialogue)) {
  2476. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  2477. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  2478. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  2479. if (!preg_match('/^[“]/', $dialogue)) {
  2480. $dialogue = '“' . $dialogue;
  2481. }
  2482. if (!preg_match('/[”]$/', $dialogue)) {
  2483. $dialogue .= '”';
  2484. }
  2485. // 将修改后的台词替换回 $segmentContent
  2486. $originalDialogue = $dialogueMatch[1];
  2487. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  2488. }
  2489. $segmentData['dialogue'] = $dialogue;
  2490. }
  2491. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  2492. $segmentData['frame_type'] = trim($frameMatch[1]);
  2493. }
  2494. // 新增:场景字段
  2495. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  2496. $segmentData['scene'] = trim($sceneMatch[1]);
  2497. }
  2498. // 新增:出镜角色字段
  2499. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  2500. $segmentData['characters'] = trim($charactersMatch[1]);
  2501. }
  2502. // 新增:尾帧描述字段
  2503. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  2504. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  2505. }
  2506. $replaceEmptyArr = [];
  2507. // 新增:情感字段
  2508. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  2509. $replaceEmptyArr[] = trim($emotionMatch[0]);
  2510. $segmentData['emotion'] = trim($emotionMatch[1]);
  2511. }
  2512. // 新增:性别字段
  2513. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  2514. $replaceEmptyArr[] = trim($genderMatch[0]);
  2515. $genderStr = trim($genderMatch[1]);
  2516. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  2517. $segmentData['gender'] = '1';
  2518. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  2519. $segmentData['gender'] = '2';
  2520. } else {
  2521. $segmentData['gender'] = '0';
  2522. }
  2523. }
  2524. // 新增:语速字段
  2525. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  2526. $replaceEmptyArr[] = trim($speedMatch[0]);
  2527. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  2528. }
  2529. // 新增:音量字段
  2530. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  2531. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  2532. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  2533. }
  2534. // 新增:情感强度字段
  2535. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  2536. $replaceEmptyArr[] = trim($scaleMatch[0]);
  2537. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  2538. }
  2539. // 新增:音调字段
  2540. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  2541. $replaceEmptyArr[] = trim($pitchMatch[0]);
  2542. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  2543. }
  2544. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  2545. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  2546. $segmentData['segment_content'] = preg_replace('/\n{2,}/', "\n", $segmentData['segment_content']);
  2547. $segmentData['segment_content'] = trim($segmentData['segment_content']);
  2548. $segments[] = $segmentData;
  2549. }
  2550. $acts[] = [
  2551. 'act_number' => $actNumber,
  2552. 'act_title' => $actTitle,
  2553. 'act_details' => $actDetails,
  2554. 'segments' => $segments
  2555. ];
  2556. }
  2557. $result['acts'] = $acts;
  2558. }
  2559. return $result;
  2560. }
  2561. /**
  2562. * 处理剧本内容(全能模式)
  2563. */
  2564. function handleScriptContentForAce($originalContent) {
  2565. if (!$originalContent) return [];
  2566. // 使用更精确的正则表达式分割内容
  2567. $parts = [];
  2568. // // 确保内容使用UTF-8编码
  2569. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  2570. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  2571. // }
  2572. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2573. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2574. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2575. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2576. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2577. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2578. // 提取剧本亮点(支持多个空格)
  2579. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2580. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2581. // 提取人物关系(支持多个空格)
  2582. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2583. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2584. // 提取核心矛盾(支持多个空格)
  2585. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2586. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2587. // 提取主体列表(支持多个空格)
  2588. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2589. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2590. $parts['roles'] = parseRolesFromTextForAce($rolesText);
  2591. // 提取美术风格(支持多个空格)
  2592. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2593. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2594. // 提取场景列表(支持多个空格)
  2595. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2596. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2597. $parts['scenes'] = parseScenesFromText($scenesText);
  2598. // 提取分集详细内容(多剧集模式,支持多个空格)
  2599. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2600. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2601. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2602. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2603. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2604. // 优先使用原文内容,其次使用分集详细内容
  2605. $parts['content'] = $generatedContent ?: $detailedContent;
  2606. $parts['episode_title'] = '';
  2607. $parts['acts'] = [];
  2608. // 单剧集格式:顶层是大纲信息,分段部分采用 handleEpisodeContentForAce 的结构标准
  2609. $singleStoryboard = '';
  2610. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2611. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2612. } elseif (preg_match('/###\s*分段剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2613. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2614. }
  2615. if ($singleStoryboard !== '') {
  2616. // 构造符合 handleEpisodeContentForAce 期望的输入格式
  2617. $episodeContent = '';
  2618. // 如果分镜剧本内容不包含剧集标题,添加默认标题
  2619. if (!preg_match('/第\d+集[::\s]+/u', $singleStoryboard)) {
  2620. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  2621. $episodeContent = $defaultEpisodeTitle . "\n\n";
  2622. }
  2623. // 组装完整的剧集内容,按 handleEpisodeContentForAce 期望的结构
  2624. $episodeSections = [];
  2625. // 添加故事梗概(如果有)
  2626. if (!empty($parts['intro'])) {
  2627. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  2628. }
  2629. // 添加美术风格(如果有)
  2630. if (!empty($parts['art_style'])) {
  2631. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  2632. }
  2633. // 添加主体列表(如果有)
  2634. if (!empty($rolesText)) {
  2635. $episodeSections[] = "###主体列表\n" . $rolesText;
  2636. }
  2637. // 添加场景列表(如果有)
  2638. if (!empty($scenesText)) {
  2639. $episodeSections[] = "###场景列表\n" . $scenesText;
  2640. }
  2641. // 添加分镜剧本内容(兼容"分镜剧本"和"分段剧本")
  2642. if (strpos($singleStoryboard, '###分镜剧本') === false && strpos($singleStoryboard, '###分段剧本') === false) {
  2643. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  2644. } else {
  2645. $episodeSections[] = $singleStoryboard;
  2646. }
  2647. // 拼接完整内容
  2648. $episodeContent .= implode("\n\n", $episodeSections);
  2649. // 调用 handleEpisodeContentForAce 方法解析
  2650. $episode_arr = handleEpisodeContentForAce($episodeContent);
  2651. if (!empty($episode_arr['acts'])) {
  2652. $parts['episode_title'] = getProp($episode_arr, 'episode_title', '');
  2653. $parts['acts'] = getProp($episode_arr, 'acts', []);
  2654. }
  2655. // 更新roles和scenes
  2656. $episode_roles = getProp($episode_arr, 'roles');
  2657. $episode_scenes = getProp($episode_arr, 'scenes');
  2658. if ($episode_roles) $parts['roles'] = $episode_roles;
  2659. if ($episode_scenes) $parts['scenes'] = $episode_scenes;
  2660. }
  2661. // 如果上面的处理没有得到 acts,尝试直接用原始内容调用 handleEpisodeContentForAce
  2662. if (empty($parts['acts'])) {
  2663. $fallbackEpisodeArr = handleEpisodeContentForAce($originalContent);
  2664. if (!empty($fallbackEpisodeArr['acts'])) {
  2665. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title', '');
  2666. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  2667. if (empty($parts['intro'])) {
  2668. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro', '');
  2669. }
  2670. if (empty($parts['art_style'])) {
  2671. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style', '');
  2672. }
  2673. }
  2674. // 更新roles和scenes
  2675. $episode_roles = getProp($fallbackEpisodeArr, 'roles');
  2676. $episode_scenes = getProp($fallbackEpisodeArr, 'scenes');
  2677. if ($episode_roles) $parts['roles'] = $episode_roles;
  2678. if ($episode_scenes) $parts['scenes'] = $episode_scenes;
  2679. }
  2680. // 多剧集格式:继续兼容旧的分集剧本结构
  2681. $fullScript = '';
  2682. if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2683. $fullScript = trim($storyboardMatch[1]);
  2684. } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2685. $fullScript = trim($storyboardMatch[1]);
  2686. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2687. $fullScript = trim($storyboardMatch[1]);
  2688. }
  2689. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  2690. $fullScript = trim($fallbackMatch[1]);
  2691. }
  2692. $episodes = [];
  2693. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  2694. foreach ($matches as $match) {
  2695. $episodeNumber = (int)trim($match[1]);
  2696. $episodeName = trim($match[2]);
  2697. $episodeContent = trim($match[3]);
  2698. $segments = [];
  2699. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  2700. foreach ($segmentMatches as $segMatch) {
  2701. $segmentNumber = (int)trim($segMatch[1]);
  2702. $segmentContent = trim($segMatch[2]);
  2703. $segments[] = [
  2704. 'segment_number' => $segmentNumber,
  2705. 'segment_content' => $segmentContent,
  2706. ];
  2707. }
  2708. $episodes[] = [
  2709. 'episode_number' => $episodeNumber,
  2710. 'title' => $episodeName,
  2711. 'content' => $episodeContent,
  2712. 'segments' => $segments,
  2713. ];
  2714. }
  2715. if (empty($episodes) && !empty($parts['acts'])) {
  2716. $singleSegments = [];
  2717. foreach ($parts['acts'] as $act) {
  2718. $actSegments = getProp($act, 'segments', []);
  2719. if (!is_array($actSegments)) {
  2720. continue;
  2721. }
  2722. foreach ($actSegments as $segment) {
  2723. $singleSegments[] = [
  2724. 'segment_number' => getProp($segment, 'segment_number'),
  2725. 'segment_content' => getProp($segment, 'segment_content'),
  2726. ];
  2727. }
  2728. }
  2729. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  2730. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  2731. $episodes[] = [
  2732. 'episode_number' => 1,
  2733. 'title' => $episodeName,
  2734. 'content' => $singleStoryboard,
  2735. 'segments' => $singleSegments,
  2736. ];
  2737. }
  2738. $parts['episodes'] = $episodes;
  2739. return $parts;
  2740. }
  2741. /**
  2742. * 将主体列表文本拆分为主体数组
  2743. *
  2744. * @param string $rolesText 主体列表文本内容
  2745. * @return array 主体名称数组
  2746. */
  2747. function parseRolesFromTextForAce(string $rolesText): array
  2748. {
  2749. if (empty($rolesText)) {
  2750. return [];
  2751. }
  2752. $roles = [];
  2753. // 按行分割文本
  2754. $lines = explode("\n", $rolesText);
  2755. foreach ($lines as $line) {
  2756. $line = trim($line);
  2757. if (empty($line)) {
  2758. continue;
  2759. }
  2760. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2761. $role = trim($charMatch[1]);
  2762. $description = trim($charMatch[2]);
  2763. $timbreName = null;
  2764. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  2765. $picPrompt = null;
  2766. $timbrePrompt = null;
  2767. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  2768. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  2769. $description = trim($fullMatch[1]);
  2770. $picPrompt = trim($fullMatch[2]);
  2771. $timbrePrompt = trim($fullMatch[3]);
  2772. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2773. // 兼容旧格式:主体描述{{音色名}}
  2774. $description = trim($timbreMatch[1]);
  2775. $timbrePrompt = trim($timbreMatch[2]);
  2776. }
  2777. $roleData = [
  2778. 'role' => $role,
  2779. 'description' => $description,
  2780. ];
  2781. // 如果有主体图片提示词,添加到数组中
  2782. if ($picPrompt) $roleData['pic_prompt'] = $picPrompt;
  2783. // 如果有音色提示词,添加到数组中
  2784. if ($timbrePrompt) $roleData['voice_prompt'] = $timbrePrompt;
  2785. if ($timbreName) {
  2786. $timbre = DB::table('mp_timbres')
  2787. ->where('is_enabled', 1)
  2788. ->where('timbre_name', 'like', "%{$timbreName}%")
  2789. ->orderBy('id')
  2790. ->select('timbre_type', 'audio_url')
  2791. ->first();
  2792. if ($timbre) {
  2793. $roleData['voice_name'] = $timbreName;
  2794. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2795. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2796. }
  2797. }
  2798. // else {
  2799. // // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  2800. // if ($picPrompt) {
  2801. // if (strstr($picPrompt, '男')) {
  2802. // $roleData['voice_name'] = '阳光青年';
  2803. // }elseif (strstr($picPrompt, '女')) {
  2804. // $roleData['voice_name'] = '爽快思思';
  2805. // }else {
  2806. // if ($description) {
  2807. // if (strstr($description, '男')) {
  2808. // $roleData['voice_name'] = '阳光青年';
  2809. // }elseif (strstr($description, '女')) {
  2810. // $roleData['voice_name'] = '爽快思思';
  2811. // }else {
  2812. // $roleData['voice_name'] = '旁白';
  2813. // }
  2814. // }
  2815. // }
  2816. // }
  2817. // if (!empty($roleData['voice_name'])) {
  2818. // if ($roleData['voice_name'] == '旁白') {
  2819. // $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  2820. // $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  2821. // }else {
  2822. // $timbre = DB::table('mp_timbres')
  2823. // ->where('is_enabled', 1)
  2824. // ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  2825. // ->orderBy('id')
  2826. // ->select('timbre_type', 'audio_url')
  2827. // ->first();
  2828. // if ($timbre) {
  2829. // $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2830. // $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2831. // }
  2832. // }
  2833. // }
  2834. // }
  2835. $roles[] = $roleData;
  2836. }
  2837. }
  2838. $hasNarrator = false;
  2839. foreach ($roles as $role) {
  2840. if (getProp($role, 'role') === '旁白') {
  2841. $hasNarrator = true;
  2842. break;
  2843. }
  2844. }
  2845. if (!$hasNarrator) {
  2846. $roles[] = [
  2847. 'role' => '旁白',
  2848. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2849. 'pic_prompt' => '',
  2850. 'voice_prompt' => '',
  2851. // 'voice_name' => '旁白',
  2852. // 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2853. // 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2854. ];
  2855. }
  2856. return $roles;
  2857. }
  2858. function handleEpisodeContentForAce($originalContent) {
  2859. if (!$originalContent) return [];
  2860. // 解析剧集内容
  2861. $result = [
  2862. 'episode_title' => '',
  2863. 'intro' => '',
  2864. 'art_style' => '',
  2865. 'roles' => [],
  2866. 'scenes' => [],
  2867. 'acts' => []
  2868. ];
  2869. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  2870. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  2871. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  2872. }
  2873. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  2874. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  2875. $result['intro'] = trim($summaryMatch[1]);
  2876. }
  2877. // 提取美术风格 - 兼容多种格式
  2878. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  2879. $result['art_style'] = trim($styleMatch[1]);
  2880. }
  2881. // 提取主体列表 - 兼容多种格式
  2882. if (preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  2883. $charactersText = trim($charactersMatch[1]);
  2884. $characterLines = explode("\n", $charactersText);
  2885. foreach ($characterLines as $line) {
  2886. $line = trim($line);
  2887. if (empty($line)) continue;
  2888. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  2889. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2890. $role = trim($charMatch[1]);
  2891. $description = trim($charMatch[2]);
  2892. $timbreName = null;
  2893. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  2894. $picPrompt = null;
  2895. $timbrePrompt = null;
  2896. // 修复正则:使用更精确的匹配,支持花括号嵌套
  2897. // 格式1: 描述{pic_prompt} {{voice_prompt}}
  2898. if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
  2899. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  2900. $description = trim($fullMatch[1]);
  2901. $picPrompt = trim($fullMatch[2]);
  2902. $timbrePrompt = trim($fullMatch[3]);
  2903. }
  2904. // 格式2: 描述{{voice_prompt}}(兼容旧格式,只有音色)
  2905. elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $timbreMatch)) {
  2906. // 兼容旧格式:主体描述{{音色名}}
  2907. $description = trim($timbreMatch[1]);
  2908. $timbrePrompt = trim($timbreMatch[2]);
  2909. }
  2910. // 格式3: 描述{pic_prompt}(只有图片提示词)
  2911. elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
  2912. $description = trim($picMatch[1]);
  2913. $picPrompt = trim($picMatch[2]);
  2914. }
  2915. $roleData = [
  2916. 'role' => $role,
  2917. 'description' => $description
  2918. ];
  2919. // 如果有主体图片提示词,添加到数组中
  2920. if ($picPrompt) {
  2921. // 检查开头是否有"全景,正面拍摄。"
  2922. $prefix = '全景,正面拍摄。';
  2923. $prefixParts = ['全景', '正面拍摄'];
  2924. // 检查是否包含完整前缀
  2925. if (strpos($picPrompt, $prefix) !== 0) {
  2926. // 检查是否包含部分前缀词汇(不论位置)
  2927. $hasAnyPrefix = false;
  2928. foreach ($prefixParts as $part) {
  2929. if (mb_strpos($picPrompt, $part) !== false) {
  2930. $hasAnyPrefix = true;
  2931. break;
  2932. }
  2933. }
  2934. if ($hasAnyPrefix) {
  2935. // 移除所有"全景"和"正面拍摄"词汇(包括它们后面的标点)
  2936. $picPrompt = preg_replace('/全景[,,、。. ]*/u', '', $picPrompt);
  2937. $picPrompt = preg_replace('/正面拍摄[,,、。. ]*/u', '', $picPrompt);
  2938. // 清理开头和结尾的标点符号和空格
  2939. $picPrompt = preg_replace('/^[。,,、 ]+|[。,,、 ]+$/u', '', $picPrompt);
  2940. }
  2941. // 在开头添加完整前缀
  2942. $picPrompt = $prefix . $picPrompt;
  2943. }
  2944. // 检查是否包含"姿态:"或"姿态:"
  2945. if (preg_match('/姿态[::]/u', $picPrompt)) {
  2946. // 如果有姿态描述,统一替换为"姿态:站立"
  2947. $picPrompt = preg_replace('/姿态[::][^.。\n]+/u', '姿态:站立', $picPrompt);
  2948. } else {
  2949. // 如果没有姿态描述,在末尾添加"姿态:站立"
  2950. $picPrompt = preg_replace('/[。,, ]+$/u', '', $picPrompt) . '。姿态:站立。';
  2951. }
  2952. $roleData['pic_prompt'] = $picPrompt;
  2953. }
  2954. if ($timbrePrompt) $roleData['voice_prompt'] = $timbrePrompt;
  2955. $result['roles'][] = $roleData;
  2956. }
  2957. }
  2958. // // 加入旁白角色(如果不存在)
  2959. // $hasNarrator = false;
  2960. // foreach ($result['roles'] as $role) {
  2961. // if (isset($role['role']) && $role['role'] === '旁白') {
  2962. // $hasNarrator = true;
  2963. // break;
  2964. // }
  2965. // }
  2966. // if (!$hasNarrator) {
  2967. // $result['roles'][] = [
  2968. // 'role' => '旁白',
  2969. // 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2970. // 'pic_prompt' => '',
  2971. // 'voice_name' => '旁白',
  2972. // 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2973. // 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2974. // ];
  2975. // }
  2976. }
  2977. // 提取场景列表 - 兼容多种格式
  2978. if (preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  2979. $scenesText = trim($scenesMatch[1]);
  2980. $sceneLines = explode("\n", $scenesText);
  2981. foreach ($sceneLines as $line) {
  2982. $line = trim($line);
  2983. if (empty($line)) continue;
  2984. // 兼容中文冒号:和英文冒号:
  2985. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  2986. $scene = trim($sceneMatch[1]);
  2987. $description = trim($sceneMatch[2]);
  2988. $picPrompt = null;
  2989. // 检查描述末尾是否有{场景图片提示词}格式
  2990. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  2991. // 匹配格式:场景描述{场景图片提示词}
  2992. $description = trim($promptMatch[1]);
  2993. $picPrompt = trim($promptMatch[2]);
  2994. }
  2995. $sceneData = [
  2996. 'scene' => $scene,
  2997. 'description' => $description
  2998. ];
  2999. // 如果有场景图片提示词,添加到数组中
  3000. if ($picPrompt) {
  3001. $sceneData['pic_prompt'] = $picPrompt;
  3002. }
  3003. $result['scenes'][] = $sceneData;
  3004. }
  3005. }
  3006. }
  3007. // 提取分镜剧本 - 兼容多种格式(旧格式:###分镜剧本,新格式:###分段剧本)
  3008. $storyboardPattern = '/###\s*(?:分镜剧本|分段剧本)\s*\n(.*?)(?=\n\s*###[^#]|\z)/s';
  3009. if (preg_match($storyboardPattern, $originalContent, $storyboardMatch)) {
  3010. $storyboardText = trim($storyboardMatch[1]);
  3011. // 提取旁白音色(新格式独有)
  3012. $narratorVoice = '';
  3013. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $storyboardText, $narratorMatch)) {
  3014. $narratorVoice = trim($narratorMatch[1]);
  3015. // 将旁白加入到roles数组
  3016. $hasNarrator = false;
  3017. foreach ($result['roles'] as $role) {
  3018. if (isset($role['role']) && $role['role'] === '旁白') {
  3019. $hasNarrator = true;
  3020. break;
  3021. }
  3022. }
  3023. if (!$hasNarrator) {
  3024. $result['roles'][] = [
  3025. 'role' => '旁白',
  3026. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  3027. 'pic_prompt' => '',
  3028. 'voice_prompt' => $narratorVoice
  3029. ];
  3030. }
  3031. }
  3032. // 按幕/片段分割 - 兼容"第X幕"和"片段X"两种格式
  3033. $acts = [];
  3034. // 先在开头添加换行符,确保第1幕/片段1也能被正确分割
  3035. $normalizedText = "\n" . $storyboardText;
  3036. $parts = preg_split('/\n\s*##/', $normalizedText);
  3037. foreach ($parts as $part) {
  3038. $part = trim($part);
  3039. if (empty($part)) continue;
  3040. // 兼容"第X幕"和"片段X"两种格式
  3041. if (!preg_match('/^(?:第\d+幕|片段\d+)/', $part)) {
  3042. continue;
  3043. }
  3044. // 分离标题和内容
  3045. $lines = explode("\n", $part, 2);
  3046. $actTitle = trim($lines[0]);
  3047. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  3048. // 解析标题,提取序号和详细信息
  3049. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  3050. // 旧格式:第X幕
  3051. $actNumber = intval($actTitleMatch[1]);
  3052. $actDetails = trim($actTitleMatch[2]);
  3053. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  3054. $actDetails = $actTitle;
  3055. }
  3056. } elseif (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  3057. // 新格式:片段X
  3058. $actNumber = intval($segmentTitleMatch[1]);
  3059. $actDetails = $actTitle;
  3060. } else {
  3061. $actNumber = count($acts) + 1;
  3062. $actDetails = $actTitle;
  3063. }
  3064. // 提取时长(新格式独有,仅保留数字)
  3065. $actDuration = '';
  3066. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  3067. $actDurationStr = trim($actDurationMatch[1]);
  3068. // 提取数字部分(支持整数和小数)
  3069. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  3070. $actDuration = $numMatch[1];
  3071. }
  3072. }
  3073. // 解析该幕/片段下的分镜
  3074. $segments = [];
  3075. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  3076. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  3077. foreach ($segmentMatches as $segmentMatch) {
  3078. $segmentNumber = intval($segmentMatch[1]);
  3079. $segmentContent = trim($segmentMatch[2]);
  3080. // 解析分镜详细信息
  3081. $segmentData = [
  3082. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT),
  3083. 'segment_number' => $segmentNumber,
  3084. 'segment_content' => $segmentContent,
  3085. 'description' => '',
  3086. 'composition' => '',
  3087. 'camera_movement' => '',
  3088. 'voice_actor' => '',
  3089. 'dialogue' => '',
  3090. 'frame_type' => '',
  3091. 'scene' => '',
  3092. 'characters' => '',
  3093. 'tail_frame' => '',
  3094. 'emotion' => '中性',
  3095. 'gender' => '0',
  3096. 'speed_ratio' => 0,
  3097. 'loudness_ratio' => 0,
  3098. 'emotion_scale' => 4,
  3099. 'pitch' => 0,
  3100. ];
  3101. // 提取场景
  3102. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3103. $segmentData['scene'] = trim($sceneMatch[1]);
  3104. }
  3105. // 提取画面描述 - 兼容新格式的方括号标注
  3106. if (preg_match('/(?:画面|画面描述|镜头描述|场景描述)[::]\s*(\[.*?\])?\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3107. $frameTypeInDesc = isset($descMatch[1]) ? trim($descMatch[1], '[]') : '';
  3108. $description = trim($descMatch[2]);
  3109. if (!empty($frameTypeInDesc)) {
  3110. $segmentData['frame_type'] = $frameTypeInDesc;
  3111. }
  3112. $segmentData['description'] = $description;
  3113. }
  3114. // 提取运镜
  3115. if (preg_match('/(?:运镜|运镜调度|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3116. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3117. }
  3118. // 提取配音台词 - 兼容新格式"中文配音:[角色] 台词"
  3119. // 修复:排除背景音效等非台词内容
  3120. if (preg_match('/配音台词[::]\s*(?:中文配音[::]?)?\s*(?:\[([^\]]+)\])?\s*([^\n]*?)(?=\n|$)/u', $segmentContent, $dialogueMatch)) {
  3121. $voiceActor = isset($dialogueMatch[1]) ? trim($dialogueMatch[1]) : '';
  3122. $dialogue = isset($dialogueMatch[2]) ? trim($dialogueMatch[2]) : '';
  3123. // 排除非台词内容(如果匹配到的是空或者是其他字段标记)
  3124. if (!empty($dialogue) && preg_match('/^(?:背景音效|音效|场景|画面|运镜|构图)[::]/u', $dialogue)) {
  3125. $dialogue = ''; // 如果匹配到的是其他字段,清空
  3126. }
  3127. if (!empty($voiceActor)) {
  3128. $segmentData['voice_actor'] = $voiceActor;
  3129. }
  3130. if ($dialogue && $dialogue !== '无') {
  3131. // 确保台词使用中文左右双引号
  3132. $dialogue = preg_replace('/^[""]/u', '"', $dialogue);
  3133. $dialogue = preg_replace('/[""]$/u', '"', $dialogue);
  3134. if (!preg_match('/^["]/', $dialogue)) {
  3135. $dialogue = '"' . $dialogue;
  3136. }
  3137. if (!preg_match('/["]$/', $dialogue)) {
  3138. $dialogue .= '"';
  3139. }
  3140. $segmentData['dialogue'] = $dialogue;
  3141. }
  3142. }
  3143. // 兼容旧格式的台词字段
  3144. // 修复:排除背景音效等非台词内容
  3145. if (empty($segmentData['dialogue']) && preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]*?)(?=\n|$)/u', $segmentContent, $oldDialogueMatch)) {
  3146. $dialogue = trim($oldDialogueMatch[1]);
  3147. // 排除非台词内容
  3148. if (!empty($dialogue) && preg_match('/^(?:背景音效|音效|场景|画面|运镜|构图)[::]/u', $dialogue)) {
  3149. $dialogue = ''; // 如果匹配到的是其他字段,清空
  3150. }
  3151. if ($dialogue && $dialogue !== '无') {
  3152. $dialogue = preg_replace('/^[""]/u', '"', $dialogue);
  3153. $dialogue = preg_replace('/[""]$/u', '"', $dialogue);
  3154. if (!preg_match('/^["]/', $dialogue)) {
  3155. $dialogue = '"' . $dialogue;
  3156. }
  3157. if (!preg_match('/["]$/', $dialogue)) {
  3158. $dialogue .= '"';
  3159. }
  3160. $segmentData['dialogue'] = $dialogue;
  3161. }
  3162. }
  3163. // 兼容旧格式的配音角色字段
  3164. if (empty($segmentData['voice_actor']) && preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3165. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3166. }
  3167. // 提取构图
  3168. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3169. $segmentData['composition'] = trim($compMatch[1]);
  3170. }
  3171. // 提取画面类型
  3172. if (empty($segmentData['frame_type']) && preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3173. $segmentData['frame_type'] = trim($frameMatch[1]);
  3174. }
  3175. // 提取出镜角色
  3176. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3177. $segmentData['characters'] = trim($charactersMatch[1]);
  3178. }
  3179. // 提取尾帧描述
  3180. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3181. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3182. }
  3183. $replaceEmptyArr = [];
  3184. // 提取情感
  3185. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3186. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3187. $segmentData['emotion'] = trim($emotionMatch[1]);
  3188. }
  3189. // 提取性别
  3190. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3191. $replaceEmptyArr[] = trim($genderMatch[0]);
  3192. $genderStr = trim($genderMatch[1]);
  3193. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3194. $segmentData['gender'] = '1';
  3195. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3196. $segmentData['gender'] = '2';
  3197. } else {
  3198. $segmentData['gender'] = '0';
  3199. }
  3200. }
  3201. // 提取语速
  3202. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3203. $replaceEmptyArr[] = trim($speedMatch[0]);
  3204. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3205. }
  3206. // 提取音量
  3207. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3208. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3209. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3210. }
  3211. // 提取情感强度
  3212. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3213. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3214. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3215. }
  3216. // 提取音调
  3217. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3218. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3219. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3220. }
  3221. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3222. $segmentData['segment_content'] = preg_replace('/\n{2,}/', "\n", $segmentData['segment_content']);
  3223. $segmentData['segment_content'] = trim($segmentData['segment_content']);
  3224. $segments[] = $segmentData;
  3225. }
  3226. $acts[] = [
  3227. 'act_number' => $actNumber,
  3228. 'act_title' => $actTitle,
  3229. 'act_details' => $actDetails,
  3230. 'act_duration' => $actDuration,
  3231. 'segments' => $segments
  3232. ];
  3233. }
  3234. $result['acts'] = $acts;
  3235. }
  3236. return $result;
  3237. }
  3238. /**
  3239. * 远程图片压缩(尽可能保持原图 fidelity,压缩到不超过 maxBytes 字节)
  3240. * 采用有损/无损组合策略:保留原始格式尽量不失真,若需要则通过尺寸缩放和质量调节来降低体积。
  3241. *
  3242. * @param string $url 远程图片 URL
  3243. * @param int $maxBytes 最大字节数,默认 3MB
  3244. * @param string|null $aspectRatio 目标长宽比,如 "16:9"、"4:3"、"1:1" 等,null 则保持原图比例
  3245. * @return string|null 返回压缩后的图片二进制数据,失败时返回 null
  3246. */
  3247. function compressRemoteImageUrlToSize(string $url, int $maxBytes = 3 * 1024 * 1024, ?string $aspectRatio = null): ?string
  3248. {
  3249. // 1) 下载图片数据(使用 Guzzle 以避免 allow_url_fopen 依赖)
  3250. try {
  3251. $client = new Client(['timeout' => 30]);
  3252. $response = $client->get($url, ['stream' => true]);
  3253. if ($response->getStatusCode() !== 200) {
  3254. return null;
  3255. }
  3256. $data = $response->getBody()->getContents();
  3257. } catch (\Exception $e) {
  3258. return null;
  3259. }
  3260. if (!$data) return null;
  3261. // 2) 识别图片类型
  3262. $imgInfo = @getimagesizefromstring($data);
  3263. $mime = $imgInfo['mime'] ?? '';
  3264. if ($mime == 'image/jpeg') return null; // JPEG 不做有损压缩
  3265. // 3) 载入图像对象
  3266. $srcImg = @imagecreatefromstring($data);
  3267. if (!$srcImg) {
  3268. return null;
  3269. }
  3270. $origW = imagesx($srcImg);
  3271. $origH = imagesy($srcImg);
  3272. // 3.2) 计算目标尺寸(根据长宽比调整)
  3273. $targetW = $origW;
  3274. $targetH = $origH;
  3275. if ($aspectRatio !== null) {
  3276. // 解析长宽比,如 "16:9" -> [16, 9]
  3277. $validRatios = array_keys(BaseConst::IMAGE_RATIOS);
  3278. if (in_array($aspectRatio, $validRatios)) {
  3279. list($ratioW, $ratioH) = explode(':', $aspectRatio);
  3280. $ratioW = (float)$ratioW;
  3281. $ratioH = (float)$ratioH;
  3282. $targetRatio = $ratioW / $ratioH;
  3283. $currentRatio = $origW / $origH;
  3284. // 根据目标比例裁剪图片
  3285. if ($currentRatio > $targetRatio) {
  3286. // 原图更宽,需要裁剪宽度
  3287. $targetW = (int)round($origH * $targetRatio);
  3288. $targetH = $origH;
  3289. } else {
  3290. // 原图更高,需要裁剪高度
  3291. $targetW = $origW;
  3292. $targetH = (int)round($origW / $targetRatio);
  3293. }
  3294. }
  3295. }
  3296. // 如果需要裁剪,创建裁剪后的图像
  3297. if ($targetW !== $origW || $targetH !== $origH) {
  3298. $croppedImg = imagecreatetruecolor($targetW, $targetH);
  3299. imagealphablending($croppedImg, false);
  3300. imagesavealpha($croppedImg, true);
  3301. // 处理透明背景
  3302. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3303. $transparent = imagecolorallocatealpha($croppedImg, 0, 0, 0, 127);
  3304. imagefill($croppedImg, 0, 0, $transparent);
  3305. }
  3306. // 居中裁剪
  3307. $srcX = (int)(($origW - $targetW) / 2);
  3308. $srcY = (int)(($origH - $targetH) / 2);
  3309. imagecopy($croppedImg, $srcImg, 0, 0, $srcX, $srcY, $targetW, $targetH);
  3310. // 替换原图
  3311. safeDestroyImage($srcImg);
  3312. $srcImg = $croppedImg;
  3313. $origW = $targetW;
  3314. $origH = $targetH;
  3315. }
  3316. // 3.1) 内部渲染成不同格式的字符串
  3317. $render = function($srcRes, string $mimeType, int $quality) {
  3318. ob_start();
  3319. switch (strtolower($mimeType)) {
  3320. case 'image/jpeg':
  3321. case 'image/jpg':
  3322. case 'image/pjpeg':
  3323. // 输出 JPEG
  3324. imagejpeg($srcRes, null, $quality);
  3325. break;
  3326. case 'image/png':
  3327. // 将 quality 映射到 PNG 的 compression level (0-9)
  3328. $level = (int)round((100 - $quality) / 11.11);
  3329. if ($level < 0) $level = 0;
  3330. if ($level > 9) $level = 9;
  3331. imagepng($srcRes, null, $level);
  3332. break;
  3333. case 'image/webp':
  3334. if (function_exists('imagewebp')) {
  3335. imagewebp($srcRes, null, $quality);
  3336. } else {
  3337. imagejpeg($srcRes, null, $quality);
  3338. }
  3339. break;
  3340. default:
  3341. imagejpeg($srcRes, null, $quality);
  3342. break;
  3343. }
  3344. $out = ob_get_contents();
  3345. ob_end_clean();
  3346. return $out;
  3347. };
  3348. // 4) 尝试策略:尽量保留原图尺寸,逐步降维/降质量,直到 <= maxBytes
  3349. $tryList = [];
  3350. // 原始尺寸,尽量保留
  3351. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>100];
  3352. // 逐步缩小尺寸
  3353. for ($s = 0.9; $s >= 0.2; $s -= 0.1) {
  3354. $tryList[] = ['scale'=>$s, 'mime'=>$mime, 'quality'=>90];
  3355. }
  3356. // 一系列质量等级(用于 JPEG/WebP)
  3357. $qualityLevels = [95, 90, 85, 75, 60, 50, 40, 30];
  3358. foreach ($qualityLevels as $q) {
  3359. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>$q];
  3360. }
  3361. $bestData = null;
  3362. foreach ($tryList as $cand) {
  3363. $scale = isset($cand['scale']) ? (float)$cand['scale'] : 1.0;
  3364. $mimeT = $cand['mime'] ?? $mime;
  3365. $quality = isset($cand['quality']) ? (int)$cand['quality'] : 90;
  3366. $w = (int)round($origW * $scale);
  3367. $h = (int)round($origH * $scale);
  3368. $src = $srcImg;
  3369. $tempImg = null;
  3370. if ($scale < 1.0) {
  3371. $tempImg = imagecreatetruecolor($w, $h);
  3372. // 处理透明通道
  3373. imagealphablending($tempImg, false);
  3374. imagesavealpha($tempImg, true);
  3375. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3376. $transparent = imagecolorallocatealpha($tempImg, 0, 0, 0, 127);
  3377. imagefill($tempImg, 0, 0, $transparent);
  3378. }
  3379. // 确保 $srcImg 有效
  3380. if (!$srcImg || (!is_resource($srcImg) && !($srcImg instanceof \GdImage))) {
  3381. safeDestroyImage($tempImg);
  3382. continue;
  3383. }
  3384. imagecopyresampled($tempImg, $srcImg, 0, 0, 0, 0, $w, $h, $origW, $origH);
  3385. $src = $tempImg;
  3386. }
  3387. $imageBytes = $render($src, $mimeT, $quality);
  3388. if ($tempImg !== null) {
  3389. safeDestroyImage($tempImg);
  3390. }
  3391. if ($imageBytes !== false && strlen($imageBytes) <= $maxBytes) {
  3392. $bestData = $imageBytes;
  3393. break;
  3394. }
  3395. }
  3396. // 5) 回退策略:若仍未达到要求,尝试更大幅度降解到一个合理的小尺寸 JPEG
  3397. if ($bestData === null) {
  3398. $tmpW = max(1, (int)round($origW * 0.5));
  3399. $tmpH = max(1, (int)round($origH * 0.5));
  3400. $tmpImg = imagecreatetruecolor($tmpW, $tmpH);
  3401. imagealphablending($tmpImg, false);
  3402. imagesavealpha($tmpImg, true);
  3403. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3404. $transparent = imagecolorallocatealpha($tmpImg, 0, 0, 0, 127);
  3405. imagefill($tmpImg, 0, 0, $transparent);
  3406. }
  3407. imagecopyresampled($tmpImg, $srcImg, 0, 0, 0, 0, $tmpW, $tmpH, $origW, $origH);
  3408. ob_start();
  3409. if (in_array(strtolower($mime), ['image/jpeg','image/jpg','image/pjpeg'])) {
  3410. imagejpeg($tmpImg, null, 75);
  3411. } elseif (strtolower($mime) === 'image/png') {
  3412. imagepng($tmpImg, null, 6);
  3413. } elseif (function_exists('imagewebp')) {
  3414. imagewebp($tmpImg, null, 75);
  3415. } else {
  3416. imagejpeg($tmpImg, null, 75);
  3417. }
  3418. $tmpBytes = ob_get_contents();
  3419. ob_end_clean();
  3420. safeDestroyImage($tmpImg);
  3421. if ($tmpBytes !== '' && strlen($tmpBytes) <= $maxBytes) {
  3422. $bestData = $tmpBytes;
  3423. }
  3424. }
  3425. // 6) 清理
  3426. safeDestroyImage($srcImg);
  3427. return $bestData;
  3428. }
  3429. /**
  3430. * 安全销毁 GD 图像资源(兼容 PHP7.4+ 的资源管理)
  3431. * 通过引用传递并在销毁后置空变量,避免未定义变量的问题
  3432. *
  3433. * @param resource|\GdImage|null &$img GD 图像资源或对象(PHP7.4 为 resource,PHP8.0+ 为 GdImage)
  3434. */
  3435. function safeDestroyImage(&$img)
  3436. {
  3437. if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
  3438. @imagedestroy($img);
  3439. }
  3440. $img = null;
  3441. }
  3442. // /**
  3443. // * 使用 Imagick 将远程图片压缩至不超过 maxBytes(默认3MB)内
  3444. // * 目标:在尽量保留原始格式和质量的前提下进行压缩,避免内存暴涨
  3445. // * 依赖:Imagick 扩展与 ImageMagick 库,下载使用 Guzzle 获取图片 blob
  3446. // *
  3447. // * @param string $url
  3448. // * @param int $maxBytes 最大字节数,默认 3*1024*1024
  3449. // * @return string|null 经过压缩后的图片 blob,失败返回 null
  3450. // */
  3451. // function compressRemoteImageUrlToSizeImagick(string $url, int $maxBytes = 3 * 1024 * 1024): ?string
  3452. // {
  3453. // // 兼容性检查
  3454. // if (!extension_loaded('imagick') || !class_exists('Imagick')) {
  3455. // return null;
  3456. // }
  3457. // try {
  3458. // $client = new Client(['timeout' => 30]);
  3459. // // 使用流式下载,将数据写入临时文件,避免一次性加载到内存
  3460. // $response = $client->get($url, ['stream' => true]);
  3461. // if ($response->getStatusCode() !== 200) {
  3462. // return null;
  3463. // }
  3464. // $body = $response->getBody();
  3465. // $tmp = tmpfile();
  3466. // if ($tmp === false) {
  3467. // return null;
  3468. // }
  3469. // stream_copy_to_stream($body, $tmp);
  3470. // rewind($tmp);
  3471. // $imagick = new Imagick();
  3472. // $imagick->readImageFile($tmp);
  3473. // $origW = $imagick->getImageWidth();
  3474. // $origH = $imagick->getImageHeight();
  3475. // $format = strtolower($imagick->getImageFormat());
  3476. // // 尝试序列:尺寸缩放 + 质量调节
  3477. // $scales = [1.0, 0.9, 0.8, 0.6, 0.4, 0.25];
  3478. // $qualities = [95, 90, 85, 75, 60, 40, 30, 20];
  3479. // $bestBlob = null;
  3480. // foreach ($scales as $scale) {
  3481. // foreach ($qualities as $q) {
  3482. // $clone = clone $imagick;
  3483. // if ($scale < 1.0) {
  3484. // $w = (int)round($origW * $scale);
  3485. // $h = (int)round($origH * $scale);
  3486. // if ($w < 1 || $h < 1) {
  3487. // $clone->destroy();
  3488. // continue;
  3489. // }
  3490. // $clone->resizeImage($w, $h, Imagick::FILTER_LANCZOS, 1);
  3491. // }
  3492. // $clone->setImageFormat($format);
  3493. // $clone->setImageCompressionQuality($q);
  3494. // $blob = $clone->getImageBlob();
  3495. // $clone->destroy();
  3496. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  3497. // $bestBlob = $blob;
  3498. // break 2;
  3499. // }
  3500. // }
  3501. // }
  3502. // if ($bestBlob !== null) {
  3503. // $imagick->destroy();
  3504. // fclose($tmp);
  3505. // return $bestBlob;
  3506. // }
  3507. // // 回退:尝试强制输出为当前格式的一个中等质量版本
  3508. // $fallback = clone $imagick;
  3509. // $fallback->setImageFormat($format);
  3510. // $fallback->setImageCompressionQuality(75);
  3511. // $blob = $fallback->getImageBlob();
  3512. // $fallback->destroy();
  3513. // $imagick->destroy();
  3514. // fclose($tmp);
  3515. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  3516. // return $blob;
  3517. // }
  3518. // } catch (\Exception $e) {
  3519. // return null;
  3520. // }
  3521. // return null;
  3522. // }
  3523. /**
  3524. * 将主体列表文本拆分为主体数组
  3525. *
  3526. * @param string $rolesText 主体列表文本内容
  3527. * @return array 主体名称数组
  3528. */
  3529. function parseRolesFromText(string $rolesText): array
  3530. {
  3531. if (empty($rolesText)) {
  3532. return [];
  3533. }
  3534. $roles = [];
  3535. // 按行分割文本
  3536. $lines = explode("\n", $rolesText);
  3537. foreach ($lines as $line) {
  3538. $line = trim($line);
  3539. if (empty($line)) {
  3540. continue;
  3541. }
  3542. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  3543. $role = trim($charMatch[1]);
  3544. $description = trim($charMatch[2]);
  3545. $timbreName = null;
  3546. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  3547. $picPrompt = null;
  3548. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  3549. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  3550. $description = trim($fullMatch[1]);
  3551. $picPrompt = trim($fullMatch[2]);
  3552. $timbreName = trim($fullMatch[3]);
  3553. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  3554. // 兼容旧格式:主体描述{{音色名}}
  3555. $description = trim($timbreMatch[1]);
  3556. $timbreName = trim($timbreMatch[2]);
  3557. }
  3558. $roleData = [
  3559. 'role' => $role,
  3560. 'description' => $description,
  3561. ];
  3562. // 如果有主体图片提示词,添加到数组中
  3563. if ($picPrompt) {
  3564. $roleData['pic_prompt'] = $picPrompt;
  3565. }
  3566. if ($timbreName) {
  3567. $timbre = DB::table('mp_timbres')
  3568. ->where('is_enabled', 1)
  3569. ->where('timbre_name', 'like', "%{$timbreName}%")
  3570. ->orderBy('id')
  3571. ->select('timbre_type', 'audio_url')
  3572. ->first();
  3573. if ($timbre) {
  3574. $roleData['voice_name'] = $timbreName;
  3575. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  3576. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  3577. }
  3578. }else {
  3579. // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  3580. if ($picPrompt) {
  3581. if (strstr($picPrompt, '男')) {
  3582. $roleData['voice_name'] = '阳光青年';
  3583. }elseif (strstr($picPrompt, '女')) {
  3584. $roleData['voice_name'] = '爽快思思';
  3585. }else {
  3586. if ($description) {
  3587. if (strstr($description, '男')) {
  3588. $roleData['voice_name'] = '阳光青年';
  3589. }elseif (strstr($description, '女')) {
  3590. $roleData['voice_name'] = '爽快思思';
  3591. }else {
  3592. $roleData['voice_name'] = '旁白';
  3593. }
  3594. }
  3595. }
  3596. }
  3597. if (!empty($roleData['voice_name'])) {
  3598. if ($roleData['voice_name'] == '旁白') {
  3599. $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  3600. $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  3601. }else {
  3602. $timbre = DB::table('mp_timbres')
  3603. ->where('is_enabled', 1)
  3604. ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  3605. ->orderBy('id')
  3606. ->select('timbre_type', 'audio_url')
  3607. ->first();
  3608. if ($timbre) {
  3609. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  3610. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  3611. }
  3612. }
  3613. }
  3614. }
  3615. $roles[] = $roleData;
  3616. }
  3617. }
  3618. $hasNarrator = false;
  3619. foreach ($roles as $role) {
  3620. if (getProp($role, 'role') === '旁白') {
  3621. $hasNarrator = true;
  3622. break;
  3623. }
  3624. }
  3625. if (!$hasNarrator) {
  3626. $roles[] = [
  3627. 'role' => '旁白',
  3628. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  3629. 'pic_prompt' => '',
  3630. 'voice_name' => '旁白',
  3631. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  3632. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  3633. ];
  3634. }
  3635. return $roles;
  3636. }
  3637. /**
  3638. * 将场景列表文本拆分为主体数组
  3639. *
  3640. * @param string $rolesText 场景列表列表文本内容
  3641. * @return array 场景名称数组
  3642. */
  3643. function parseScenesFromText(string $scenesText): array
  3644. {
  3645. if (empty($scenesText)) {
  3646. return [];
  3647. }
  3648. $scenes = [];
  3649. // 按行分割文本
  3650. $lines = explode("\n", $scenesText);
  3651. foreach ($lines as $line) {
  3652. $line = trim($line);
  3653. if (empty($line)) {
  3654. continue;
  3655. }
  3656. $line = str_replace(':', ':', $line);
  3657. if (strstr($line, ':')) {
  3658. $line_arr = explode(':', $line, 2);
  3659. if (count($line_arr) == 2) {
  3660. $scene = trim($line_arr[0]);
  3661. $description = trim($line_arr[1]);
  3662. $picPrompt = null;
  3663. // 检查描述末尾是否有{场景图片提示词}格式
  3664. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  3665. // 匹配格式:场景描述{场景图片提示词}
  3666. $description = trim($promptMatch[1]);
  3667. $picPrompt = trim($promptMatch[2]);
  3668. }
  3669. $sceneData = [
  3670. 'scene' => $scene,
  3671. 'description' => $description,
  3672. ];
  3673. // 如果有场景图片提示词,添加到数组中
  3674. if ($picPrompt) {
  3675. $sceneData['pic_prompt'] = $picPrompt;
  3676. }
  3677. $scenes[] = $sceneData;
  3678. }
  3679. }
  3680. }
  3681. return $scenes;
  3682. }
  3683. /**
  3684. * 记录日志到数据库
  3685. *
  3686. * @param string $channel 日志频道/目录名
  3687. * @param string $level 日志级别 (info, error, warning, debug)
  3688. * @param string $message 日志信息
  3689. * @param array $context 日志详细数据
  3690. * @return void
  3691. */
  3692. function logDB($channel, $level, $message, $context = []) {
  3693. try {
  3694. // 获取调用堆栈信息
  3695. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  3696. $caller = $trace[1] ?? $trace[0];
  3697. // 在 create 之前添加:
  3698. $jsonEncoded = json_encode($context, JSON_INVALID_UTF8_SUBSTITUTE);
  3699. $cleanContext = json_decode($jsonEncoded, true);
  3700. \App\Models\SystemLog::create([
  3701. 'channel' => $channel,
  3702. 'level' => $level,
  3703. 'message' => $message,
  3704. 'context' => $cleanContext,
  3705. 'file' => $caller['file'] ?? '',
  3706. 'line' => $caller['line'] ?? 0,
  3707. 'log_time' => date('Y-m-d H:i:s'),
  3708. ]);
  3709. } catch (\Exception $e) {
  3710. // 记录日志失败时不影响主流程
  3711. \Log::error('记录日志到数据库失败: ' . $e->getMessage());
  3712. }
  3713. }
  3714. function filterScriptContent($content) {
  3715. if (!$content) return '';
  3716. if (mb_substr($content, 0, 6) == '确认分镜大纲') return '确认分镜大纲';
  3717. if (mb_strlen($content) > 500) return '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。';
  3718. return $content;
  3719. }
  3720. /**
  3721. * 根据错误信息返回映射错误说明
  3722. *
  3723. * @param string $errorMessage 错误信息
  3724. * @return string 映射后的错误说明
  3725. */
  3726. function mapErrorMessage($errorMessage)
  3727. {
  3728. if (empty($errorMessage)) {
  3729. return '未知异常,请重试';
  3730. }
  3731. // 按优先级匹配错误信息
  3732. if (stripos($errorMessage, 'OutputImageSensitiveContentDetected') !== false) {
  3733. return '输出结果含有敏感词,请重试';
  3734. }
  3735. if (stripos($errorMessage, '系统繁忙,请稍后再试') !== false) {
  3736. return '系统繁忙,请稍后再试';
  3737. }
  3738. if (stripos($errorMessage, 'InternalServiceError') !== false) {
  3739. return '外部服务器网络错误,请稍后重试';
  3740. }
  3741. if (stripos($errorMessage, 'InputTextSensitiveContentDetected') !== false) {
  3742. return '输入文字含有敏感词,请调整后重试';
  3743. }
  3744. if (stripos($errorMessage, 'ServerOverloaded') !== false) {
  3745. return '当前系统过载,请稍后重试';
  3746. }
  3747. if (stripos($errorMessage, 'The request failed because the output video may be related to copyright restrictions') !== false) {
  3748. return '涉及到版权问题无法生成,请调整后重试';
  3749. }
  3750. if (stripos($errorMessage, 'sensitive') !== false) {
  3751. return '含有敏感词,请调整后重试';
  3752. }
  3753. // 默认返回
  3754. return '未知异常,请重试';
  3755. }