Helpers.php 207 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562
  1. <?php
  2. use App\Consts\BaseConst;
  3. use GuzzleHttp\Client;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\Log;
  7. use Monolog\Handler\StreamHandler;
  8. use Monolog\Logger;
  9. use OSS\OssClient;
  10. use OSS\Core\OssException;
  11. use Tos\TosClient;
  12. use Tos\Exception\TosClientException;
  13. use Tos\Exception\TosServerException;
  14. use Tos\Model\PutObjectInput;
  15. // use Imagick;
  16. /**
  17. * 截取字符串
  18. *
  19. * @param $string
  20. * @param $length
  21. * @param bool $append
  22. * @return array|string
  23. */
  24. function sysSubStr($string, $length, $append = false)
  25. {
  26. if (strlen($string) <= $length) {
  27. return $string;
  28. }
  29. $i = 0;
  30. $stringLast = [];
  31. while ($i < $length) {
  32. $stringTMP = mb_substr($string, $i, 1);
  33. if (ord($stringTMP) >= 224) {
  34. $stringTMP = mb_substr($string, $i, 3);
  35. $i += 3;
  36. } elseif (ord($stringTMP) >= 192) {
  37. $stringTMP = mb_substr($string, $i, 2);
  38. $i += 2;
  39. } else {
  40. ++$i;
  41. }
  42. $stringLast[] = $stringTMP;
  43. }
  44. $stringLast = implode('', $stringLast);
  45. if ($append) {
  46. $stringLast .= '...';
  47. }
  48. return $stringLast;
  49. }
  50. /**
  51. * 自定义日志
  52. *
  53. * @param $name
  54. * @param string $filename
  55. * @return \Illuminate\Log\Writer
  56. */
  57. function myLog($name, $filename = '')
  58. {
  59. if (!$filename) {
  60. $filename = $name;
  61. }
  62. $filename = $filename . '.log';
  63. $logger = new Logger($name);
  64. $writer = new \Illuminate\Log\Writer($logger);
  65. $writer->useDailyFiles(storage_path('logs/' . $filename));
  66. return $writer;
  67. }
  68. /**
  69. * 业务调试日志
  70. *
  71. * @return Logger
  72. */
  73. function commonLog()
  74. {
  75. $name = 'common';
  76. $filename = $name . '.log';
  77. $logger = new Logger($name);
  78. $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
  79. return $logger;
  80. }
  81. /**
  82. * @param $name
  83. * @return Logger
  84. */
  85. function dLog($name)
  86. {
  87. $filename = $name . '-' . date('Y-m-d') . '.log';
  88. $logger = new Logger($name);
  89. $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
  90. return $logger;
  91. }
  92. /**
  93. * 获取对象或数组的属性值
  94. *
  95. * @param $param
  96. * @param $key
  97. * @param string $default
  98. * @return mixed|string
  99. */
  100. function getProp($param, $key, $default = '')
  101. {
  102. $result = $default;
  103. if (is_object($param) && isset($param->$key)) {
  104. $result = $param->$key;
  105. }
  106. if (is_array($param) && isset($param[$key])) {
  107. $result = $param[$key];
  108. }
  109. return $result;
  110. }
  111. /**
  112. * @param $data
  113. * @param array $trans
  114. * @return array
  115. */
  116. function assetData($data, $trans = []): array
  117. {
  118. $result = [];
  119. if (empty($data)) {
  120. return $result;
  121. }
  122. if (empty($trans)) {
  123. return $data;
  124. }
  125. foreach ($trans as $tran) {
  126. [$originKey, $newKey, $conv, $default] = [$tran['o'], $tran['n'], $tran['conv'], $tran['default']];
  127. if (isset($data[$originKey])) {
  128. $result[$newKey] = $conv(getProp($data, $originKey, $default));
  129. }
  130. }
  131. return $result;
  132. }
  133. /**
  134. * 随机数
  135. *
  136. * @param int $num
  137. * @return string
  138. * @throws Exception
  139. */
  140. function random($num = 16)
  141. {
  142. $bytes = random_bytes($num);
  143. return bin2hex($bytes);
  144. }
  145. /**
  146. * 生成订单
  147. *
  148. * @param string $prefix 订单前缀
  149. * @return string
  150. */
  151. function generateOrderSn($prefix = '')
  152. {
  153. return $prefix . date('YmdHis') . getMillisecond() . rand(1000, 9999);
  154. }
  155. /**
  156. * 分页数据
  157. *
  158. * @param $data
  159. * @return array
  160. */
  161. function getMeta($data)
  162. {
  163. $currentPage = (int)$data->currentPage();
  164. $lastPage = (int)$data->lastPage();
  165. return [
  166. 'current_page' => $currentPage,
  167. 'next_page' => $currentPage >= $lastPage ? $lastPage : ++$currentPage,
  168. 'last_page' => $lastPage,
  169. 'per_page' => (int)$data->perPage(),
  170. 'total' => (int)$data->total(),
  171. 'is_end' => !$data->hasMorePages(),
  172. 'next_page_url' => (string)$data->nextPageUrl(),
  173. 'prev_page_url' => (string)$data->previousPageUrl()
  174. ];
  175. }
  176. /**
  177. * 钉钉通知异常
  178. *
  179. * @param $message
  180. */
  181. function sendNotice($message)
  182. {
  183. $webHook = env('DD_WEB_HOOK');
  184. $data = [
  185. 'msgtype' => 'text',
  186. 'text' => [
  187. 'content' => $message
  188. ],
  189. 'at' => [
  190. 'isAll' => true
  191. ]
  192. ];
  193. // 异步发送
  194. $client = new GuzzleHttp\Client();
  195. $client->post($webHook, ['json' => $data]);
  196. }
  197. /**
  198. * 判断数据是合法的json数据
  199. *
  200. * @param $string
  201. * @return bool
  202. */
  203. function is_json($string)
  204. {
  205. json_decode($string);
  206. return (json_last_error() == JSON_ERROR_NONE);
  207. }
  208. /**
  209. * 获取ip地址
  210. *
  211. * @return mixed|string
  212. */
  213. function getIpAddr()
  214. {
  215. $ipaddress = '';
  216. if (isset($_SERVER['HTTP_CLIENT_IP']))
  217. $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  218. else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  219. $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  220. else if (isset($_SERVER['HTTP_X_FORWARDED']))
  221. $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  222. else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
  223. $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  224. else if (isset($_SERVER['HTTP_FORWARDED']))
  225. $ipaddress = $_SERVER['HTTP_FORWARDED'];
  226. else if (isset($_SERVER['REMOTE_ADDR']))
  227. $ipaddress = $_SERVER['REMOTE_ADDR'];
  228. else
  229. $ipaddress = 'UNKNOWN';
  230. return $ipaddress;
  231. }
  232. /**
  233. * @param int $num
  234. * @return bool|string
  235. * @throws Exception
  236. */
  237. function randStr($num = 5)
  238. {
  239. $str = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm';
  240. return substr(str_shuffle($str), random_int(0, strlen($str) - 11), $num);
  241. }
  242. /**
  243. * 上传文件(火山云tos)
  244. *
  245. * @param $prefix 文件夹前缀
  246. * @param $file 文件二进制
  247. * @param $filename 文件名(不带后缀)
  248. * @return mixed
  249. */
  250. function uploadFileByTos($prefix, $file, $filename='')
  251. {
  252. if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  253. else $filename = $filename . '.' . $file->getClientOriginalExtension();
  254. try {
  255. $client = new TosClient([
  256. 'region' => env('VOLC_REGION'),
  257. 'endpoint' => env('VOLC_END_POINT'),
  258. 'ak' => env('VOLC_AK'),
  259. 'sk' => env('VOLC_SK'),
  260. ]);
  261. $stream = fopen($file->getRealPath(), 'r');
  262. $input = new PutObjectInput(env('VOLC_BUCKET'), "$prefix/$filename", $stream);
  263. $output = $client->putObject($input);
  264. if ($output->getRequestId()) {
  265. return "https://".env('VOLC_BUCKET').'.'.env('VOLC_END_POINT')."/$prefix/$filename";
  266. }
  267. } catch (TosClientException $ex) {
  268. dLog('exception')->info('saveToTos', [$ex->getMessage()]);
  269. } catch (TosServerException $ex) {
  270. dLog('exception')->info('saveToTos', [$ex->getRequestId(), $ex->getStatusCode(), $ex->getErrorCode()]);
  271. }
  272. return '';
  273. }
  274. /**
  275. * 上传文件流(火山云tos)
  276. *
  277. * @param $prefix 文件夹前缀
  278. * @param $file 文件二进制
  279. * @param $filename 文件名(带后缀)
  280. * @return mixed
  281. */
  282. function uploadStreamByTos($prefix, $stream, $filename)
  283. {
  284. try {
  285. $client = new TosClient([
  286. 'region' => env('VOLC_REGION'),
  287. 'endpoint' => env('VOLC_END_POINT'),
  288. 'ak' => env('VOLC_AK'),
  289. 'sk' => env('VOLC_SK'),
  290. ]);
  291. $input = new PutObjectInput(env('VOLC_BUCKET'), "$prefix/$filename", $stream);
  292. $output = $client->putObject($input);
  293. if ($output->getRequestId()) {
  294. return "https://".env('VOLC_BUCKET').'.'.env('VOLC_END_POINT')."/$prefix/$filename";
  295. }
  296. } catch (TosClientException $ex) {
  297. dLog('exception')->info('saveToTos', [$ex->getMessage()]);
  298. } catch (TosServerException $ex) {
  299. dLog('exception')->info('saveToTos', [$ex->getRequestId(), $ex->getStatusCode(), $ex->getErrorCode()]);
  300. }
  301. return '';
  302. }
  303. // 从图片URL获取图片扩展名
  304. function getImgExtFromUrl(string $url): ?string {
  305. $imageInfo = @getimagesize($url);
  306. if ($imageInfo !== false) {
  307. // 返回MIME类型
  308. return mimeToExt($imageInfo['mime']);
  309. // 或者返回文件扩展名
  310. // return image_type_to_extension($imageInfo[2], false);
  311. }
  312. return null;
  313. }
  314. /**
  315. * 从视频URL获取视频扩展名
  316. * 通过下载文件头部字节来识别真实的视频格式
  317. *
  318. * @param string $url 视频URL
  319. * @return string 返回扩展名(如 .mp4),默认 .mp4
  320. */
  321. function getVideoExtFromUrl(string $url): string {
  322. try {
  323. // 方法1:从URL路径中提取扩展名
  324. $parsedUrl = parse_url($url);
  325. $path = $parsedUrl['path'] ?? '';
  326. $pathInfo = pathinfo($path);
  327. $extension = $pathInfo['extension'] ?? '';
  328. if ($extension) {
  329. // 验证是否为常见视频格式
  330. $validVideoExts = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v', 'mpeg', 'mpg'];
  331. if (in_array(strtolower($extension), $validVideoExts)) {
  332. return '.' . strtolower($extension);
  333. }
  334. }
  335. // 方法2:下载文件头部字节来识别格式
  336. $client = new \GuzzleHttp\Client(['timeout' => 30]);
  337. // 先尝试HEAD请求获取Content-Type
  338. try {
  339. $response = $client->head($url);
  340. $contentType = $response->getHeader('Content-Type')[0] ?? '';
  341. // 根据Content-Type映射扩展名
  342. $mimeMap = [
  343. 'video/mp4' => '.mp4',
  344. 'video/x-msvideo' => '.avi',
  345. 'video/quicktime' => '.mov',
  346. 'video/x-ms-wmv' => '.wmv',
  347. 'video/x-flv' => '.flv',
  348. 'video/x-matroska' => '.mkv',
  349. 'video/webm' => '.webm',
  350. 'video/mpeg' => '.mpeg',
  351. ];
  352. if (isset($mimeMap[$contentType])) {
  353. return $mimeMap[$contentType];
  354. }
  355. } catch (\Exception $e) {
  356. // HEAD请求失败,继续尝试其他方法
  357. }
  358. // 方法3:下载前几个字节分析文件魔数(Magic Number)
  359. $response = $client->get($url, [
  360. 'stream' => true,
  361. 'headers' => [
  362. 'Range' => 'bytes=0-31' // 只下载前32字节
  363. ]
  364. ]);
  365. $header = $response->getBody()->read(32);
  366. // 根据文件魔数判断格式
  367. // MP4/M4V: 以 ftyp 开头(偏移4-8字节)
  368. if (strpos($header, 'ftyp') !== false) {
  369. // 进一步判断是否为 M4V
  370. if (strpos($header, 'M4V') !== false || strpos($header, 'm4v') !== false) {
  371. return '.m4v';
  372. }
  373. return '.mp4';
  374. }
  375. // AVI: 以 RIFF 开头,包含 AVI
  376. if (substr($header, 0, 4) === 'RIFF' && strpos($header, 'AVI') !== false) {
  377. return '.avi';
  378. }
  379. // MOV: 包含 moov 或 mdat
  380. if (strpos($header, 'moov') !== false || strpos($header, 'mdat') !== false) {
  381. return '.mov';
  382. }
  383. // FLV: 以 FLV 开头
  384. if (substr($header, 0, 3) === 'FLV') {
  385. return '.flv';
  386. }
  387. // WebM: 以 0x1A 0x45 0xDF 0xA3 开头
  388. if (ord($header[0]) === 0x1A && ord($header[1]) === 0x45 &&
  389. ord($header[2]) === 0xDF && ord($header[3]) === 0xA3) {
  390. return '.webm';
  391. }
  392. // MKV: 与WebM类似,但包含 matroska
  393. if (strpos($header, 'matroska') !== false) {
  394. return '.mkv';
  395. }
  396. // MPEG: 以 0x00 0x00 0x01 开头
  397. if (ord($header[0]) === 0x00 && ord($header[1]) === 0x00 && ord($header[2]) === 0x01) {
  398. return '.mpeg';
  399. }
  400. // 默认返回 .mp4(最常见的格式)
  401. return '.mp4';
  402. } catch (\Exception $e) {
  403. // 出错时返回默认格式
  404. return '.mp4';
  405. }
  406. }
  407. // 辅助 MIME 映射函数
  408. function mimeToExt(string $mime): ?string {
  409. $map = [
  410. 'audio/wav' => '.wav',
  411. 'audio/x-ms-wma' => '.wma',
  412. 'video/x-ms-wmv' => '.wmv',
  413. 'video/mp4' => '.mp4',
  414. 'audio/mpeg' => '.mp3',
  415. 'audio/amr' => '.amr',
  416. 'application/vnd.rn-realmedia' => '.rm',
  417. 'audio/mid' => '.mid',
  418. 'image/bmp' => '.bmp',
  419. 'image/gif' => '.gif',
  420. 'image/png' => '.png',
  421. 'image/tiff' => '.tiff',
  422. 'image/jpeg' => '.jpg',
  423. 'application/pdf' => '.pdf',
  424. ];
  425. return $map[$mime] ?? null;
  426. }
  427. /**
  428. * 上传文件(阿里云oss)
  429. *
  430. * @param $prefix 文件夹前缀
  431. * @param $file 文件二进制
  432. * @param $filename 文件名(不带后缀)
  433. * @return mixed
  434. */
  435. function uploadFile($prefix, $file, $filename='')
  436. {
  437. // 阿里云主账号
  438. $accessKeyId = env('OSS_ACCESS_ID');
  439. $accessKeySecret = env('OSS_ACCESS_KEY');
  440. $endpoint = env('OSS_END_POINT');
  441. $bucket = env('OSS_BUCKET');
  442. if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  443. else $filename = $filename . '.' . $file->getClientOriginalExtension();
  444. // 设置文件名称。
  445. $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
  446. $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
  447. try {
  448. $configs = [
  449. "provider" => $provider,
  450. "endpoint" => $endpoint,
  451. "signatureVersion" => 'v4',
  452. "region" => "cn-hangzhou"
  453. ];
  454. $ossClient = new OssClient($configs);
  455. $uploadRes = $ossClient->uploadFile($bucket, $object, $file->path());
  456. } catch (OssException $e) {
  457. dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
  458. return '';
  459. }
  460. // 替换域名
  461. if (!isset($uploadRes['oss-request-url'])) return '';
  462. $url = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
  463. $url = urldecode($url);
  464. return str_ireplace('http://', 'https://', $url);
  465. }
  466. /**
  467. * 上传文件流(阿里云oss)
  468. *
  469. * @param $prefix 文件夹前缀
  470. * @param $file 文件二进制
  471. * @param $filename 文件名(带后缀)
  472. * @return mixed
  473. */
  474. function uploadStreamToOss($prefix, $stream, $filename) {
  475. $accessKeyId = env('OSS_ACCESS_ID');
  476. $accessKeySecret = env('OSS_ACCESS_KEY');
  477. $endpoint = env('OSS_END_POINT');
  478. $bucket = env('OSS_BUCKET');
  479. // if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  480. // 设置文件名称。
  481. $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
  482. $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
  483. try{
  484. $configs = [
  485. "provider" => $provider,
  486. "endpoint" => $endpoint,
  487. "signatureVersion" => 'v4',
  488. "region"=> "cn-hangzhou"
  489. ];
  490. $ossClient = new OssClient($configs);
  491. $uploadRes = $ossClient->putObject($bucket, $object, $stream);
  492. } catch (OssException $e) {
  493. dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
  494. return '';
  495. }
  496. // 替换域名
  497. if (!isset($uploadRes['oss-request-url'])) return '';
  498. $url = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
  499. $url = urldecode($url);
  500. return str_ireplace('http://', 'https://', $url);
  501. }
  502. /**
  503. * 下载文件到本地
  504. *
  505. * @param $object
  506. * @param $localFile
  507. * @return string
  508. */
  509. function downloadFile($object, $localFile)
  510. {
  511. // 阿里云主账号
  512. $accessKeyId = env('OSS_ACCESS_ID');
  513. $accessKeySecret = env('OSS_ACCESS_KEY');
  514. $endpoint = env('OSS_END_POINT');
  515. $bucket = env('OSS_BUCKET');
  516. try {
  517. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  518. $ossClient->getObject($bucket, $object, [
  519. OssClient::OSS_FILE_DOWNLOAD => $localFile
  520. ]);
  521. } catch (OssException $e) {
  522. printf($e->getMessage());
  523. return '';
  524. }
  525. }
  526. /**
  527. * 上传封面
  528. *
  529. * @param $file
  530. * @return string
  531. * @throws Exception
  532. */
  533. function uploadCoverFile($file)
  534. {
  535. // 阿里云主账号
  536. $accessKeyId = env('OSS_ACCESS_ID');
  537. $accessKeySecret = env('OSS_ACCESS_KEY');
  538. $endpoint = env('OSS_END_POINT');
  539. $bucket = env('OSS_BUCKET');
  540. // 设置文件名称。
  541. $object = 'books/cover/' . randStr(10) . '.' . $file->getClientOriginalExtension();
  542. try {
  543. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  544. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  545. } catch (OssException $e) {
  546. printf($e->getMessage());
  547. return '';
  548. }
  549. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  550. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  551. }
  552. function uploadAgreementFile($file)
  553. {
  554. // 阿里云主账号
  555. $accessKeyId = env('OSS_ACCESS_ID');
  556. $accessKeySecret = env('OSS_ACCESS_KEY');
  557. $endpoint = env('OSS_END_POINT');
  558. $bucket = env('OSS_BUCKET');
  559. $file_name = $file->getClientOriginalName();
  560. $file_name = str_replace('.' . $file->getClientOriginalExtension(), '', $file_name);
  561. // 设置文件名称。
  562. $object = 'books/contract/' . $file_name . '-' . date('YmdHi') . '.' . $file->getClientOriginalExtension();
  563. try {
  564. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  565. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file);
  566. } catch (OssException $e) {
  567. printf($e->getMessage());
  568. return '';
  569. }
  570. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  571. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . urldecode(getProp($urlArr, 'path')) : '';
  572. }
  573. /**
  574. * 上传wap推荐图片
  575. *
  576. * @param $file
  577. * @param $filename
  578. * @return string
  579. * @throws Exception
  580. */
  581. function uploadWapRecommendPic($file, $filename)
  582. {
  583. // 阿里云主账号
  584. $accessKeyId = env('OSS_ACCESS_ID');
  585. $accessKeySecret = env('OSS_ACCESS_KEY');
  586. $endpoint = env('OSS_END_POINT');
  587. $bucket = env('OSS_BUCKET_YCSD');
  588. // 设置文件名称。
  589. $object = 'ycsd_web_3nd/images/homebanners/' . $filename . '.' . $file->getClientOriginalExtension();
  590. try {
  591. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  592. $options = array(
  593. OssClient::OSS_HEADERS => array(
  594. 'Content-Type' => 'image/jpeg',
  595. 'Content-Disposition' => 'inline'
  596. ),
  597. );
  598. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path(), $options);
  599. } catch (OssException $e) {
  600. printf($e->getMessage());
  601. return '';
  602. }
  603. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  604. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  605. }
  606. /**
  607. * @param $path
  608. * @return Generator
  609. */
  610. function readFileContent($path)
  611. {
  612. if ($handle = fopen($path, 'r')) {
  613. while (!feof($handle)) {
  614. yield trim(fgets($handle));
  615. }
  616. fclose($handle);
  617. }
  618. }
  619. function exportFileCsv(array $headers, array $data, string $filename)
  620. {
  621. header("Content-type:application/vnd.ms-excel");
  622. header("Content-Disposition:attachment;filename=" . $filename . ".csv");
  623. $headers = collect($headers)->map(function ($item) {
  624. return "\"" . mb_convert_encoding($item, "GBK", "UTF-8") . "\"";
  625. })->all();
  626. echo implode(",", $headers);
  627. echo "\r\n";
  628. foreach ($data as $item) {
  629. $rows = collect($item)->map(function ($row) {
  630. return "\"" . mb_convert_encoding(is_numeric($row) && strlen($row) > 12 ? "'" . $row : $row, "GBK", "UTF-8") . "\"";
  631. })->all();
  632. echo implode(",", $rows);
  633. echo "\r\n";
  634. }
  635. exit();
  636. }
  637. //function exportFileCsv(array $header, array $data, string $filename) {
  638. // header('Content-Encoding: UTF-8');
  639. // header("Content-type:application/vnd.ms-excel;charset=UTF-8");
  640. // header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
  641. //
  642. // //打开php标准输出流
  643. // $fp = fopen('php://output', 'a');
  644. //
  645. // //添加BOM头,以UTF8编码导出CSV文件,如果文件头未添加BOM头,打开会出现乱码。
  646. // fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
  647. // //添加导出标题
  648. // fputcsv($fp, $header);
  649. //
  650. // foreach ($data as $k => $item) {
  651. // fputcsv($fp, $item);
  652. // if ($k % 5000 == 0) {
  653. // //每1万条数据就刷新缓冲区
  654. // ob_flush();
  655. // flush();
  656. // }
  657. // }
  658. // exit();
  659. //}
  660. //function exportFileCsv(array $header, array $data, string $filename) {
  661. //
  662. // header('Content-Type: application/vnd.ms-excel');
  663. // header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
  664. // header('Cache-Control: max-age=0');
  665. //
  666. // //打开PHP文件句柄,php://output 表示直接输出到浏览器
  667. // $fp = fopen('php://output', 'a');
  668. //
  669. // //输出Excel列名信息
  670. // foreach ($header as $key => $value) {
  671. // //CSV的Excel支持GBK编码,一定要转换,否则乱码
  672. // $header[$key] = iconv('utf-8', 'gbk', $value);
  673. // }
  674. //
  675. // //将数据通过fputcsv写到文件句柄
  676. // fputcsv($fp, $header);
  677. //
  678. // //计数器
  679. // $num = 0;
  680. //
  681. // //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
  682. // $limit = 10000;
  683. //
  684. // //逐行取出数据,不浪费内存
  685. // $count = count($data);
  686. // for ($i = 0; $i < $count; $i++) {
  687. //
  688. // $num++;
  689. //
  690. // //刷新一下输出buffer,防止由于数据过多造成问题
  691. // if ($limit == $num) {
  692. // ob_flush();
  693. // flush();
  694. // $num = 0;
  695. // }
  696. //
  697. // $row = $data[$i];
  698. // foreach ($row as $key => $value) {
  699. // $row[$key] = iconv('utf-8', 'gbk', $value);
  700. // }
  701. //
  702. // fputcsv($fp, $row);
  703. // }
  704. // exit();
  705. //}
  706. // 获取除空格外的字数
  707. function getSize(string $content)
  708. {
  709. $content = preg_replace('/\s+/', '', $content);
  710. return mb_strlen($content, 'utf-8');
  711. }
  712. // 获取word字符数(不计空格)
  713. function getChargeSize(string $content)
  714. {
  715. //判断是否存在替换字符
  716. $is_replace_count = substr_count($content, "龘");
  717. try {
  718. //先将回车换行符做特殊处理
  719. $str = preg_replace('/(\r\n+|\s+| +)/', "龘", $content);
  720. //处理英文字符数字,连续字母、数字、英文符号视为一个单词
  721. $str = preg_replace('/[a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",\'<>~`\?:;|]/', "m", $str);
  722. //合并字符m,连续字母、数字、英文符号视为一个单词
  723. $str = preg_replace('/m+/', "*", $str);
  724. //去掉回车换行符
  725. $str = preg_replace('/龘+/', "", $str);
  726. //返回字数
  727. return mb_strlen($str) + $is_replace_count;
  728. } catch (\Exception $e) {
  729. return 0;
  730. }
  731. }
  732. // 将阿拉伯数字转换成中文
  733. function chineseNum($figure, $capital = false, $mode = true)
  734. {
  735. if ($figure == '0') return '零';
  736. $numberChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  737. $unitChar = ['', '十', '百', '千', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
  738. if ($capital !== false) {
  739. $numberChar = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  740. $unitChar = ['', '拾', '佰', '仟', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
  741. }
  742. $dec = "点";
  743. $target = '';
  744. $matches = [];
  745. if ($mode) {
  746. preg_match("/^0*(\d*)\.?(\d*)/", $figure, $matches);
  747. } else {
  748. preg_match("/(\d*)\.?(\d*)/", $figure, $matches);
  749. }
  750. list(, $number, $point) = $matches;
  751. if ($point) {
  752. $target = $dec . chineseNum($point, $capital, false);
  753. }
  754. if (!$number) {
  755. return $target;
  756. }
  757. $str = strrev($number);
  758. for ($i = 0; $i < strlen($str); $i++) {
  759. $out[$i] = $numberChar[$str[$i]];
  760. if ($mode === false) {
  761. continue;
  762. }
  763. $out[$i] .= $str[$i] != '0' ? $unitChar[$i % 4] : '';
  764. if ($i > 0 && $str[$i] + $str[$i - 1] == 0) {
  765. $out[$i] = '';
  766. }
  767. if ($i % 4 == 0) {
  768. $temp = substr($str, $i, 4);
  769. $out[$i] = str_replace($numberChar[0], '', $out[$i]);
  770. if (strrev($temp) > 0) {
  771. $out[$i] .= $unitChar[4 + floor($i / 4)];
  772. } else {
  773. $out[$i] .= $numberChar[0];
  774. }
  775. }
  776. }
  777. $result = join('', array_reverse($out)) . $target;
  778. return mb_substr($result, 0, 2) == '一十' ? mb_substr($result, 1) : $result;
  779. }
  780. function addPrefix($str)
  781. {
  782. if (!$str) return '';
  783. if (mb_substr($str, 0, 4) == 'http') return $str;
  784. if (mb_substr($str, 0, 5) == 'https') return $str;
  785. if (mb_substr($str, 0, 7) == '/books/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  786. if (mb_substr($str, 0, 6) == '/card/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  787. if (mb_substr($str, 0, 15) == 'uploader/idcard') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com/' . $str;
  788. if (mb_substr($str, 0, 6) == '/cover') return 'https://cdn-newyc.ycsd.cn/ycsd_cover/covermiddle' . mb_substr($str, 6);
  789. if (mb_substr($str, 0, 8) == '/images/') return 'https://cdn-newyc.ycsd.cn/ycsd_cover' . $str;
  790. }
  791. /**
  792. * 章节内容排版
  793. *
  794. * @param $content
  795. * @return string
  796. */
  797. function filterContent($content)
  798. {
  799. if (!$content) return '';
  800. $content = str_replace(
  801. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  802. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  803. $content);
  804. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  805. // 段落首字母前加两个中文空格
  806. $string = explode(PHP_EOL, $content);
  807. foreach ($string as $line => $text) {
  808. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' '], '', $string[$line]);
  809. if (!$string[$line]) {
  810. unset($string[$line]);
  811. } else {
  812. $string[$line] = $string[$line] . PHP_EOL;
  813. // if (mb_substr($string[$line], 0, 1) == ' ') {
  814. // $string[$line] = str_replace(' ', '', $string[$line]); // 去除多个空格
  815. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  816. // }
  817. // if (mb_substr($string[$line], 0, 2) != '  ') {
  818. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  819. // }
  820. // if (mb_substr($string[$line], 0, 2) == '  ' && str_replace(' ', '', $string[$line])) {
  821. // $string[$line] .= PHP_EOL;
  822. // }
  823. }
  824. }
  825. $content = implode(PHP_EOL, $string);
  826. return $content;
  827. }
  828. /**
  829. * 书籍简介排版
  830. *
  831. * @param $content
  832. * @return string
  833. */
  834. function filterContent2($content)
  835. {
  836. if (!$content) return '';
  837. $content = str_replace(
  838. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  839. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  840. $content);
  841. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  842. // 段落首字母前加两个中文空格
  843. $string = explode(PHP_EOL, $content);
  844. $content = '';
  845. foreach ($string as $line => $text) {
  846. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  847. if (!$string[$line]) {
  848. unset($string[$line]);
  849. } else {
  850. $string[$line] = '  ' . $string[$line] . '<br />';
  851. $content .= $string[$line];
  852. }
  853. }
  854. $content = trim($content, '<br />');
  855. return $content;
  856. }
  857. /**
  858. * 书籍简介排版-抖音版
  859. *
  860. * @param $content
  861. * @return string
  862. */
  863. function filterIntro($content)
  864. {
  865. if (!$content) return '';
  866. $content = str_replace(
  867. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  868. [' ', ' ', ' ', ' ', ' ', '', ' ', '“', '”', '...', '‘', '’', '-'],
  869. $content);
  870. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  871. // 段落首字母前加两个中文空格
  872. $string = explode(PHP_EOL, $content);
  873. $content = '';
  874. foreach ($string as $line => $text) {
  875. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  876. if (!$string[$line]) {
  877. unset($string[$line]);
  878. } else {
  879. $content .= $string[$line];
  880. }
  881. }
  882. $content = trim($content, '<br />');
  883. return $content;
  884. }
  885. /**
  886. * 压缩视频文件
  887. * 压缩策略:3秒视频约1M~1.5M
  888. *
  889. * @param string $videoUrl 视频URL地址
  890. * @param string $prefix 上传文件夹前缀(如:'videos')
  891. * @return string 返回压缩后的视频URL,失败返回空字符串
  892. */
  893. function compressVideo($videoUrl, $prefix = 'videos')
  894. {
  895. if (env('APP_ENV') == 'local') return $videoUrl;
  896. try {
  897. // 创建临时目录
  898. $tempDir = storage_path('app/temp/videos');
  899. if (!is_dir($tempDir)) {
  900. mkdir($tempDir, 0775, true);
  901. // 确保目录权限正确
  902. chmod($tempDir, 0775);
  903. }
  904. // 生成唯一文件名(不包含点号)
  905. $uniqueId = uniqid('video_') . bin2hex(random_bytes(4));
  906. $videoExt = getVideoExtFromUrl($videoUrl);
  907. $inputFile = $tempDir . '/' . $uniqueId . '_input' . $videoExt;
  908. $outputFile = $tempDir . '/' . $uniqueId . '_output.mp4';
  909. // 下载视频到本地
  910. dLog('video_compress')->info('开始下载视频', ['url' => $videoUrl]);
  911. $client = new \GuzzleHttp\Client(['timeout' => 300]);
  912. $response = $client->get($videoUrl);
  913. // 使用更安全的方式写入文件
  914. $fileContent = $response->getBody()->getContents();
  915. if (file_put_contents($inputFile, $fileContent) === false) {
  916. dLog('video_compress')->error('视频文件写入失败', [
  917. 'url' => $videoUrl,
  918. 'file' => $inputFile,
  919. 'dir_writable' => is_writable($tempDir)
  920. ]);
  921. return '';
  922. }
  923. // 设置文件权限
  924. chmod($inputFile, 0664);
  925. if (!file_exists($inputFile)) {
  926. dLog('video_compress')->error('视频下载失败', ['url' => $videoUrl]);
  927. return '';
  928. }
  929. $inputFileSize = filesize($inputFile);
  930. dLog('video_compress')->info('视频下载成功', [
  931. 'url' => $videoUrl,
  932. 'size' => $inputFileSize,
  933. 'size_mb' => round($inputFileSize / 1024 / 1024, 2) . 'MB'
  934. ]);
  935. // 获取视频时长(秒)
  936. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  937. $durationCmd = "$ffprobePath -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 \"$inputFile\"";
  938. $duration = (float)trim(shell_exec($durationCmd));
  939. if ($duration <= 0) {
  940. dLog('video_compress')->error('无法获取视频时长', ['file' => $inputFile]);
  941. @unlink($inputFile);
  942. return '';
  943. }
  944. // 计算目标码率
  945. // 目标:3秒视频 = 1~1.5MB,即每秒约 0.33~0.5MB = 2730~4096 kbps
  946. // 使用中间值:3500 kbps
  947. $targetBitrate = 3500; // kbps
  948. // 根据视频时长动态调整码率,确保文件大小合理
  949. // 目标文件大小 = duration * 0.4MB/s = duration * 400KB/s
  950. $targetFileSizeKB = $duration * 400; // KB
  951. $targetBitrateCalculated = (int)(($targetFileSizeKB * 8) / $duration); // kbps
  952. // 使用计算出的码率,但不低于1500kbps,不高于5000kbps
  953. $targetBitrate = max(1500, min(5000, $targetBitrateCalculated));
  954. dLog('video_compress')->info('视频信息', [
  955. 'duration' => $duration . 's',
  956. 'target_bitrate' => $targetBitrate . 'kbps',
  957. 'estimated_size' => round($targetFileSizeKB / 1024, 2) . 'MB'
  958. ]);
  959. // 使用FFmpeg压缩视频
  960. // -c:v libx264: 使用H.264编码器
  961. // -b:v: 视频码率
  962. // -c:a aac: 音频编码器
  963. // -b:a 128k: 音频码率
  964. // -movflags +faststart: 优化网络播放
  965. // -preset medium: 编码速度与质量平衡
  966. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  967. $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";
  968. dLog('video_compress')->info('开始压缩视频', ['command' => $ffmpegCmd]);
  969. $output = shell_exec($ffmpegCmd);
  970. if (!file_exists($outputFile)) {
  971. dLog('video_compress')->error('视频压缩失败', [
  972. 'input' => $inputFile,
  973. 'output' => $output
  974. ]);
  975. @unlink($inputFile);
  976. return '';
  977. }
  978. // 设置输出文件权限
  979. chmod($outputFile, 0664);
  980. $outputFileSize = filesize($outputFile);
  981. $compressionRatio = round((1 - $outputFileSize / $inputFileSize) * 100, 2);
  982. dLog('video_compress')->info('视频压缩成功', [
  983. 'input_size' => round($inputFileSize / 1024 / 1024, 2) . 'MB',
  984. 'output_size' => round($outputFileSize / 1024 / 1024, 2) . 'MB',
  985. 'compression_ratio' => $compressionRatio . '%',
  986. 'duration' => $duration . 's',
  987. 'size_per_second' => round($outputFileSize / $duration / 1024 / 1024, 2) . 'MB/s'
  988. ]);
  989. // 上传压缩后的视频到云存储
  990. $stream = fopen($outputFile, 'r');
  991. if (!$stream) {
  992. dLog('video_compress')->error('无法打开压缩后的视频文件', ['file' => $outputFile]);
  993. @unlink($inputFile);
  994. @unlink($outputFile);
  995. return '';
  996. }
  997. $filename = $uniqueId . '.mp4';
  998. // 根据环境变量选择上传方式
  999. $uploadMethod = env('VIDEO_UPLOAD_METHOD', 'tos'); // 默认使用火山云
  1000. if ($uploadMethod === 'oss') {
  1001. $compressedUrl = uploadStreamToOss($prefix, $stream, $filename);
  1002. } else {
  1003. $compressedUrl = uploadStreamByTos($prefix, $stream, $filename);
  1004. }
  1005. // 安全关闭文件流
  1006. if (is_resource($stream)) {
  1007. fclose($stream);
  1008. }
  1009. // 清理临时文件
  1010. @unlink($inputFile);
  1011. @unlink($outputFile);
  1012. if (!$compressedUrl) {
  1013. dLog('video_compress')->error('压缩视频上传失败');
  1014. return '';
  1015. }
  1016. dLog('video_compress')->info('压缩视频上传成功', [
  1017. 'original_url' => $videoUrl,
  1018. 'compressed_url' => $compressedUrl
  1019. ]);
  1020. return $compressedUrl;
  1021. } catch (\Exception $e) {
  1022. dLog('video_compress')->error('视频压缩异常', [
  1023. 'url' => $videoUrl,
  1024. 'error' => $e->getMessage(),
  1025. 'trace' => $e->getTraceAsString()
  1026. ]);
  1027. // 安全关闭文件流(如果存在)
  1028. if (isset($stream) && is_resource($stream)) {
  1029. @fclose($stream);
  1030. }
  1031. // 清理可能存在的临时文件
  1032. if (isset($inputFile) && file_exists($inputFile)) {
  1033. @unlink($inputFile);
  1034. }
  1035. if (isset($outputFile) && file_exists($outputFile)) {
  1036. @unlink($outputFile);
  1037. }
  1038. return ''; // 出错时返回空字符串
  1039. }
  1040. }
  1041. /**
  1042. * 获取视频第一帧并上传
  1043. * 根据远程视频URL获取第一帧图片并保存到TOS或OSS(默认TOS)
  1044. *
  1045. * @param string $videoUrl 视频URL地址
  1046. * @param string $prefix 上传文件夹前缀(如:'videos')
  1047. * @param string $uploadMethod 上传方式:'tos'(默认) 或 'oss'
  1048. * @return string 返回图片URL地址,失败返回空字符串
  1049. */
  1050. function getVideoFirstFrame($videoUrl, $prefix = 'videos', $uploadMethod = 'tos')
  1051. {
  1052. if (env('APP_ENV') == 'local') return '';
  1053. try {
  1054. // 创建临时目录
  1055. $tempDir = storage_path('app/temp/video_frames');
  1056. if (!is_dir($tempDir)) {
  1057. mkdir($tempDir, 0775, true);
  1058. chmod($tempDir, 0775);
  1059. }
  1060. // 生成唯一文件名
  1061. $uniqueId = uniqid('frame_') . bin2hex(random_bytes(4));
  1062. $videoExt = getVideoExtFromUrl($videoUrl);
  1063. $inputFile = $tempDir . '/' . $uniqueId . '_video' . $videoExt;
  1064. $outputFile = $tempDir . '/' . $uniqueId . '_frame.jpg';
  1065. // 下载视频到本地
  1066. dLog('video_frame')->info('开始下载视频', ['url' => $videoUrl]);
  1067. $client = new \GuzzleHttp\Client(['timeout' => 300]);
  1068. $response = $client->get($videoUrl);
  1069. $fileContent = $response->getBody()->getContents();
  1070. if (file_put_contents($inputFile, $fileContent) === false) {
  1071. dLog('video_frame')->error('视频文件写入失败', [
  1072. 'url' => $videoUrl,
  1073. 'file' => $inputFile
  1074. ]);
  1075. return '';
  1076. }
  1077. chmod($inputFile, 0664);
  1078. if (!file_exists($inputFile)) {
  1079. dLog('video_frame')->error('视频下载失败', ['url' => $videoUrl]);
  1080. return '';
  1081. }
  1082. dLog('video_frame')->info('视频下载成功', [
  1083. 'url' => $videoUrl,
  1084. 'size_mb' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB'
  1085. ]);
  1086. // 使用FFmpeg提取第一帧
  1087. // -i: 输入文件
  1088. // -ss 00:00:00: 从视频开始位置(第0秒)
  1089. // -vframes 1: 只提取1帧
  1090. // -q:v 2: 图片质量(1-31,数字越小质量越高)
  1091. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1092. $ffmpegCmd = "$ffmpegPath -i \"$inputFile\" -ss 00:00:00 -vframes 1 -q:v 2 -y \"$outputFile\" 2>&1";
  1093. dLog('video_frame')->info('开始提取第一帧', ['command' => $ffmpegCmd]);
  1094. $output = shell_exec($ffmpegCmd);
  1095. if (!file_exists($outputFile)) {
  1096. dLog('video_frame')->error('提取第一帧失败', [
  1097. 'input' => $inputFile,
  1098. 'output' => $output
  1099. ]);
  1100. @unlink($inputFile);
  1101. return '';
  1102. }
  1103. chmod($outputFile, 0664);
  1104. dLog('video_frame')->info('第一帧提取成功', [
  1105. 'size' => round(filesize($outputFile) / 1024, 2) . 'KB'
  1106. ]);
  1107. // 上传图片到云存储
  1108. $stream = fopen($outputFile, 'r');
  1109. if (!$stream) {
  1110. dLog('video_frame')->error('无法打开图片文件', ['file' => $outputFile]);
  1111. @unlink($inputFile);
  1112. @unlink($outputFile);
  1113. return '';
  1114. }
  1115. $filename = $uniqueId . '.jpg';
  1116. // 根据参数选择上传方式,默认使用TOS
  1117. if ($uploadMethod === 'oss') {
  1118. $frameUrl = uploadStreamToOss($prefix, $stream, $filename);
  1119. } else {
  1120. $frameUrl = uploadStreamByTos($prefix, $stream, $filename);
  1121. }
  1122. // 安全关闭文件流
  1123. if (is_resource($stream)) {
  1124. fclose($stream);
  1125. }
  1126. // 清理临时文件
  1127. @unlink($inputFile);
  1128. @unlink($outputFile);
  1129. if (!$frameUrl) {
  1130. dLog('video_frame')->error('图片上传失败');
  1131. return '';
  1132. }
  1133. dLog('video_frame')->info('图片上传成功', [
  1134. 'video_url' => $videoUrl,
  1135. 'frame_url' => $frameUrl
  1136. ]);
  1137. return $frameUrl;
  1138. } catch (\Exception $e) {
  1139. dLog('video_frame')->error('提取视频第一帧异常', [
  1140. 'url' => $videoUrl,
  1141. 'error' => $e->getMessage(),
  1142. 'trace' => $e->getTraceAsString()
  1143. ]);
  1144. // 安全关闭文件流(如果存在)
  1145. if (isset($stream) && is_resource($stream)) {
  1146. @fclose($stream);
  1147. }
  1148. // 清理可能存在的临时文件
  1149. if (isset($inputFile) && file_exists($inputFile)) {
  1150. @unlink($inputFile);
  1151. }
  1152. if (isset($outputFile) && file_exists($outputFile)) {
  1153. @unlink($outputFile);
  1154. }
  1155. return '';
  1156. }
  1157. }
  1158. function sensitiveStr($list, $string)
  1159. {
  1160. $count = 0; //违规词的个数
  1161. $sensitiveWord = ''; //违规词
  1162. $stringAfter = $string; //替换后的内容
  1163. $total = count($list);
  1164. $size = 500;
  1165. $last = ceil($total / $size);
  1166. $patternList = [];
  1167. for ($page = 1; $page <= $last; $page++) {
  1168. $arr = array_slice($list, $size * ($page - 1), $size);
  1169. $filter = [];
  1170. foreach ($arr as $v) {
  1171. if (preg_match('/[^a-zA-Z0-9\|\p{Han}\·]/u', $v)) continue;
  1172. $filter[] = $v;
  1173. // $a = preg_replace('/[^a-zA-Z0-9\|\p{Han}]/u', '', $v);
  1174. // if ($a) $filter[] = $a;
  1175. }
  1176. $pattern = "/" . implode("|", $filter) . "/i"; //定义正则表达式
  1177. if (preg_match_all($pattern, $string, $matches)) { //匹配到了结果
  1178. $patternList = array_merge($patternList, $matches[0]); //匹配到的数组
  1179. }
  1180. }
  1181. $sensitiveWord = '';
  1182. if ($patternList) {
  1183. $count = count($patternList);
  1184. // $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
  1185. $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '*')); //把匹配到的数组进行合并,替换使用
  1186. $stringAfter = strtr($string, $replaceArray); //结果替换
  1187. // 将敏感词合并
  1188. $return_pattern = [];
  1189. foreach ($patternList as $v) {
  1190. if (!isset($return_pattern[$v])) {
  1191. $return_pattern[$v] = [
  1192. 'word' => $v,
  1193. 'count' => 1,
  1194. ];
  1195. } else {
  1196. $return_pattern[$v]['count'] += 1;
  1197. }
  1198. }
  1199. foreach ($return_pattern as $v) {
  1200. $sensitiveWord .= $v['word'] . ',';
  1201. }
  1202. }
  1203. return [
  1204. 'count' => $count,
  1205. 'sensitive_words' => trim($sensitiveWord, ','),
  1206. 'content' => $stringAfter
  1207. ];
  1208. }
  1209. /**
  1210. * 转换时间格式
  1211. *
  1212. * @param $date
  1213. * @param string $format
  1214. * @return false|string
  1215. */
  1216. function transDate($date, $format = 'Y-m-d H:i:s')
  1217. {
  1218. return strtotime($date) > 0 ? date($format, strtotime($date)) : '';
  1219. }
  1220. /**
  1221. * 根据网段获取计算所有IP
  1222. *
  1223. * @param string $segment 网段 '139.217.0.1/24'
  1224. * @return array [网络地址:139.217.0.1 广播地址:139.217.0.255 IP列表: ['139.217.0.2','139.217.0.3'……'139.217.0.254']]
  1225. */
  1226. function getIpBySegment($segment)
  1227. {
  1228. $segmentInfo = explode("/", $segment);
  1229. $beginIpArray = explode(".", $segmentInfo[0]);
  1230. $mask = intval($segmentInfo['1']);
  1231. $endIp = array();
  1232. foreach ($beginIpArray as $ipKey => $item) {
  1233. $beginFlag = 8 * ($ipKey); //0 8 16 24
  1234. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  1235. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  1236. $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));
  1237. }
  1238. $ipArray = array();
  1239. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0]++) {
  1240. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1]++) {
  1241. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2]++) {
  1242. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3]++) {
  1243. $ipArray[] = implode(".", $beginIp);
  1244. }
  1245. }
  1246. }
  1247. }
  1248. $network_ip_addr = $beginIpArray[0] . '.' . $beginIpArray[1] . '.' . $beginIpArray[2] . '.' . '0'; // 网络地址
  1249. $broadcast_ip_addr = end($ipArray); // 广播地址
  1250. if ($ipArray[0] == $network_ip_addr) { // 如果是网络地址则删掉
  1251. unset($ipArray[0]);
  1252. }
  1253. $last = count($ipArray);
  1254. unset($ipArray[$last]);
  1255. return [$network_ip_addr, $broadcast_ip_addr, $ipArray];
  1256. }
  1257. /**
  1258. * 在指定网段中分配子网段
  1259. *
  1260. * @param string $segment 指定网段
  1261. * @param int $ipNum 需要的IP数
  1262. * @param array $usedIpArray 不可用(已经使用)的IP,默认为空数组
  1263. * @return bool|string 成功则返回分配的网段
  1264. */
  1265. function allocateSegment($segment, $ipNum, $usedIpArray = [])
  1266. {
  1267. $usedIpArray = empty($usedIpArray) ? [] : array_flip($usedIpArray);
  1268. //计算需要多少个IP
  1269. $i = 0;
  1270. $ipCount = pow(2, $i);
  1271. while ($ipCount < $ipNum) {
  1272. $i++;
  1273. $ipCount = pow(2, $i);
  1274. }
  1275. $newMask = 32 - $i;
  1276. //大网段的开始和结束IP
  1277. $segmentInfo = explode("/", $segment); //['139.217.0.1',24]
  1278. $beginIpArray = explode(".", $segmentInfo[0]);//[139,217,0,1]
  1279. $mask = intval($segmentInfo['1']); //24
  1280. if ($newMask < $mask) {
  1281. return false;
  1282. }
  1283. $endIp = array();
  1284. $step = [];
  1285. foreach ($beginIpArray as $ipKey => $item) {
  1286. $beginFlag = 8 * ($ipKey); //0 8 16 24
  1287. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  1288. $step[$ipKey] = $newMask > $endFlag ? 1 : ($endFlag - $newMask < 8 ? pow(2, $endFlag - $newMask) : pow(2, 8));
  1289. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  1290. $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));
  1291. }
  1292. //遍历生成网段
  1293. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0] += $step[0]) {
  1294. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1] += $step[1]) {
  1295. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2] += $step[2]) {
  1296. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3] += $step[3]) {
  1297. $newSegment = implode('.', $beginIp) . '/' . $newMask;
  1298. //获取该网段所有的IP
  1299. $ipArray = getIpBySegment($newSegment);
  1300. $canUse = true;
  1301. //判断该网段是否可用
  1302. if (!empty($usedIpArray)) {
  1303. foreach ($ipArray as $ip) {
  1304. if (isset($usedIpArray[$ip])) {
  1305. $canUse = false;
  1306. break;
  1307. }
  1308. }
  1309. }
  1310. if ($canUse) {
  1311. return $newSegment;
  1312. }
  1313. }
  1314. }
  1315. }
  1316. }
  1317. return false;
  1318. }
  1319. function remove_xss($val)
  1320. {
  1321. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  1322. // this prevents some character re-spacing such as <java\0script>
  1323. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
  1324. $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
  1325. // straight replacements, the user should never need these since they're normal characters
  1326. // this prevents like <IMG SRC=@avascript:alert('XSS')>
  1327. $search = 'abcdefghijklmnopqrstuvwxyz';
  1328. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1329. $search .= '1234567890!@#$%^&*()';
  1330. $search .= '~`";:?+/={}[]-_|\'\\';
  1331. for ($i = 0; $i < strlen($search); $i++) {
  1332. // ;? matches the ;, which is optional
  1333. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  1334. // @ @ search for the hex values
  1335. $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
  1336. // @ @ 0{0,7} matches '0' zero to seven times
  1337. $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
  1338. }
  1339. // now the only remaining whitespace attacks are \t, \n, and \r
  1340. $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  1341. $ra2 = array(
  1342. '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'
  1343. );
  1344. $ra = array_merge($ra1, $ra2);
  1345. $found = true; // keep replacing as long as the previous round replaced something
  1346. while ($found == true) {
  1347. $val_before = $val;
  1348. for ($i = 0; $i < sizeof($ra); $i++) {
  1349. $pattern = '/';
  1350. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  1351. if ($j > 0) {
  1352. $pattern .= '(';
  1353. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  1354. $pattern .= '|';
  1355. $pattern .= '|(�{0,8}([9|10|13]);)';
  1356. $pattern .= ')*';
  1357. }
  1358. $pattern .= $ra[$i][$j];
  1359. }
  1360. $pattern .= '/i';
  1361. $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
  1362. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  1363. if ($val_before == $val) {
  1364. // no replacements were made, so exit the loop
  1365. $found = false;
  1366. }
  1367. }
  1368. }
  1369. return $val;
  1370. }
  1371. /**
  1372. * 计算作者积分等级
  1373. *
  1374. * @param $score
  1375. */
  1376. function calcAuthorLevel($score): int
  1377. {
  1378. switch (true) {
  1379. case $score <= 0:
  1380. $level = 0;
  1381. break;
  1382. case $score <= 5000:
  1383. $level = 1;
  1384. break;
  1385. case $score <= 50000:
  1386. $level = 2;
  1387. break;
  1388. case $score <= 100000:
  1389. $level = 3;
  1390. break;
  1391. case $score <= 300000:
  1392. $level = 4;
  1393. break;
  1394. case $score <= 800000:
  1395. $level = 5;
  1396. break;
  1397. case $score <= 1500000:
  1398. $level = 6;
  1399. break;
  1400. case $score <= 2500000:
  1401. $level = 7;
  1402. break;
  1403. case $score <= 5000000:
  1404. $level = 8;
  1405. break;
  1406. case $score <= 10000000:
  1407. $level = 9;
  1408. break;
  1409. default:
  1410. $level = 10;
  1411. break;
  1412. }
  1413. return $level;
  1414. }
  1415. /**
  1416. * 运营数据(上传附件)
  1417. *
  1418. * @param $file
  1419. * @return string
  1420. * @throws Exception
  1421. */
  1422. function uploadEnclosureFile($file)
  1423. {
  1424. // 阿里云主账号
  1425. $accessKeyId = env('OSS_ACCESS_ID');
  1426. $accessKeySecret = env('OSS_ACCESS_KEY');
  1427. $endpoint = env('OSS_END_POINT');
  1428. $bucket = env('OSS_BUCKET');
  1429. // 设置文件名称。
  1430. $object = 'books/enclosure/' . randStr(10) . '--' . $file->getClientOriginalName();
  1431. try {
  1432. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  1433. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  1434. } catch (OssException $e) {
  1435. printf($e->getMessage());
  1436. return '';
  1437. }
  1438. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  1439. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  1440. }
  1441. // 获取当前域名是http还是https
  1442. function getHttpType()
  1443. {
  1444. return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
  1445. }
  1446. // 根据id生成唯一邀请码
  1447. function enCodeId($user_id)
  1448. {
  1449. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1450. $num = strlen($key);
  1451. $code = ''; // 邀请码
  1452. while ($user_id > 0) { // 转进制
  1453. $mod = $user_id % $num; // 求模
  1454. $user_id = ($user_id - $mod) / $num;
  1455. $code = $key[$mod] . $code;
  1456. }
  1457. $code = str_pad($code, 6, 'A', STR_PAD_LEFT); // 不足用0补充
  1458. return $code;
  1459. }
  1460. // 根据邀请码解密为id
  1461. function deCodeId($code)
  1462. {
  1463. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1464. $num = strlen($key);
  1465. if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0') + 1);
  1466. $len = strlen($code);
  1467. $code = strrev($code);
  1468. $user_id = 0;
  1469. for ($i = 0; $i < $len; $i++) {
  1470. $user_id += strpos($key, $code[$i]) * pow($num, $i);
  1471. }
  1472. return $user_id;
  1473. }
  1474. /**
  1475. * 将二维数组按其中的某个数组排序(此方法适用于将数据库数据按数组取出后自动按ID排序的情况 ps:即未按该数组排序)
  1476. *
  1477. * @param array $array 二维数组
  1478. * @param array $sort 排序数组
  1479. * @param string $field 排序字段(二维数组和排序数组相同的字段)
  1480. * @return array
  1481. */
  1482. function sortByArray(array $array, array $sort, string $field): array
  1483. {
  1484. $data = [];
  1485. if (is_array($array) && is_array($sort)) {
  1486. foreach ($sort as $v) {
  1487. foreach ($array as $key => $val) {
  1488. if ($v == $val[$field]) {
  1489. array_push($data, $array[$key]);
  1490. }
  1491. }
  1492. }
  1493. }
  1494. return $data;
  1495. }
  1496. /**
  1497. * 将二维数组按其中的字段排序(正序或倒序)
  1498. *
  1499. * @param array $array 二维数组
  1500. * @param string $field 排序字段
  1501. * @param mixed $type 排序方式(3倒序,4正序)
  1502. * @return array|mixed
  1503. */
  1504. function sortByField(array $array, string $field, $type): array
  1505. {
  1506. if (is_array($array)) {
  1507. array_multisort(array_column($array, $field), $type, $array);
  1508. }
  1509. return $array;
  1510. }
  1511. // 生成用户邀请码
  1512. function setUserInviteCode($id)
  1513. {
  1514. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->encode($id);
  1515. }
  1516. // 解密用户邀请码
  1517. function decodeUserInviteCode($code)
  1518. {
  1519. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->decode($code);
  1520. }
  1521. function getMillisecond()
  1522. {
  1523. list($microsecond, $time) = explode(' ', microtime());
  1524. return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
  1525. }
  1526. function get_client_ip($type = 0, $adv = false)
  1527. {
  1528. $type = $type ? 1 : 0;
  1529. static $ip = null;
  1530. if (null !== $ip) {
  1531. return $ip[$type];
  1532. }
  1533. if ($adv) {
  1534. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1535. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1536. $pos = array_search('unknown', $arr);
  1537. if (false !== $pos) {
  1538. unset($arr[$pos]);
  1539. }
  1540. $ip = trim($arr[0]);
  1541. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1542. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1543. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1544. $ip = $_SERVER['REMOTE_ADDR'];
  1545. }
  1546. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1547. $ip = $_SERVER['REMOTE_ADDR'];
  1548. }
  1549. // IP地址合法验证
  1550. $long = sprintf("%u", ip2long($ip));
  1551. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  1552. return $ip[$type];
  1553. }
  1554. /**
  1555. * 获取真实IP
  1556. */
  1557. function _getIp()
  1558. {
  1559. if (getenv('HTTP_X_FORWARDED_FOR')) {
  1560. $ip = getenv('HTTP_X_FORWARDED_FOR');
  1561. } else if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  1562. $ip = getenv("HTTP_CLIENT_IP");
  1563. else if (getenv("HTTP_X_FORWARD_FOR") && strcasecmp(getenv("HTTP_X_FORWARD_FOR"), "unknown"))
  1564. $ip = getenv("HTTP_X_FORWARD_FOR");
  1565. else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  1566. $ip = getenv("REMOTE_ADDR");
  1567. else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  1568. $ip = $_SERVER['REMOTE_ADDR'];
  1569. else
  1570. $ip = "unknown";
  1571. return ($ip);
  1572. }
  1573. /**
  1574. * 数组 转 对象
  1575. *
  1576. * @param array $arr 数组
  1577. * @return object
  1578. */
  1579. function array_to_object($arr)
  1580. {
  1581. if (gettype($arr) != 'array') {
  1582. return;
  1583. }
  1584. foreach ($arr as $k => $v) {
  1585. if (gettype($v) == 'array' || getType($v) == 'object') {
  1586. $arr[$k] = (object)array_to_object($v);
  1587. }
  1588. }
  1589. return (object)$arr;
  1590. }
  1591. /**
  1592. * 对象 转 数组
  1593. *
  1594. * @param object $obj 对象
  1595. * @return array
  1596. */
  1597. function object_to_array($obj)
  1598. {
  1599. $obj = (array)$obj;
  1600. foreach ($obj as $k => $v) {
  1601. if (gettype($v) == 'resource') {
  1602. return;
  1603. }
  1604. if (gettype($v) == 'object' || gettype($v) == 'array') {
  1605. $obj[$k] = (array)object_to_array($v);
  1606. }
  1607. }
  1608. return $obj;
  1609. }
  1610. /**
  1611. * 检查是否为手机号码
  1612. */
  1613. function _isPhone($number)
  1614. {
  1615. return preg_match("/^1[34578][0-9]{9}$/", $number);
  1616. }
  1617. /**
  1618. * 判断所传的参数是否缺少,如果缺少返回渠道的字段,正确返回0
  1619. *
  1620. * @param array $param
  1621. * @param array $must
  1622. * @return int|mixed
  1623. */
  1624. function checkParam(array $param, array $must)
  1625. {
  1626. foreach ($must as $item) {
  1627. if (array_key_exists($item, $param) && $param[$item] != '') {
  1628. } else {
  1629. return $item;
  1630. }
  1631. }
  1632. return 0;
  1633. }
  1634. /**
  1635. * 对象 转 数组
  1636. *
  1637. * @param object $obj 对象
  1638. * @return array
  1639. */
  1640. function ignoreKeyInArray($targetArray, $delete_keys = [], $changes = [])
  1641. {
  1642. $change_keys = array_keys($changes);
  1643. foreach ($targetArray as $key => $value) {
  1644. if (in_array($key, $delete_keys) && isset($targetArray[$key])) unset($targetArray[$key]);
  1645. if (in_array($key, $change_keys) && isset($targetArray[$key])) $targetArray[$key] = $changes[$key];
  1646. if (is_array($value)) ignoreKeyInArray($value, $delete_keys, $change_keys);
  1647. }
  1648. return $targetArray;
  1649. }
  1650. function itemTransform($trans, $data)
  1651. {
  1652. if ($data) {
  1653. return $trans->transform($data);
  1654. } else {
  1655. return [];
  1656. }
  1657. }
  1658. function collectionTransform($trans, $data)
  1659. {
  1660. $ret_data = [];
  1661. if ($data) {
  1662. foreach ($data as $item) {
  1663. $ret_data[] = $trans->transform($item);
  1664. }
  1665. }
  1666. return $ret_data;
  1667. }
  1668. function paginationTransform($trans, $paginator)
  1669. {
  1670. $ret = [];
  1671. $ret['list'] = [];
  1672. if ($paginator) {
  1673. foreach ($paginator as $item) {
  1674. $ret['list'][] = $trans->transform($item);
  1675. }
  1676. $ret['meta'] = [
  1677. 'total' => (int)$paginator->total(),
  1678. 'per_page' => (int)$paginator->perPage(),
  1679. 'current_page' => (int)$paginator->currentPage(),
  1680. 'last_page' => (int)$paginator->lastPage(),
  1681. 'next_page_url' => (string)$paginator->nextPageUrl(),
  1682. 'prev_page_url' => (string)$paginator->previousPageUrl()
  1683. ];
  1684. }
  1685. return $ret;
  1686. }
  1687. /**
  1688. * 加密site id
  1689. */
  1690. function encodeDistributionChannelId($id)
  1691. {
  1692. $encrypt_pool = [
  1693. ];
  1694. if (isset($encrypt_pool[$id])) {
  1695. return $encrypt_pool[$id];
  1696. }
  1697. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1698. return $hashids->encode($id);
  1699. }
  1700. /**
  1701. * 解密密site id
  1702. */
  1703. function decodeDistributionChannelId($code)
  1704. {
  1705. $encrypt_pool = [
  1706. ];
  1707. if (isset($encrypt_pool[$code])) {
  1708. return $encrypt_pool[$code];
  1709. }
  1710. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1711. $res = $hashids->decode($code);
  1712. if ($res && isset($res[0])) {
  1713. return $res[0];
  1714. }
  1715. return null;
  1716. }
  1717. //bid加密
  1718. function book_hash_encode($bid)
  1719. {
  1720. return Vinkla\Hashids\Facades\Hashids::encode($bid);
  1721. }
  1722. function decodeBid($encode_bid)
  1723. {
  1724. $bid = 0;
  1725. try {
  1726. $bid_arr = \Hashids::decode($encode_bid);
  1727. if (isset($bid_arr[0])) {
  1728. $bid = $bid_arr[0];
  1729. }
  1730. } catch (\Exception $e) {
  1731. return null;
  1732. }
  1733. return $bid;
  1734. }
  1735. /**
  1736. * 获取当前域名
  1737. */
  1738. function _domain()
  1739. {
  1740. return str_replace('https://', '', str_replace('http://', '', url('/')));
  1741. }
  1742. /**
  1743. * 字符串转*
  1744. *
  1745. * @param $str // 待转的字符串
  1746. * @param $start // 转*起始位置
  1747. * @param int $end // 转*结束位置
  1748. * @param string $dot // 转换的字符(必须是单字符,默认是*)
  1749. * @param string $charset // 编码方式
  1750. * @param string $end_char // 特殊字符(碰到此字符则确定end位置)
  1751. * @return string
  1752. */
  1753. function trans_pass($str, $start, $end = 0, $dot = "*", $charset = "UTF-8", $end_char = '@'): string
  1754. {
  1755. $len = mb_strlen($str, $charset);
  1756. if ($start == 0 || $start > $len) {
  1757. $start = 1;
  1758. }
  1759. if ($end != 0 && $end > $len) {
  1760. $end = $len - 2;
  1761. }
  1762. if (strstr($str, $end_char)) {
  1763. $end = $len - strrpos($str, $end_char);
  1764. }
  1765. $endStart = $len - $end;
  1766. $top = mb_substr($str, 0, $start, $charset);
  1767. $bottom = "";
  1768. if ($endStart > 0) {
  1769. $bottom = mb_substr($str, $endStart, $end, $charset);
  1770. }
  1771. $len -= mb_strlen($top, $charset);
  1772. $len -= mb_strlen($bottom, $charset);
  1773. $newStr = $top;
  1774. for ($i = 0; $i < $len; $i++) {
  1775. $newStr .= $dot;
  1776. }
  1777. $newStr .= $bottom;
  1778. return $newStr;
  1779. }
  1780. /**
  1781. * 格式化章节内容
  1782. *
  1783. * @param $content
  1784. * @return false|string
  1785. */
  1786. function formatContent($content)
  1787. {
  1788. if (!$content) return '';
  1789. $content = str_replace(
  1790. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p >', '&ldquo;', '&rdquo;', '&hellip;'],
  1791. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...'],
  1792. $content);
  1793. $content = str_replace(["&nbsp;", '&ldquo;', '&hellip;', '&rdquo;', '<p>'], '', $content);
  1794. // 段落首字母前加两个中文空格
  1795. $string = explode(PHP_EOL, $content);
  1796. foreach ($string as $line => $text) {
  1797. if (mb_substr($text, 0, 2) != '  ') $string[$line] = '  ' . $text;
  1798. }
  1799. $content = implode(PHP_EOL, $string);
  1800. $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8,GBK,GB2312');
  1801. $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);
  1802. return $content;
  1803. }
  1804. /**
  1805. * 筛选出有效的id集合
  1806. *
  1807. * @param array $ids
  1808. * @return array
  1809. */
  1810. function filterValidIds(array $ids): array
  1811. {
  1812. // 传参
  1813. if (empty($ids)) {
  1814. return [];
  1815. }
  1816. $result = [];
  1817. foreach ($ids as $id) {
  1818. if (in_array($id, $result) || !is_numeric($id) || (int)$id < 1) {
  1819. continue;
  1820. }
  1821. $result[] = (int)$id;
  1822. }
  1823. return $result;
  1824. }
  1825. function arrayToStr($map)
  1826. {
  1827. $isMap = isArrMap($map);
  1828. $result = "";
  1829. if ($isMap) {
  1830. $result = "map[";
  1831. }
  1832. $keyArr = array_keys($map);
  1833. if ($isMap) {
  1834. sort($keyArr);
  1835. }
  1836. $paramsArr = array();
  1837. foreach ($keyArr as $k) {
  1838. $v = $map[$k];
  1839. if ($isMap) {
  1840. if (is_array($v)) {
  1841. $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
  1842. } else {
  1843. $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
  1844. }
  1845. } else {
  1846. if (is_array($v)) {
  1847. $paramsArr[] = arrayToStr($v);
  1848. } else {
  1849. $paramsArr[] = trim(strval($v));
  1850. }
  1851. }
  1852. }
  1853. $result = sprintf("%s%s", $result, join(" ", $paramsArr));
  1854. if (!$isMap) {
  1855. $result = sprintf("[%s]", $result);
  1856. } else {
  1857. $result = sprintf("%s]", $result);
  1858. }
  1859. return $result;
  1860. }
  1861. function isArrMap($map)
  1862. {
  1863. foreach ($map as $k => $v) {
  1864. if (is_string($k)) {
  1865. return true;
  1866. }
  1867. }
  1868. return false;
  1869. }
  1870. /**
  1871. * 随机字符串
  1872. *
  1873. * @param $length
  1874. * @return string
  1875. */
  1876. function makeRandStr($length): string
  1877. {
  1878. // 密码字符集,可任意添加你需要的字符
  1879. $str = [
  1880. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  1881. 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  1882. 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
  1883. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  1884. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  1885. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  1886. ];
  1887. // 在 $str 中随机取 $length 个数组元素键名
  1888. $keys = array_rand($str, $length);
  1889. $password = '';
  1890. for ($i = 0; $i < $length; $i++) {
  1891. // 将 $length 个数组元素连接成字符串
  1892. $password .= $str[$keys[$i]];
  1893. }
  1894. return $password;
  1895. }
  1896. /**
  1897. * 导出数据为excel表格
  1898. *
  1899. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1900. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1901. * @param $filename 下载的文件名
  1902. * @examlpe10
  1903. */
  1904. function exportExcel($data = [], $title = [], $filename = 'report')
  1905. {
  1906. ob_end_clean();
  1907. ob_start();
  1908. header("Content-type:application/octet-stream");
  1909. header("Accept-Ranges:bytes");
  1910. header("Content-type:application/vnd.ms-excel");
  1911. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1912. header("Pragma: no-cache");
  1913. header("Expires: 0");
  1914. //导出xls 开始
  1915. if (!empty($title)) {
  1916. foreach ($title as $k => $v) {
  1917. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1918. }
  1919. $title = implode("\t", $title);
  1920. echo "$title\n";
  1921. }
  1922. if (!empty($data)) {
  1923. foreach ($data as $key => $val) {
  1924. foreach ($val as $ck => $cv) {
  1925. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1926. }
  1927. $data[$key] = implode("\t", $data[$key]);
  1928. }
  1929. echo implode("\n", $data);
  1930. }
  1931. }
  1932. /**
  1933. * 导出csv文件
  1934. * @param string $name
  1935. * @param array $headers
  1936. * @param array $data
  1937. * @return void
  1938. */
  1939. function exportCsv(string $name, array $headers, array $data = [])
  1940. {
  1941. header('Content-Description: File Transfer');
  1942. header('Content-Type: application/csv');
  1943. header("Content-Disposition: attachment; filename=".$name.".csv");
  1944. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  1945. $handle = fopen('php://output', 'w');
  1946. ob_clean();
  1947. fputcsv($handle, $headers);
  1948. if ($data) {
  1949. foreach ($data as $row) {
  1950. fputcsv($handle, $row);
  1951. }
  1952. }
  1953. ob_flush();
  1954. fclose($handle);
  1955. die();
  1956. }
  1957. // 树状分类
  1958. function buildCategoryTree($categories, $pid = 0) {
  1959. $tree = [];
  1960. foreach ($categories as $category) {
  1961. if ($category['pid'] == $pid) {
  1962. $children = buildCategoryTree($categories, $category['category_id']);
  1963. if ($children) {
  1964. $category['children'] = $children;
  1965. }
  1966. $tree[] = $category;
  1967. }
  1968. }
  1969. return $tree;
  1970. }
  1971. // 获取文件的md5值
  1972. function getFileContentMD5($filePath){
  1973. //获取文件MD5的128位二进制数组
  1974. $md5Bytes = md5_file($filePath,true);
  1975. //计算文件的Content-MD5
  1976. $contentMD5 = base64_encode($md5Bytes);
  1977. return $contentMD5;
  1978. }
  1979. function getTextTokens($text) {
  1980. // 方法1:按空格分词(西文较准)
  1981. $words = preg_split('/\s+/', $text);
  1982. $wordCount = count($words);
  1983. // 方法2:按字符数估算(中文较准:1个汉字 ≈ 1.5-2 tokens)
  1984. $charCount = mb_strlen($text);
  1985. // 综合估算(根据语言调整权重)
  1986. $tokenCount = $wordCount + $charCount * 0.5; // 示例公式
  1987. // 更简单:直接按字符数 * 系数(中文推荐)
  1988. // $tokenCount = $charCount * 1.8; // 经验系数
  1989. return (int)ceil($tokenCount);
  1990. }
  1991. // 处理小说剧本文本
  1992. function handleScriptWords($text, $enable_emotion=1) {
  1993. $text = preg_replace('/[\r\n]+/', PHP_EOL, $text);
  1994. $text_arr = explode(PHP_EOL, $text);
  1995. $roles = [];
  1996. $words = [];
  1997. $role_gender = [];
  1998. // $sequence = 0;
  1999. foreach ($text_arr as $line) {
  2000. $line = trim($line);
  2001. if ($enable_emotion) {
  2002. $match_rule = '/^(.*?)\:(.*?)\{(.*?)\}$/';
  2003. $count = 4;
  2004. } else {
  2005. $match_rule = '/^(.*?)\:(.*?)$/';
  2006. $count = 3;
  2007. }
  2008. preg_match($match_rule, $line, $matches);
  2009. if (count($matches) == $count) {
  2010. $gender = '0';
  2011. // 角色部分拆分
  2012. preg_match('/^(.*?)\((.*?)\)$/', $matches[1], $matches2);
  2013. if (count($matches2) == 3) {
  2014. $role = $matches2[1];
  2015. $gender_arr = ['男'=>'1', '女'=>'2'];
  2016. $gender = isset($gender_arr[$matches2[2]]) ? $gender_arr[$matches2[2]] : '0';
  2017. }else {
  2018. $role = $matches[1];
  2019. }
  2020. if (!in_array($role, $roles)) {
  2021. $roles[] = $role; // 记录角色
  2022. $role_gender[$role] = $gender;
  2023. }
  2024. $words[] = [
  2025. 'role' => $role,
  2026. 'gender' => $gender,
  2027. 'text' => $matches[2],
  2028. 'emotion' => $enable_emotion ? $matches[3] : '中性',
  2029. ];
  2030. }
  2031. }
  2032. $new_words = [];
  2033. $tmp = '';
  2034. $tmp_arr = [];
  2035. $tmp_text = '';
  2036. // 将words数组按照role和emotion合并相邻的text内容,不相邻则跳过合并
  2037. foreach ($words as $word) {
  2038. if(!$tmp) $tmp = $word['role'].'-'.$word['emotion'];
  2039. if($tmp == $word['role'].'-'.$word['emotion']) {
  2040. $tmp_text .= PHP_EOL.$word['text'];
  2041. $tmp_arr = [
  2042. 'role' => $word['role'],
  2043. 'gender' => $word['gender'],
  2044. 'text' => trim($tmp_text, PHP_EOL),
  2045. 'emotion' => $word['emotion'],
  2046. ];
  2047. }else {
  2048. // $sequence++;
  2049. // $tmp_arr['sequence'] = $sequence;
  2050. $new_words[] = $tmp_arr;
  2051. $tmp = $word['role'].'-'.$word['emotion'];
  2052. $tmp_text = $word['text'];
  2053. $tmp_arr = [
  2054. 'role' => $word['role'],
  2055. 'gender' => $word['gender'],
  2056. 'text' => trim($tmp_text, PHP_EOL),
  2057. 'emotion' => $word['emotion'],
  2058. ];
  2059. }
  2060. }
  2061. if ($tmp_arr) {
  2062. // $sequence++;
  2063. // $tmp_arr['sequence'] = $sequence;
  2064. $new_words[] = $tmp_arr;
  2065. }
  2066. return [
  2067. 'roles' => $roles,
  2068. 'role_gender' => $role_gender,
  2069. 'words' => $new_words,
  2070. ];
  2071. }
  2072. function extractScriptContent($originalContent) {
  2073. if (!$originalContent) return [];
  2074. // 使用更精确的正则表达式分割内容
  2075. $parts = [];
  2076. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2077. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2078. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2079. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2080. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2081. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2082. // 提取剧本亮点(支持多个空格)
  2083. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2084. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2085. // 提取人物关系(支持多个空格)
  2086. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2087. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2088. // 提取核心矛盾(支持多个空格)
  2089. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2090. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2091. // 提取主体列表(支持多个空格)
  2092. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2093. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2094. $parts['roles'] = parseRolesFromText($rolesText);
  2095. // 提取美术风格(支持多个空格)
  2096. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2097. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2098. // 提取场景列表(支持多个空格)
  2099. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2100. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2101. $parts['scenes'] = parseScenesFromText($scenesText);
  2102. // 提取分集详细内容(多剧集模式,支持多个空格)
  2103. preg_match('/###\s*分集剧本\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2104. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2105. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2106. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2107. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2108. // 优先使用原文内容,其次使用分集详细内容
  2109. // $parts['content'] = $generatedContent ?: $detailedContent;
  2110. // 解析分集剧本内容
  2111. $episodes = [];
  2112. if ($detailedContent) {
  2113. // 按 ##分集 分割
  2114. preg_match_all('/##\s*分集(\d+)\s*\n(.*?)(?=\n\s*##分集|\z)/s', $detailedContent, $episodeMatches, PREG_SET_ORDER);
  2115. foreach ($episodeMatches as $episodeMatch) {
  2116. $episodeNum = $episodeMatch[1];
  2117. $episodeContent = trim($episodeMatch[2]);
  2118. $episode = [
  2119. 'episode_number' => $episodeNum,
  2120. 'episode_content' => $episodeContent,
  2121. 'episode_name' => '',
  2122. 'scene_description' => '',
  2123. 'camera_movement' => '',
  2124. 'characters' => '',
  2125. 'dialogues' => []
  2126. ];
  2127. // 提取分集名(格式:##分集01第一集: 第一集的标题)
  2128. if (preg_match('/^第.*?集\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $nameMatch)) {
  2129. $episode['episode_name'] = trim($nameMatch[1]);
  2130. }
  2131. // 提取场景描述
  2132. if (preg_match('/场景描述\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $sceneMatch)) {
  2133. $episode['scene_description'] = trim($sceneMatch[1]);
  2134. }
  2135. // 提取运镜
  2136. if (preg_match('/运镜\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $cameraMatch)) {
  2137. $episode['camera_movement'] = trim($cameraMatch[1]);
  2138. }
  2139. // 提取出场角色
  2140. if (preg_match('/出场角色\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $charactersMatch)) {
  2141. $episode['characters'] = trim($charactersMatch[1]);
  2142. }
  2143. // 提取台词内容
  2144. if (preg_match('/台词内容\s*[::]\s*\n(.*?)$/su', $episodeContent, $dialoguesMatch)) {
  2145. $dialoguesText = trim($dialoguesMatch[1]);
  2146. $dialogueLines = explode("\n", $dialoguesText);
  2147. foreach ($dialogueLines as $line) {
  2148. $line = trim($line);
  2149. if (empty($line)) {
  2150. continue;
  2151. }
  2152. // 匹配格式:角色名: 对话内容 或 角色名:对话内容
  2153. if (preg_match('/^(.+?)\s*[::]\s*(.+)$/u', $line, $dialogueMatch)) {
  2154. $episode['dialogues'][] = [
  2155. 'character' => trim($dialogueMatch[1]),
  2156. 'text' => trim($dialogueMatch[2])
  2157. ];
  2158. }
  2159. }
  2160. }
  2161. $episodes[] = $episode;
  2162. }
  2163. }
  2164. $parts['episodes'] = $episodes;
  2165. return $parts;
  2166. }
  2167. /**
  2168. * 处理剧本内容
  2169. */
  2170. function handleScriptContent($originalContent) {
  2171. if (!$originalContent) return [];
  2172. // 使用更精确的正则表达式分割内容
  2173. $parts = [];
  2174. // // 确保内容使用UTF-8编码
  2175. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  2176. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  2177. // }
  2178. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2179. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2180. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2181. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2182. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2183. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2184. // 提取剧本亮点(支持多个空格)
  2185. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2186. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2187. // 提取人物关系(支持多个空格)
  2188. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2189. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2190. // 提取核心矛盾(支持多个空格)
  2191. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2192. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2193. // 提取主体列表(支持多个空格)
  2194. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2195. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2196. $parts['roles'] = parseRolesFromText($rolesText);
  2197. // 提取美术风格(支持多个空格)
  2198. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2199. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2200. // 提取场景列表(支持多个空格)
  2201. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2202. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2203. $parts['scenes'] = parseScenesFromText($scenesText);
  2204. // 提取分集详细内容(多剧集模式,支持多个空格)
  2205. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2206. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2207. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2208. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2209. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2210. // 优先使用原文内容,其次使用分集详细内容
  2211. $parts['content'] = $generatedContent ?: $detailedContent;
  2212. $parts['episode_title'] = '';
  2213. $parts['acts'] = [];
  2214. // 单剧集格式:顶层是大纲信息,分镜部分采用 handleEpisodeContent 的结构标准
  2215. $singleStoryboard = '';
  2216. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2217. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2218. }
  2219. if ($singleStoryboard !== '') {
  2220. $episodeContent = $singleStoryboard;
  2221. if (!preg_match('/第\d+集[::\s]+/u', $episodeContent)) {
  2222. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  2223. $episodeContent = $defaultEpisodeTitle . "\n\n" . $episodeContent;
  2224. }
  2225. $episodeSections = [];
  2226. $episodeSections[] = $episodeContent;
  2227. if ($parts['intro'] !== '') {
  2228. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  2229. }
  2230. if ($parts['art_style'] !== '') {
  2231. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  2232. }
  2233. if ($rolesText !== '') {
  2234. $episodeSections[] = "###主体列表\n" . $rolesText;
  2235. }
  2236. if ($scenesText !== '') {
  2237. $episodeSections[] = "###场景列表\n" . $scenesText;
  2238. }
  2239. if (strpos($episodeContent, '###分镜剧本') === false) {
  2240. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  2241. }
  2242. $episode_arr = handleEpisodeContent(implode("\n\n", $episodeSections));
  2243. if (!empty($episode_arr['acts'])) {
  2244. $parts['episode_title'] = getProp($episode_arr, 'episode_title');
  2245. $parts['acts'] = getProp($episode_arr, 'acts', []);
  2246. if (empty($parts['roles'])) {
  2247. $parts['roles'] = getProp($episode_arr, 'roles', []);
  2248. }
  2249. if (empty($parts['scenes'])) {
  2250. $parts['scenes'] = getProp($episode_arr, 'scenes', []);
  2251. }
  2252. }
  2253. }
  2254. if (empty($parts['acts'])) {
  2255. $fallbackEpisodeArr = handleEpisodeContent($originalContent);
  2256. if (!empty($fallbackEpisodeArr['acts'])) {
  2257. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title');
  2258. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  2259. if (empty($parts['intro'])) {
  2260. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro');
  2261. }
  2262. if (empty($parts['art_style'])) {
  2263. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style');
  2264. }
  2265. if (empty($parts['roles'])) {
  2266. $parts['roles'] = getProp($fallbackEpisodeArr, 'roles', []);
  2267. }
  2268. if (empty($parts['scenes'])) {
  2269. $parts['scenes'] = getProp($fallbackEpisodeArr, 'scenes', []);
  2270. }
  2271. }
  2272. }
  2273. // 多剧集格式:继续兼容旧的分集剧本结构
  2274. $fullScript = '';
  2275. if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2276. $fullScript = trim($storyboardMatch[1]);
  2277. } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2278. $fullScript = trim($storyboardMatch[1]);
  2279. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2280. $fullScript = trim($storyboardMatch[1]);
  2281. }
  2282. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  2283. $fullScript = trim($fallbackMatch[1]);
  2284. }
  2285. $episodes = [];
  2286. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  2287. foreach ($matches as $match) {
  2288. $episodeNumber = (int)trim($match[1]);
  2289. $episodeName = trim($match[2]);
  2290. $episodeContent = trim($match[3]);
  2291. $segments = [];
  2292. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  2293. foreach ($segmentMatches as $segMatch) {
  2294. $segmentNumber = (int)trim($segMatch[1]);
  2295. $segmentContent = trim($segMatch[2]);
  2296. $segments[] = [
  2297. 'segment_number' => $segmentNumber,
  2298. 'segment_content' => $segmentContent,
  2299. ];
  2300. }
  2301. $episodes[] = [
  2302. 'episode_number' => $episodeNumber,
  2303. 'title' => $episodeName,
  2304. 'content' => $episodeContent,
  2305. 'segments' => $segments,
  2306. ];
  2307. }
  2308. if (empty($episodes) && !empty($parts['acts'])) {
  2309. $singleSegments = [];
  2310. foreach ($parts['acts'] as $act) {
  2311. $actSegments = getProp($act, 'segments', []);
  2312. if (!is_array($actSegments)) {
  2313. continue;
  2314. }
  2315. foreach ($actSegments as $segment) {
  2316. $singleSegments[] = [
  2317. 'segment_number' => getProp($segment, 'segment_number'),
  2318. 'segment_content' => getProp($segment, 'segment_content'),
  2319. ];
  2320. }
  2321. }
  2322. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  2323. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  2324. $episodes[] = [
  2325. 'episode_number' => 1,
  2326. 'title' => $episodeName,
  2327. 'content' => $singleStoryboard,
  2328. 'segments' => $singleSegments,
  2329. ];
  2330. }
  2331. $parts['episodes'] = $episodes;
  2332. return $parts;
  2333. }
  2334. function handleEpisodeContent($originalContent) {
  2335. if (!$originalContent) return [];
  2336. // 解析剧集内容
  2337. $result = [
  2338. 'episode_title' => '',
  2339. 'intro' => '',
  2340. 'art_style' => '',
  2341. 'roles' => [],
  2342. 'scenes' => [],
  2343. 'acts' => []
  2344. ];
  2345. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  2346. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  2347. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  2348. }
  2349. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  2350. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  2351. $result['intro'] = trim($summaryMatch[1]);
  2352. }
  2353. // 提取美术风格 - 兼容多种格式
  2354. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  2355. $result['art_style'] = trim($styleMatch[1]);
  2356. }
  2357. // 提取主体列表 - 兼容多种格式
  2358. if (preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  2359. $charactersText = trim($charactersMatch[1]);
  2360. $characterLines = explode("\n", $charactersText);
  2361. foreach ($characterLines as $line) {
  2362. $line = trim($line);
  2363. if (empty($line)) continue;
  2364. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  2365. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2366. $role = trim($charMatch[1]);
  2367. $description = trim($charMatch[2]);
  2368. $timbreName = null;
  2369. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  2370. $picPrompt = null;
  2371. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  2372. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  2373. $description = trim($fullMatch[1]);
  2374. $picPrompt = trim($fullMatch[2]);
  2375. $timbreName = trim($fullMatch[3]);
  2376. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2377. // 兼容旧格式:主体描述{{音色名}}
  2378. $description = trim($timbreMatch[1]);
  2379. $timbreName = trim($timbreMatch[2]);
  2380. }
  2381. $roleData = [
  2382. 'role' => $role,
  2383. 'description' => $description
  2384. ];
  2385. // 如果有主体图片提示词,添加到数组中
  2386. if ($picPrompt) {
  2387. // 检查开头是否有"全景,正面拍摄。"
  2388. $prefix = '全景,正面拍摄。';
  2389. $prefixParts = ['全景', '正面拍摄'];
  2390. // 检查是否包含完整前缀
  2391. if (strpos($picPrompt, $prefix) !== 0) {
  2392. // 检查是否包含部分前缀词汇(不论位置)
  2393. $hasAnyPrefix = false;
  2394. foreach ($prefixParts as $part) {
  2395. if (mb_strpos($picPrompt, $part) !== false) {
  2396. $hasAnyPrefix = true;
  2397. break;
  2398. }
  2399. }
  2400. if ($hasAnyPrefix) {
  2401. // 移除所有"全景"和"正面拍摄"词汇(包括它们后面的标点)
  2402. $picPrompt = preg_replace('/全景[,,、。. ]*/u', '', $picPrompt);
  2403. $picPrompt = preg_replace('/正面拍摄[,,、。. ]*/u', '', $picPrompt);
  2404. // 清理开头和结尾的标点符号和空格
  2405. $picPrompt = preg_replace('/^[。,,、 ]+|[。,,、 ]+$/u', '', $picPrompt);
  2406. }
  2407. // 在开头添加完整前缀
  2408. $picPrompt = $prefix . $picPrompt;
  2409. }
  2410. // 检查是否包含"姿态:"或"姿态:"
  2411. if (preg_match('/姿态[::]/u', $picPrompt)) {
  2412. // 如果有姿态描述,统一替换为"姿态:站立"
  2413. $picPrompt = preg_replace('/姿态[::][^.。\n]+/u', '姿态:站立', $picPrompt);
  2414. } else {
  2415. // 如果没有姿态描述,在末尾添加"姿态:站立"
  2416. $picPrompt = preg_replace('/[。,, ]+$/u', '', $picPrompt) . '。姿态:站立。';
  2417. }
  2418. $roleData['pic_prompt'] = $picPrompt;
  2419. }
  2420. // 如果有音色信息,添加到数组中
  2421. if ($timbreName) {
  2422. $timbre = DB::table('mp_timbres')->where('is_enabled', 1)->where('timbre_name', 'like', "%{$timbreName}%")->orderBy('id')->select('timbre_type', 'audio_url')->first();
  2423. if ($timbre) {
  2424. $roleData['voice_name'] = $timbreName;
  2425. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2426. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');;
  2427. }
  2428. }else {
  2429. // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  2430. if ($picPrompt) {
  2431. if (strstr($picPrompt, '男')) {
  2432. $roleData['voice_name'] = '阳光青年';
  2433. }elseif (strstr($picPrompt, '女')) {
  2434. $roleData['voice_name'] = '爽快思思';
  2435. }else {
  2436. if ($description) {
  2437. if (strstr($description, '男')) {
  2438. $roleData['voice_name'] = '阳光青年';
  2439. }elseif (strstr($description, '女')) {
  2440. $roleData['voice_name'] = '爽快思思';
  2441. }else {
  2442. $roleData['voice_name'] = '旁白';
  2443. }
  2444. }
  2445. }
  2446. }
  2447. if (!empty($roleData['voice_name'])) {
  2448. if ($roleData['voice_name'] == '旁白') {
  2449. $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  2450. $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  2451. }else {
  2452. $timbre = DB::table('mp_timbres')
  2453. ->where('is_enabled', 1)
  2454. ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  2455. ->orderBy('id')
  2456. ->select('timbre_type', 'audio_url')
  2457. ->first();
  2458. if ($timbre) {
  2459. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2460. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2461. }
  2462. }
  2463. }
  2464. }
  2465. $result['roles'][] = $roleData;
  2466. }
  2467. }
  2468. // 加入旁白角色(如果不存在)
  2469. $hasNarrator = false;
  2470. foreach ($result['roles'] as $role) {
  2471. if (isset($role['role']) && $role['role'] === '旁白') {
  2472. $hasNarrator = true;
  2473. break;
  2474. }
  2475. }
  2476. if (!$hasNarrator) {
  2477. $result['roles'][] = [
  2478. 'role' => '旁白',
  2479. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2480. 'pic_prompt' => '',
  2481. 'voice_name' => '旁白',
  2482. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2483. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2484. ];
  2485. }
  2486. }
  2487. // 提取场景列表 - 兼容多种格式
  2488. if (preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  2489. $scenesText = trim($scenesMatch[1]);
  2490. $sceneLines = explode("\n", $scenesText);
  2491. foreach ($sceneLines as $line) {
  2492. $line = trim($line);
  2493. if (empty($line)) continue;
  2494. // 兼容中文冒号:和英文冒号:
  2495. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  2496. $scene = trim($sceneMatch[1]);
  2497. $description = trim($sceneMatch[2]);
  2498. $picPrompt = null;
  2499. // 检查描述末尾是否有{场景图片提示词}格式
  2500. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  2501. // 匹配格式:场景描述{场景图片提示词}
  2502. $description = trim($promptMatch[1]);
  2503. $picPrompt = trim($promptMatch[2]);
  2504. }
  2505. $sceneData = [
  2506. 'scene' => $scene,
  2507. 'description' => $description
  2508. ];
  2509. // 如果有场景图片提示词,添加到数组中
  2510. if ($picPrompt) {
  2511. $sceneData['pic_prompt'] = $picPrompt;
  2512. }
  2513. $result['scenes'][] = $sceneData;
  2514. }
  2515. }
  2516. }
  2517. // 提取分镜剧本 - 兼容多种格式
  2518. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $storyboardMatch)) {
  2519. $storyboardText = trim($storyboardMatch[1]);
  2520. // 按幕分割 - 修复第1幕识别和乱码问题
  2521. $acts = [];
  2522. // 先在开头添加换行符,确保第1幕也能被正确分割
  2523. $normalizedText = "\n" . $storyboardText;
  2524. $parts = preg_split('/\n\s*##/', $normalizedText);
  2525. foreach ($parts as $part) {
  2526. $part = trim($part);
  2527. if (empty($part)) continue;
  2528. // 如果不是以"第"开头,跳过
  2529. if (!preg_match('/^第\d+幕/', $part)) {
  2530. continue;
  2531. }
  2532. // 分离标题和内容
  2533. $lines = explode("\n", $part, 2);
  2534. $actTitle = trim($lines[0]);
  2535. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  2536. // 解析幕标题,提取序号和详细信息 - 修复乱码问题
  2537. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  2538. $actNumber = intval($actTitleMatch[1]);
  2539. $actDetails = trim($actTitleMatch[2]);
  2540. // 如果详细信息为空或者就是冒号,使用完整标题
  2541. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  2542. $actDetails = $actTitle;
  2543. }
  2544. } else {
  2545. $actNumber = count($acts) + 1;
  2546. $actDetails = $actTitle;
  2547. }
  2548. // 解析该幕下的分镜
  2549. $segments = [];
  2550. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  2551. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  2552. foreach ($segmentMatches as $segmentMatch) {
  2553. $segmentNumber = intval($segmentMatch[1]);
  2554. $segmentContent = trim($segmentMatch[2]);
  2555. // 解析分镜详细信息
  2556. $segmentData = [
  2557. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT), // 生成唯一ID(后续可在生成任务里查看历史版本)
  2558. 'segment_number' => $segmentNumber,
  2559. 'segment_content' => $segmentContent,
  2560. 'description' => '',
  2561. 'composition' => '',
  2562. 'camera_movement' => '',
  2563. 'voice_actor' => '',
  2564. 'dialogue' => '',
  2565. 'frame_type' => '',
  2566. 'scene' => '', // 新增:场景
  2567. 'characters' => '', // 新增:出镜角色
  2568. 'tail_frame' => '', // 新增:尾帧描述
  2569. // 新增字段
  2570. 'emotion' => '中性', // 新增: 情感
  2571. 'gender' => '0', // 新增: 性别(0未知,1男,2女)
  2572. 'speed_ratio' => 0, // 新增: 语速
  2573. 'loudness_ratio' => 0, // 新增: 音量
  2574. 'emotion_scale' => 4, // 新增: 语调
  2575. 'pitch' => 0, // 新增: 音调
  2576. ];
  2577. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  2578. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  2579. $segmentData['description'] = trim($descMatch[1]);
  2580. }
  2581. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  2582. $segmentData['composition'] = trim($compMatch[1]);
  2583. }
  2584. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  2585. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  2586. }
  2587. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  2588. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  2589. }
  2590. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  2591. $dialogue = trim($dialogueMatch[1]) == '无' ? '' : trim($dialogueMatch[1]);
  2592. // 确保台词使用中文左右双引号
  2593. if (!empty($dialogue)) {
  2594. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  2595. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  2596. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  2597. if (!preg_match('/^[“]/', $dialogue)) {
  2598. $dialogue = '“' . $dialogue;
  2599. }
  2600. if (!preg_match('/[”]$/', $dialogue)) {
  2601. $dialogue .= '”';
  2602. }
  2603. // 将修改后的台词替换回 $segmentContent
  2604. $originalDialogue = $dialogueMatch[1];
  2605. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  2606. }
  2607. $segmentData['dialogue'] = $dialogue;
  2608. }
  2609. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  2610. $segmentData['frame_type'] = trim($frameMatch[1]);
  2611. }
  2612. // 新增:场景字段
  2613. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  2614. $segmentData['scene'] = trim($sceneMatch[1]);
  2615. }
  2616. // 新增:出镜角色字段
  2617. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  2618. $segmentData['characters'] = trim($charactersMatch[1]);
  2619. }
  2620. // 新增:尾帧描述字段
  2621. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  2622. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  2623. }
  2624. $replaceEmptyArr = [];
  2625. // 新增:情感字段
  2626. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  2627. $replaceEmptyArr[] = trim($emotionMatch[0]);
  2628. $segmentData['emotion'] = trim($emotionMatch[1]);
  2629. }
  2630. // 新增:性别字段
  2631. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  2632. $replaceEmptyArr[] = trim($genderMatch[0]);
  2633. $genderStr = trim($genderMatch[1]);
  2634. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  2635. $segmentData['gender'] = '1';
  2636. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  2637. $segmentData['gender'] = '2';
  2638. } else {
  2639. $segmentData['gender'] = '0';
  2640. }
  2641. }
  2642. // 新增:语速字段
  2643. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  2644. $replaceEmptyArr[] = trim($speedMatch[0]);
  2645. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  2646. }
  2647. // 新增:音量字段
  2648. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  2649. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  2650. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  2651. }
  2652. // 新增:情感强度字段
  2653. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  2654. $replaceEmptyArr[] = trim($scaleMatch[0]);
  2655. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  2656. }
  2657. // 新增:音调字段
  2658. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  2659. $replaceEmptyArr[] = trim($pitchMatch[0]);
  2660. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  2661. }
  2662. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  2663. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  2664. $segmentData['segment_content'] = preg_replace('/\n{2,}/', "\n", $segmentData['segment_content']);
  2665. $segmentData['segment_content'] = trim($segmentData['segment_content']);
  2666. $segments[] = $segmentData;
  2667. }
  2668. $acts[] = [
  2669. 'act_number' => $actNumber,
  2670. 'act_title' => $actTitle,
  2671. 'act_details' => $actDetails,
  2672. 'segments' => $segments
  2673. ];
  2674. }
  2675. $result['acts'] = $acts;
  2676. }
  2677. return $result;
  2678. }
  2679. /**
  2680. * 处理剧本内容(全能模式)
  2681. */
  2682. function handleScriptContentForAce($originalContent) {
  2683. if (!$originalContent) return [];
  2684. // 使用更精确的正则表达式分割内容
  2685. $parts = [];
  2686. // // 确保内容使用UTF-8编码
  2687. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  2688. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  2689. // }
  2690. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2691. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2692. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2693. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2694. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2695. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2696. // 提取剧本亮点(支持多个空格)
  2697. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2698. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2699. // 提取人物关系(支持多个空格)
  2700. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2701. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2702. // 提取核心矛盾(支持多个空格)
  2703. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2704. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2705. // 提取主体列表(支持多个空格)
  2706. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2707. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2708. $parts['roles'] = parseRolesFromTextForAce($rolesText);
  2709. // 提取美术风格(支持多个空格)
  2710. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2711. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2712. // 提取场景列表(支持多个空格)
  2713. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2714. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2715. $parts['scenes'] = parseScenesFromText($scenesText);
  2716. // 提取道具列表(支持多个空格)
  2717. preg_match('/###\s*道具列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $propsMatch);
  2718. $propsText = isset($propsMatch[1]) ? trim($propsMatch[1]) : '';
  2719. $parts['props'] = parsePropsFromText($propsText);
  2720. // 提取分集详细内容(多剧集模式,支持多个空格)
  2721. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2722. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2723. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2724. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2725. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2726. // 优先使用原文内容,其次使用分集详细内容
  2727. $parts['content'] = $generatedContent ?: $detailedContent;
  2728. $parts['episode_title'] = '';
  2729. $parts['acts'] = [];
  2730. // 单剧集格式:顶层是大纲信息,分段部分采用 handleEpisodeContentForAce 的结构标准
  2731. $singleStoryboard = '';
  2732. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2733. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2734. } elseif (preg_match('/###\s*分段剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2735. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2736. }
  2737. if ($singleStoryboard !== '') {
  2738. // 构造符合 handleEpisodeContentForAce 期望的输入格式
  2739. $episodeContent = '';
  2740. // 如果分镜剧本内容不包含剧集标题,添加默认标题
  2741. if (!preg_match('/第\d+集[::\s]+/u', $singleStoryboard)) {
  2742. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  2743. $episodeContent = $defaultEpisodeTitle . "\n\n";
  2744. }
  2745. // 组装完整的剧集内容,按 handleEpisodeContentForAce 期望的结构
  2746. $episodeSections = [];
  2747. // 添加故事梗概(如果有)
  2748. if (!empty($parts['intro'])) {
  2749. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  2750. }
  2751. // 添加美术风格(如果有)
  2752. if (!empty($parts['art_style'])) {
  2753. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  2754. }
  2755. // 添加主体列表(如果有)
  2756. if (!empty($rolesText)) {
  2757. $episodeSections[] = "###主体列表\n" . $rolesText;
  2758. }
  2759. // 添加场景列表(如果有)
  2760. if (!empty($scenesText)) {
  2761. $episodeSections[] = "###场景列表\n" . $scenesText;
  2762. }
  2763. // 添加道具列表(如果有)
  2764. if (!empty($propsText)) {
  2765. $episodeSections[] = "###道具列表\n" . $propsText;
  2766. }
  2767. // 添加分镜剧本内容(兼容"分镜剧本"和"分段剧本")
  2768. if (strpos($singleStoryboard, '###分镜剧本') === false && strpos($singleStoryboard, '###分段剧本') === false) {
  2769. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  2770. } else {
  2771. $episodeSections[] = $singleStoryboard;
  2772. }
  2773. // 拼接完整内容
  2774. $episodeContent .= implode("\n\n", $episodeSections);
  2775. // 调用 handleEpisodeContentForAce 方法解析
  2776. $episode_arr = handleEpisodeContentForAce($episodeContent);
  2777. if (!empty($episode_arr['acts'])) {
  2778. $parts['episode_title'] = getProp($episode_arr, 'episode_title', '');
  2779. $parts['acts'] = getProp($episode_arr, 'acts', []);
  2780. }
  2781. // 更新roles、scenes和props
  2782. $episode_roles = getProp($episode_arr, 'roles');
  2783. $episode_scenes = getProp($episode_arr, 'scenes');
  2784. $episode_props = getProp($episode_arr, 'props');
  2785. if ($episode_roles) $parts['roles'] = $episode_roles;
  2786. if ($episode_scenes) $parts['scenes'] = $episode_scenes;
  2787. if ($episode_props) $parts['props'] = $episode_props;
  2788. }
  2789. // 如果上面的处理没有得到 acts,尝试直接用原始内容调用 handleEpisodeContentForAce
  2790. if (empty($parts['acts'])) {
  2791. $fallbackEpisodeArr = handleEpisodeContentForAce($originalContent);
  2792. if (!empty($fallbackEpisodeArr['acts'])) {
  2793. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title', '');
  2794. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  2795. if (empty($parts['intro'])) {
  2796. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro', '');
  2797. }
  2798. if (empty($parts['art_style'])) {
  2799. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style', '');
  2800. }
  2801. }
  2802. // 更新roles、scenes和props
  2803. $episode_roles = getProp($fallbackEpisodeArr, 'roles');
  2804. $episode_scenes = getProp($fallbackEpisodeArr, 'scenes');
  2805. $episode_props = getProp($fallbackEpisodeArr, 'props');
  2806. if ($episode_roles) $parts['roles'] = $episode_roles;
  2807. if ($episode_scenes) $parts['scenes'] = $episode_scenes;
  2808. if ($episode_props) $parts['props'] = $episode_props;
  2809. }
  2810. // 多剧集格式:继续兼容旧的分集剧本结构
  2811. $fullScript = '';
  2812. if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2813. $fullScript = trim($storyboardMatch[1]);
  2814. } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2815. $fullScript = trim($storyboardMatch[1]);
  2816. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2817. $fullScript = trim($storyboardMatch[1]);
  2818. }
  2819. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  2820. $fullScript = trim($fallbackMatch[1]);
  2821. }
  2822. $episodes = [];
  2823. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  2824. foreach ($matches as $match) {
  2825. $episodeNumber = (int)trim($match[1]);
  2826. $episodeName = trim($match[2]);
  2827. $episodeContent = trim($match[3]);
  2828. $segments = [];
  2829. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  2830. foreach ($segmentMatches as $segMatch) {
  2831. $segmentNumber = (int)trim($segMatch[1]);
  2832. $segmentContent = trim($segMatch[2]);
  2833. $segments[] = [
  2834. 'segment_number' => $segmentNumber,
  2835. 'segment_content' => $segmentContent,
  2836. ];
  2837. }
  2838. $episodes[] = [
  2839. 'episode_number' => $episodeNumber,
  2840. 'title' => $episodeName,
  2841. 'content' => $episodeContent,
  2842. 'segments' => $segments,
  2843. ];
  2844. }
  2845. if (empty($episodes) && !empty($parts['acts'])) {
  2846. $singleSegments = [];
  2847. foreach ($parts['acts'] as $act) {
  2848. $actSegments = getProp($act, 'segments', []);
  2849. if (!is_array($actSegments)) {
  2850. continue;
  2851. }
  2852. foreach ($actSegments as $segment) {
  2853. $singleSegments[] = [
  2854. 'segment_number' => getProp($segment, 'segment_number'),
  2855. 'segment_content' => getProp($segment, 'segment_content'),
  2856. ];
  2857. }
  2858. }
  2859. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  2860. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  2861. $episodes[] = [
  2862. 'episode_number' => 1,
  2863. 'title' => $episodeName,
  2864. 'content' => $singleStoryboard,
  2865. 'segments' => $singleSegments,
  2866. ];
  2867. }
  2868. $parts['episodes'] = $episodes;
  2869. return $parts;
  2870. }
  2871. /**
  2872. * 将主体列表文本拆分为主体数组
  2873. *
  2874. * @param string $rolesText 主体列表文本内容
  2875. * @return array 主体名称数组
  2876. */
  2877. function parseRolesFromTextForAce(string $rolesText): array
  2878. {
  2879. if (empty($rolesText)) {
  2880. return [];
  2881. }
  2882. $roles = [];
  2883. // 按行分割文本
  2884. $lines = explode("\n", $rolesText);
  2885. foreach ($lines as $line) {
  2886. $line = trim($line);
  2887. if (empty($line)) {
  2888. continue;
  2889. }
  2890. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2891. $role = trim($charMatch[1]);
  2892. $description = trim($charMatch[2]);
  2893. $timbreName = null;
  2894. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  2895. $picPrompt = null;
  2896. $timbrePrompt = null;
  2897. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  2898. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  2899. $description = trim($fullMatch[1]);
  2900. $picPrompt = trim($fullMatch[2]);
  2901. $timbrePrompt = trim($fullMatch[3]);
  2902. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2903. // 兼容旧格式:主体描述{{音色名}}
  2904. $description = trim($timbreMatch[1]);
  2905. $timbrePrompt = trim($timbreMatch[2]);
  2906. }
  2907. $roleData = [
  2908. 'role' => $role,
  2909. 'description' => $description,
  2910. ];
  2911. // 如果有主体图片提示词,添加到数组中
  2912. if ($picPrompt) $roleData['pic_prompt'] = $picPrompt;
  2913. // 如果有音色提示词,添加到数组中
  2914. if ($timbrePrompt) $roleData['voice_prompt'] = $timbrePrompt;
  2915. if ($timbreName) {
  2916. $timbre = DB::table('mp_timbres')
  2917. ->where('is_enabled', 1)
  2918. ->where('timbre_name', 'like', "%{$timbreName}%")
  2919. ->orderBy('id')
  2920. ->select('timbre_type', 'audio_url')
  2921. ->first();
  2922. if ($timbre) {
  2923. $roleData['voice_name'] = $timbreName;
  2924. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2925. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2926. }
  2927. }
  2928. // else {
  2929. // // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  2930. // if ($picPrompt) {
  2931. // if (strstr($picPrompt, '男')) {
  2932. // $roleData['voice_name'] = '阳光青年';
  2933. // }elseif (strstr($picPrompt, '女')) {
  2934. // $roleData['voice_name'] = '爽快思思';
  2935. // }else {
  2936. // if ($description) {
  2937. // if (strstr($description, '男')) {
  2938. // $roleData['voice_name'] = '阳光青年';
  2939. // }elseif (strstr($description, '女')) {
  2940. // $roleData['voice_name'] = '爽快思思';
  2941. // }else {
  2942. // $roleData['voice_name'] = '旁白';
  2943. // }
  2944. // }
  2945. // }
  2946. // }
  2947. // if (!empty($roleData['voice_name'])) {
  2948. // if ($roleData['voice_name'] == '旁白') {
  2949. // $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  2950. // $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  2951. // }else {
  2952. // $timbre = DB::table('mp_timbres')
  2953. // ->where('is_enabled', 1)
  2954. // ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  2955. // ->orderBy('id')
  2956. // ->select('timbre_type', 'audio_url')
  2957. // ->first();
  2958. // if ($timbre) {
  2959. // $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2960. // $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2961. // }
  2962. // }
  2963. // }
  2964. // }
  2965. $roles[] = $roleData;
  2966. }
  2967. }
  2968. $hasNarrator = false;
  2969. foreach ($roles as $role) {
  2970. if (getProp($role, 'role') === '旁白') {
  2971. $hasNarrator = true;
  2972. break;
  2973. }
  2974. }
  2975. if (!$hasNarrator) {
  2976. $roles[] = [
  2977. 'role' => '旁白',
  2978. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2979. 'pic_prompt' => '',
  2980. 'voice_prompt' => '',
  2981. // 'voice_name' => '旁白',
  2982. // 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2983. // 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2984. ];
  2985. }
  2986. return $roles;
  2987. }
  2988. function handleEpisodeContentForAce($originalContent) {
  2989. if (!$originalContent) return [];
  2990. // 解析剧集内容
  2991. $result = [
  2992. 'episode_title' => '',
  2993. 'intro' => '',
  2994. 'art_style' => '',
  2995. 'roles' => [],
  2996. 'scenes' => [],
  2997. 'props' => [],
  2998. 'acts' => []
  2999. ];
  3000. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  3001. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  3002. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  3003. }
  3004. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  3005. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  3006. $result['intro'] = trim($summaryMatch[1]);
  3007. }
  3008. // 提取美术风格 - 兼容多种格式
  3009. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  3010. $result['art_style'] = trim($styleMatch[1]);
  3011. }
  3012. // 提取主体列表 - 兼容多种格式
  3013. // 旧正则(2026-08-14 前):只允许 ### 与标题同行,初衷是防止板块为空时把后续"###分段剧本"当板块内容;
  3014. // 但不兼容模型偶发的"###\n主体列表"换行标题格式(如 mp_anime_records id=31915),导致 roles/scenes/props 解析为空。
  3015. // if (preg_match('/###[ \t]*主体列表[ \t]*\r?\n(.*?)(?=###[^#\n]|\z)/s', $originalContent, $charactersMatch)) {
  3016. // 新正则:开头 \s*? 非贪婪,兼容 ###主体列表、### 主体列表、###\n主体列表、###\n\n主体列表;
  3017. // 结束边界 (?=\n?\s*###[^#]|\z) 保证空板块(### 后直接跟下一章节)与换行标题格式都不会吞入后续内容。
  3018. if (preg_match('/###\s*?主体列表\s*?\r?\n(.*?)(?=\n?\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  3019. $charactersText = trim($charactersMatch[1]);
  3020. $characterLines = explode("\n", $charactersText);
  3021. foreach ($characterLines as $line) {
  3022. $line = trim($line);
  3023. if (empty($line)) continue;
  3024. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  3025. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  3026. $role = trim($charMatch[1]);
  3027. $description = trim($charMatch[2]);
  3028. $timbreName = null;
  3029. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  3030. $picPrompt = null;
  3031. $timbrePrompt = null;
  3032. // 修复正则:使用更精确的匹配,支持花括号嵌套
  3033. // 格式1: 描述{pic_prompt} {{voice_prompt}}
  3034. if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
  3035. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  3036. $description = trim($fullMatch[1]);
  3037. $picPrompt = trim($fullMatch[2]);
  3038. $timbrePrompt = trim($fullMatch[3]);
  3039. }
  3040. // 格式2: 描述{{voice_prompt}}(兼容旧格式,只有音色)
  3041. elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $timbreMatch)) {
  3042. // 兼容旧格式:主体描述{{音色名}}
  3043. $description = trim($timbreMatch[1]);
  3044. $timbrePrompt = trim($timbreMatch[2]);
  3045. }
  3046. // 格式3: 描述{pic_prompt}(只有图片提示词)
  3047. elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
  3048. $description = trim($picMatch[1]);
  3049. $picPrompt = trim($picMatch[2]);
  3050. }
  3051. $roleData = [
  3052. 'role' => $role,
  3053. 'description' => $description
  3054. ];
  3055. // 如果有主体图片提示词,添加到数组中
  3056. if ($picPrompt) {
  3057. // 检查开头是否有"全景,正面拍摄。"
  3058. $prefix = '全景,正面拍摄。';
  3059. $prefixParts = ['全景', '正面拍摄'];
  3060. // 检查是否包含完整前缀
  3061. if (strpos($picPrompt, $prefix) !== 0) {
  3062. // 检查是否包含部分前缀词汇(不论位置)
  3063. $hasAnyPrefix = false;
  3064. foreach ($prefixParts as $part) {
  3065. if (mb_strpos($picPrompt, $part) !== false) {
  3066. $hasAnyPrefix = true;
  3067. break;
  3068. }
  3069. }
  3070. if ($hasAnyPrefix) {
  3071. // 移除所有"全景"和"正面拍摄"词汇(包括它们后面的标点)
  3072. $picPrompt = preg_replace('/全景[,,、。. ]*/u', '', $picPrompt);
  3073. $picPrompt = preg_replace('/正面拍摄[,,、。. ]*/u', '', $picPrompt);
  3074. // 清理开头和结尾的标点符号和空格
  3075. $picPrompt = preg_replace('/^[。,,、 ]+|[。,,、 ]+$/u', '', $picPrompt);
  3076. }
  3077. // 在开头添加完整前缀
  3078. $picPrompt = $prefix . $picPrompt;
  3079. }
  3080. // 检查是否包含"姿态:"或"姿态:"
  3081. if (preg_match('/姿态[::]/u', $picPrompt)) {
  3082. // 如果有姿态描述,统一替换为"姿态:站立"
  3083. $picPrompt = preg_replace('/姿态[::][^.。\n]+/u', '姿态:站立', $picPrompt);
  3084. } else {
  3085. // 如果没有姿态描述,在末尾添加"姿态:站立"
  3086. $picPrompt = preg_replace('/[。,, ]+$/u', '', $picPrompt) . '。姿态:站立。';
  3087. }
  3088. $roleData['pic_prompt'] = $picPrompt;
  3089. }
  3090. if ($timbrePrompt) $roleData['voice_prompt'] = $timbrePrompt;
  3091. $result['roles'][] = $roleData;
  3092. }
  3093. }
  3094. // // 加入旁白角色(如果不存在)
  3095. // $hasNarrator = false;
  3096. // foreach ($result['roles'] as $role) {
  3097. // if (isset($role['role']) && $role['role'] === '旁白') {
  3098. // $hasNarrator = true;
  3099. // break;
  3100. // }
  3101. // }
  3102. // if (!$hasNarrator) {
  3103. // $result['roles'][] = [
  3104. // 'role' => '旁白',
  3105. // 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  3106. // 'pic_prompt' => '',
  3107. // 'voice_name' => '旁白',
  3108. // 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  3109. // 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  3110. // ];
  3111. // }
  3112. }
  3113. // 提取场景列表 - 兼容多种格式
  3114. // 旧正则(2026-08-14 前):只允许 ### 与标题同行,原因同上方主体列表,不兼容"###\n场景列表"换行标题格式。
  3115. // if (preg_match('/###[ \t]*场景列表[ \t]*\r?\n(.*?)(?=###[^#\n]|\z)/s', $originalContent, $scenesMatch)) {
  3116. if (preg_match('/###\s*?场景列表\s*?\r?\n(.*?)(?=\n?\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  3117. $scenesText = trim($scenesMatch[1]);
  3118. $sceneLines = explode("\n", $scenesText);
  3119. foreach ($sceneLines as $line) {
  3120. $line = trim($line);
  3121. if (empty($line)) continue;
  3122. // 兼容中文冒号:和英文冒号:
  3123. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  3124. $scene = trim($sceneMatch[1]);
  3125. $description = trim($sceneMatch[2]);
  3126. $picPrompt = null;
  3127. // 检查描述末尾是否有{场景图片提示词}或{场景图片提示词}{{补充说明}}格式
  3128. // 格式1: 描述{pic_prompt}{{补充说明}}(如"{...}{{无人物}}")
  3129. if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
  3130. $description = trim($fullMatch[1]);
  3131. $picPrompt = trim($fullMatch[2]);
  3132. }
  3133. // 格式2: 描述{{补充说明}}(只有补充说明,无图片提示词)
  3134. elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $voiceMatch)) {
  3135. $description = trim($voiceMatch[1]);
  3136. }
  3137. // 格式3: 描述{pic_prompt}(只有图片提示词)
  3138. elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
  3139. $description = trim($picMatch[1]);
  3140. $picPrompt = trim($picMatch[2]);
  3141. }
  3142. $sceneData = [
  3143. 'scene' => $scene,
  3144. 'description' => $description
  3145. ];
  3146. // 如果有场景图片提示词,添加到数组中
  3147. if ($picPrompt) {
  3148. $sceneData['pic_prompt'] = $picPrompt;
  3149. }
  3150. $result['scenes'][] = $sceneData;
  3151. }
  3152. }
  3153. }
  3154. // 提取道具列表 - 兼容多种格式
  3155. // 旧正则(2026-08-14 前):只允许 ### 与标题同行,原因同上方主体列表,不兼容"###\n道具列表"换行标题格式;
  3156. // 同时旧代码仅在提取到 pic_prompt 时才保存道具,用于兜底防止把分段剧本误当道具,代价是纯描述道具被丢弃。
  3157. // if (preg_match('/###[ \t]*道具列表[ \t]*\r?\n(.*?)(?=###[^#\n]|\z)/s', $originalContent, $propsMatch)) {
  3158. if (preg_match('/###\s*?道具列表\s*?\r?\n(.*?)(?=\n?\s*###[^#]|\z)/s', $originalContent, $propsMatch)) {
  3159. $propsText = trim($propsMatch[1]);
  3160. $propLines = explode("\n", $propsText);
  3161. foreach ($propLines as $line) {
  3162. $line = trim($line);
  3163. if (empty($line)) continue;
  3164. // 兼容中文冒号:和英文冒号:
  3165. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $propMatch)) {
  3166. $prop = trim($propMatch[1]);
  3167. $description = trim($propMatch[2]);
  3168. $picPrompt = null;
  3169. // 检查描述末尾是否有{道具图片提示词}或{道具图片提示词}{{音效提示词}}格式(与主体列表保持一致)
  3170. // 格式1: 描述{pic_prompt}{{voice_prompt}}(图片提示词+音效提示词)
  3171. if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
  3172. $description = trim($fullMatch[1]);
  3173. $picPrompt = trim($fullMatch[2]);
  3174. }
  3175. // 格式2: 描述{{voice_prompt}}(只有音效提示词)
  3176. elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $voiceMatch)) {
  3177. $description = trim($voiceMatch[1]);
  3178. }
  3179. // 格式3: 描述{pic_prompt}(只有图片提示词)
  3180. elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
  3181. $description = trim($picMatch[1]);
  3182. $picPrompt = trim($picMatch[2]);
  3183. }
  3184. $propData = [
  3185. 'prop' => $prop,
  3186. 'description' => $description
  3187. ];
  3188. // 新正则已精确切分道具板块,不再依赖"必须有提示词"兜底,纯描述道具也保留
  3189. if ($picPrompt) {
  3190. $propData['pic_prompt'] = $picPrompt;
  3191. }
  3192. $result['props'][] = $propData;
  3193. }
  3194. }
  3195. }
  3196. // 提取分镜剧本 - 兼容多种格式(旧格式:###分镜剧本,新格式:###分段剧本)
  3197. $storyboardPattern = '/###\s*(?:分镜剧本|分段剧本)\s*\n(.*?)(?=\n\s*###[^#]|\z)/s';
  3198. if (preg_match($storyboardPattern, $originalContent, $storyboardMatch)) {
  3199. $storyboardText = trim($storyboardMatch[1]);
  3200. // 提取旁白音色(新格式独有)
  3201. $narratorVoice = '';
  3202. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $storyboardText, $narratorMatch)) {
  3203. $narratorVoice = trim($narratorMatch[1]);
  3204. // 将旁白加入到roles数组
  3205. $hasNarrator = false;
  3206. foreach ($result['roles'] as $role) {
  3207. if (isset($role['role']) && $role['role'] === '旁白') {
  3208. $hasNarrator = true;
  3209. break;
  3210. }
  3211. }
  3212. if (!$hasNarrator) {
  3213. $result['roles'][] = [
  3214. 'role' => '旁白',
  3215. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  3216. 'pic_prompt' => '',
  3217. 'voice_prompt' => $narratorVoice
  3218. ];
  3219. }
  3220. }
  3221. // 按幕/片段分割 - 兼容"第X幕"和"片段X"两种格式
  3222. $acts = [];
  3223. // 先在开头添加换行符,确保第1幕/片段1也能被正确分割
  3224. $normalizedText = "\n" . $storyboardText;
  3225. $parts = preg_split('/\n\s*##/', $normalizedText);
  3226. foreach ($parts as $part) {
  3227. $part = trim($part);
  3228. if (empty($part)) continue;
  3229. // 兼容"第X幕"和"片段X"两种格式
  3230. if (!preg_match('/^(?:第\d+幕|片段\d+)/', $part)) {
  3231. continue;
  3232. }
  3233. // 分离标题和内容
  3234. $lines = explode("\n", $part, 2);
  3235. $actTitle = trim($lines[0]);
  3236. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  3237. // 解析标题,提取序号和详细信息
  3238. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  3239. // 旧格式:第X幕
  3240. $actNumber = intval($actTitleMatch[1]);
  3241. $actDetails = trim($actTitleMatch[2]);
  3242. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  3243. $actDetails = $actTitle;
  3244. }
  3245. } elseif (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  3246. // 新格式:片段X
  3247. $actNumber = intval($segmentTitleMatch[1]);
  3248. $actDetails = $actTitle;
  3249. } else {
  3250. $actNumber = count($acts) + 1;
  3251. $actDetails = $actTitle;
  3252. }
  3253. // 提取时长(新格式独有,仅保留数字)
  3254. $actDuration = '';
  3255. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  3256. $actDurationStr = trim($actDurationMatch[1]);
  3257. // 提取数字部分(支持整数和小数)
  3258. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  3259. $actDuration = $numMatch[1];
  3260. }
  3261. }
  3262. // 解析该幕/片段下的分镜
  3263. $segments = [];
  3264. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  3265. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  3266. foreach ($segmentMatches as $segmentMatch) {
  3267. $segmentNumber = intval($segmentMatch[1]);
  3268. $segmentContent = trim($segmentMatch[2]);
  3269. // 解析分镜详细信息
  3270. $segmentData = [
  3271. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT),
  3272. 'segment_number' => $segmentNumber,
  3273. 'segment_content' => $segmentContent,
  3274. 'description' => '',
  3275. 'composition' => '',
  3276. 'camera_movement' => '',
  3277. 'voice_actor' => '',
  3278. 'dialogue' => '',
  3279. 'frame_type' => '',
  3280. 'scene' => '',
  3281. 'characters' => '',
  3282. 'tail_frame' => '',
  3283. 'emotion' => '中性',
  3284. 'gender' => '0',
  3285. 'speed_ratio' => 0,
  3286. 'loudness_ratio' => 0,
  3287. 'emotion_scale' => 4,
  3288. 'pitch' => 0,
  3289. ];
  3290. // 提取场景
  3291. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3292. $segmentData['scene'] = trim($sceneMatch[1]);
  3293. }
  3294. // 提取画面描述 - 兼容新格式的方括号标注
  3295. if (preg_match('/(?:画面|画面描述|镜头描述|场景描述)[::]\s*(\[.*?\])?\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3296. $frameTypeInDesc = isset($descMatch[1]) ? trim($descMatch[1], '[]') : '';
  3297. $description = trim($descMatch[2]);
  3298. if (!empty($frameTypeInDesc)) {
  3299. $segmentData['frame_type'] = $frameTypeInDesc;
  3300. }
  3301. $segmentData['description'] = $description;
  3302. }
  3303. // 提取运镜
  3304. if (preg_match('/(?:运镜|运镜调度|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3305. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3306. }
  3307. // 提取配音台词 - 兼容新格式"中文配音:[角色] 台词"
  3308. // 修复:排除背景音效等非台词内容
  3309. if (preg_match('/配音台词[::]\s*(?:中文配音[::]?)?\s*(?:\[([^\]]+)\])?\s*([^\n]*?)(?=\n|$)/u', $segmentContent, $dialogueMatch)) {
  3310. $voiceActor = isset($dialogueMatch[1]) ? trim($dialogueMatch[1]) : '';
  3311. $dialogue = isset($dialogueMatch[2]) ? trim($dialogueMatch[2]) : '';
  3312. // 排除非台词内容(如果匹配到的是空或者是其他字段标记)
  3313. if (!empty($dialogue) && preg_match('/^(?:背景音效|音效|场景|画面|运镜|构图)[::]/u', $dialogue)) {
  3314. $dialogue = ''; // 如果匹配到的是其他字段,清空
  3315. }
  3316. if (!empty($voiceActor)) {
  3317. $segmentData['voice_actor'] = $voiceActor;
  3318. }
  3319. if ($dialogue && $dialogue !== '无') {
  3320. // 确保台词使用中文左右双引号
  3321. $dialogue = preg_replace('/^[""]/u', '"', $dialogue);
  3322. $dialogue = preg_replace('/[""]$/u', '"', $dialogue);
  3323. if (!preg_match('/^["]/', $dialogue)) {
  3324. $dialogue = '"' . $dialogue;
  3325. }
  3326. if (!preg_match('/["]$/', $dialogue)) {
  3327. $dialogue .= '"';
  3328. }
  3329. $segmentData['dialogue'] = $dialogue;
  3330. }
  3331. }
  3332. // 兼容旧格式的台词字段
  3333. // 修复:排除背景音效等非台词内容
  3334. if (empty($segmentData['dialogue']) && preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]*?)(?=\n|$)/u', $segmentContent, $oldDialogueMatch)) {
  3335. $dialogue = trim($oldDialogueMatch[1]);
  3336. // 排除非台词内容
  3337. if (!empty($dialogue) && preg_match('/^(?:背景音效|音效|场景|画面|运镜|构图)[::]/u', $dialogue)) {
  3338. $dialogue = ''; // 如果匹配到的是其他字段,清空
  3339. }
  3340. if ($dialogue && $dialogue !== '无') {
  3341. $dialogue = preg_replace('/^[""]/u', '"', $dialogue);
  3342. $dialogue = preg_replace('/[""]$/u', '"', $dialogue);
  3343. if (!preg_match('/^["]/', $dialogue)) {
  3344. $dialogue = '"' . $dialogue;
  3345. }
  3346. if (!preg_match('/["]$/', $dialogue)) {
  3347. $dialogue .= '"';
  3348. }
  3349. $segmentData['dialogue'] = $dialogue;
  3350. }
  3351. }
  3352. // 兼容旧格式的配音角色字段
  3353. if (empty($segmentData['voice_actor']) && preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3354. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3355. }
  3356. // 提取构图
  3357. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3358. $segmentData['composition'] = trim($compMatch[1]);
  3359. }
  3360. // 提取画面类型
  3361. if (empty($segmentData['frame_type']) && preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3362. $segmentData['frame_type'] = trim($frameMatch[1]);
  3363. }
  3364. // 提取出镜角色
  3365. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3366. $segmentData['characters'] = trim($charactersMatch[1]);
  3367. }
  3368. // 提取尾帧描述
  3369. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3370. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3371. }
  3372. $replaceEmptyArr = [];
  3373. // 提取情感
  3374. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3375. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3376. $segmentData['emotion'] = trim($emotionMatch[1]);
  3377. }
  3378. // 提取性别
  3379. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3380. $replaceEmptyArr[] = trim($genderMatch[0]);
  3381. $genderStr = trim($genderMatch[1]);
  3382. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3383. $segmentData['gender'] = '1';
  3384. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3385. $segmentData['gender'] = '2';
  3386. } else {
  3387. $segmentData['gender'] = '0';
  3388. }
  3389. }
  3390. // 提取语速
  3391. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3392. $replaceEmptyArr[] = trim($speedMatch[0]);
  3393. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3394. }
  3395. // 提取音量
  3396. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3397. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3398. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3399. }
  3400. // 提取情感强度
  3401. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3402. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3403. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3404. }
  3405. // 提取音调
  3406. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3407. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3408. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3409. }
  3410. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3411. $segmentData['segment_content'] = preg_replace('/\n{2,}/', "\n", $segmentData['segment_content']);
  3412. $segmentData['segment_content'] = trim($segmentData['segment_content']);
  3413. $segments[] = $segmentData;
  3414. }
  3415. $acts[] = [
  3416. 'act_number' => $actNumber,
  3417. 'act_title' => $actTitle,
  3418. 'act_details' => $actDetails,
  3419. 'act_duration' => $actDuration,
  3420. 'segments' => $segments
  3421. ];
  3422. }
  3423. $result['acts'] = $acts;
  3424. }
  3425. return $result;
  3426. }
  3427. /**
  3428. * 远程图片压缩(尽可能保持原图 fidelity,压缩到不超过 maxBytes 字节)
  3429. * 采用有损/无损组合策略:保留原始格式尽量不失真,若需要则通过尺寸缩放和质量调节来降低体积。
  3430. *
  3431. * @param string $url 远程图片 URL
  3432. * @param int $maxBytes 最大字节数,默认 3MB
  3433. * @param string|null $aspectRatio 目标长宽比,如 "16:9"、"4:3"、"1:1" 等,null 则保持原图比例
  3434. * @return string|null 返回压缩后的图片二进制数据,失败时返回 null
  3435. */
  3436. function compressRemoteImageUrlToSize(string $url, int $maxBytes = 3 * 1024 * 1024, ?string $aspectRatio = null): ?string
  3437. {
  3438. // 1) 下载图片数据(使用 Guzzle 以避免 allow_url_fopen 依赖)
  3439. try {
  3440. $client = new Client(['timeout' => 30]);
  3441. $response = $client->get($url, ['stream' => true]);
  3442. if ($response->getStatusCode() !== 200) {
  3443. return null;
  3444. }
  3445. $data = $response->getBody()->getContents();
  3446. } catch (\Exception $e) {
  3447. return null;
  3448. }
  3449. if (!$data) return null;
  3450. // 2) 识别图片类型
  3451. $imgInfo = @getimagesizefromstring($data);
  3452. $mime = $imgInfo['mime'] ?? '';
  3453. if ($mime == 'image/jpeg') return null; // JPEG 不做有损压缩
  3454. // 3) 载入图像对象
  3455. $srcImg = @imagecreatefromstring($data);
  3456. if (!$srcImg) {
  3457. return null;
  3458. }
  3459. $origW = imagesx($srcImg);
  3460. $origH = imagesy($srcImg);
  3461. // 3.2) 计算目标尺寸(根据长宽比调整)
  3462. $targetW = $origW;
  3463. $targetH = $origH;
  3464. if ($aspectRatio !== null) {
  3465. // 解析长宽比,如 "16:9" -> [16, 9]
  3466. $validRatios = array_keys(BaseConst::IMAGE_RATIOS);
  3467. if (in_array($aspectRatio, $validRatios)) {
  3468. list($ratioW, $ratioH) = explode(':', $aspectRatio);
  3469. $ratioW = (float)$ratioW;
  3470. $ratioH = (float)$ratioH;
  3471. $targetRatio = $ratioW / $ratioH;
  3472. $currentRatio = $origW / $origH;
  3473. // 根据目标比例裁剪图片
  3474. if ($currentRatio > $targetRatio) {
  3475. // 原图更宽,需要裁剪宽度
  3476. $targetW = (int)round($origH * $targetRatio);
  3477. $targetH = $origH;
  3478. } else {
  3479. // 原图更高,需要裁剪高度
  3480. $targetW = $origW;
  3481. $targetH = (int)round($origW / $targetRatio);
  3482. }
  3483. }
  3484. }
  3485. // 如果需要裁剪,创建裁剪后的图像
  3486. if ($targetW !== $origW || $targetH !== $origH) {
  3487. $croppedImg = imagecreatetruecolor($targetW, $targetH);
  3488. imagealphablending($croppedImg, false);
  3489. imagesavealpha($croppedImg, true);
  3490. // 处理透明背景
  3491. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3492. $transparent = imagecolorallocatealpha($croppedImg, 0, 0, 0, 127);
  3493. imagefill($croppedImg, 0, 0, $transparent);
  3494. }
  3495. // 居中裁剪
  3496. $srcX = (int)(($origW - $targetW) / 2);
  3497. $srcY = (int)(($origH - $targetH) / 2);
  3498. imagecopy($croppedImg, $srcImg, 0, 0, $srcX, $srcY, $targetW, $targetH);
  3499. // 替换原图
  3500. safeDestroyImage($srcImg);
  3501. $srcImg = $croppedImg;
  3502. $origW = $targetW;
  3503. $origH = $targetH;
  3504. }
  3505. // 3.1) 内部渲染成不同格式的字符串
  3506. $render = function($srcRes, string $mimeType, int $quality) {
  3507. ob_start();
  3508. switch (strtolower($mimeType)) {
  3509. case 'image/jpeg':
  3510. case 'image/jpg':
  3511. case 'image/pjpeg':
  3512. // 输出 JPEG
  3513. imagejpeg($srcRes, null, $quality);
  3514. break;
  3515. case 'image/png':
  3516. // 将 quality 映射到 PNG 的 compression level (0-9)
  3517. $level = (int)round((100 - $quality) / 11.11);
  3518. if ($level < 0) $level = 0;
  3519. if ($level > 9) $level = 9;
  3520. imagepng($srcRes, null, $level);
  3521. break;
  3522. case 'image/webp':
  3523. if (function_exists('imagewebp')) {
  3524. imagewebp($srcRes, null, $quality);
  3525. } else {
  3526. imagejpeg($srcRes, null, $quality);
  3527. }
  3528. break;
  3529. default:
  3530. imagejpeg($srcRes, null, $quality);
  3531. break;
  3532. }
  3533. $out = ob_get_contents();
  3534. ob_end_clean();
  3535. return $out;
  3536. };
  3537. // 4) 尝试策略:尽量保留原图尺寸,逐步降维/降质量,直到 <= maxBytes
  3538. $tryList = [];
  3539. // 原始尺寸,尽量保留
  3540. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>100];
  3541. // 逐步缩小尺寸
  3542. for ($s = 0.9; $s >= 0.2; $s -= 0.1) {
  3543. $tryList[] = ['scale'=>$s, 'mime'=>$mime, 'quality'=>90];
  3544. }
  3545. // 一系列质量等级(用于 JPEG/WebP)
  3546. $qualityLevels = [95, 90, 85, 75, 60, 50, 40, 30];
  3547. foreach ($qualityLevels as $q) {
  3548. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>$q];
  3549. }
  3550. $bestData = null;
  3551. foreach ($tryList as $cand) {
  3552. $scale = isset($cand['scale']) ? (float)$cand['scale'] : 1.0;
  3553. $mimeT = $cand['mime'] ?? $mime;
  3554. $quality = isset($cand['quality']) ? (int)$cand['quality'] : 90;
  3555. $w = (int)round($origW * $scale);
  3556. $h = (int)round($origH * $scale);
  3557. $src = $srcImg;
  3558. $tempImg = null;
  3559. if ($scale < 1.0) {
  3560. $tempImg = imagecreatetruecolor($w, $h);
  3561. // 处理透明通道
  3562. imagealphablending($tempImg, false);
  3563. imagesavealpha($tempImg, true);
  3564. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3565. $transparent = imagecolorallocatealpha($tempImg, 0, 0, 0, 127);
  3566. imagefill($tempImg, 0, 0, $transparent);
  3567. }
  3568. // 确保 $srcImg 有效
  3569. if (!$srcImg || (!is_resource($srcImg) && !($srcImg instanceof \GdImage))) {
  3570. safeDestroyImage($tempImg);
  3571. continue;
  3572. }
  3573. imagecopyresampled($tempImg, $srcImg, 0, 0, 0, 0, $w, $h, $origW, $origH);
  3574. $src = $tempImg;
  3575. }
  3576. $imageBytes = $render($src, $mimeT, $quality);
  3577. if ($tempImg !== null) {
  3578. safeDestroyImage($tempImg);
  3579. }
  3580. if ($imageBytes !== false && strlen($imageBytes) <= $maxBytes) {
  3581. $bestData = $imageBytes;
  3582. break;
  3583. }
  3584. }
  3585. // 5) 回退策略:若仍未达到要求,尝试更大幅度降解到一个合理的小尺寸 JPEG
  3586. if ($bestData === null) {
  3587. $tmpW = max(1, (int)round($origW * 0.5));
  3588. $tmpH = max(1, (int)round($origH * 0.5));
  3589. $tmpImg = imagecreatetruecolor($tmpW, $tmpH);
  3590. imagealphablending($tmpImg, false);
  3591. imagesavealpha($tmpImg, true);
  3592. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3593. $transparent = imagecolorallocatealpha($tmpImg, 0, 0, 0, 127);
  3594. imagefill($tmpImg, 0, 0, $transparent);
  3595. }
  3596. imagecopyresampled($tmpImg, $srcImg, 0, 0, 0, 0, $tmpW, $tmpH, $origW, $origH);
  3597. ob_start();
  3598. if (in_array(strtolower($mime), ['image/jpeg','image/jpg','image/pjpeg'])) {
  3599. imagejpeg($tmpImg, null, 75);
  3600. } elseif (strtolower($mime) === 'image/png') {
  3601. imagepng($tmpImg, null, 6);
  3602. } elseif (function_exists('imagewebp')) {
  3603. imagewebp($tmpImg, null, 75);
  3604. } else {
  3605. imagejpeg($tmpImg, null, 75);
  3606. }
  3607. $tmpBytes = ob_get_contents();
  3608. ob_end_clean();
  3609. safeDestroyImage($tmpImg);
  3610. if ($tmpBytes !== '' && strlen($tmpBytes) <= $maxBytes) {
  3611. $bestData = $tmpBytes;
  3612. }
  3613. }
  3614. // 6) 清理
  3615. safeDestroyImage($srcImg);
  3616. return $bestData;
  3617. }
  3618. /**
  3619. * 安全销毁 GD 图像资源(兼容 PHP7.4+ 的资源管理)
  3620. * 通过引用传递并在销毁后置空变量,避免未定义变量的问题
  3621. *
  3622. * @param resource|\GdImage|null &$img GD 图像资源或对象(PHP7.4 为 resource,PHP8.0+ 为 GdImage)
  3623. */
  3624. function safeDestroyImage(&$img)
  3625. {
  3626. if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
  3627. @imagedestroy($img);
  3628. }
  3629. $img = null;
  3630. }
  3631. /**
  3632. * 图片超清(超分辨率)放大
  3633. *
  3634. * 默认使用 FFmpeg(Lanczos + unsharp)进行放大,画质优于 GD;
  3635. * 本地环境(APP_ENV=local)或服务器未安装 FFmpeg 时自动回退到 GD 插值放大,
  3636. * 使用 GD 前会先检查 GD 扩展是否可用,避免报错。
  3637. * 说明:插值放大不会像 AI 超分那样生成全新细节,但零外部 API、可实时完成。
  3638. *
  3639. * 参数:
  3640. * - image_url string 必填 原图 URL(https)或服务器本地绝对路径
  3641. * - target string 可选 目标档位:1080p / 2k / 4k,默认 4k(按长边放大)
  3642. * - width int 可选 指定目标宽度(与 height 同时传时优先于 target)
  3643. * - height int 可选 指定目标高度
  3644. * - format string 可选 输出格式:jpg / png / webp,默认保持原图格式
  3645. * (gif 转 png;webp 带透明转 png、无透明转 jpg)
  3646. * - quality int 可选 输出质量 1-100,默认 95(jpg/webp 生效)
  3647. * - sharpen bool 可选 是否锐化,默认 true
  3648. * - sharpen_amount float 可选 锐化强度 0-2,默认 0.35
  3649. * - upload bool 可选 是否上传 TOS 返回 URL,默认 true;false 时返回 base64
  3650. * - driver string 可选 处理驱动:ffmpeg(默认)/ gd;本地环境强制跳过 ffmpeg
  3651. *
  3652. * @param array $params
  3653. * @return array
  3654. * @throws \InvalidArgumentException|\RuntimeException
  3655. */
  3656. function upscaleImage(array $params): array
  3657. {
  3658. $imageUrl = trim((string)($params['image_url'] ?? ''));
  3659. if ($imageUrl === '') {
  3660. throw new \InvalidArgumentException('image_url不能为空');
  3661. }
  3662. // 读取图片二进制(支持远程URL和本地路径)
  3663. $binary = @file_get_contents($imageUrl);
  3664. if ($binary === false || strlen($binary) === 0) {
  3665. throw new \RuntimeException('图片读取失败: ' . $imageUrl);
  3666. }
  3667. $info = @getimagesizefromstring($binary);
  3668. if ($info === false) {
  3669. throw new \RuntimeException('无法识别的图片格式: ' . $imageUrl);
  3670. }
  3671. $srcWidth = max(1, (int)$info[0]);
  3672. $srcHeight = max(1, (int)$info[1]);
  3673. $srcType = (int)($info[2] ?? IMAGETYPE_PNG);
  3674. // WebP 默认输出格式取决于是否带透明通道(有透明转PNG保留透明,无透明转JPG控制体积)
  3675. $srcHasAlpha = $srcType === IMAGETYPE_WEBP && upscaleImageHasAlpha($binary);
  3676. // 计算目标尺寸
  3677. [$dstWidth, $dstHeight] = upscaleImageResolveTargetDimensions($srcWidth, $srcHeight, $params);
  3678. // 目标尺寸不比原图大时不降采样,直接返回原图
  3679. if ($dstWidth <= $srcWidth && $dstHeight <= $srcHeight) {
  3680. return [
  3681. 'url' => $imageUrl,
  3682. 'base64' => null,
  3683. 'width' => $srcWidth,
  3684. 'height' => $srcHeight,
  3685. 'src_width' => $srcWidth,
  3686. 'src_height' => $srcHeight,
  3687. 'upscaled' => false,
  3688. 'driver' => 'original',
  3689. ];
  3690. }
  3691. // 驱动选择:默认 ffmpeg;本地环境跳过 ffmpeg;ffmpeg 不可用时回退 gd;
  3692. // 使用 gd 前先检查 GD 扩展是否可用,防止报错
  3693. $driver = strtolower((string)($params['driver'] ?? 'ffmpeg'));
  3694. if (!in_array($driver, ['ffmpeg', 'gd'], true)) {
  3695. throw new \InvalidArgumentException('不支持的driver: ' . $driver . '(可选: gd / ffmpeg)');
  3696. }
  3697. $isLocal = env('APP_ENV') === 'local';
  3698. $useFfmpeg = false;
  3699. $useGd = false;
  3700. if ($driver === 'ffmpeg') {
  3701. if ($isLocal) {
  3702. // 本地环境跳过 ffmpeg,使用 GD 超分
  3703. $useGd = true;
  3704. } elseif (upscaleImageIsFfmpegAvailable((string)env('FFMPEG_PATH', 'ffmpeg'))) {
  3705. $useFfmpeg = true;
  3706. } else {
  3707. // 线上未安装 ffmpeg,回退 GD 超分
  3708. $useGd = true;
  3709. }
  3710. } else {
  3711. $useGd = true;
  3712. }
  3713. if ($useGd && !upscaleImageGdAvailable()) {
  3714. $reason = $isLocal ? '本地环境已跳过FFmpeg' : 'FFmpeg不可用';
  3715. throw new \RuntimeException($reason . ',且当前PHP环境缺少GD扩展,无法进行图片超分');
  3716. }
  3717. if ($useFfmpeg) {
  3718. return upscaleImageWithFfmpeg(
  3719. $params,
  3720. $binary,
  3721. $srcType,
  3722. $srcHasAlpha,
  3723. $srcWidth,
  3724. $srcHeight,
  3725. $dstWidth,
  3726. $dstHeight
  3727. );
  3728. }
  3729. return upscaleImageWithGd(
  3730. $params,
  3731. $binary,
  3732. $srcType,
  3733. $srcHasAlpha,
  3734. $srcWidth,
  3735. $srcHeight,
  3736. $dstWidth,
  3737. $dstHeight
  3738. );
  3739. }
  3740. /**
  3741. * 使用 GD 进行图片超分放大(Blackman/Bicubic 插值 + 卷积锐化)
  3742. *
  3743. * @param array $params
  3744. * @param string $binary 图片二进制内容
  3745. * @param int $srcType 原图类型(IMAGETYPE_*)
  3746. * @param bool $srcHasAlpha 原图是否带透明通道(WebP 默认格式判断用)
  3747. * @param int $srcWidth
  3748. * @param int $srcHeight
  3749. * @param int $dstWidth
  3750. * @param int $dstHeight
  3751. * @return array
  3752. * @throws \RuntimeException
  3753. */
  3754. function upscaleImageWithGd(
  3755. array $params,
  3756. string $binary,
  3757. int $srcType,
  3758. bool $srcHasAlpha,
  3759. int $srcWidth,
  3760. int $srcHeight,
  3761. int $dstWidth,
  3762. int $dstHeight
  3763. ): array {
  3764. // 4K 放大峰值内存较高:目标图(4B/像素) + 锐化卷积临时缓冲(4B/像素) + 源图 + 编码缓冲,
  3765. // 按需临时提升内存限制,避免超过默认 128M 报 FatalError
  3766. upscaleImageEnsureMemory(
  3767. $dstWidth * $dstHeight * 8 + $srcWidth * $srcHeight * 4 + 96 * 1024 * 1024
  3768. );
  3769. $srcImg = @imagecreatefromstring($binary);
  3770. if (!$srcImg) {
  3771. throw new \RuntimeException('图片解码失败');
  3772. }
  3773. $dstImg = null;
  3774. try {
  3775. // 高质量插值放大(Blackman 优于 Bicubic,PHP7.4 低版本需回退)
  3776. $filter = defined('IMG_BLACKMAN') ? IMG_BLACKMAN : IMG_BICUBIC;
  3777. $dstImg = imagescale($srcImg, $dstWidth, $dstHeight, $filter);
  3778. if (!$dstImg) {
  3779. throw new \RuntimeException('图片放大失败');
  3780. }
  3781. // 缩放完成后原图不再需要,提前释放以降低内存峰值
  3782. safeDestroyImage($srcImg);
  3783. // 可选锐化,弥补插值放大后的发虚感
  3784. $sharpen = (bool)($params['sharpen'] ?? true);
  3785. $sharpenAmount = (float)($params['sharpen_amount'] ?? 0.35);
  3786. if ($sharpen && $sharpenAmount > 0.01 && function_exists('imageconvolution')) {
  3787. upscaleImageSharpen($dstImg, min(2.0, max(0.01, $sharpenAmount)));
  3788. }
  3789. // 确定输出格式并编码
  3790. $format = upscaleImageResolveOutputFormat($params, $srcType, $srcHasAlpha);
  3791. $quality = max(1, min(100, (int)($params['quality'] ?? 95)));
  3792. $encoded = upscaleImageEncode($dstImg, $format, $quality);
  3793. if ($encoded === null) {
  3794. throw new \RuntimeException('图片编码失败,不支持的输出格式: ' . $format);
  3795. }
  3796. return upscaleImageBuildResult(
  3797. $params,
  3798. $encoded,
  3799. $format,
  3800. $dstWidth,
  3801. $dstHeight,
  3802. $srcWidth,
  3803. $srcHeight,
  3804. 'gd'
  3805. );
  3806. } finally {
  3807. safeDestroyImage($srcImg);
  3808. safeDestroyImage($dstImg);
  3809. }
  3810. }
  3811. /**
  3812. * 使用 FFmpeg 进行图片超分放大(Lanczos 插值 + unsharp 锐化)
  3813. *
  3814. * 与视频超分保持一致的 ffmpeg 用法,仅当 ffmpeg 可用时进入。
  3815. *
  3816. * @param array $params
  3817. * @param string $binary 图片二进制内容
  3818. * @param int $srcType 原图类型(IMAGETYPE_*)
  3819. * @param bool $srcHasAlpha 原图是否带透明通道(WebP 默认格式判断用)
  3820. * @param int $srcWidth
  3821. * @param int $srcHeight
  3822. * @param int $dstWidth
  3823. * @param int $dstHeight
  3824. * @return array
  3825. * @throws \RuntimeException
  3826. */
  3827. function upscaleImageWithFfmpeg(
  3828. array $params,
  3829. string $binary,
  3830. int $srcType,
  3831. bool $srcHasAlpha,
  3832. int $srcWidth,
  3833. int $srcHeight,
  3834. int $dstWidth,
  3835. int $dstHeight
  3836. ): array {
  3837. $ffmpegPath = (string)env('FFMPEG_PATH', 'ffmpeg');
  3838. // 创建临时目录
  3839. $tempDir = storage_path('app/temp/images');
  3840. if (!is_dir($tempDir)) {
  3841. @mkdir($tempDir, 0775, true);
  3842. }
  3843. $format = upscaleImageResolveOutputFormat($params, $srcType, $srcHasAlpha);
  3844. $ext = $format === 'jpeg' ? 'jpg' : $format;
  3845. $quality = max(1, min(100, (int)($params['quality'] ?? 95)));
  3846. $uniqueId = 'img_upscale_' . date('YmdHis') . '_' . uniqid() . '_' . bin2hex(random_bytes(4));
  3847. $inputFile = $tempDir . '/' . $uniqueId . '_input';
  3848. $outputFile = $tempDir . '/' . $uniqueId . '_output.' . $ext;
  3849. try {
  3850. if (file_put_contents($inputFile, $binary) === false) {
  3851. throw new \RuntimeException('图片写入临时文件失败');
  3852. }
  3853. // 构建滤镜链:Lanczos 缩放 + unsharp 锐化(亮度通道)
  3854. $filters = ['scale=' . $dstWidth . ':' . $dstHeight . ':flags=lanczos'];
  3855. $sharpen = (bool)($params['sharpen'] ?? true);
  3856. if ($sharpen) {
  3857. $sharpenAmount = (float)($params['sharpen_amount'] ?? 0.35);
  3858. $luma = number_format(min(2.0, max(0.1, $sharpenAmount * 2)), 2, '.', '');
  3859. $filters[] = 'unsharp=5:5:' . $luma . ':5:5:0.0';
  3860. }
  3861. $encodeArgs = upscaleImageBuildFfmpegEncodeArgs($format, $quality);
  3862. $ffmpegCmd = escapeshellarg($ffmpegPath)
  3863. . ' -y -i ' . escapeshellarg($inputFile)
  3864. . ' -vf ' . escapeshellarg(implode(',', $filters))
  3865. . ' ' . $encodeArgs
  3866. . ' ' . escapeshellarg($outputFile)
  3867. . ' 2>&1';
  3868. dLog('generate')->info('FFmpeg图片放大命令', ['command' => $ffmpegCmd]);
  3869. $output = shell_exec($ffmpegCmd);
  3870. if (!file_exists($outputFile) || filesize($outputFile) === 0) {
  3871. throw new \RuntimeException('FFmpeg图片放大失败: ' . trim((string)$output));
  3872. }
  3873. $encoded = file_get_contents($outputFile);
  3874. if ($encoded === false || strlen($encoded) === 0) {
  3875. throw new \RuntimeException('FFmpeg放大结果读取失败');
  3876. }
  3877. return upscaleImageBuildResult(
  3878. $params,
  3879. $encoded,
  3880. $format,
  3881. $dstWidth,
  3882. $dstHeight,
  3883. $srcWidth,
  3884. $srcHeight,
  3885. 'ffmpeg'
  3886. );
  3887. } finally {
  3888. @unlink($inputFile);
  3889. @unlink($outputFile);
  3890. }
  3891. }
  3892. /**
  3893. * 检查 GD 扩展是否可用于图片超分
  3894. *
  3895. * @return bool
  3896. */
  3897. function upscaleImageGdAvailable(): bool
  3898. {
  3899. return extension_loaded('gd')
  3900. && function_exists('imagecreatefromstring')
  3901. && function_exists('imagescale');
  3902. }
  3903. /**
  3904. * 获取当前 PHP 内存限制(字节),-1 表示无限制
  3905. *
  3906. * @return int
  3907. */
  3908. function upscaleImageMemoryLimitBytes(): int
  3909. {
  3910. $val = trim((string)ini_get('memory_limit'));
  3911. if ($val === '' || $val === '-1') {
  3912. return -1;
  3913. }
  3914. $unit = strtoupper(substr($val, -1));
  3915. $num = (float)$val;
  3916. switch ($unit) {
  3917. case 'G':
  3918. return (int)($num * 1024 * 1024 * 1024);
  3919. case 'M':
  3920. return (int)($num * 1024 * 1024);
  3921. case 'K':
  3922. return (int)($num * 1024);
  3923. default:
  3924. return (int)$num;
  3925. }
  3926. }
  3927. /**
  3928. * 确保 PHP 内存限制满足图片超分需要(只升不降;已是无限制时不做处理)
  3929. *
  3930. * 4K 放大时源图解码、目标图、锐化卷积缓冲同时存在,峰值内存较大,
  3931. * 按目标尺寸估算并临时调高 memory_limit,避免 FatalError OOM。
  3932. *
  3933. * @param int $neededBytes 预估需要的内存字节数
  3934. * @return void
  3935. */
  3936. function upscaleImageEnsureMemory(int $neededBytes): void
  3937. {
  3938. $current = upscaleImageMemoryLimitBytes();
  3939. if ($current > 0 && $neededBytes > $current) {
  3940. @ini_set('memory_limit', (string)(int)ceil($neededBytes / (1024 * 1024)) . 'M');
  3941. }
  3942. }
  3943. /**
  3944. * 检查 ffmpeg 是否可用
  3945. *
  3946. * @param string $ffmpegPath
  3947. * @return bool
  3948. */
  3949. function upscaleImageIsFfmpegAvailable(string $ffmpegPath): bool
  3950. {
  3951. // 配置了绝对路径时直接检查文件
  3952. if (strpos($ffmpegPath, '/') !== false || strpos($ffmpegPath, '\\') !== false) {
  3953. return file_exists($ffmpegPath);
  3954. }
  3955. $cmd = (PHP_OS_FAMILY === 'Windows')
  3956. ? 'where ' . escapeshellarg($ffmpegPath) . ' 2>NUL'
  3957. : 'command -v ' . escapeshellarg($ffmpegPath) . ' 2>/dev/null';
  3958. $output = @shell_exec($cmd);
  3959. return !empty(trim((string)$output));
  3960. }
  3961. /**
  3962. * 构建 ffmpeg 图片输出编码参数
  3963. *
  3964. * @param string $format
  3965. * @param int $quality
  3966. * @return string
  3967. */
  3968. function upscaleImageBuildFfmpegEncodeArgs(string $format, int $quality): string
  3969. {
  3970. switch ($format) {
  3971. case 'jpg':
  3972. case 'jpeg':
  3973. // mjpeg 质量范围 2-31,2 最佳
  3974. return '-frames:v 1 -q:v ' . (2 + (int)round((100 - $quality) / 100 * 29));
  3975. case 'png':
  3976. return '-frames:v 1 -compression_level ' . max(0, min(9, (int)round((100 - $quality) / 10)));
  3977. case 'webp':
  3978. return '-frames:v 1 -q:v ' . (2 + (int)round((100 - $quality) / 100 * 29));
  3979. }
  3980. return '-frames:v 1';
  3981. }
  3982. /**
  3983. * 确定放大后的输出格式
  3984. *
  3985. * @param array $params
  3986. * @param int $srcType
  3987. * @param bool $srcHasAlpha 原图是否带透明通道
  3988. * @return string
  3989. */
  3990. function upscaleImageResolveOutputFormat(array $params, int $srcType, bool $srcHasAlpha = false): string
  3991. {
  3992. $format = strtolower((string)($params['format'] ?? ''));
  3993. if (in_array($format, ['jpg', 'jpeg', 'png', 'webp'], true)) {
  3994. return $format;
  3995. }
  3996. return upscaleImageGuessFormatByType($srcType, $srcHasAlpha);
  3997. }
  3998. /**
  3999. * 根据图片类型推断默认输出格式
  4000. *
  4001. * @param int $srcType
  4002. * @param bool $srcHasAlpha 原图是否带透明通道
  4003. * @return string
  4004. */
  4005. function upscaleImageGuessFormatByType(int $srcType, bool $srcHasAlpha = false): string
  4006. {
  4007. switch ($srcType) {
  4008. case IMAGETYPE_PNG:
  4009. return 'png';
  4010. case IMAGETYPE_WEBP:
  4011. // 带透明通道的 WebP 转 PNG 保留透明,否则转 JPG 控制体积
  4012. return $srcHasAlpha ? 'png' : 'jpg';
  4013. case IMAGETYPE_GIF:
  4014. return 'png'; // GIF 转 PNG,保留透明通道
  4015. case IMAGETYPE_JPEG:
  4016. default:
  4017. return 'jpg';
  4018. }
  4019. }
  4020. /**
  4021. * 检测图片二进制是否带透明通道(目前用于 WebP 默认输出格式判断)
  4022. *
  4023. * 通过解析容器头判断,不整图解码,速度快:
  4024. * - WebP: ALPH 块存在、VP8X 扩展头的 ALPHA 标志位、VP8L 无损格式的 alpha 标志
  4025. *
  4026. * @param string $binary
  4027. * @return bool
  4028. */
  4029. function upscaleImageHasAlpha(string $binary): bool
  4030. {
  4031. if (strlen($binary) < 16 || substr($binary, 0, 4) !== 'RIFF' || substr($binary, 8, 4) !== 'WEBP') {
  4032. return false;
  4033. }
  4034. $offset = 12;
  4035. $len = strlen($binary);
  4036. while ($offset + 8 <= $len) {
  4037. $fourcc = substr($binary, $offset, 4);
  4038. $chunkSize = (int)unpack('V', substr($binary, $offset + 4, 4))[1];
  4039. if ($fourcc === 'ALPH') {
  4040. return true;
  4041. }
  4042. if ($fourcc === 'VP8X' && $chunkSize >= 1) {
  4043. // VP8X 扩展头标志字节:bit4(0x10)=ALPHA
  4044. return (ord($binary[$offset + 8]) & 0x10) !== 0;
  4045. }
  4046. if ($fourcc === 'VP8L' && $chunkSize >= 1) {
  4047. // VP8L 无损格式:首字节 bit2=alpha_is_used
  4048. return ((ord($binary[$offset + 8]) >> 2) & 1) !== 0;
  4049. }
  4050. if ($chunkSize <= 0) {
  4051. break;
  4052. }
  4053. // RIFF 块数据为奇数长度时补 1 字节对齐
  4054. $offset += 8 + $chunkSize + ($chunkSize % 2);
  4055. }
  4056. return false;
  4057. }
  4058. /**
  4059. * 使用卷积矩阵对图片进行锐化(C级实现,速度快)
  4060. *
  4061. * @param resource|\GdImage $img
  4062. * @param float $amount 锐化强度 0-2
  4063. * @return void
  4064. */
  4065. function upscaleImageSharpen($img, float $amount): void
  4066. {
  4067. $neighbor = -$amount;
  4068. $center = 1 + 4 * $amount;
  4069. imageconvolution($img, [
  4070. [0, $neighbor, 0],
  4071. [$neighbor, $center, $neighbor],
  4072. [0, $neighbor, 0],
  4073. ], 1, 0);
  4074. }
  4075. /**
  4076. * 将 GD 图像编码为指定格式的二进制
  4077. *
  4078. * @param resource|\GdImage $img
  4079. * @param string $format
  4080. * @param int $quality
  4081. * @return string|null 失败返回 null
  4082. */
  4083. function upscaleImageEncode($img, string $format, int $quality): ?string
  4084. {
  4085. $encoded = null;
  4086. ob_start();
  4087. try {
  4088. switch ($format) {
  4089. case 'jpg':
  4090. case 'jpeg':
  4091. imagejpeg($img, null, $quality);
  4092. break;
  4093. case 'png':
  4094. // 显式开启 alpha 通道保存,否则透明区域会丢失
  4095. imagesavealpha($img, true);
  4096. // quality 100-1 映射到 PNG 压缩级别 0-9
  4097. imagepng($img, null, (int)round((100 - $quality) / 10));
  4098. break;
  4099. case 'webp':
  4100. if (!function_exists('imagewebp')) {
  4101. throw new \RuntimeException('GD扩展不支持WebP输出');
  4102. }
  4103. imagesavealpha($img, true);
  4104. imagewebp($img, null, $quality);
  4105. break;
  4106. default:
  4107. throw new \RuntimeException('不支持的输出格式: ' . $format);
  4108. }
  4109. $encoded = ob_get_clean();
  4110. } catch (\Throwable $e) {
  4111. ob_end_clean();
  4112. $encoded = null;
  4113. }
  4114. return $encoded;
  4115. }
  4116. /**
  4117. * 组装放大结果:上传 TOS 返回 URL,或返回 base64
  4118. *
  4119. * @param array $params
  4120. * @param string $encoded
  4121. * @param string $format
  4122. * @param int $dstWidth
  4123. * @param int $dstHeight
  4124. * @param int $srcWidth
  4125. * @param int $srcHeight
  4126. * @param string $driver
  4127. * @return array
  4128. * @throws \RuntimeException
  4129. */
  4130. function upscaleImageBuildResult(
  4131. array $params,
  4132. string $encoded,
  4133. string $format,
  4134. int $dstWidth,
  4135. int $dstHeight,
  4136. int $srcWidth,
  4137. int $srcHeight,
  4138. string $driver
  4139. ): array {
  4140. $upload = (bool)($params['upload'] ?? true);
  4141. if ($upload) {
  4142. $ext = $format === 'jpeg' ? 'jpg' : $format;
  4143. $filename = 'upscale_' . date('YmdHis') . '_' . uniqid() . '.' . $ext;
  4144. $url = uploadStreamByTos('image', $encoded, $filename);
  4145. if (!$url) {
  4146. throw new \RuntimeException('放大图片上传TOS失败');
  4147. }
  4148. return [
  4149. 'url' => $url,
  4150. 'base64' => null,
  4151. 'width' => $dstWidth,
  4152. 'height' => $dstHeight,
  4153. 'src_width' => $srcWidth,
  4154. 'src_height' => $srcHeight,
  4155. 'upscaled' => true,
  4156. 'driver' => $driver,
  4157. ];
  4158. }
  4159. $mime = $format === 'jpg' || $format === 'jpeg' ? 'image/jpeg' : 'image/' . $format;
  4160. return [
  4161. 'url' => null,
  4162. 'base64' => 'data:' . $mime . ';base64,' . base64_encode($encoded),
  4163. 'width' => $dstWidth,
  4164. 'height' => $dstHeight,
  4165. 'src_width' => $srcWidth,
  4166. 'src_height' => $srcHeight,
  4167. 'upscaled' => true,
  4168. 'driver' => $driver,
  4169. ];
  4170. }
  4171. /**
  4172. * 计算放大后的目标尺寸
  4173. *
  4174. * @param int $srcWidth
  4175. * @param int $srcHeight
  4176. * @param array $params
  4177. * @return array [width, height]
  4178. */
  4179. function upscaleImageResolveTargetDimensions(int $srcWidth, int $srcHeight, array $params): array
  4180. {
  4181. $width = (int)($params['width'] ?? 0);
  4182. $height = (int)($params['height'] ?? 0);
  4183. // 显式指定宽高时,按指定尺寸处理(支持只传其中一个,另一个按比例计算)
  4184. if ($width > 0 || $height > 0) {
  4185. $ratio = $srcWidth / $srcHeight;
  4186. if ($width > 0 && $height > 0) {
  4187. return [$width, $height];
  4188. }
  4189. return $width > 0
  4190. ? [$width, max(1, (int)round($width / $ratio))]
  4191. : [max(1, (int)round($height * $ratio)), $height];
  4192. }
  4193. // 预设档位:按长边放大(1080p=1920,2K=2560,4K=3840)
  4194. $presets = [
  4195. '1080p' => 1920,
  4196. '2k' => 2560,
  4197. '4k' => 3840,
  4198. ];
  4199. $target = strtolower((string)($params['target'] ?? '4k'));
  4200. $maxEdge = $presets[$target] ?? $presets['4k'];
  4201. $ratio = $srcWidth / $srcHeight;
  4202. if ($srcWidth >= $srcHeight) {
  4203. $dstWidth = $maxEdge;
  4204. $dstHeight = max(1, (int)round($maxEdge / $ratio));
  4205. } else {
  4206. $dstHeight = $maxEdge;
  4207. $dstWidth = max(1, (int)round($maxEdge * $ratio));
  4208. }
  4209. return [$dstWidth, $dstHeight];
  4210. }
  4211. // /**
  4212. // * 使用 Imagick 将远程图片压缩至不超过 maxBytes(默认3MB)内
  4213. // * 目标:在尽量保留原始格式和质量的前提下进行压缩,避免内存暴涨
  4214. // * 依赖:Imagick 扩展与 ImageMagick 库,下载使用 Guzzle 获取图片 blob
  4215. // *
  4216. // * @param string $url
  4217. // * @param int $maxBytes 最大字节数,默认 3*1024*1024
  4218. // * @return string|null 经过压缩后的图片 blob,失败返回 null
  4219. // */
  4220. // function compressRemoteImageUrlToSizeImagick(string $url, int $maxBytes = 3 * 1024 * 1024): ?string
  4221. // {
  4222. // // 兼容性检查
  4223. // if (!extension_loaded('imagick') || !class_exists('Imagick')) {
  4224. // return null;
  4225. // }
  4226. // try {
  4227. // $client = new Client(['timeout' => 30]);
  4228. // // 使用流式下载,将数据写入临时文件,避免一次性加载到内存
  4229. // $response = $client->get($url, ['stream' => true]);
  4230. // if ($response->getStatusCode() !== 200) {
  4231. // return null;
  4232. // }
  4233. // $body = $response->getBody();
  4234. // $tmp = tmpfile();
  4235. // if ($tmp === false) {
  4236. // return null;
  4237. // }
  4238. // stream_copy_to_stream($body, $tmp);
  4239. // rewind($tmp);
  4240. // $imagick = new Imagick();
  4241. // $imagick->readImageFile($tmp);
  4242. // $origW = $imagick->getImageWidth();
  4243. // $origH = $imagick->getImageHeight();
  4244. // $format = strtolower($imagick->getImageFormat());
  4245. // // 尝试序列:尺寸缩放 + 质量调节
  4246. // $scales = [1.0, 0.9, 0.8, 0.6, 0.4, 0.25];
  4247. // $qualities = [95, 90, 85, 75, 60, 40, 30, 20];
  4248. // $bestBlob = null;
  4249. // foreach ($scales as $scale) {
  4250. // foreach ($qualities as $q) {
  4251. // $clone = clone $imagick;
  4252. // if ($scale < 1.0) {
  4253. // $w = (int)round($origW * $scale);
  4254. // $h = (int)round($origH * $scale);
  4255. // if ($w < 1 || $h < 1) {
  4256. // $clone->destroy();
  4257. // continue;
  4258. // }
  4259. // $clone->resizeImage($w, $h, Imagick::FILTER_LANCZOS, 1);
  4260. // }
  4261. // $clone->setImageFormat($format);
  4262. // $clone->setImageCompressionQuality($q);
  4263. // $blob = $clone->getImageBlob();
  4264. // $clone->destroy();
  4265. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  4266. // $bestBlob = $blob;
  4267. // break 2;
  4268. // }
  4269. // }
  4270. // }
  4271. // if ($bestBlob !== null) {
  4272. // $imagick->destroy();
  4273. // fclose($tmp);
  4274. // return $bestBlob;
  4275. // }
  4276. // // 回退:尝试强制输出为当前格式的一个中等质量版本
  4277. // $fallback = clone $imagick;
  4278. // $fallback->setImageFormat($format);
  4279. // $fallback->setImageCompressionQuality(75);
  4280. // $blob = $fallback->getImageBlob();
  4281. // $fallback->destroy();
  4282. // $imagick->destroy();
  4283. // fclose($tmp);
  4284. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  4285. // return $blob;
  4286. // }
  4287. // } catch (\Exception $e) {
  4288. // return null;
  4289. // }
  4290. // return null;
  4291. // }
  4292. /**
  4293. * 将主体列表文本拆分为主体数组
  4294. *
  4295. * @param string $rolesText 主体列表文本内容
  4296. * @return array 主体名称数组
  4297. */
  4298. function parseRolesFromText(string $rolesText): array
  4299. {
  4300. if (empty($rolesText)) {
  4301. return [];
  4302. }
  4303. $roles = [];
  4304. // 按行分割文本
  4305. $lines = explode("\n", $rolesText);
  4306. foreach ($lines as $line) {
  4307. $line = trim($line);
  4308. if (empty($line)) {
  4309. continue;
  4310. }
  4311. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  4312. $role = trim($charMatch[1]);
  4313. $description = trim($charMatch[2]);
  4314. $timbreName = null;
  4315. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  4316. $picPrompt = null;
  4317. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  4318. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  4319. $description = trim($fullMatch[1]);
  4320. $picPrompt = trim($fullMatch[2]);
  4321. $timbreName = trim($fullMatch[3]);
  4322. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  4323. // 兼容旧格式:主体描述{{音色名}}
  4324. $description = trim($timbreMatch[1]);
  4325. $timbreName = trim($timbreMatch[2]);
  4326. }
  4327. $roleData = [
  4328. 'role' => $role,
  4329. 'description' => $description,
  4330. ];
  4331. // 如果有主体图片提示词,添加到数组中
  4332. if ($picPrompt) {
  4333. $roleData['pic_prompt'] = $picPrompt;
  4334. }
  4335. if ($timbreName) {
  4336. $timbre = DB::table('mp_timbres')
  4337. ->where('is_enabled', 1)
  4338. ->where('timbre_name', 'like', "%{$timbreName}%")
  4339. ->orderBy('id')
  4340. ->select('timbre_type', 'audio_url')
  4341. ->first();
  4342. if ($timbre) {
  4343. $roleData['voice_name'] = $timbreName;
  4344. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  4345. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  4346. }
  4347. }else {
  4348. // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  4349. if ($picPrompt) {
  4350. if (strstr($picPrompt, '男')) {
  4351. $roleData['voice_name'] = '阳光青年';
  4352. }elseif (strstr($picPrompt, '女')) {
  4353. $roleData['voice_name'] = '爽快思思';
  4354. }else {
  4355. if ($description) {
  4356. if (strstr($description, '男')) {
  4357. $roleData['voice_name'] = '阳光青年';
  4358. }elseif (strstr($description, '女')) {
  4359. $roleData['voice_name'] = '爽快思思';
  4360. }else {
  4361. $roleData['voice_name'] = '旁白';
  4362. }
  4363. }
  4364. }
  4365. }
  4366. if (!empty($roleData['voice_name'])) {
  4367. if ($roleData['voice_name'] == '旁白') {
  4368. $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  4369. $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  4370. }else {
  4371. $timbre = DB::table('mp_timbres')
  4372. ->where('is_enabled', 1)
  4373. ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  4374. ->orderBy('id')
  4375. ->select('timbre_type', 'audio_url')
  4376. ->first();
  4377. if ($timbre) {
  4378. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  4379. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  4380. }
  4381. }
  4382. }
  4383. }
  4384. $roles[] = $roleData;
  4385. }
  4386. }
  4387. $hasNarrator = false;
  4388. foreach ($roles as $role) {
  4389. if (getProp($role, 'role') === '旁白') {
  4390. $hasNarrator = true;
  4391. break;
  4392. }
  4393. }
  4394. if (!$hasNarrator) {
  4395. $roles[] = [
  4396. 'role' => '旁白',
  4397. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  4398. 'pic_prompt' => '',
  4399. 'voice_name' => '旁白',
  4400. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  4401. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  4402. ];
  4403. }
  4404. return $roles;
  4405. }
  4406. /**
  4407. * 将场景列表文本拆分为场景数组
  4408. *
  4409. * @param string $rolesText 场景列表列表文本内容
  4410. * @return array 场景名称数组
  4411. */
  4412. function parseScenesFromText(string $scenesText): array
  4413. {
  4414. if (empty($scenesText)) {
  4415. return [];
  4416. }
  4417. $scenes = [];
  4418. // 按行分割文本
  4419. $lines = explode("\n", $scenesText);
  4420. foreach ($lines as $line) {
  4421. $line = trim($line);
  4422. if (empty($line)) {
  4423. continue;
  4424. }
  4425. $line = str_replace(':', ':', $line);
  4426. if (strstr($line, ':')) {
  4427. $line_arr = explode(':', $line, 2);
  4428. if (count($line_arr) == 2) {
  4429. $scene = trim($line_arr[0]);
  4430. $description = trim($line_arr[1]);
  4431. $picPrompt = null;
  4432. // 检查描述末尾是否有{场景图片提示词}格式
  4433. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  4434. // 匹配格式:场景描述{场景图片提示词}
  4435. $description = trim($promptMatch[1]);
  4436. $picPrompt = trim($promptMatch[2]);
  4437. }
  4438. $sceneData = [
  4439. 'scene' => $scene,
  4440. 'description' => $description,
  4441. ];
  4442. // 如果有场景图片提示词,添加到数组中
  4443. if ($picPrompt) {
  4444. $sceneData['pic_prompt'] = $picPrompt;
  4445. }
  4446. $scenes[] = $sceneData;
  4447. }
  4448. }
  4449. }
  4450. return $scenes;
  4451. }
  4452. /**
  4453. * 将道具列表文本拆分为道具数组
  4454. *
  4455. * @param string $propsText 道具列表文本内容
  4456. * @return array 道具数组
  4457. */
  4458. function parsePropsFromText(string $propsText): array
  4459. {
  4460. if (empty($propsText)) {
  4461. return [];
  4462. }
  4463. $props = [];
  4464. // 按行分割文本
  4465. $lines = explode("\n", $propsText);
  4466. foreach ($lines as $line) {
  4467. $line = trim($line);
  4468. if (empty($line)) {
  4469. continue;
  4470. }
  4471. $line = str_replace(':', ':', $line);
  4472. if (strstr($line, ':')) {
  4473. $line_arr = explode(':', $line, 2);
  4474. if (count($line_arr) == 2) {
  4475. $prop = trim($line_arr[0]);
  4476. $description = trim($line_arr[1]);
  4477. $picPrompt = null;
  4478. // 检查描述末尾是否有{道具图片提示词}格式
  4479. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  4480. // 匹配格式:道具描述{道具图片提示词}
  4481. $description = trim($promptMatch[1]);
  4482. $picPrompt = trim($promptMatch[2]);
  4483. }
  4484. $propData = [
  4485. 'prop' => $prop,
  4486. 'description' => $description,
  4487. ];
  4488. // 如果有道具图片提示词,添加到数组中
  4489. if ($picPrompt) {
  4490. $propData['pic_prompt'] = $picPrompt;
  4491. }
  4492. $props[] = $propData;
  4493. }
  4494. }
  4495. }
  4496. return $props;
  4497. }
  4498. // 拆分章节内容
  4499. function splitContent($content) {
  4500. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  4501. $chapters = [];
  4502. // 匹配章节标题格式:
  4503. // 1. 标题可能独占一行,也可能在正文末尾或中间
  4504. // 2. 格式支持:
  4505. // - **第一集**
  4506. // - 第一集:
  4507. // - ###第1章 重生
  4508. // - ##第2章 相救
  4509. // - 第三章 共处一室
  4510. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  4511. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  4512. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  4513. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  4514. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  4515. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  4516. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场话]|$)/u';
  4517. // 先在每个标题前插入换行符(如果前面不是换行的话)
  4518. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场话])/u', "$1\n\n$2第$3$4", $content);
  4519. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  4520. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场话]).*$/mu';
  4521. // 用正则找出所有章节标题的位置
  4522. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  4523. $titleCount = count($matches[0]);
  4524. for ($i = 0; $i < $titleCount; $i++) {
  4525. // 获取当前章节标题
  4526. $titleLine = trim($matches[0][$i][0]);
  4527. // 去除标题开头的特殊符号
  4528. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/u', '', $titleLine);
  4529. // 去除标题结尾的冒号和特殊符号
  4530. $cleanTitle = preg_replace('/[#*·::\s]+$/u', '', $cleanTitle);
  4531. $cleanTitle = trim($cleanTitle);
  4532. // 获取当前标题的结束位置
  4533. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  4534. // 获取下一个章节标题的开始位置(如果存在)
  4535. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  4536. // 提取章节内容(从标题结束到下一个标题开始)
  4537. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  4538. // 清理内容:去除前后空白和分隔线
  4539. $chapterContent = trim($chapterContent);
  4540. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  4541. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  4542. if (!empty($cleanTitle) && !empty($chapterContent)) {
  4543. $chapters[] = [
  4544. 'title' => $cleanTitle,
  4545. 'content' => $chapterContent
  4546. ];
  4547. }
  4548. }
  4549. } else {
  4550. // 如果没有匹配到章节,返回整个内容
  4551. $chapters[] = [
  4552. 'title' => '',
  4553. 'content' => $content
  4554. ];
  4555. }
  4556. return $chapters;
  4557. }
  4558. /**
  4559. * 记录日志到数据库
  4560. *
  4561. * @param string $channel 日志频道/目录名
  4562. * @param string $level 日志级别 (info, error, warning, debug)
  4563. * @param string $message 日志信息
  4564. * @param array $context 日志详细数据
  4565. * @return void
  4566. */
  4567. function logDB($channel, $level, $message, $context = []) {
  4568. try {
  4569. // 获取调用堆栈信息
  4570. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  4571. $caller = $trace[1] ?? $trace[0];
  4572. // 在 create 之前添加:
  4573. $jsonEncoded = json_encode($context, JSON_INVALID_UTF8_SUBSTITUTE);
  4574. $cleanContext = json_decode($jsonEncoded, true);
  4575. \App\Models\SystemLog::create([
  4576. 'channel' => $channel,
  4577. 'level' => $level,
  4578. 'message' => $message,
  4579. 'context' => $cleanContext,
  4580. 'file' => $caller['file'] ?? '',
  4581. 'line' => $caller['line'] ?? 0,
  4582. 'log_time' => date('Y-m-d H:i:s'),
  4583. ]);
  4584. } catch (\Exception $e) {
  4585. // 记录日志失败时不影响主流程
  4586. \Log::error('记录日志到数据库失败: ' . $e->getMessage());
  4587. }
  4588. }
  4589. function filterScriptContent($content) {
  4590. if (!$content) return '';
  4591. if (mb_substr($content, 0, 6) == '确认分镜大纲') return '确认分镜大纲';
  4592. if (mb_strlen($content) > 500) return '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。';
  4593. return $content;
  4594. }
  4595. /**
  4596. * 根据错误信息返回映射错误说明
  4597. *
  4598. * @param string $errorMessage 错误信息
  4599. * @return string 映射后的错误说明
  4600. */
  4601. function mapErrorMessage($errorMessage)
  4602. {
  4603. if (empty($errorMessage)) {
  4604. return '未知异常,请重试';
  4605. }
  4606. // 按优先级匹配错误信息
  4607. if (stripos($errorMessage, 'OutputImageSensitiveContentDetected') !== false) {
  4608. return '输出结果含有敏感词,请重试';
  4609. }
  4610. if (stripos($errorMessage, '系统繁忙,请稍后再试') !== false) {
  4611. return '系统繁忙,请稍后再试';
  4612. }
  4613. if (stripos($errorMessage, 'InternalServiceError') !== false) {
  4614. return '外部服务器网络错误,请稍后重试';
  4615. }
  4616. if (stripos($errorMessage, 'InputTextSensitiveContentDetected') !== false) {
  4617. return '输入文字含有敏感词,请调整后重试';
  4618. }
  4619. if (stripos($errorMessage, 'ServerOverloaded') !== false) {
  4620. return '当前系统过载,请稍后重试';
  4621. }
  4622. if (stripos($errorMessage, 'The request failed because the output video may be related to copyright restrictions') !== false) {
  4623. return '输出视频可能涉及版权限制,请更换内容或降低相似度后重试。';
  4624. }
  4625. // 未命中预设错误:调用模型生成友好翻译并缓存,避免轮询场景重复消耗
  4626. try {
  4627. $cacheKey = 'unknown_error_translate_' . md5((string)$errorMessage);
  4628. return Cache::remember($cacheKey, 600, function () use ($errorMessage) {
  4629. $friendlyError = app(\App\Services\DeepSeek\DeepSeekService::class)->analyzeErrorMessage($errorMessage);
  4630. return $friendlyError ?: '未知异常,请重试';
  4631. });
  4632. } catch (\Throwable $e) {
  4633. return '未知异常,请重试';
  4634. }
  4635. }
  4636. /**
  4637. * 视频超分:480p档升级到720p,720p档升级到1080p(使用FFmpeg本地超分)
  4638. * 目标分辨率按源视频方向强制为标准档位(横屏 16:9 / 竖屏 9:16)
  4639. * 可通过 $targetResolution 显式指定目标档位(720p/1080p),显式指定优先;未指定时按源档位自动识别
  4640. *
  4641. * @param string|resource $videoSource 视频URL地址或视频内容(字符串)
  4642. * @param string $prefix 上传文件夹前缀(如:'video')
  4643. * @param bool $isContent 是否为视频内容而非URL(默认false)
  4644. * @param string $targetResolution 显式目标档位:'720p' 或 '1080p',空字符串表示自动识别
  4645. * @return string 返回超分后的视频URL,失败返回原视频URL或空字符串
  4646. */
  4647. function upgrade480pTo720p($videoSource, $prefix = 'video', $isContent = false, $targetResolution = '')
  4648. {
  4649. if (env('APP_ENV') == 'local') {
  4650. return $isContent ? '' : $videoSource;
  4651. }
  4652. try {
  4653. // 创建临时目录
  4654. $tempDir = storage_path('app/temp/videos');
  4655. if (!is_dir($tempDir)) {
  4656. mkdir($tempDir, 0775, true);
  4657. chmod($tempDir, 0775);
  4658. }
  4659. // 生成唯一文件名
  4660. $uniqueId = uniqid('video_upgrade_') . bin2hex(random_bytes(4));
  4661. // 处理输入源
  4662. if ($isContent) {
  4663. // 如果是视频内容,直接写入临时文件
  4664. dLog('video_upgrade')->info('检测到视频内容,写入临时文件');
  4665. $inputFile = $tempDir . '/' . $uniqueId . '_input.mp4';
  4666. if (file_put_contents($inputFile, $videoSource) === false) {
  4667. dLog('video_upgrade')->error('视频内容写入临时文件失败');
  4668. return '';
  4669. }
  4670. $videoUrl = '视频内容';
  4671. } else {
  4672. // 如果是URL,下载视频
  4673. $videoUrl = $videoSource;
  4674. $videoExt = getVideoExtFromUrl($videoUrl);
  4675. $inputFile = $tempDir . '/' . $uniqueId . '_input' . $videoExt;
  4676. // 下载视频到本地
  4677. dLog('video_upgrade')->info('开始下载视频进行升级', ['url' => $videoUrl]);
  4678. $client = new \GuzzleHttp\Client(['timeout' => 300]);
  4679. $response = $client->get($videoUrl);
  4680. $fileContent = $response->getBody()->getContents();
  4681. if (file_put_contents($inputFile, $fileContent) === false) {
  4682. dLog('video_upgrade')->error('视频文件写入失败', [
  4683. 'url' => $videoUrl,
  4684. 'file' => $inputFile
  4685. ]);
  4686. return $videoUrl;
  4687. }
  4688. }
  4689. chmod($inputFile, 0664);
  4690. if (!file_exists($inputFile)) {
  4691. dLog('video_upgrade')->error('视频文件不存在', ['file' => $inputFile]);
  4692. return $isContent ? '' : $videoSource;
  4693. }
  4694. $inputFileSize = filesize($inputFile);
  4695. dLog('video_upgrade')->info('视频准备完成,开始超分', [
  4696. 'source' => $videoUrl,
  4697. 'size' => $inputFileSize,
  4698. 'size_mb' => round($inputFileSize / 1024 / 1024, 2) . 'MB'
  4699. ]);
  4700. // 获取视频分辨率,根据源档位选择目标档位
  4701. // 使用 ffprobe 的 JSON 输出,这是最可靠的方式
  4702. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  4703. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  4704. // 获取视频流信息,使用JSON格式输出
  4705. $probeCmd = "$ffprobePath -v quiet -print_format json -show_streams \"$inputFile\"";
  4706. $probeOutput = shell_exec($probeCmd);
  4707. $videoInfo = json_decode($probeOutput, true);
  4708. $width = 0;
  4709. $height = 0;
  4710. // 从JSON中提取视频流的宽高
  4711. if (isset($videoInfo['streams']) && is_array($videoInfo['streams'])) {
  4712. foreach ($videoInfo['streams'] as $stream) {
  4713. if (isset($stream['codec_type']) && $stream['codec_type'] === 'video') {
  4714. $width = isset($stream['width']) ? (int)$stream['width'] : 0;
  4715. $height = isset($stream['height']) ? (int)$stream['height'] : 0;
  4716. break;
  4717. }
  4718. }
  4719. }
  4720. dLog('video_upgrade')->info('ffprobe获取视频分辨率', [
  4721. 'width' => $width,
  4722. 'height' => $height,
  4723. 'json_parsed' => !empty($videoInfo)
  4724. ]);
  4725. // 根据视频方向决定目标标准分辨率
  4726. // 480p档 -> 720p(720*1280 竖屏 / 1280*720 横屏)
  4727. // 720p档 -> 1080p(1080*1920 竖屏 / 1920*1080 横屏)
  4728. $shortSide = min($width, $height);
  4729. $targetShortSide = 0;
  4730. $targetResolution = strtolower(trim($targetResolution));
  4731. if (in_array($targetResolution, ['720p', '1080p'], true)) {
  4732. // 显式指定档位优先(不允许降级:源短边超过目标档位则跳过)
  4733. $targetShortSide = $targetResolution === '720p' ? 720 : 1080;
  4734. if ($shortSide > $targetShortSide + 40) {
  4735. dLog('video_upgrade')->info('视频分辨率高于目标档位,跳过超分', [
  4736. 'width' => $width,
  4737. 'height' => $height,
  4738. 'target' => $targetResolution
  4739. ]);
  4740. @unlink($inputFile);
  4741. return $isContent ? '' : $videoSource;
  4742. }
  4743. } elseif ($shortSide > 0 && abs($shortSide - 480) <= 40) {
  4744. $targetShortSide = 720;
  4745. } elseif ($shortSide > 0 && abs($shortSide - 720) <= 40) {
  4746. $targetShortSide = 1080;
  4747. } else {
  4748. // 自动识别且非480p/720p档,无需超分,直接返回原视频
  4749. dLog('video_upgrade')->info('视频不属于480p/720p档位,跳过超分', [
  4750. 'width' => $width,
  4751. 'height' => $height,
  4752. 'short_side' => $shortSide
  4753. ]);
  4754. @unlink($inputFile);
  4755. return $isContent ? '' : $videoSource;
  4756. }
  4757. $isPortrait = $width > 0 && $height > 0 && $width < $height;
  4758. $targetWidth = $isPortrait ? $targetShortSide : (int)round($targetShortSide * 16 / 9);
  4759. $targetHeight = $isPortrait ? (int)round($targetShortSide * 16 / 9) : $targetShortSide;
  4760. $scaleFilter = "scale={$targetWidth}:{$targetHeight}:flags=lanczos:force_original_aspect_ratio=decrease,pad={$targetWidth}:{$targetHeight}:(ow-iw)/2:(oh-ih)/2";
  4761. if ($width > 0 && $height > 0) {
  4762. dLog('video_upgrade')->info('缩放计算详情', [
  4763. 'original' => "{$width}x{$height}",
  4764. 'target' => "{$targetWidth}x{$targetHeight}",
  4765. 'is_portrait' => $width < $height ? 'yes' : 'no'
  4766. ]);
  4767. dLog('video_upgrade')->info(($isPortrait ? '竖屏' : '横屏') . '视频超分', [
  4768. 'original_size' => "{$width}x{$height}",
  4769. 'target_size' => "{$targetWidth}x{$targetHeight}",
  4770. 'scale_filter' => $scaleFilter
  4771. ]);
  4772. } else {
  4773. // 无法获取分辨率,默认按横屏处理
  4774. $targetWidth = (int)round($targetShortSide * 16 / 9);
  4775. $targetHeight = $targetShortSide;
  4776. $scaleFilter = "scale={$targetWidth}:{$targetHeight}:flags=lanczos:force_original_aspect_ratio=decrease,pad={$targetWidth}:{$targetHeight}:(ow-iw)/2:(oh-ih)/2";
  4777. dLog('video_upgrade')->warning('无法获取视频分辨率,默认按横屏处理');
  4778. }
  4779. // 输出文件路径
  4780. $outputFile = $tempDir . '/' . $uniqueId . '_output.mp4';
  4781. // 使用FFmpeg超分视频,使用高质量的Lanczos算法和锐化滤镜
  4782. // 滤镜说明:
  4783. // 1. scale: 使用Lanczos算法缩放并保持宽高比,pad补边到标准分辨率(720p或1080p档)
  4784. // 2. unsharp=5:5:1.0:5:5:0.5: 锐化滤镜,增强细节
  4785. // - 5:5:1.0 表示亮度锐化(luma_msize_x:luma_msize_y:luma_amount)
  4786. // - 5:5:0.5 表示色度锐化(chroma_msize_x:chroma_msize_y:chroma_amount)
  4787. // 3. hqdn3d=1.5:1.5:6:6: 降噪滤镜,轻微降噪以改善画质
  4788. // - 参数分别为亮度空间/时间和色度空间/时间
  4789. // 编码参数:
  4790. // -c:v libx264: 使用H.264编码器
  4791. // -preset slow: 编码速度预设(ultrafast到veryslow,越慢压缩率越高)
  4792. // 可选值: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow
  4793. // 推荐: slow(平衡速度和压缩率)或 slower(更好压缩)
  4794. // -crf 23: 恒定质量模式(0-51,数值越小画质越好,文件越大)
  4795. // 推荐值: 18(高质量,大文件) 23(默认,平衡) 28(中等质量,小文件)
  4796. // 当前设置可在.env中配置 VIDEO_UPGRADE_CRF,默认23
  4797. // -tune film: 针对电影内容优化(适合AI生成的动画视频)
  4798. // -profile:v high: 使用H.264 High Profile,支持更高级的压缩特性
  4799. // -level 4.1: H.264 level 4.1,支持更高的码率和分辨率
  4800. // -pix_fmt yuv420p: 像素格式,确保兼容性
  4801. // -c:a aac -b:a 128k: 音频使用AAC编码,128kbps(比直接copy更小)
  4802. // -movflags +faststart: 优化网络播放
  4803. // 从环境变量读取编码参数,允许灵活配置
  4804. $crf = env('VIDEO_UPGRADE_CRF', 23); // CRF值: 18(高质量) 23(默认) 28(小文件)
  4805. $preset = env('VIDEO_UPGRADE_PRESET', 'slow'); // 编码速度: slow, slower, veryslow
  4806. $audioBitrate = env('VIDEO_UPGRADE_AUDIO_BITRATE', '128k'); // 音频码率
  4807. $unsharp = env('VIDEO_UPGRADE_UNSHARP', '5:5:0.5:5:5:0.2');
  4808. dLog('video_upgrade')->info('使用编码参数', [
  4809. 'crf' => $crf,
  4810. 'preset' => $preset,
  4811. 'audio_bitrate' => $audioBitrate
  4812. ]);
  4813. $ffmpegCmd = "$ffmpegPath -i \"$inputFile\" -vf \"$scaleFilter,unsharp=$unsharp,hqdn3d=1.5:1.5:6:6\" -c:v libx264 -preset $preset -crf $crf -tune film -profile:v high -level 4.1 -pix_fmt yuv420p -c:a aac -b:a $audioBitrate -movflags +faststart -y \"$outputFile\" 2>&1";
  4814. dLog('video_upgrade')->info('开始FFmpeg超分视频', ['command' => $ffmpegCmd]);
  4815. $output = shell_exec($ffmpegCmd);
  4816. if (!file_exists($outputFile)) {
  4817. dLog('video_upgrade')->error('视频升级失败', [
  4818. 'input' => $inputFile,
  4819. 'output' => $output
  4820. ]);
  4821. @unlink($inputFile);
  4822. return $isContent ? '' : $videoSource;
  4823. }
  4824. chmod($outputFile, 0664);
  4825. // 验证输出视频的分辨率(使用JSON格式,最可靠)
  4826. $verifyCmd = "$ffprobePath -v quiet -print_format json -show_streams \"$outputFile\"";
  4827. $verifyOutput = shell_exec($verifyCmd);
  4828. $outputVideoInfo = json_decode($verifyOutput, true);
  4829. $outputWidth = 0;
  4830. $outputHeight = 0;
  4831. if (isset($outputVideoInfo['streams']) && is_array($outputVideoInfo['streams'])) {
  4832. foreach ($outputVideoInfo['streams'] as $stream) {
  4833. if (isset($stream['codec_type']) && $stream['codec_type'] === 'video') {
  4834. $outputWidth = isset($stream['width']) ? (int)$stream['width'] : 0;
  4835. $outputHeight = isset($stream['height']) ? (int)$stream['height'] : 0;
  4836. break;
  4837. }
  4838. }
  4839. }
  4840. dLog('video_upgrade')->info('输出视频分辨率验证', [
  4841. 'input_original' => "{$width}x{$height}",
  4842. 'expected' => ($width > 0 && $height > 0) ? ($width < $height ? '720x1280' : '1280x720') : '1280x720',
  4843. 'actual_output' => "{$outputWidth}x{$outputHeight}",
  4844. 'success' => ($outputWidth > 0 && $outputHeight > 0)
  4845. ]);
  4846. $outputFileSize = filesize($outputFile);
  4847. $sizeRatio = round($outputFileSize / $inputFileSize, 2);
  4848. dLog('video_upgrade')->info('视频升级成功', [
  4849. 'input_size' => round($inputFileSize / 1024 / 1024, 2) . 'MB',
  4850. 'output_size' => round($outputFileSize / 1024 / 1024, 2) . 'MB',
  4851. 'size_ratio' => $sizeRatio
  4852. ]);
  4853. // 上传到TOS - 使用普通的文件名,不暴露是升级后的视频
  4854. $video_name = 'ai_generation_' . time() . '_' . uniqid() . '.mp4';
  4855. $uploadedUrl = uploadStreamByTos($prefix, file_get_contents($outputFile), $video_name);
  4856. // 清理临时文件
  4857. @unlink($inputFile);
  4858. @unlink($outputFile);
  4859. if (!$uploadedUrl) {
  4860. dLog('video_upgrade')->error('升级后的视频上传失败');
  4861. return $isContent ? '' : $videoSource;
  4862. }
  4863. dLog('video_upgrade')->info('升级后的视频上传成功', ['url' => $uploadedUrl]);
  4864. return $uploadedUrl;
  4865. } catch (\Exception $e) {
  4866. dLog('video_upgrade')->error('视频升级过程出错', [
  4867. 'source' => $isContent ? '视频内容' : $videoSource,
  4868. 'error' => $e->getMessage()
  4869. ]);
  4870. // 清理可能存在的临时文件
  4871. if (isset($inputFile) && file_exists($inputFile)) {
  4872. @unlink($inputFile);
  4873. }
  4874. if (isset($outputFile) && file_exists($outputFile)) {
  4875. @unlink($outputFile);
  4876. }
  4877. // 出错时返回原视频URL或空字符串
  4878. return $isContent ? '' : $videoSource;
  4879. }
  4880. }