Helpers.php 207 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563
  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. // UTF-8 BOM,避免 Excel 打开 CSV 中文乱码
  1948. fwrite($handle, "\xEF\xBB\xBF");
  1949. fputcsv($handle, $headers);
  1950. if ($data) {
  1951. foreach ($data as $row) {
  1952. fputcsv($handle, $row);
  1953. }
  1954. }
  1955. ob_flush();
  1956. fclose($handle);
  1957. die();
  1958. }
  1959. // 树状分类
  1960. function buildCategoryTree($categories, $pid = 0) {
  1961. $tree = [];
  1962. foreach ($categories as $category) {
  1963. if ($category['pid'] == $pid) {
  1964. $children = buildCategoryTree($categories, $category['category_id']);
  1965. if ($children) {
  1966. $category['children'] = $children;
  1967. }
  1968. $tree[] = $category;
  1969. }
  1970. }
  1971. return $tree;
  1972. }
  1973. // 获取文件的md5值
  1974. function getFileContentMD5($filePath){
  1975. //获取文件MD5的128位二进制数组
  1976. $md5Bytes = md5_file($filePath,true);
  1977. //计算文件的Content-MD5
  1978. $contentMD5 = base64_encode($md5Bytes);
  1979. return $contentMD5;
  1980. }
  1981. function getTextTokens($text) {
  1982. // 方法1:按空格分词(西文较准)
  1983. $words = preg_split('/\s+/', $text);
  1984. $wordCount = count($words);
  1985. // 方法2:按字符数估算(中文较准:1个汉字 ≈ 1.5-2 tokens)
  1986. $charCount = mb_strlen($text);
  1987. // 综合估算(根据语言调整权重)
  1988. $tokenCount = $wordCount + $charCount * 0.5; // 示例公式
  1989. // 更简单:直接按字符数 * 系数(中文推荐)
  1990. // $tokenCount = $charCount * 1.8; // 经验系数
  1991. return (int)ceil($tokenCount);
  1992. }
  1993. // 处理小说剧本文本
  1994. function handleScriptWords($text, $enable_emotion=1) {
  1995. $text = preg_replace('/[\r\n]+/', PHP_EOL, $text);
  1996. $text_arr = explode(PHP_EOL, $text);
  1997. $roles = [];
  1998. $words = [];
  1999. $role_gender = [];
  2000. // $sequence = 0;
  2001. foreach ($text_arr as $line) {
  2002. $line = trim($line);
  2003. if ($enable_emotion) {
  2004. $match_rule = '/^(.*?)\:(.*?)\{(.*?)\}$/';
  2005. $count = 4;
  2006. } else {
  2007. $match_rule = '/^(.*?)\:(.*?)$/';
  2008. $count = 3;
  2009. }
  2010. preg_match($match_rule, $line, $matches);
  2011. if (count($matches) == $count) {
  2012. $gender = '0';
  2013. // 角色部分拆分
  2014. preg_match('/^(.*?)\((.*?)\)$/', $matches[1], $matches2);
  2015. if (count($matches2) == 3) {
  2016. $role = $matches2[1];
  2017. $gender_arr = ['男'=>'1', '女'=>'2'];
  2018. $gender = isset($gender_arr[$matches2[2]]) ? $gender_arr[$matches2[2]] : '0';
  2019. }else {
  2020. $role = $matches[1];
  2021. }
  2022. if (!in_array($role, $roles)) {
  2023. $roles[] = $role; // 记录角色
  2024. $role_gender[$role] = $gender;
  2025. }
  2026. $words[] = [
  2027. 'role' => $role,
  2028. 'gender' => $gender,
  2029. 'text' => $matches[2],
  2030. 'emotion' => $enable_emotion ? $matches[3] : '中性',
  2031. ];
  2032. }
  2033. }
  2034. $new_words = [];
  2035. $tmp = '';
  2036. $tmp_arr = [];
  2037. $tmp_text = '';
  2038. // 将words数组按照role和emotion合并相邻的text内容,不相邻则跳过合并
  2039. foreach ($words as $word) {
  2040. if(!$tmp) $tmp = $word['role'].'-'.$word['emotion'];
  2041. if($tmp == $word['role'].'-'.$word['emotion']) {
  2042. $tmp_text .= PHP_EOL.$word['text'];
  2043. $tmp_arr = [
  2044. 'role' => $word['role'],
  2045. 'gender' => $word['gender'],
  2046. 'text' => trim($tmp_text, PHP_EOL),
  2047. 'emotion' => $word['emotion'],
  2048. ];
  2049. }else {
  2050. // $sequence++;
  2051. // $tmp_arr['sequence'] = $sequence;
  2052. $new_words[] = $tmp_arr;
  2053. $tmp = $word['role'].'-'.$word['emotion'];
  2054. $tmp_text = $word['text'];
  2055. $tmp_arr = [
  2056. 'role' => $word['role'],
  2057. 'gender' => $word['gender'],
  2058. 'text' => trim($tmp_text, PHP_EOL),
  2059. 'emotion' => $word['emotion'],
  2060. ];
  2061. }
  2062. }
  2063. if ($tmp_arr) {
  2064. // $sequence++;
  2065. // $tmp_arr['sequence'] = $sequence;
  2066. $new_words[] = $tmp_arr;
  2067. }
  2068. return [
  2069. 'roles' => $roles,
  2070. 'role_gender' => $role_gender,
  2071. 'words' => $new_words,
  2072. ];
  2073. }
  2074. function extractScriptContent($originalContent) {
  2075. if (!$originalContent) return [];
  2076. // 使用更精确的正则表达式分割内容
  2077. $parts = [];
  2078. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2079. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2080. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2081. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2082. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2083. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2084. // 提取剧本亮点(支持多个空格)
  2085. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2086. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2087. // 提取人物关系(支持多个空格)
  2088. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2089. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2090. // 提取核心矛盾(支持多个空格)
  2091. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2092. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2093. // 提取主体列表(支持多个空格)
  2094. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2095. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2096. $parts['roles'] = parseRolesFromText($rolesText);
  2097. // 提取美术风格(支持多个空格)
  2098. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2099. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2100. // 提取场景列表(支持多个空格)
  2101. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2102. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2103. $parts['scenes'] = parseScenesFromText($scenesText);
  2104. // 提取分集详细内容(多剧集模式,支持多个空格)
  2105. preg_match('/###\s*分集剧本\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2106. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2107. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2108. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2109. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2110. // 优先使用原文内容,其次使用分集详细内容
  2111. // $parts['content'] = $generatedContent ?: $detailedContent;
  2112. // 解析分集剧本内容
  2113. $episodes = [];
  2114. if ($detailedContent) {
  2115. // 按 ##分集 分割
  2116. preg_match_all('/##\s*分集(\d+)\s*\n(.*?)(?=\n\s*##分集|\z)/s', $detailedContent, $episodeMatches, PREG_SET_ORDER);
  2117. foreach ($episodeMatches as $episodeMatch) {
  2118. $episodeNum = $episodeMatch[1];
  2119. $episodeContent = trim($episodeMatch[2]);
  2120. $episode = [
  2121. 'episode_number' => $episodeNum,
  2122. 'episode_content' => $episodeContent,
  2123. 'episode_name' => '',
  2124. 'scene_description' => '',
  2125. 'camera_movement' => '',
  2126. 'characters' => '',
  2127. 'dialogues' => []
  2128. ];
  2129. // 提取分集名(格式:##分集01第一集: 第一集的标题)
  2130. if (preg_match('/^第.*?集\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $nameMatch)) {
  2131. $episode['episode_name'] = trim($nameMatch[1]);
  2132. }
  2133. // 提取场景描述
  2134. if (preg_match('/场景描述\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $sceneMatch)) {
  2135. $episode['scene_description'] = trim($sceneMatch[1]);
  2136. }
  2137. // 提取运镜
  2138. if (preg_match('/运镜\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $cameraMatch)) {
  2139. $episode['camera_movement'] = trim($cameraMatch[1]);
  2140. }
  2141. // 提取出场角色
  2142. if (preg_match('/出场角色\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $charactersMatch)) {
  2143. $episode['characters'] = trim($charactersMatch[1]);
  2144. }
  2145. // 提取台词内容
  2146. if (preg_match('/台词内容\s*[::]\s*\n(.*?)$/su', $episodeContent, $dialoguesMatch)) {
  2147. $dialoguesText = trim($dialoguesMatch[1]);
  2148. $dialogueLines = explode("\n", $dialoguesText);
  2149. foreach ($dialogueLines as $line) {
  2150. $line = trim($line);
  2151. if (empty($line)) {
  2152. continue;
  2153. }
  2154. // 匹配格式:角色名: 对话内容 或 角色名:对话内容
  2155. if (preg_match('/^(.+?)\s*[::]\s*(.+)$/u', $line, $dialogueMatch)) {
  2156. $episode['dialogues'][] = [
  2157. 'character' => trim($dialogueMatch[1]),
  2158. 'text' => trim($dialogueMatch[2])
  2159. ];
  2160. }
  2161. }
  2162. }
  2163. $episodes[] = $episode;
  2164. }
  2165. }
  2166. $parts['episodes'] = $episodes;
  2167. return $parts;
  2168. }
  2169. /**
  2170. * 处理剧本内容
  2171. */
  2172. function handleScriptContent($originalContent) {
  2173. if (!$originalContent) return [];
  2174. // 使用更精确的正则表达式分割内容
  2175. $parts = [];
  2176. // // 确保内容使用UTF-8编码
  2177. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  2178. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  2179. // }
  2180. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2181. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2182. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2183. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2184. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2185. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2186. // 提取剧本亮点(支持多个空格)
  2187. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2188. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2189. // 提取人物关系(支持多个空格)
  2190. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2191. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2192. // 提取核心矛盾(支持多个空格)
  2193. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2194. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2195. // 提取主体列表(支持多个空格)
  2196. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2197. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2198. $parts['roles'] = parseRolesFromText($rolesText);
  2199. // 提取美术风格(支持多个空格)
  2200. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2201. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2202. // 提取场景列表(支持多个空格)
  2203. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2204. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2205. $parts['scenes'] = parseScenesFromText($scenesText);
  2206. // 提取分集详细内容(多剧集模式,支持多个空格)
  2207. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2208. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2209. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2210. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2211. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2212. // 优先使用原文内容,其次使用分集详细内容
  2213. $parts['content'] = $generatedContent ?: $detailedContent;
  2214. $parts['episode_title'] = '';
  2215. $parts['acts'] = [];
  2216. // 单剧集格式:顶层是大纲信息,分镜部分采用 handleEpisodeContent 的结构标准
  2217. $singleStoryboard = '';
  2218. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2219. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2220. }
  2221. if ($singleStoryboard !== '') {
  2222. $episodeContent = $singleStoryboard;
  2223. if (!preg_match('/第\d+集[::\s]+/u', $episodeContent)) {
  2224. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  2225. $episodeContent = $defaultEpisodeTitle . "\n\n" . $episodeContent;
  2226. }
  2227. $episodeSections = [];
  2228. $episodeSections[] = $episodeContent;
  2229. if ($parts['intro'] !== '') {
  2230. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  2231. }
  2232. if ($parts['art_style'] !== '') {
  2233. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  2234. }
  2235. if ($rolesText !== '') {
  2236. $episodeSections[] = "###主体列表\n" . $rolesText;
  2237. }
  2238. if ($scenesText !== '') {
  2239. $episodeSections[] = "###场景列表\n" . $scenesText;
  2240. }
  2241. if (strpos($episodeContent, '###分镜剧本') === false) {
  2242. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  2243. }
  2244. $episode_arr = handleEpisodeContent(implode("\n\n", $episodeSections));
  2245. if (!empty($episode_arr['acts'])) {
  2246. $parts['episode_title'] = getProp($episode_arr, 'episode_title');
  2247. $parts['acts'] = getProp($episode_arr, 'acts', []);
  2248. if (empty($parts['roles'])) {
  2249. $parts['roles'] = getProp($episode_arr, 'roles', []);
  2250. }
  2251. if (empty($parts['scenes'])) {
  2252. $parts['scenes'] = getProp($episode_arr, 'scenes', []);
  2253. }
  2254. }
  2255. }
  2256. if (empty($parts['acts'])) {
  2257. $fallbackEpisodeArr = handleEpisodeContent($originalContent);
  2258. if (!empty($fallbackEpisodeArr['acts'])) {
  2259. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title');
  2260. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  2261. if (empty($parts['intro'])) {
  2262. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro');
  2263. }
  2264. if (empty($parts['art_style'])) {
  2265. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style');
  2266. }
  2267. if (empty($parts['roles'])) {
  2268. $parts['roles'] = getProp($fallbackEpisodeArr, 'roles', []);
  2269. }
  2270. if (empty($parts['scenes'])) {
  2271. $parts['scenes'] = getProp($fallbackEpisodeArr, 'scenes', []);
  2272. }
  2273. }
  2274. }
  2275. // 多剧集格式:继续兼容旧的分集剧本结构
  2276. $fullScript = '';
  2277. if (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. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2282. $fullScript = trim($storyboardMatch[1]);
  2283. }
  2284. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  2285. $fullScript = trim($fallbackMatch[1]);
  2286. }
  2287. $episodes = [];
  2288. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  2289. foreach ($matches as $match) {
  2290. $episodeNumber = (int)trim($match[1]);
  2291. $episodeName = trim($match[2]);
  2292. $episodeContent = trim($match[3]);
  2293. $segments = [];
  2294. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  2295. foreach ($segmentMatches as $segMatch) {
  2296. $segmentNumber = (int)trim($segMatch[1]);
  2297. $segmentContent = trim($segMatch[2]);
  2298. $segments[] = [
  2299. 'segment_number' => $segmentNumber,
  2300. 'segment_content' => $segmentContent,
  2301. ];
  2302. }
  2303. $episodes[] = [
  2304. 'episode_number' => $episodeNumber,
  2305. 'title' => $episodeName,
  2306. 'content' => $episodeContent,
  2307. 'segments' => $segments,
  2308. ];
  2309. }
  2310. if (empty($episodes) && !empty($parts['acts'])) {
  2311. $singleSegments = [];
  2312. foreach ($parts['acts'] as $act) {
  2313. $actSegments = getProp($act, 'segments', []);
  2314. if (!is_array($actSegments)) {
  2315. continue;
  2316. }
  2317. foreach ($actSegments as $segment) {
  2318. $singleSegments[] = [
  2319. 'segment_number' => getProp($segment, 'segment_number'),
  2320. 'segment_content' => getProp($segment, 'segment_content'),
  2321. ];
  2322. }
  2323. }
  2324. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  2325. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  2326. $episodes[] = [
  2327. 'episode_number' => 1,
  2328. 'title' => $episodeName,
  2329. 'content' => $singleStoryboard,
  2330. 'segments' => $singleSegments,
  2331. ];
  2332. }
  2333. $parts['episodes'] = $episodes;
  2334. return $parts;
  2335. }
  2336. function handleEpisodeContent($originalContent) {
  2337. if (!$originalContent) return [];
  2338. // 解析剧集内容
  2339. $result = [
  2340. 'episode_title' => '',
  2341. 'intro' => '',
  2342. 'art_style' => '',
  2343. 'roles' => [],
  2344. 'scenes' => [],
  2345. 'acts' => []
  2346. ];
  2347. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  2348. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  2349. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  2350. }
  2351. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  2352. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  2353. $result['intro'] = trim($summaryMatch[1]);
  2354. }
  2355. // 提取美术风格 - 兼容多种格式
  2356. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  2357. $result['art_style'] = trim($styleMatch[1]);
  2358. }
  2359. // 提取主体列表 - 兼容多种格式
  2360. if (preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  2361. $charactersText = trim($charactersMatch[1]);
  2362. $characterLines = explode("\n", $charactersText);
  2363. foreach ($characterLines as $line) {
  2364. $line = trim($line);
  2365. if (empty($line)) continue;
  2366. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  2367. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2368. $role = trim($charMatch[1]);
  2369. $description = trim($charMatch[2]);
  2370. $timbreName = null;
  2371. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  2372. $picPrompt = null;
  2373. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  2374. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  2375. $description = trim($fullMatch[1]);
  2376. $picPrompt = trim($fullMatch[2]);
  2377. $timbreName = trim($fullMatch[3]);
  2378. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2379. // 兼容旧格式:主体描述{{音色名}}
  2380. $description = trim($timbreMatch[1]);
  2381. $timbreName = trim($timbreMatch[2]);
  2382. }
  2383. $roleData = [
  2384. 'role' => $role,
  2385. 'description' => $description
  2386. ];
  2387. // 如果有主体图片提示词,添加到数组中
  2388. if ($picPrompt) {
  2389. // 检查开头是否有"全景,正面拍摄。"
  2390. $prefix = '全景,正面拍摄。';
  2391. $prefixParts = ['全景', '正面拍摄'];
  2392. // 检查是否包含完整前缀
  2393. if (strpos($picPrompt, $prefix) !== 0) {
  2394. // 检查是否包含部分前缀词汇(不论位置)
  2395. $hasAnyPrefix = false;
  2396. foreach ($prefixParts as $part) {
  2397. if (mb_strpos($picPrompt, $part) !== false) {
  2398. $hasAnyPrefix = true;
  2399. break;
  2400. }
  2401. }
  2402. if ($hasAnyPrefix) {
  2403. // 移除所有"全景"和"正面拍摄"词汇(包括它们后面的标点)
  2404. $picPrompt = preg_replace('/全景[,,、。. ]*/u', '', $picPrompt);
  2405. $picPrompt = preg_replace('/正面拍摄[,,、。. ]*/u', '', $picPrompt);
  2406. // 清理开头和结尾的标点符号和空格
  2407. $picPrompt = preg_replace('/^[。,,、 ]+|[。,,、 ]+$/u', '', $picPrompt);
  2408. }
  2409. // 在开头添加完整前缀
  2410. $picPrompt = $prefix . $picPrompt;
  2411. }
  2412. // 检查是否包含"姿态:"或"姿态:"
  2413. if (preg_match('/姿态[::]/u', $picPrompt)) {
  2414. // 如果有姿态描述,统一替换为"姿态:站立"
  2415. $picPrompt = preg_replace('/姿态[::][^.。\n]+/u', '姿态:站立', $picPrompt);
  2416. } else {
  2417. // 如果没有姿态描述,在末尾添加"姿态:站立"
  2418. $picPrompt = preg_replace('/[。,, ]+$/u', '', $picPrompt) . '。姿态:站立。';
  2419. }
  2420. $roleData['pic_prompt'] = $picPrompt;
  2421. }
  2422. // 如果有音色信息,添加到数组中
  2423. if ($timbreName) {
  2424. $timbre = DB::table('mp_timbres')->where('is_enabled', 1)->where('timbre_name', 'like', "%{$timbreName}%")->orderBy('id')->select('timbre_type', 'audio_url')->first();
  2425. if ($timbre) {
  2426. $roleData['voice_name'] = $timbreName;
  2427. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2428. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');;
  2429. }
  2430. }else {
  2431. // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  2432. if ($picPrompt) {
  2433. if (strstr($picPrompt, '男')) {
  2434. $roleData['voice_name'] = '阳光青年';
  2435. }elseif (strstr($picPrompt, '女')) {
  2436. $roleData['voice_name'] = '爽快思思';
  2437. }else {
  2438. if ($description) {
  2439. if (strstr($description, '男')) {
  2440. $roleData['voice_name'] = '阳光青年';
  2441. }elseif (strstr($description, '女')) {
  2442. $roleData['voice_name'] = '爽快思思';
  2443. }else {
  2444. $roleData['voice_name'] = '旁白';
  2445. }
  2446. }
  2447. }
  2448. }
  2449. if (!empty($roleData['voice_name'])) {
  2450. if ($roleData['voice_name'] == '旁白') {
  2451. $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  2452. $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  2453. }else {
  2454. $timbre = DB::table('mp_timbres')
  2455. ->where('is_enabled', 1)
  2456. ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  2457. ->orderBy('id')
  2458. ->select('timbre_type', 'audio_url')
  2459. ->first();
  2460. if ($timbre) {
  2461. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2462. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2463. }
  2464. }
  2465. }
  2466. }
  2467. $result['roles'][] = $roleData;
  2468. }
  2469. }
  2470. // 加入旁白角色(如果不存在)
  2471. $hasNarrator = false;
  2472. foreach ($result['roles'] as $role) {
  2473. if (isset($role['role']) && $role['role'] === '旁白') {
  2474. $hasNarrator = true;
  2475. break;
  2476. }
  2477. }
  2478. if (!$hasNarrator) {
  2479. $result['roles'][] = [
  2480. 'role' => '旁白',
  2481. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2482. 'pic_prompt' => '',
  2483. 'voice_name' => '旁白',
  2484. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2485. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2486. ];
  2487. }
  2488. }
  2489. // 提取场景列表 - 兼容多种格式
  2490. if (preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  2491. $scenesText = trim($scenesMatch[1]);
  2492. $sceneLines = explode("\n", $scenesText);
  2493. foreach ($sceneLines as $line) {
  2494. $line = trim($line);
  2495. if (empty($line)) continue;
  2496. // 兼容中文冒号:和英文冒号:
  2497. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  2498. $scene = trim($sceneMatch[1]);
  2499. $description = trim($sceneMatch[2]);
  2500. $picPrompt = null;
  2501. // 检查描述末尾是否有{场景图片提示词}格式
  2502. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  2503. // 匹配格式:场景描述{场景图片提示词}
  2504. $description = trim($promptMatch[1]);
  2505. $picPrompt = trim($promptMatch[2]);
  2506. }
  2507. $sceneData = [
  2508. 'scene' => $scene,
  2509. 'description' => $description
  2510. ];
  2511. // 如果有场景图片提示词,添加到数组中
  2512. if ($picPrompt) {
  2513. $sceneData['pic_prompt'] = $picPrompt;
  2514. }
  2515. $result['scenes'][] = $sceneData;
  2516. }
  2517. }
  2518. }
  2519. // 提取分镜剧本 - 兼容多种格式
  2520. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $storyboardMatch)) {
  2521. $storyboardText = trim($storyboardMatch[1]);
  2522. // 按幕分割 - 修复第1幕识别和乱码问题
  2523. $acts = [];
  2524. // 先在开头添加换行符,确保第1幕也能被正确分割
  2525. $normalizedText = "\n" . $storyboardText;
  2526. $parts = preg_split('/\n\s*##/', $normalizedText);
  2527. foreach ($parts as $part) {
  2528. $part = trim($part);
  2529. if (empty($part)) continue;
  2530. // 如果不是以"第"开头,跳过
  2531. if (!preg_match('/^第\d+幕/', $part)) {
  2532. continue;
  2533. }
  2534. // 分离标题和内容
  2535. $lines = explode("\n", $part, 2);
  2536. $actTitle = trim($lines[0]);
  2537. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  2538. // 解析幕标题,提取序号和详细信息 - 修复乱码问题
  2539. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  2540. $actNumber = intval($actTitleMatch[1]);
  2541. $actDetails = trim($actTitleMatch[2]);
  2542. // 如果详细信息为空或者就是冒号,使用完整标题
  2543. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  2544. $actDetails = $actTitle;
  2545. }
  2546. } else {
  2547. $actNumber = count($acts) + 1;
  2548. $actDetails = $actTitle;
  2549. }
  2550. // 解析该幕下的分镜
  2551. $segments = [];
  2552. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  2553. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  2554. foreach ($segmentMatches as $segmentMatch) {
  2555. $segmentNumber = intval($segmentMatch[1]);
  2556. $segmentContent = trim($segmentMatch[2]);
  2557. // 解析分镜详细信息
  2558. $segmentData = [
  2559. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT), // 生成唯一ID(后续可在生成任务里查看历史版本)
  2560. 'segment_number' => $segmentNumber,
  2561. 'segment_content' => $segmentContent,
  2562. 'description' => '',
  2563. 'composition' => '',
  2564. 'camera_movement' => '',
  2565. 'voice_actor' => '',
  2566. 'dialogue' => '',
  2567. 'frame_type' => '',
  2568. 'scene' => '', // 新增:场景
  2569. 'characters' => '', // 新增:出镜角色
  2570. 'tail_frame' => '', // 新增:尾帧描述
  2571. // 新增字段
  2572. 'emotion' => '中性', // 新增: 情感
  2573. 'gender' => '0', // 新增: 性别(0未知,1男,2女)
  2574. 'speed_ratio' => 0, // 新增: 语速
  2575. 'loudness_ratio' => 0, // 新增: 音量
  2576. 'emotion_scale' => 4, // 新增: 语调
  2577. 'pitch' => 0, // 新增: 音调
  2578. ];
  2579. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  2580. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  2581. $segmentData['description'] = trim($descMatch[1]);
  2582. }
  2583. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  2584. $segmentData['composition'] = trim($compMatch[1]);
  2585. }
  2586. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  2587. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  2588. }
  2589. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  2590. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  2591. }
  2592. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  2593. $dialogue = trim($dialogueMatch[1]) == '无' ? '' : trim($dialogueMatch[1]);
  2594. // 确保台词使用中文左右双引号
  2595. if (!empty($dialogue)) {
  2596. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  2597. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  2598. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  2599. if (!preg_match('/^[“]/', $dialogue)) {
  2600. $dialogue = '“' . $dialogue;
  2601. }
  2602. if (!preg_match('/[”]$/', $dialogue)) {
  2603. $dialogue .= '”';
  2604. }
  2605. // 将修改后的台词替换回 $segmentContent
  2606. $originalDialogue = $dialogueMatch[1];
  2607. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  2608. }
  2609. $segmentData['dialogue'] = $dialogue;
  2610. }
  2611. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  2612. $segmentData['frame_type'] = trim($frameMatch[1]);
  2613. }
  2614. // 新增:场景字段
  2615. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  2616. $segmentData['scene'] = trim($sceneMatch[1]);
  2617. }
  2618. // 新增:出镜角色字段
  2619. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  2620. $segmentData['characters'] = trim($charactersMatch[1]);
  2621. }
  2622. // 新增:尾帧描述字段
  2623. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  2624. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  2625. }
  2626. $replaceEmptyArr = [];
  2627. // 新增:情感字段
  2628. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  2629. $replaceEmptyArr[] = trim($emotionMatch[0]);
  2630. $segmentData['emotion'] = trim($emotionMatch[1]);
  2631. }
  2632. // 新增:性别字段
  2633. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  2634. $replaceEmptyArr[] = trim($genderMatch[0]);
  2635. $genderStr = trim($genderMatch[1]);
  2636. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  2637. $segmentData['gender'] = '1';
  2638. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  2639. $segmentData['gender'] = '2';
  2640. } else {
  2641. $segmentData['gender'] = '0';
  2642. }
  2643. }
  2644. // 新增:语速字段
  2645. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  2646. $replaceEmptyArr[] = trim($speedMatch[0]);
  2647. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  2648. }
  2649. // 新增:音量字段
  2650. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  2651. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  2652. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  2653. }
  2654. // 新增:情感强度字段
  2655. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  2656. $replaceEmptyArr[] = trim($scaleMatch[0]);
  2657. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  2658. }
  2659. // 新增:音调字段
  2660. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  2661. $replaceEmptyArr[] = trim($pitchMatch[0]);
  2662. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  2663. }
  2664. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  2665. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  2666. $segmentData['segment_content'] = preg_replace('/\n{2,}/', "\n", $segmentData['segment_content']);
  2667. $segmentData['segment_content'] = trim($segmentData['segment_content']);
  2668. $segments[] = $segmentData;
  2669. }
  2670. $acts[] = [
  2671. 'act_number' => $actNumber,
  2672. 'act_title' => $actTitle,
  2673. 'act_details' => $actDetails,
  2674. 'segments' => $segments
  2675. ];
  2676. }
  2677. $result['acts'] = $acts;
  2678. }
  2679. return $result;
  2680. }
  2681. /**
  2682. * 处理剧本内容(全能模式)
  2683. */
  2684. function handleScriptContentForAce($originalContent) {
  2685. if (!$originalContent) return [];
  2686. // 使用更精确的正则表达式分割内容
  2687. $parts = [];
  2688. // // 确保内容使用UTF-8编码
  2689. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  2690. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  2691. // }
  2692. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2693. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2694. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2695. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2696. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2697. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2698. // 提取剧本亮点(支持多个空格)
  2699. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2700. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2701. // 提取人物关系(支持多个空格)
  2702. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2703. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2704. // 提取核心矛盾(支持多个空格)
  2705. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2706. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2707. // 提取主体列表(支持多个空格)
  2708. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2709. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2710. $parts['roles'] = parseRolesFromTextForAce($rolesText);
  2711. // 提取美术风格(支持多个空格)
  2712. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2713. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2714. // 提取场景列表(支持多个空格)
  2715. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2716. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2717. $parts['scenes'] = parseScenesFromText($scenesText);
  2718. // 提取道具列表(支持多个空格)
  2719. preg_match('/###\s*道具列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $propsMatch);
  2720. $propsText = isset($propsMatch[1]) ? trim($propsMatch[1]) : '';
  2721. $parts['props'] = parsePropsFromText($propsText);
  2722. // 提取分集详细内容(多剧集模式,支持多个空格)
  2723. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2724. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2725. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2726. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2727. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2728. // 优先使用原文内容,其次使用分集详细内容
  2729. $parts['content'] = $generatedContent ?: $detailedContent;
  2730. $parts['episode_title'] = '';
  2731. $parts['acts'] = [];
  2732. // 单剧集格式:顶层是大纲信息,分段部分采用 handleEpisodeContentForAce 的结构标准
  2733. $singleStoryboard = '';
  2734. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2735. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2736. } elseif (preg_match('/###\s*分段剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2737. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2738. }
  2739. if ($singleStoryboard !== '') {
  2740. // 构造符合 handleEpisodeContentForAce 期望的输入格式
  2741. $episodeContent = '';
  2742. // 如果分镜剧本内容不包含剧集标题,添加默认标题
  2743. if (!preg_match('/第\d+集[::\s]+/u', $singleStoryboard)) {
  2744. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  2745. $episodeContent = $defaultEpisodeTitle . "\n\n";
  2746. }
  2747. // 组装完整的剧集内容,按 handleEpisodeContentForAce 期望的结构
  2748. $episodeSections = [];
  2749. // 添加故事梗概(如果有)
  2750. if (!empty($parts['intro'])) {
  2751. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  2752. }
  2753. // 添加美术风格(如果有)
  2754. if (!empty($parts['art_style'])) {
  2755. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  2756. }
  2757. // 添加主体列表(如果有)
  2758. if (!empty($rolesText)) {
  2759. $episodeSections[] = "###主体列表\n" . $rolesText;
  2760. }
  2761. // 添加场景列表(如果有)
  2762. if (!empty($scenesText)) {
  2763. $episodeSections[] = "###场景列表\n" . $scenesText;
  2764. }
  2765. // 添加道具列表(如果有)
  2766. if (!empty($propsText)) {
  2767. $episodeSections[] = "###道具列表\n" . $propsText;
  2768. }
  2769. // 添加分镜剧本内容(兼容"分镜剧本"和"分段剧本")
  2770. if (strpos($singleStoryboard, '###分镜剧本') === false && strpos($singleStoryboard, '###分段剧本') === false) {
  2771. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  2772. } else {
  2773. $episodeSections[] = $singleStoryboard;
  2774. }
  2775. // 拼接完整内容
  2776. $episodeContent .= implode("\n\n", $episodeSections);
  2777. // 调用 handleEpisodeContentForAce 方法解析
  2778. $episode_arr = handleEpisodeContentForAce($episodeContent);
  2779. if (!empty($episode_arr['acts'])) {
  2780. $parts['episode_title'] = getProp($episode_arr, 'episode_title', '');
  2781. $parts['acts'] = getProp($episode_arr, 'acts', []);
  2782. }
  2783. // 更新roles、scenes和props
  2784. $episode_roles = getProp($episode_arr, 'roles');
  2785. $episode_scenes = getProp($episode_arr, 'scenes');
  2786. $episode_props = getProp($episode_arr, 'props');
  2787. if ($episode_roles) $parts['roles'] = $episode_roles;
  2788. if ($episode_scenes) $parts['scenes'] = $episode_scenes;
  2789. if ($episode_props) $parts['props'] = $episode_props;
  2790. }
  2791. // 如果上面的处理没有得到 acts,尝试直接用原始内容调用 handleEpisodeContentForAce
  2792. if (empty($parts['acts'])) {
  2793. $fallbackEpisodeArr = handleEpisodeContentForAce($originalContent);
  2794. if (!empty($fallbackEpisodeArr['acts'])) {
  2795. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title', '');
  2796. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  2797. if (empty($parts['intro'])) {
  2798. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro', '');
  2799. }
  2800. if (empty($parts['art_style'])) {
  2801. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style', '');
  2802. }
  2803. }
  2804. // 更新roles、scenes和props
  2805. $episode_roles = getProp($fallbackEpisodeArr, 'roles');
  2806. $episode_scenes = getProp($fallbackEpisodeArr, 'scenes');
  2807. $episode_props = getProp($fallbackEpisodeArr, 'props');
  2808. if ($episode_roles) $parts['roles'] = $episode_roles;
  2809. if ($episode_scenes) $parts['scenes'] = $episode_scenes;
  2810. if ($episode_props) $parts['props'] = $episode_props;
  2811. }
  2812. // 多剧集格式:继续兼容旧的分集剧本结构
  2813. $fullScript = '';
  2814. if (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. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2819. $fullScript = trim($storyboardMatch[1]);
  2820. }
  2821. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  2822. $fullScript = trim($fallbackMatch[1]);
  2823. }
  2824. $episodes = [];
  2825. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  2826. foreach ($matches as $match) {
  2827. $episodeNumber = (int)trim($match[1]);
  2828. $episodeName = trim($match[2]);
  2829. $episodeContent = trim($match[3]);
  2830. $segments = [];
  2831. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  2832. foreach ($segmentMatches as $segMatch) {
  2833. $segmentNumber = (int)trim($segMatch[1]);
  2834. $segmentContent = trim($segMatch[2]);
  2835. $segments[] = [
  2836. 'segment_number' => $segmentNumber,
  2837. 'segment_content' => $segmentContent,
  2838. ];
  2839. }
  2840. $episodes[] = [
  2841. 'episode_number' => $episodeNumber,
  2842. 'title' => $episodeName,
  2843. 'content' => $episodeContent,
  2844. 'segments' => $segments,
  2845. ];
  2846. }
  2847. if (empty($episodes) && !empty($parts['acts'])) {
  2848. $singleSegments = [];
  2849. foreach ($parts['acts'] as $act) {
  2850. $actSegments = getProp($act, 'segments', []);
  2851. if (!is_array($actSegments)) {
  2852. continue;
  2853. }
  2854. foreach ($actSegments as $segment) {
  2855. $singleSegments[] = [
  2856. 'segment_number' => getProp($segment, 'segment_number'),
  2857. 'segment_content' => getProp($segment, 'segment_content'),
  2858. ];
  2859. }
  2860. }
  2861. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  2862. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  2863. $episodes[] = [
  2864. 'episode_number' => 1,
  2865. 'title' => $episodeName,
  2866. 'content' => $singleStoryboard,
  2867. 'segments' => $singleSegments,
  2868. ];
  2869. }
  2870. $parts['episodes'] = $episodes;
  2871. return $parts;
  2872. }
  2873. /**
  2874. * 将主体列表文本拆分为主体数组
  2875. *
  2876. * @param string $rolesText 主体列表文本内容
  2877. * @return array 主体名称数组
  2878. */
  2879. function parseRolesFromTextForAce(string $rolesText): array
  2880. {
  2881. if (empty($rolesText)) {
  2882. return [];
  2883. }
  2884. $roles = [];
  2885. // 按行分割文本
  2886. $lines = explode("\n", $rolesText);
  2887. foreach ($lines as $line) {
  2888. $line = trim($line);
  2889. if (empty($line)) {
  2890. continue;
  2891. }
  2892. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2893. $role = trim($charMatch[1]);
  2894. $description = trim($charMatch[2]);
  2895. $timbreName = null;
  2896. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  2897. $picPrompt = null;
  2898. $timbrePrompt = null;
  2899. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  2900. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  2901. $description = trim($fullMatch[1]);
  2902. $picPrompt = trim($fullMatch[2]);
  2903. $timbrePrompt = trim($fullMatch[3]);
  2904. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2905. // 兼容旧格式:主体描述{{音色名}}
  2906. $description = trim($timbreMatch[1]);
  2907. $timbrePrompt = trim($timbreMatch[2]);
  2908. }
  2909. $roleData = [
  2910. 'role' => $role,
  2911. 'description' => $description,
  2912. ];
  2913. // 如果有主体图片提示词,添加到数组中
  2914. if ($picPrompt) $roleData['pic_prompt'] = $picPrompt;
  2915. // 如果有音色提示词,添加到数组中
  2916. if ($timbrePrompt) $roleData['voice_prompt'] = $timbrePrompt;
  2917. if ($timbreName) {
  2918. $timbre = DB::table('mp_timbres')
  2919. ->where('is_enabled', 1)
  2920. ->where('timbre_name', 'like', "%{$timbreName}%")
  2921. ->orderBy('id')
  2922. ->select('timbre_type', 'audio_url')
  2923. ->first();
  2924. if ($timbre) {
  2925. $roleData['voice_name'] = $timbreName;
  2926. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2927. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2928. }
  2929. }
  2930. // else {
  2931. // // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  2932. // if ($picPrompt) {
  2933. // if (strstr($picPrompt, '男')) {
  2934. // $roleData['voice_name'] = '阳光青年';
  2935. // }elseif (strstr($picPrompt, '女')) {
  2936. // $roleData['voice_name'] = '爽快思思';
  2937. // }else {
  2938. // if ($description) {
  2939. // if (strstr($description, '男')) {
  2940. // $roleData['voice_name'] = '阳光青年';
  2941. // }elseif (strstr($description, '女')) {
  2942. // $roleData['voice_name'] = '爽快思思';
  2943. // }else {
  2944. // $roleData['voice_name'] = '旁白';
  2945. // }
  2946. // }
  2947. // }
  2948. // }
  2949. // if (!empty($roleData['voice_name'])) {
  2950. // if ($roleData['voice_name'] == '旁白') {
  2951. // $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  2952. // $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  2953. // }else {
  2954. // $timbre = DB::table('mp_timbres')
  2955. // ->where('is_enabled', 1)
  2956. // ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  2957. // ->orderBy('id')
  2958. // ->select('timbre_type', 'audio_url')
  2959. // ->first();
  2960. // if ($timbre) {
  2961. // $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2962. // $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2963. // }
  2964. // }
  2965. // }
  2966. // }
  2967. $roles[] = $roleData;
  2968. }
  2969. }
  2970. $hasNarrator = false;
  2971. foreach ($roles as $role) {
  2972. if (getProp($role, 'role') === '旁白') {
  2973. $hasNarrator = true;
  2974. break;
  2975. }
  2976. }
  2977. if (!$hasNarrator) {
  2978. $roles[] = [
  2979. 'role' => '旁白',
  2980. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2981. 'pic_prompt' => '',
  2982. 'voice_prompt' => '',
  2983. // 'voice_name' => '旁白',
  2984. // 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2985. // 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2986. ];
  2987. }
  2988. return $roles;
  2989. }
  2990. function handleEpisodeContentForAce($originalContent) {
  2991. if (!$originalContent) return [];
  2992. // 解析剧集内容
  2993. $result = [
  2994. 'episode_title' => '',
  2995. 'intro' => '',
  2996. 'art_style' => '',
  2997. 'roles' => [],
  2998. 'scenes' => [],
  2999. 'props' => [],
  3000. 'acts' => []
  3001. ];
  3002. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  3003. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  3004. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  3005. }
  3006. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  3007. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  3008. $result['intro'] = trim($summaryMatch[1]);
  3009. }
  3010. // 提取美术风格 - 兼容多种格式
  3011. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  3012. $result['art_style'] = trim($styleMatch[1]);
  3013. }
  3014. // 提取主体列表 - 兼容多种格式
  3015. // 旧正则(2026-08-14 前):只允许 ### 与标题同行,初衷是防止板块为空时把后续"###分段剧本"当板块内容;
  3016. // 但不兼容模型偶发的"###\n主体列表"换行标题格式(如 mp_anime_records id=31915),导致 roles/scenes/props 解析为空。
  3017. // if (preg_match('/###[ \t]*主体列表[ \t]*\r?\n(.*?)(?=###[^#\n]|\z)/s', $originalContent, $charactersMatch)) {
  3018. // 新正则:开头 \s*? 非贪婪,兼容 ###主体列表、### 主体列表、###\n主体列表、###\n\n主体列表;
  3019. // 结束边界 (?=\n?\s*###[^#]|\z) 保证空板块(### 后直接跟下一章节)与换行标题格式都不会吞入后续内容。
  3020. if (preg_match('/###\s*?主体列表\s*?\r?\n(.*?)(?=\n?\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  3021. $charactersText = trim($charactersMatch[1]);
  3022. $characterLines = explode("\n", $charactersText);
  3023. foreach ($characterLines as $line) {
  3024. $line = trim($line);
  3025. if (empty($line)) continue;
  3026. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  3027. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  3028. $role = trim($charMatch[1]);
  3029. $description = trim($charMatch[2]);
  3030. $timbreName = null;
  3031. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  3032. $picPrompt = null;
  3033. $timbrePrompt = null;
  3034. // 修复正则:使用更精确的匹配,支持花括号嵌套
  3035. // 格式1: 描述{pic_prompt} {{voice_prompt}}
  3036. if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
  3037. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  3038. $description = trim($fullMatch[1]);
  3039. $picPrompt = trim($fullMatch[2]);
  3040. $timbrePrompt = trim($fullMatch[3]);
  3041. }
  3042. // 格式2: 描述{{voice_prompt}}(兼容旧格式,只有音色)
  3043. elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $timbreMatch)) {
  3044. // 兼容旧格式:主体描述{{音色名}}
  3045. $description = trim($timbreMatch[1]);
  3046. $timbrePrompt = trim($timbreMatch[2]);
  3047. }
  3048. // 格式3: 描述{pic_prompt}(只有图片提示词)
  3049. elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
  3050. $description = trim($picMatch[1]);
  3051. $picPrompt = trim($picMatch[2]);
  3052. }
  3053. $roleData = [
  3054. 'role' => $role,
  3055. 'description' => $description
  3056. ];
  3057. // 如果有主体图片提示词,添加到数组中
  3058. if ($picPrompt) {
  3059. // 检查开头是否有"全景,正面拍摄。"
  3060. $prefix = '全景,正面拍摄。';
  3061. $prefixParts = ['全景', '正面拍摄'];
  3062. // 检查是否包含完整前缀
  3063. if (strpos($picPrompt, $prefix) !== 0) {
  3064. // 检查是否包含部分前缀词汇(不论位置)
  3065. $hasAnyPrefix = false;
  3066. foreach ($prefixParts as $part) {
  3067. if (mb_strpos($picPrompt, $part) !== false) {
  3068. $hasAnyPrefix = true;
  3069. break;
  3070. }
  3071. }
  3072. if ($hasAnyPrefix) {
  3073. // 移除所有"全景"和"正面拍摄"词汇(包括它们后面的标点)
  3074. $picPrompt = preg_replace('/全景[,,、。. ]*/u', '', $picPrompt);
  3075. $picPrompt = preg_replace('/正面拍摄[,,、。. ]*/u', '', $picPrompt);
  3076. // 清理开头和结尾的标点符号和空格
  3077. $picPrompt = preg_replace('/^[。,,、 ]+|[。,,、 ]+$/u', '', $picPrompt);
  3078. }
  3079. // 在开头添加完整前缀
  3080. $picPrompt = $prefix . $picPrompt;
  3081. }
  3082. // 检查是否包含"姿态:"或"姿态:"
  3083. if (preg_match('/姿态[::]/u', $picPrompt)) {
  3084. // 如果有姿态描述,统一替换为"姿态:站立"
  3085. $picPrompt = preg_replace('/姿态[::][^.。\n]+/u', '姿态:站立', $picPrompt);
  3086. } else {
  3087. // 如果没有姿态描述,在末尾添加"姿态:站立"
  3088. $picPrompt = preg_replace('/[。,, ]+$/u', '', $picPrompt) . '。姿态:站立。';
  3089. }
  3090. $roleData['pic_prompt'] = $picPrompt;
  3091. }
  3092. if ($timbrePrompt) $roleData['voice_prompt'] = $timbrePrompt;
  3093. $result['roles'][] = $roleData;
  3094. }
  3095. }
  3096. // // 加入旁白角色(如果不存在)
  3097. // $hasNarrator = false;
  3098. // foreach ($result['roles'] as $role) {
  3099. // if (isset($role['role']) && $role['role'] === '旁白') {
  3100. // $hasNarrator = true;
  3101. // break;
  3102. // }
  3103. // }
  3104. // if (!$hasNarrator) {
  3105. // $result['roles'][] = [
  3106. // 'role' => '旁白',
  3107. // 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  3108. // 'pic_prompt' => '',
  3109. // 'voice_name' => '旁白',
  3110. // 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  3111. // 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  3112. // ];
  3113. // }
  3114. }
  3115. // 提取场景列表 - 兼容多种格式
  3116. // 旧正则(2026-08-14 前):只允许 ### 与标题同行,原因同上方主体列表,不兼容"###\n场景列表"换行标题格式。
  3117. // if (preg_match('/###[ \t]*场景列表[ \t]*\r?\n(.*?)(?=###[^#\n]|\z)/s', $originalContent, $scenesMatch)) {
  3118. if (preg_match('/###\s*?场景列表\s*?\r?\n(.*?)(?=\n?\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  3119. $scenesText = trim($scenesMatch[1]);
  3120. $sceneLines = explode("\n", $scenesText);
  3121. foreach ($sceneLines as $line) {
  3122. $line = trim($line);
  3123. if (empty($line)) continue;
  3124. // 兼容中文冒号:和英文冒号:
  3125. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  3126. $scene = trim($sceneMatch[1]);
  3127. $description = trim($sceneMatch[2]);
  3128. $picPrompt = null;
  3129. // 检查描述末尾是否有{场景图片提示词}或{场景图片提示词}{{补充说明}}格式
  3130. // 格式1: 描述{pic_prompt}{{补充说明}}(如"{...}{{无人物}}")
  3131. if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
  3132. $description = trim($fullMatch[1]);
  3133. $picPrompt = trim($fullMatch[2]);
  3134. }
  3135. // 格式2: 描述{{补充说明}}(只有补充说明,无图片提示词)
  3136. elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $voiceMatch)) {
  3137. $description = trim($voiceMatch[1]);
  3138. }
  3139. // 格式3: 描述{pic_prompt}(只有图片提示词)
  3140. elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
  3141. $description = trim($picMatch[1]);
  3142. $picPrompt = trim($picMatch[2]);
  3143. }
  3144. $sceneData = [
  3145. 'scene' => $scene,
  3146. 'description' => $description
  3147. ];
  3148. // 如果有场景图片提示词,添加到数组中
  3149. if ($picPrompt) {
  3150. $sceneData['pic_prompt'] = $picPrompt;
  3151. }
  3152. $result['scenes'][] = $sceneData;
  3153. }
  3154. }
  3155. }
  3156. // 提取道具列表 - 兼容多种格式
  3157. // 旧正则(2026-08-14 前):只允许 ### 与标题同行,原因同上方主体列表,不兼容"###\n道具列表"换行标题格式;
  3158. // 同时旧代码仅在提取到 pic_prompt 时才保存道具,用于兜底防止把分段剧本误当道具,代价是纯描述道具被丢弃。
  3159. // if (preg_match('/###[ \t]*道具列表[ \t]*\r?\n(.*?)(?=###[^#\n]|\z)/s', $originalContent, $propsMatch)) {
  3160. if (preg_match('/###\s*?道具列表\s*?\r?\n(.*?)(?=\n?\s*###[^#]|\z)/s', $originalContent, $propsMatch)) {
  3161. $propsText = trim($propsMatch[1]);
  3162. $propLines = explode("\n", $propsText);
  3163. foreach ($propLines as $line) {
  3164. $line = trim($line);
  3165. if (empty($line)) continue;
  3166. // 兼容中文冒号:和英文冒号:
  3167. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $propMatch)) {
  3168. $prop = trim($propMatch[1]);
  3169. $description = trim($propMatch[2]);
  3170. $picPrompt = null;
  3171. // 检查描述末尾是否有{道具图片提示词}或{道具图片提示词}{{音效提示词}}格式(与主体列表保持一致)
  3172. // 格式1: 描述{pic_prompt}{{voice_prompt}}(图片提示词+音效提示词)
  3173. if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
  3174. $description = trim($fullMatch[1]);
  3175. $picPrompt = trim($fullMatch[2]);
  3176. }
  3177. // 格式2: 描述{{voice_prompt}}(只有音效提示词)
  3178. elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $voiceMatch)) {
  3179. $description = trim($voiceMatch[1]);
  3180. }
  3181. // 格式3: 描述{pic_prompt}(只有图片提示词)
  3182. elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
  3183. $description = trim($picMatch[1]);
  3184. $picPrompt = trim($picMatch[2]);
  3185. }
  3186. $propData = [
  3187. 'prop' => $prop,
  3188. 'description' => $description
  3189. ];
  3190. // 新正则已精确切分道具板块,不再依赖"必须有提示词"兜底,纯描述道具也保留
  3191. if ($picPrompt) {
  3192. $propData['pic_prompt'] = $picPrompt;
  3193. }
  3194. $result['props'][] = $propData;
  3195. }
  3196. }
  3197. }
  3198. // 提取分镜剧本 - 兼容多种格式(旧格式:###分镜剧本,新格式:###分段剧本)
  3199. $storyboardPattern = '/###\s*(?:分镜剧本|分段剧本)\s*\n(.*?)(?=\n\s*###[^#]|\z)/s';
  3200. if (preg_match($storyboardPattern, $originalContent, $storyboardMatch)) {
  3201. $storyboardText = trim($storyboardMatch[1]);
  3202. // 提取旁白音色(新格式独有)
  3203. $narratorVoice = '';
  3204. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $storyboardText, $narratorMatch)) {
  3205. $narratorVoice = trim($narratorMatch[1]);
  3206. // 将旁白加入到roles数组
  3207. $hasNarrator = false;
  3208. foreach ($result['roles'] as $role) {
  3209. if (isset($role['role']) && $role['role'] === '旁白') {
  3210. $hasNarrator = true;
  3211. break;
  3212. }
  3213. }
  3214. if (!$hasNarrator) {
  3215. $result['roles'][] = [
  3216. 'role' => '旁白',
  3217. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  3218. 'pic_prompt' => '',
  3219. 'voice_prompt' => $narratorVoice
  3220. ];
  3221. }
  3222. }
  3223. // 按幕/片段分割 - 兼容"第X幕"和"片段X"两种格式
  3224. $acts = [];
  3225. // 先在开头添加换行符,确保第1幕/片段1也能被正确分割
  3226. $normalizedText = "\n" . $storyboardText;
  3227. $parts = preg_split('/\n\s*##/', $normalizedText);
  3228. foreach ($parts as $part) {
  3229. $part = trim($part);
  3230. if (empty($part)) continue;
  3231. // 兼容"第X幕"和"片段X"两种格式
  3232. if (!preg_match('/^(?:第\d+幕|片段\d+)/', $part)) {
  3233. continue;
  3234. }
  3235. // 分离标题和内容
  3236. $lines = explode("\n", $part, 2);
  3237. $actTitle = trim($lines[0]);
  3238. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  3239. // 解析标题,提取序号和详细信息
  3240. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  3241. // 旧格式:第X幕
  3242. $actNumber = intval($actTitleMatch[1]);
  3243. $actDetails = trim($actTitleMatch[2]);
  3244. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  3245. $actDetails = $actTitle;
  3246. }
  3247. } elseif (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  3248. // 新格式:片段X
  3249. $actNumber = intval($segmentTitleMatch[1]);
  3250. $actDetails = $actTitle;
  3251. } else {
  3252. $actNumber = count($acts) + 1;
  3253. $actDetails = $actTitle;
  3254. }
  3255. // 提取时长(新格式独有,仅保留数字)
  3256. $actDuration = '';
  3257. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  3258. $actDurationStr = trim($actDurationMatch[1]);
  3259. // 提取数字部分(支持整数和小数)
  3260. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  3261. $actDuration = $numMatch[1];
  3262. }
  3263. }
  3264. // 解析该幕/片段下的分镜
  3265. $segments = [];
  3266. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  3267. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  3268. foreach ($segmentMatches as $segmentMatch) {
  3269. $segmentNumber = intval($segmentMatch[1]);
  3270. $segmentContent = trim($segmentMatch[2]);
  3271. // 解析分镜详细信息
  3272. $segmentData = [
  3273. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT),
  3274. 'segment_number' => $segmentNumber,
  3275. 'segment_content' => $segmentContent,
  3276. 'description' => '',
  3277. 'composition' => '',
  3278. 'camera_movement' => '',
  3279. 'voice_actor' => '',
  3280. 'dialogue' => '',
  3281. 'frame_type' => '',
  3282. 'scene' => '',
  3283. 'characters' => '',
  3284. 'tail_frame' => '',
  3285. 'emotion' => '中性',
  3286. 'gender' => '0',
  3287. 'speed_ratio' => 0,
  3288. 'loudness_ratio' => 0,
  3289. 'emotion_scale' => 4,
  3290. 'pitch' => 0,
  3291. ];
  3292. // 提取场景
  3293. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3294. $segmentData['scene'] = trim($sceneMatch[1]);
  3295. }
  3296. // 提取画面描述 - 兼容新格式的方括号标注
  3297. if (preg_match('/(?:画面|画面描述|镜头描述|场景描述)[::]\s*(\[.*?\])?\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3298. $frameTypeInDesc = isset($descMatch[1]) ? trim($descMatch[1], '[]') : '';
  3299. $description = trim($descMatch[2]);
  3300. if (!empty($frameTypeInDesc)) {
  3301. $segmentData['frame_type'] = $frameTypeInDesc;
  3302. }
  3303. $segmentData['description'] = $description;
  3304. }
  3305. // 提取运镜
  3306. if (preg_match('/(?:运镜|运镜调度|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3307. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3308. }
  3309. // 提取配音台词 - 兼容新格式"中文配音:[角色] 台词"
  3310. // 修复:排除背景音效等非台词内容
  3311. if (preg_match('/配音台词[::]\s*(?:中文配音[::]?)?\s*(?:\[([^\]]+)\])?\s*([^\n]*?)(?=\n|$)/u', $segmentContent, $dialogueMatch)) {
  3312. $voiceActor = isset($dialogueMatch[1]) ? trim($dialogueMatch[1]) : '';
  3313. $dialogue = isset($dialogueMatch[2]) ? trim($dialogueMatch[2]) : '';
  3314. // 排除非台词内容(如果匹配到的是空或者是其他字段标记)
  3315. if (!empty($dialogue) && preg_match('/^(?:背景音效|音效|场景|画面|运镜|构图)[::]/u', $dialogue)) {
  3316. $dialogue = ''; // 如果匹配到的是其他字段,清空
  3317. }
  3318. if (!empty($voiceActor)) {
  3319. $segmentData['voice_actor'] = $voiceActor;
  3320. }
  3321. if ($dialogue && $dialogue !== '无') {
  3322. // 确保台词使用中文左右双引号
  3323. $dialogue = preg_replace('/^[""]/u', '"', $dialogue);
  3324. $dialogue = preg_replace('/[""]$/u', '"', $dialogue);
  3325. if (!preg_match('/^["]/', $dialogue)) {
  3326. $dialogue = '"' . $dialogue;
  3327. }
  3328. if (!preg_match('/["]$/', $dialogue)) {
  3329. $dialogue .= '"';
  3330. }
  3331. $segmentData['dialogue'] = $dialogue;
  3332. }
  3333. }
  3334. // 兼容旧格式的台词字段
  3335. // 修复:排除背景音效等非台词内容
  3336. if (empty($segmentData['dialogue']) && preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]*?)(?=\n|$)/u', $segmentContent, $oldDialogueMatch)) {
  3337. $dialogue = trim($oldDialogueMatch[1]);
  3338. // 排除非台词内容
  3339. if (!empty($dialogue) && preg_match('/^(?:背景音效|音效|场景|画面|运镜|构图)[::]/u', $dialogue)) {
  3340. $dialogue = ''; // 如果匹配到的是其他字段,清空
  3341. }
  3342. if ($dialogue && $dialogue !== '无') {
  3343. $dialogue = preg_replace('/^[""]/u', '"', $dialogue);
  3344. $dialogue = preg_replace('/[""]$/u', '"', $dialogue);
  3345. if (!preg_match('/^["]/', $dialogue)) {
  3346. $dialogue = '"' . $dialogue;
  3347. }
  3348. if (!preg_match('/["]$/', $dialogue)) {
  3349. $dialogue .= '"';
  3350. }
  3351. $segmentData['dialogue'] = $dialogue;
  3352. }
  3353. }
  3354. // 兼容旧格式的配音角色字段
  3355. if (empty($segmentData['voice_actor']) && preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3356. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3357. }
  3358. // 提取构图
  3359. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3360. $segmentData['composition'] = trim($compMatch[1]);
  3361. }
  3362. // 提取画面类型
  3363. if (empty($segmentData['frame_type']) && preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3364. $segmentData['frame_type'] = trim($frameMatch[1]);
  3365. }
  3366. // 提取出镜角色
  3367. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3368. $segmentData['characters'] = trim($charactersMatch[1]);
  3369. }
  3370. // 提取尾帧描述
  3371. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3372. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3373. }
  3374. $replaceEmptyArr = [];
  3375. // 提取情感
  3376. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3377. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3378. $segmentData['emotion'] = trim($emotionMatch[1]);
  3379. }
  3380. // 提取性别
  3381. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3382. $replaceEmptyArr[] = trim($genderMatch[0]);
  3383. $genderStr = trim($genderMatch[1]);
  3384. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3385. $segmentData['gender'] = '1';
  3386. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3387. $segmentData['gender'] = '2';
  3388. } else {
  3389. $segmentData['gender'] = '0';
  3390. }
  3391. }
  3392. // 提取语速
  3393. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3394. $replaceEmptyArr[] = trim($speedMatch[0]);
  3395. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3396. }
  3397. // 提取音量
  3398. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3399. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3400. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3401. }
  3402. // 提取情感强度
  3403. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3404. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3405. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3406. }
  3407. // 提取音调
  3408. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3409. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3410. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3411. }
  3412. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3413. $segmentData['segment_content'] = preg_replace('/\n{2,}/', "\n", $segmentData['segment_content']);
  3414. $segmentData['segment_content'] = trim($segmentData['segment_content']);
  3415. $segments[] = $segmentData;
  3416. }
  3417. $acts[] = [
  3418. 'act_number' => $actNumber,
  3419. 'act_title' => $actTitle,
  3420. 'act_details' => $actDetails,
  3421. 'act_duration' => $actDuration,
  3422. 'segments' => $segments
  3423. ];
  3424. }
  3425. $result['acts'] = $acts;
  3426. }
  3427. return $result;
  3428. }
  3429. /**
  3430. * 远程图片压缩(尽可能保持原图 fidelity,压缩到不超过 maxBytes 字节)
  3431. * 采用有损/无损组合策略:保留原始格式尽量不失真,若需要则通过尺寸缩放和质量调节来降低体积。
  3432. *
  3433. * @param string $url 远程图片 URL
  3434. * @param int $maxBytes 最大字节数,默认 3MB
  3435. * @param string|null $aspectRatio 目标长宽比,如 "16:9"、"4:3"、"1:1" 等,null 则保持原图比例
  3436. * @return string|null 返回压缩后的图片二进制数据,失败时返回 null
  3437. */
  3438. function compressRemoteImageUrlToSize(string $url, int $maxBytes = 3 * 1024 * 1024, ?string $aspectRatio = null): ?string
  3439. {
  3440. // 1) 下载图片数据(使用 Guzzle 以避免 allow_url_fopen 依赖)
  3441. try {
  3442. $client = new Client(['timeout' => 30]);
  3443. $response = $client->get($url, ['stream' => true]);
  3444. if ($response->getStatusCode() !== 200) {
  3445. return null;
  3446. }
  3447. $data = $response->getBody()->getContents();
  3448. } catch (\Exception $e) {
  3449. return null;
  3450. }
  3451. if (!$data) return null;
  3452. // 2) 识别图片类型
  3453. $imgInfo = @getimagesizefromstring($data);
  3454. $mime = $imgInfo['mime'] ?? '';
  3455. if ($mime == 'image/jpeg') return null; // JPEG 不做有损压缩
  3456. // 3) 载入图像对象
  3457. $srcImg = @imagecreatefromstring($data);
  3458. if (!$srcImg) {
  3459. return null;
  3460. }
  3461. $origW = imagesx($srcImg);
  3462. $origH = imagesy($srcImg);
  3463. // 3.2) 计算目标尺寸(根据长宽比调整)
  3464. $targetW = $origW;
  3465. $targetH = $origH;
  3466. if ($aspectRatio !== null) {
  3467. // 解析长宽比,如 "16:9" -> [16, 9]
  3468. $validRatios = array_keys(BaseConst::IMAGE_RATIOS);
  3469. if (in_array($aspectRatio, $validRatios)) {
  3470. list($ratioW, $ratioH) = explode(':', $aspectRatio);
  3471. $ratioW = (float)$ratioW;
  3472. $ratioH = (float)$ratioH;
  3473. $targetRatio = $ratioW / $ratioH;
  3474. $currentRatio = $origW / $origH;
  3475. // 根据目标比例裁剪图片
  3476. if ($currentRatio > $targetRatio) {
  3477. // 原图更宽,需要裁剪宽度
  3478. $targetW = (int)round($origH * $targetRatio);
  3479. $targetH = $origH;
  3480. } else {
  3481. // 原图更高,需要裁剪高度
  3482. $targetW = $origW;
  3483. $targetH = (int)round($origW / $targetRatio);
  3484. }
  3485. }
  3486. }
  3487. // 如果需要裁剪,创建裁剪后的图像
  3488. if ($targetW !== $origW || $targetH !== $origH) {
  3489. $croppedImg = imagecreatetruecolor($targetW, $targetH);
  3490. imagealphablending($croppedImg, false);
  3491. imagesavealpha($croppedImg, true);
  3492. // 处理透明背景
  3493. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3494. $transparent = imagecolorallocatealpha($croppedImg, 0, 0, 0, 127);
  3495. imagefill($croppedImg, 0, 0, $transparent);
  3496. }
  3497. // 居中裁剪
  3498. $srcX = (int)(($origW - $targetW) / 2);
  3499. $srcY = (int)(($origH - $targetH) / 2);
  3500. imagecopy($croppedImg, $srcImg, 0, 0, $srcX, $srcY, $targetW, $targetH);
  3501. // 替换原图
  3502. safeDestroyImage($srcImg);
  3503. $srcImg = $croppedImg;
  3504. $origW = $targetW;
  3505. $origH = $targetH;
  3506. }
  3507. // 3.1) 内部渲染成不同格式的字符串
  3508. $render = function($srcRes, string $mimeType, int $quality) {
  3509. ob_start();
  3510. switch (strtolower($mimeType)) {
  3511. case 'image/jpeg':
  3512. case 'image/jpg':
  3513. case 'image/pjpeg':
  3514. // 输出 JPEG
  3515. imagejpeg($srcRes, null, $quality);
  3516. break;
  3517. case 'image/png':
  3518. // 将 quality 映射到 PNG 的 compression level (0-9)
  3519. $level = (int)round((100 - $quality) / 11.11);
  3520. if ($level < 0) $level = 0;
  3521. if ($level > 9) $level = 9;
  3522. imagepng($srcRes, null, $level);
  3523. break;
  3524. case 'image/webp':
  3525. if (function_exists('imagewebp')) {
  3526. imagewebp($srcRes, null, $quality);
  3527. } else {
  3528. imagejpeg($srcRes, null, $quality);
  3529. }
  3530. break;
  3531. default:
  3532. imagejpeg($srcRes, null, $quality);
  3533. break;
  3534. }
  3535. $out = ob_get_contents();
  3536. ob_end_clean();
  3537. return $out;
  3538. };
  3539. // 4) 尝试策略:尽量保留原图尺寸,逐步降维/降质量,直到 <= maxBytes
  3540. $tryList = [];
  3541. // 原始尺寸,尽量保留
  3542. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>100];
  3543. // 逐步缩小尺寸
  3544. for ($s = 0.9; $s >= 0.2; $s -= 0.1) {
  3545. $tryList[] = ['scale'=>$s, 'mime'=>$mime, 'quality'=>90];
  3546. }
  3547. // 一系列质量等级(用于 JPEG/WebP)
  3548. $qualityLevels = [95, 90, 85, 75, 60, 50, 40, 30];
  3549. foreach ($qualityLevels as $q) {
  3550. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>$q];
  3551. }
  3552. $bestData = null;
  3553. foreach ($tryList as $cand) {
  3554. $scale = isset($cand['scale']) ? (float)$cand['scale'] : 1.0;
  3555. $mimeT = $cand['mime'] ?? $mime;
  3556. $quality = isset($cand['quality']) ? (int)$cand['quality'] : 90;
  3557. $w = (int)round($origW * $scale);
  3558. $h = (int)round($origH * $scale);
  3559. $src = $srcImg;
  3560. $tempImg = null;
  3561. if ($scale < 1.0) {
  3562. $tempImg = imagecreatetruecolor($w, $h);
  3563. // 处理透明通道
  3564. imagealphablending($tempImg, false);
  3565. imagesavealpha($tempImg, true);
  3566. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3567. $transparent = imagecolorallocatealpha($tempImg, 0, 0, 0, 127);
  3568. imagefill($tempImg, 0, 0, $transparent);
  3569. }
  3570. // 确保 $srcImg 有效
  3571. if (!$srcImg || (!is_resource($srcImg) && !($srcImg instanceof \GdImage))) {
  3572. safeDestroyImage($tempImg);
  3573. continue;
  3574. }
  3575. imagecopyresampled($tempImg, $srcImg, 0, 0, 0, 0, $w, $h, $origW, $origH);
  3576. $src = $tempImg;
  3577. }
  3578. $imageBytes = $render($src, $mimeT, $quality);
  3579. if ($tempImg !== null) {
  3580. safeDestroyImage($tempImg);
  3581. }
  3582. if ($imageBytes !== false && strlen($imageBytes) <= $maxBytes) {
  3583. $bestData = $imageBytes;
  3584. break;
  3585. }
  3586. }
  3587. // 5) 回退策略:若仍未达到要求,尝试更大幅度降解到一个合理的小尺寸 JPEG
  3588. if ($bestData === null) {
  3589. $tmpW = max(1, (int)round($origW * 0.5));
  3590. $tmpH = max(1, (int)round($origH * 0.5));
  3591. $tmpImg = imagecreatetruecolor($tmpW, $tmpH);
  3592. imagealphablending($tmpImg, false);
  3593. imagesavealpha($tmpImg, true);
  3594. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3595. $transparent = imagecolorallocatealpha($tmpImg, 0, 0, 0, 127);
  3596. imagefill($tmpImg, 0, 0, $transparent);
  3597. }
  3598. imagecopyresampled($tmpImg, $srcImg, 0, 0, 0, 0, $tmpW, $tmpH, $origW, $origH);
  3599. ob_start();
  3600. if (in_array(strtolower($mime), ['image/jpeg','image/jpg','image/pjpeg'])) {
  3601. imagejpeg($tmpImg, null, 75);
  3602. } elseif (strtolower($mime) === 'image/png') {
  3603. imagepng($tmpImg, null, 6);
  3604. } elseif (function_exists('imagewebp')) {
  3605. imagewebp($tmpImg, null, 75);
  3606. } else {
  3607. imagejpeg($tmpImg, null, 75);
  3608. }
  3609. $tmpBytes = ob_get_contents();
  3610. ob_end_clean();
  3611. safeDestroyImage($tmpImg);
  3612. if ($tmpBytes !== '' && strlen($tmpBytes) <= $maxBytes) {
  3613. $bestData = $tmpBytes;
  3614. }
  3615. }
  3616. // 6) 清理
  3617. safeDestroyImage($srcImg);
  3618. return $bestData;
  3619. }
  3620. /**
  3621. * 安全销毁 GD 图像资源(兼容 PHP7.4+ 的资源管理)
  3622. * 通过引用传递并在销毁后置空变量,避免未定义变量的问题
  3623. *
  3624. * @param resource|\GdImage|null &$img GD 图像资源或对象(PHP7.4 为 resource,PHP8.0+ 为 GdImage)
  3625. */
  3626. function safeDestroyImage(&$img)
  3627. {
  3628. if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
  3629. @imagedestroy($img);
  3630. }
  3631. $img = null;
  3632. }
  3633. /**
  3634. * 图片超清(超分辨率)放大
  3635. *
  3636. * 默认使用 FFmpeg(Lanczos + unsharp)进行放大,画质优于 GD;
  3637. * 本地环境(APP_ENV=local)或服务器未安装 FFmpeg 时自动回退到 GD 插值放大,
  3638. * 使用 GD 前会先检查 GD 扩展是否可用,避免报错。
  3639. * 说明:插值放大不会像 AI 超分那样生成全新细节,但零外部 API、可实时完成。
  3640. *
  3641. * 参数:
  3642. * - image_url string 必填 原图 URL(https)或服务器本地绝对路径
  3643. * - target string 可选 目标档位:1080p / 2k / 4k,默认 4k(按长边放大)
  3644. * - width int 可选 指定目标宽度(与 height 同时传时优先于 target)
  3645. * - height int 可选 指定目标高度
  3646. * - format string 可选 输出格式:jpg / png / webp,默认保持原图格式
  3647. * (gif 转 png;webp 带透明转 png、无透明转 jpg)
  3648. * - quality int 可选 输出质量 1-100,默认 95(jpg/webp 生效)
  3649. * - sharpen bool 可选 是否锐化,默认 true
  3650. * - sharpen_amount float 可选 锐化强度 0-2,默认 0.35
  3651. * - upload bool 可选 是否上传 TOS 返回 URL,默认 true;false 时返回 base64
  3652. * - driver string 可选 处理驱动:ffmpeg(默认)/ gd;本地环境强制跳过 ffmpeg
  3653. *
  3654. * @param array $params
  3655. * @return array
  3656. * @throws \InvalidArgumentException|\RuntimeException
  3657. */
  3658. function upscaleImage(array $params): array
  3659. {
  3660. $imageUrl = trim((string)($params['image_url'] ?? ''));
  3661. if ($imageUrl === '') {
  3662. throw new \InvalidArgumentException('image_url不能为空');
  3663. }
  3664. // 读取图片二进制(支持远程URL和本地路径)
  3665. $binary = @file_get_contents($imageUrl);
  3666. if ($binary === false || strlen($binary) === 0) {
  3667. throw new \RuntimeException('图片读取失败: ' . $imageUrl);
  3668. }
  3669. $info = @getimagesizefromstring($binary);
  3670. if ($info === false) {
  3671. throw new \RuntimeException('无法识别的图片格式: ' . $imageUrl);
  3672. }
  3673. $srcWidth = max(1, (int)$info[0]);
  3674. $srcHeight = max(1, (int)$info[1]);
  3675. $srcType = (int)($info[2] ?? IMAGETYPE_PNG);
  3676. // WebP 默认输出格式取决于是否带透明通道(有透明转PNG保留透明,无透明转JPG控制体积)
  3677. $srcHasAlpha = $srcType === IMAGETYPE_WEBP && upscaleImageHasAlpha($binary);
  3678. // 计算目标尺寸
  3679. [$dstWidth, $dstHeight] = upscaleImageResolveTargetDimensions($srcWidth, $srcHeight, $params);
  3680. // 目标尺寸不比原图大时不降采样,直接返回原图
  3681. if ($dstWidth <= $srcWidth && $dstHeight <= $srcHeight) {
  3682. return [
  3683. 'url' => $imageUrl,
  3684. 'base64' => null,
  3685. 'width' => $srcWidth,
  3686. 'height' => $srcHeight,
  3687. 'src_width' => $srcWidth,
  3688. 'src_height' => $srcHeight,
  3689. 'upscaled' => false,
  3690. 'driver' => 'original',
  3691. ];
  3692. }
  3693. // 驱动选择:默认 ffmpeg;本地环境跳过 ffmpeg;ffmpeg 不可用时回退 gd;
  3694. // 使用 gd 前先检查 GD 扩展是否可用,防止报错
  3695. $driver = strtolower((string)($params['driver'] ?? 'ffmpeg'));
  3696. if (!in_array($driver, ['ffmpeg', 'gd'], true)) {
  3697. throw new \InvalidArgumentException('不支持的driver: ' . $driver . '(可选: gd / ffmpeg)');
  3698. }
  3699. $isLocal = env('APP_ENV') === 'local';
  3700. $useFfmpeg = false;
  3701. $useGd = false;
  3702. if ($driver === 'ffmpeg') {
  3703. if ($isLocal) {
  3704. // 本地环境跳过 ffmpeg,使用 GD 超分
  3705. $useGd = true;
  3706. } elseif (upscaleImageIsFfmpegAvailable((string)env('FFMPEG_PATH', 'ffmpeg'))) {
  3707. $useFfmpeg = true;
  3708. } else {
  3709. // 线上未安装 ffmpeg,回退 GD 超分
  3710. $useGd = true;
  3711. }
  3712. } else {
  3713. $useGd = true;
  3714. }
  3715. if ($useGd && !upscaleImageGdAvailable()) {
  3716. $reason = $isLocal ? '本地环境已跳过FFmpeg' : 'FFmpeg不可用';
  3717. throw new \RuntimeException($reason . ',且当前PHP环境缺少GD扩展,无法进行图片超分');
  3718. }
  3719. if ($useFfmpeg) {
  3720. return upscaleImageWithFfmpeg(
  3721. $params,
  3722. $binary,
  3723. $srcType,
  3724. $srcHasAlpha,
  3725. $srcWidth,
  3726. $srcHeight,
  3727. $dstWidth,
  3728. $dstHeight
  3729. );
  3730. }
  3731. return upscaleImageWithGd(
  3732. $params,
  3733. $binary,
  3734. $srcType,
  3735. $srcHasAlpha,
  3736. $srcWidth,
  3737. $srcHeight,
  3738. $dstWidth,
  3739. $dstHeight
  3740. );
  3741. }
  3742. /**
  3743. * 使用 GD 进行图片超分放大(Blackman/Bicubic 插值 + 卷积锐化)
  3744. *
  3745. * @param array $params
  3746. * @param string $binary 图片二进制内容
  3747. * @param int $srcType 原图类型(IMAGETYPE_*)
  3748. * @param bool $srcHasAlpha 原图是否带透明通道(WebP 默认格式判断用)
  3749. * @param int $srcWidth
  3750. * @param int $srcHeight
  3751. * @param int $dstWidth
  3752. * @param int $dstHeight
  3753. * @return array
  3754. * @throws \RuntimeException
  3755. */
  3756. function upscaleImageWithGd(
  3757. array $params,
  3758. string $binary,
  3759. int $srcType,
  3760. bool $srcHasAlpha,
  3761. int $srcWidth,
  3762. int $srcHeight,
  3763. int $dstWidth,
  3764. int $dstHeight
  3765. ): array {
  3766. // 4K 放大峰值内存较高:目标图(4B/像素) + 锐化卷积临时缓冲(4B/像素) + 源图 + 编码缓冲,
  3767. // 按需临时提升内存限制,避免超过默认 128M 报 FatalError
  3768. upscaleImageEnsureMemory(
  3769. $dstWidth * $dstHeight * 8 + $srcWidth * $srcHeight * 4 + 96 * 1024 * 1024
  3770. );
  3771. $srcImg = @imagecreatefromstring($binary);
  3772. if (!$srcImg) {
  3773. throw new \RuntimeException('图片解码失败');
  3774. }
  3775. $dstImg = null;
  3776. try {
  3777. // 高质量插值放大(Blackman 优于 Bicubic,PHP7.4 低版本需回退)
  3778. $filter = defined('IMG_BLACKMAN') ? IMG_BLACKMAN : IMG_BICUBIC;
  3779. $dstImg = imagescale($srcImg, $dstWidth, $dstHeight, $filter);
  3780. if (!$dstImg) {
  3781. throw new \RuntimeException('图片放大失败');
  3782. }
  3783. // 缩放完成后原图不再需要,提前释放以降低内存峰值
  3784. safeDestroyImage($srcImg);
  3785. // 可选锐化,弥补插值放大后的发虚感
  3786. $sharpen = (bool)($params['sharpen'] ?? true);
  3787. $sharpenAmount = (float)($params['sharpen_amount'] ?? 0.35);
  3788. if ($sharpen && $sharpenAmount > 0.01 && function_exists('imageconvolution')) {
  3789. upscaleImageSharpen($dstImg, min(2.0, max(0.01, $sharpenAmount)));
  3790. }
  3791. // 确定输出格式并编码
  3792. $format = upscaleImageResolveOutputFormat($params, $srcType, $srcHasAlpha);
  3793. $quality = max(1, min(100, (int)($params['quality'] ?? 95)));
  3794. $encoded = upscaleImageEncode($dstImg, $format, $quality);
  3795. if ($encoded === null) {
  3796. throw new \RuntimeException('图片编码失败,不支持的输出格式: ' . $format);
  3797. }
  3798. return upscaleImageBuildResult(
  3799. $params,
  3800. $encoded,
  3801. $format,
  3802. $dstWidth,
  3803. $dstHeight,
  3804. $srcWidth,
  3805. $srcHeight,
  3806. 'gd'
  3807. );
  3808. } finally {
  3809. safeDestroyImage($srcImg);
  3810. safeDestroyImage($dstImg);
  3811. }
  3812. }
  3813. /**
  3814. * 使用 FFmpeg 进行图片超分放大(Lanczos 插值 + unsharp 锐化)
  3815. *
  3816. * 与视频超分保持一致的 ffmpeg 用法,仅当 ffmpeg 可用时进入。
  3817. *
  3818. * @param array $params
  3819. * @param string $binary 图片二进制内容
  3820. * @param int $srcType 原图类型(IMAGETYPE_*)
  3821. * @param bool $srcHasAlpha 原图是否带透明通道(WebP 默认格式判断用)
  3822. * @param int $srcWidth
  3823. * @param int $srcHeight
  3824. * @param int $dstWidth
  3825. * @param int $dstHeight
  3826. * @return array
  3827. * @throws \RuntimeException
  3828. */
  3829. function upscaleImageWithFfmpeg(
  3830. array $params,
  3831. string $binary,
  3832. int $srcType,
  3833. bool $srcHasAlpha,
  3834. int $srcWidth,
  3835. int $srcHeight,
  3836. int $dstWidth,
  3837. int $dstHeight
  3838. ): array {
  3839. $ffmpegPath = (string)env('FFMPEG_PATH', 'ffmpeg');
  3840. // 创建临时目录
  3841. $tempDir = storage_path('app/temp/images');
  3842. if (!is_dir($tempDir)) {
  3843. @mkdir($tempDir, 0775, true);
  3844. }
  3845. $format = upscaleImageResolveOutputFormat($params, $srcType, $srcHasAlpha);
  3846. $ext = $format === 'jpeg' ? 'jpg' : $format;
  3847. $quality = max(1, min(100, (int)($params['quality'] ?? 95)));
  3848. $uniqueId = 'img_upscale_' . date('YmdHis') . '_' . uniqid() . '_' . bin2hex(random_bytes(4));
  3849. $inputFile = $tempDir . '/' . $uniqueId . '_input';
  3850. $outputFile = $tempDir . '/' . $uniqueId . '_output.' . $ext;
  3851. try {
  3852. if (file_put_contents($inputFile, $binary) === false) {
  3853. throw new \RuntimeException('图片写入临时文件失败');
  3854. }
  3855. // 构建滤镜链:Lanczos 缩放 + unsharp 锐化(亮度通道)
  3856. $filters = ['scale=' . $dstWidth . ':' . $dstHeight . ':flags=lanczos'];
  3857. $sharpen = (bool)($params['sharpen'] ?? true);
  3858. if ($sharpen) {
  3859. $sharpenAmount = (float)($params['sharpen_amount'] ?? 0.35);
  3860. $luma = number_format(min(2.0, max(0.1, $sharpenAmount * 2)), 2, '.', '');
  3861. $filters[] = 'unsharp=5:5:' . $luma . ':5:5:0.0';
  3862. }
  3863. $encodeArgs = upscaleImageBuildFfmpegEncodeArgs($format, $quality);
  3864. $ffmpegCmd = escapeshellarg($ffmpegPath)
  3865. . ' -y -i ' . escapeshellarg($inputFile)
  3866. . ' -vf ' . escapeshellarg(implode(',', $filters))
  3867. . ' ' . $encodeArgs
  3868. . ' ' . escapeshellarg($outputFile)
  3869. . ' 2>&1';
  3870. dLog('generate')->info('FFmpeg图片放大命令', ['command' => $ffmpegCmd]);
  3871. $output = shell_exec($ffmpegCmd);
  3872. if (!file_exists($outputFile) || filesize($outputFile) === 0) {
  3873. throw new \RuntimeException('FFmpeg图片放大失败: ' . trim((string)$output));
  3874. }
  3875. $encoded = file_get_contents($outputFile);
  3876. if ($encoded === false || strlen($encoded) === 0) {
  3877. throw new \RuntimeException('FFmpeg放大结果读取失败');
  3878. }
  3879. return upscaleImageBuildResult(
  3880. $params,
  3881. $encoded,
  3882. $format,
  3883. $dstWidth,
  3884. $dstHeight,
  3885. $srcWidth,
  3886. $srcHeight,
  3887. 'ffmpeg'
  3888. );
  3889. } finally {
  3890. @unlink($inputFile);
  3891. @unlink($outputFile);
  3892. }
  3893. }
  3894. /**
  3895. * 检查 GD 扩展是否可用于图片超分
  3896. *
  3897. * @return bool
  3898. */
  3899. function upscaleImageGdAvailable(): bool
  3900. {
  3901. return extension_loaded('gd')
  3902. && function_exists('imagecreatefromstring')
  3903. && function_exists('imagescale');
  3904. }
  3905. /**
  3906. * 获取当前 PHP 内存限制(字节),-1 表示无限制
  3907. *
  3908. * @return int
  3909. */
  3910. function upscaleImageMemoryLimitBytes(): int
  3911. {
  3912. $val = trim((string)ini_get('memory_limit'));
  3913. if ($val === '' || $val === '-1') {
  3914. return -1;
  3915. }
  3916. $unit = strtoupper(substr($val, -1));
  3917. $num = (float)$val;
  3918. switch ($unit) {
  3919. case 'G':
  3920. return (int)($num * 1024 * 1024 * 1024);
  3921. case 'M':
  3922. return (int)($num * 1024 * 1024);
  3923. case 'K':
  3924. return (int)($num * 1024);
  3925. default:
  3926. return (int)$num;
  3927. }
  3928. }
  3929. /**
  3930. * 确保 PHP 内存限制满足图片超分需要(只升不降;已是无限制时不做处理)
  3931. *
  3932. * 4K 放大时源图解码、目标图、锐化卷积缓冲同时存在,峰值内存较大,
  3933. * 按目标尺寸估算并临时调高 memory_limit,避免 FatalError OOM。
  3934. *
  3935. * @param int $neededBytes 预估需要的内存字节数
  3936. * @return void
  3937. */
  3938. function upscaleImageEnsureMemory(int $neededBytes): void
  3939. {
  3940. $current = upscaleImageMemoryLimitBytes();
  3941. if ($current > 0 && $neededBytes > $current) {
  3942. @ini_set('memory_limit', (string)(int)ceil($neededBytes / (1024 * 1024)) . 'M');
  3943. }
  3944. }
  3945. /**
  3946. * 检查 ffmpeg 是否可用
  3947. *
  3948. * @param string $ffmpegPath
  3949. * @return bool
  3950. */
  3951. function upscaleImageIsFfmpegAvailable(string $ffmpegPath): bool
  3952. {
  3953. // 配置了绝对路径时直接检查文件
  3954. if (strpos($ffmpegPath, '/') !== false || strpos($ffmpegPath, '\\') !== false) {
  3955. return file_exists($ffmpegPath);
  3956. }
  3957. $cmd = (PHP_OS_FAMILY === 'Windows')
  3958. ? 'where ' . escapeshellarg($ffmpegPath) . ' 2>NUL'
  3959. : 'command -v ' . escapeshellarg($ffmpegPath) . ' 2>/dev/null';
  3960. $output = @shell_exec($cmd);
  3961. return !empty(trim((string)$output));
  3962. }
  3963. /**
  3964. * 构建 ffmpeg 图片输出编码参数
  3965. *
  3966. * @param string $format
  3967. * @param int $quality
  3968. * @return string
  3969. */
  3970. function upscaleImageBuildFfmpegEncodeArgs(string $format, int $quality): string
  3971. {
  3972. switch ($format) {
  3973. case 'jpg':
  3974. case 'jpeg':
  3975. // mjpeg 质量范围 2-31,2 最佳
  3976. return '-frames:v 1 -q:v ' . (2 + (int)round((100 - $quality) / 100 * 29));
  3977. case 'png':
  3978. return '-frames:v 1 -compression_level ' . max(0, min(9, (int)round((100 - $quality) / 10)));
  3979. case 'webp':
  3980. return '-frames:v 1 -q:v ' . (2 + (int)round((100 - $quality) / 100 * 29));
  3981. }
  3982. return '-frames:v 1';
  3983. }
  3984. /**
  3985. * 确定放大后的输出格式
  3986. *
  3987. * @param array $params
  3988. * @param int $srcType
  3989. * @param bool $srcHasAlpha 原图是否带透明通道
  3990. * @return string
  3991. */
  3992. function upscaleImageResolveOutputFormat(array $params, int $srcType, bool $srcHasAlpha = false): string
  3993. {
  3994. $format = strtolower((string)($params['format'] ?? ''));
  3995. if (in_array($format, ['jpg', 'jpeg', 'png', 'webp'], true)) {
  3996. return $format;
  3997. }
  3998. return upscaleImageGuessFormatByType($srcType, $srcHasAlpha);
  3999. }
  4000. /**
  4001. * 根据图片类型推断默认输出格式
  4002. *
  4003. * @param int $srcType
  4004. * @param bool $srcHasAlpha 原图是否带透明通道
  4005. * @return string
  4006. */
  4007. function upscaleImageGuessFormatByType(int $srcType, bool $srcHasAlpha = false): string
  4008. {
  4009. switch ($srcType) {
  4010. case IMAGETYPE_PNG:
  4011. return 'png';
  4012. case IMAGETYPE_WEBP:
  4013. // 带透明通道的 WebP 转 PNG 保留透明,否则转 JPG 控制体积
  4014. return $srcHasAlpha ? 'png' : 'jpg';
  4015. case IMAGETYPE_GIF:
  4016. return 'png'; // GIF 转 PNG,保留透明通道
  4017. case IMAGETYPE_JPEG:
  4018. default:
  4019. return 'jpg';
  4020. }
  4021. }
  4022. /**
  4023. * 检测图片二进制是否带透明通道(目前用于 WebP 默认输出格式判断)
  4024. *
  4025. * 通过解析容器头判断,不整图解码,速度快:
  4026. * - WebP: ALPH 块存在、VP8X 扩展头的 ALPHA 标志位、VP8L 无损格式的 alpha 标志
  4027. *
  4028. * @param string $binary
  4029. * @return bool
  4030. */
  4031. function upscaleImageHasAlpha(string $binary): bool
  4032. {
  4033. if (strlen($binary) < 16 || substr($binary, 0, 4) !== 'RIFF' || substr($binary, 8, 4) !== 'WEBP') {
  4034. return false;
  4035. }
  4036. $offset = 12;
  4037. $len = strlen($binary);
  4038. while ($offset + 8 <= $len) {
  4039. $fourcc = substr($binary, $offset, 4);
  4040. $chunkSize = (int)unpack('V', substr($binary, $offset + 4, 4))[1];
  4041. if ($fourcc === 'ALPH') {
  4042. return true;
  4043. }
  4044. if ($fourcc === 'VP8X' && $chunkSize >= 1) {
  4045. // VP8X 扩展头标志字节:bit4(0x10)=ALPHA
  4046. return (ord($binary[$offset + 8]) & 0x10) !== 0;
  4047. }
  4048. if ($fourcc === 'VP8L' && $chunkSize >= 1) {
  4049. // VP8L 无损格式:首字节 bit2=alpha_is_used
  4050. return ((ord($binary[$offset + 8]) >> 2) & 1) !== 0;
  4051. }
  4052. if ($chunkSize <= 0) {
  4053. break;
  4054. }
  4055. // RIFF 块数据为奇数长度时补 1 字节对齐
  4056. $offset += 8 + $chunkSize + ($chunkSize % 2);
  4057. }
  4058. return false;
  4059. }
  4060. /**
  4061. * 使用卷积矩阵对图片进行锐化(C级实现,速度快)
  4062. *
  4063. * @param resource|\GdImage $img
  4064. * @param float $amount 锐化强度 0-2
  4065. * @return void
  4066. */
  4067. function upscaleImageSharpen($img, float $amount): void
  4068. {
  4069. $neighbor = -$amount;
  4070. $center = 1 + 4 * $amount;
  4071. imageconvolution($img, [
  4072. [0, $neighbor, 0],
  4073. [$neighbor, $center, $neighbor],
  4074. [0, $neighbor, 0],
  4075. ], 1, 0);
  4076. }
  4077. /**
  4078. * 将 GD 图像编码为指定格式的二进制
  4079. *
  4080. * @param resource|\GdImage $img
  4081. * @param string $format
  4082. * @param int $quality
  4083. * @return string|null 失败返回 null
  4084. */
  4085. function upscaleImageEncode($img, string $format, int $quality): ?string
  4086. {
  4087. $encoded = null;
  4088. ob_start();
  4089. try {
  4090. switch ($format) {
  4091. case 'jpg':
  4092. case 'jpeg':
  4093. imagejpeg($img, null, $quality);
  4094. break;
  4095. case 'png':
  4096. // 显式开启 alpha 通道保存,否则透明区域会丢失
  4097. imagesavealpha($img, true);
  4098. // quality 100-1 映射到 PNG 压缩级别 0-9
  4099. imagepng($img, null, (int)round((100 - $quality) / 10));
  4100. break;
  4101. case 'webp':
  4102. if (!function_exists('imagewebp')) {
  4103. throw new \RuntimeException('GD扩展不支持WebP输出');
  4104. }
  4105. imagesavealpha($img, true);
  4106. imagewebp($img, null, $quality);
  4107. break;
  4108. default:
  4109. throw new \RuntimeException('不支持的输出格式: ' . $format);
  4110. }
  4111. $encoded = ob_get_clean();
  4112. } catch (\Throwable $e) {
  4113. ob_end_clean();
  4114. $encoded = null;
  4115. }
  4116. return $encoded;
  4117. }
  4118. /**
  4119. * 组装放大结果:上传 TOS 返回 URL,或返回 base64
  4120. *
  4121. * @param array $params
  4122. * @param string $encoded
  4123. * @param string $format
  4124. * @param int $dstWidth
  4125. * @param int $dstHeight
  4126. * @param int $srcWidth
  4127. * @param int $srcHeight
  4128. * @param string $driver
  4129. * @return array
  4130. * @throws \RuntimeException
  4131. */
  4132. function upscaleImageBuildResult(
  4133. array $params,
  4134. string $encoded,
  4135. string $format,
  4136. int $dstWidth,
  4137. int $dstHeight,
  4138. int $srcWidth,
  4139. int $srcHeight,
  4140. string $driver
  4141. ): array {
  4142. $upload = (bool)($params['upload'] ?? true);
  4143. if ($upload) {
  4144. $ext = $format === 'jpeg' ? 'jpg' : $format;
  4145. $filename = 'upscale_' . date('YmdHis') . '_' . uniqid() . '.' . $ext;
  4146. $url = uploadStreamByTos('image', $encoded, $filename);
  4147. if (!$url) {
  4148. throw new \RuntimeException('放大图片上传TOS失败');
  4149. }
  4150. return [
  4151. 'url' => $url,
  4152. 'base64' => null,
  4153. 'width' => $dstWidth,
  4154. 'height' => $dstHeight,
  4155. 'src_width' => $srcWidth,
  4156. 'src_height' => $srcHeight,
  4157. 'upscaled' => true,
  4158. 'driver' => $driver,
  4159. ];
  4160. }
  4161. $mime = $format === 'jpg' || $format === 'jpeg' ? 'image/jpeg' : 'image/' . $format;
  4162. return [
  4163. 'url' => null,
  4164. 'base64' => 'data:' . $mime . ';base64,' . base64_encode($encoded),
  4165. 'width' => $dstWidth,
  4166. 'height' => $dstHeight,
  4167. 'src_width' => $srcWidth,
  4168. 'src_height' => $srcHeight,
  4169. 'upscaled' => true,
  4170. 'driver' => $driver,
  4171. ];
  4172. }
  4173. /**
  4174. * 计算放大后的目标尺寸
  4175. *
  4176. * @param int $srcWidth
  4177. * @param int $srcHeight
  4178. * @param array $params
  4179. * @return array [width, height]
  4180. */
  4181. function upscaleImageResolveTargetDimensions(int $srcWidth, int $srcHeight, array $params): array
  4182. {
  4183. $width = (int)($params['width'] ?? 0);
  4184. $height = (int)($params['height'] ?? 0);
  4185. // 显式指定宽高时,按指定尺寸处理(支持只传其中一个,另一个按比例计算)
  4186. if ($width > 0 || $height > 0) {
  4187. $ratio = $srcWidth / $srcHeight;
  4188. if ($width > 0 && $height > 0) {
  4189. return [$width, $height];
  4190. }
  4191. return $width > 0
  4192. ? [$width, max(1, (int)round($width / $ratio))]
  4193. : [max(1, (int)round($height * $ratio)), $height];
  4194. }
  4195. // 预设档位:按长边放大(1080p=1920,2K=2560,4K=3840)
  4196. $presets = [
  4197. '1080p' => 1920,
  4198. '2k' => 2560,
  4199. '4k' => 3840,
  4200. ];
  4201. $target = strtolower((string)($params['target'] ?? '4k'));
  4202. $maxEdge = $presets[$target] ?? $presets['4k'];
  4203. $ratio = $srcWidth / $srcHeight;
  4204. if ($srcWidth >= $srcHeight) {
  4205. $dstWidth = $maxEdge;
  4206. $dstHeight = max(1, (int)round($maxEdge / $ratio));
  4207. } else {
  4208. $dstHeight = $maxEdge;
  4209. $dstWidth = max(1, (int)round($maxEdge * $ratio));
  4210. }
  4211. return [$dstWidth, $dstHeight];
  4212. }
  4213. // /**
  4214. // * 使用 Imagick 将远程图片压缩至不超过 maxBytes(默认3MB)内
  4215. // * 目标:在尽量保留原始格式和质量的前提下进行压缩,避免内存暴涨
  4216. // * 依赖:Imagick 扩展与 ImageMagick 库,下载使用 Guzzle 获取图片 blob
  4217. // *
  4218. // * @param string $url
  4219. // * @param int $maxBytes 最大字节数,默认 3*1024*1024
  4220. // * @return string|null 经过压缩后的图片 blob,失败返回 null
  4221. // */
  4222. // function compressRemoteImageUrlToSizeImagick(string $url, int $maxBytes = 3 * 1024 * 1024): ?string
  4223. // {
  4224. // // 兼容性检查
  4225. // if (!extension_loaded('imagick') || !class_exists('Imagick')) {
  4226. // return null;
  4227. // }
  4228. // try {
  4229. // $client = new Client(['timeout' => 30]);
  4230. // // 使用流式下载,将数据写入临时文件,避免一次性加载到内存
  4231. // $response = $client->get($url, ['stream' => true]);
  4232. // if ($response->getStatusCode() !== 200) {
  4233. // return null;
  4234. // }
  4235. // $body = $response->getBody();
  4236. // $tmp = tmpfile();
  4237. // if ($tmp === false) {
  4238. // return null;
  4239. // }
  4240. // stream_copy_to_stream($body, $tmp);
  4241. // rewind($tmp);
  4242. // $imagick = new Imagick();
  4243. // $imagick->readImageFile($tmp);
  4244. // $origW = $imagick->getImageWidth();
  4245. // $origH = $imagick->getImageHeight();
  4246. // $format = strtolower($imagick->getImageFormat());
  4247. // // 尝试序列:尺寸缩放 + 质量调节
  4248. // $scales = [1.0, 0.9, 0.8, 0.6, 0.4, 0.25];
  4249. // $qualities = [95, 90, 85, 75, 60, 40, 30, 20];
  4250. // $bestBlob = null;
  4251. // foreach ($scales as $scale) {
  4252. // foreach ($qualities as $q) {
  4253. // $clone = clone $imagick;
  4254. // if ($scale < 1.0) {
  4255. // $w = (int)round($origW * $scale);
  4256. // $h = (int)round($origH * $scale);
  4257. // if ($w < 1 || $h < 1) {
  4258. // $clone->destroy();
  4259. // continue;
  4260. // }
  4261. // $clone->resizeImage($w, $h, Imagick::FILTER_LANCZOS, 1);
  4262. // }
  4263. // $clone->setImageFormat($format);
  4264. // $clone->setImageCompressionQuality($q);
  4265. // $blob = $clone->getImageBlob();
  4266. // $clone->destroy();
  4267. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  4268. // $bestBlob = $blob;
  4269. // break 2;
  4270. // }
  4271. // }
  4272. // }
  4273. // if ($bestBlob !== null) {
  4274. // $imagick->destroy();
  4275. // fclose($tmp);
  4276. // return $bestBlob;
  4277. // }
  4278. // // 回退:尝试强制输出为当前格式的一个中等质量版本
  4279. // $fallback = clone $imagick;
  4280. // $fallback->setImageFormat($format);
  4281. // $fallback->setImageCompressionQuality(75);
  4282. // $blob = $fallback->getImageBlob();
  4283. // $fallback->destroy();
  4284. // $imagick->destroy();
  4285. // fclose($tmp);
  4286. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  4287. // return $blob;
  4288. // }
  4289. // } catch (\Exception $e) {
  4290. // return null;
  4291. // }
  4292. // return null;
  4293. // }
  4294. /**
  4295. * 将主体列表文本拆分为主体数组
  4296. *
  4297. * @param string $rolesText 主体列表文本内容
  4298. * @return array 主体名称数组
  4299. */
  4300. function parseRolesFromText(string $rolesText): array
  4301. {
  4302. if (empty($rolesText)) {
  4303. return [];
  4304. }
  4305. $roles = [];
  4306. // 按行分割文本
  4307. $lines = explode("\n", $rolesText);
  4308. foreach ($lines as $line) {
  4309. $line = trim($line);
  4310. if (empty($line)) {
  4311. continue;
  4312. }
  4313. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  4314. $role = trim($charMatch[1]);
  4315. $description = trim($charMatch[2]);
  4316. $timbreName = null;
  4317. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  4318. $picPrompt = null;
  4319. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  4320. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  4321. $description = trim($fullMatch[1]);
  4322. $picPrompt = trim($fullMatch[2]);
  4323. $timbreName = trim($fullMatch[3]);
  4324. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  4325. // 兼容旧格式:主体描述{{音色名}}
  4326. $description = trim($timbreMatch[1]);
  4327. $timbreName = trim($timbreMatch[2]);
  4328. }
  4329. $roleData = [
  4330. 'role' => $role,
  4331. 'description' => $description,
  4332. ];
  4333. // 如果有主体图片提示词,添加到数组中
  4334. if ($picPrompt) {
  4335. $roleData['pic_prompt'] = $picPrompt;
  4336. }
  4337. if ($timbreName) {
  4338. $timbre = DB::table('mp_timbres')
  4339. ->where('is_enabled', 1)
  4340. ->where('timbre_name', 'like', "%{$timbreName}%")
  4341. ->orderBy('id')
  4342. ->select('timbre_type', 'audio_url')
  4343. ->first();
  4344. if ($timbre) {
  4345. $roleData['voice_name'] = $timbreName;
  4346. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  4347. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  4348. }
  4349. }else {
  4350. // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  4351. if ($picPrompt) {
  4352. if (strstr($picPrompt, '男')) {
  4353. $roleData['voice_name'] = '阳光青年';
  4354. }elseif (strstr($picPrompt, '女')) {
  4355. $roleData['voice_name'] = '爽快思思';
  4356. }else {
  4357. if ($description) {
  4358. if (strstr($description, '男')) {
  4359. $roleData['voice_name'] = '阳光青年';
  4360. }elseif (strstr($description, '女')) {
  4361. $roleData['voice_name'] = '爽快思思';
  4362. }else {
  4363. $roleData['voice_name'] = '旁白';
  4364. }
  4365. }
  4366. }
  4367. }
  4368. if (!empty($roleData['voice_name'])) {
  4369. if ($roleData['voice_name'] == '旁白') {
  4370. $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  4371. $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  4372. }else {
  4373. $timbre = DB::table('mp_timbres')
  4374. ->where('is_enabled', 1)
  4375. ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  4376. ->orderBy('id')
  4377. ->select('timbre_type', 'audio_url')
  4378. ->first();
  4379. if ($timbre) {
  4380. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  4381. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  4382. }
  4383. }
  4384. }
  4385. }
  4386. $roles[] = $roleData;
  4387. }
  4388. }
  4389. $hasNarrator = false;
  4390. foreach ($roles as $role) {
  4391. if (getProp($role, 'role') === '旁白') {
  4392. $hasNarrator = true;
  4393. break;
  4394. }
  4395. }
  4396. if (!$hasNarrator) {
  4397. $roles[] = [
  4398. 'role' => '旁白',
  4399. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  4400. 'pic_prompt' => '',
  4401. 'voice_name' => '旁白',
  4402. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  4403. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  4404. ];
  4405. }
  4406. return $roles;
  4407. }
  4408. /**
  4409. * 将场景列表文本拆分为场景数组
  4410. *
  4411. * @param string $rolesText 场景列表列表文本内容
  4412. * @return array 场景名称数组
  4413. */
  4414. function parseScenesFromText(string $scenesText): array
  4415. {
  4416. if (empty($scenesText)) {
  4417. return [];
  4418. }
  4419. $scenes = [];
  4420. // 按行分割文本
  4421. $lines = explode("\n", $scenesText);
  4422. foreach ($lines as $line) {
  4423. $line = trim($line);
  4424. if (empty($line)) {
  4425. continue;
  4426. }
  4427. $line = str_replace(':', ':', $line);
  4428. if (strstr($line, ':')) {
  4429. $line_arr = explode(':', $line, 2);
  4430. if (count($line_arr) == 2) {
  4431. $scene = trim($line_arr[0]);
  4432. $description = trim($line_arr[1]);
  4433. $picPrompt = null;
  4434. // 检查描述末尾是否有{场景图片提示词}格式
  4435. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  4436. // 匹配格式:场景描述{场景图片提示词}
  4437. $description = trim($promptMatch[1]);
  4438. $picPrompt = trim($promptMatch[2]);
  4439. }
  4440. $sceneData = [
  4441. 'scene' => $scene,
  4442. 'description' => $description,
  4443. ];
  4444. // 如果有场景图片提示词,添加到数组中
  4445. if ($picPrompt) {
  4446. $sceneData['pic_prompt'] = $picPrompt;
  4447. }
  4448. $scenes[] = $sceneData;
  4449. }
  4450. }
  4451. }
  4452. return $scenes;
  4453. }
  4454. /**
  4455. * 将道具列表文本拆分为道具数组
  4456. *
  4457. * @param string $propsText 道具列表文本内容
  4458. * @return array 道具数组
  4459. */
  4460. function parsePropsFromText(string $propsText): array
  4461. {
  4462. if (empty($propsText)) {
  4463. return [];
  4464. }
  4465. $props = [];
  4466. // 按行分割文本
  4467. $lines = explode("\n", $propsText);
  4468. foreach ($lines as $line) {
  4469. $line = trim($line);
  4470. if (empty($line)) {
  4471. continue;
  4472. }
  4473. $line = str_replace(':', ':', $line);
  4474. if (strstr($line, ':')) {
  4475. $line_arr = explode(':', $line, 2);
  4476. if (count($line_arr) == 2) {
  4477. $prop = trim($line_arr[0]);
  4478. $description = trim($line_arr[1]);
  4479. $picPrompt = null;
  4480. // 检查描述末尾是否有{道具图片提示词}格式
  4481. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  4482. // 匹配格式:道具描述{道具图片提示词}
  4483. $description = trim($promptMatch[1]);
  4484. $picPrompt = trim($promptMatch[2]);
  4485. }
  4486. $propData = [
  4487. 'prop' => $prop,
  4488. 'description' => $description,
  4489. ];
  4490. // 如果有道具图片提示词,添加到数组中
  4491. if ($picPrompt) {
  4492. $propData['pic_prompt'] = $picPrompt;
  4493. }
  4494. $props[] = $propData;
  4495. }
  4496. }
  4497. }
  4498. return $props;
  4499. }
  4500. // 拆分章节内容
  4501. function splitContent($content) {
  4502. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  4503. $chapters = [];
  4504. // 匹配章节标题格式:
  4505. // 1. 标题可能独占一行,也可能在正文末尾或中间
  4506. // 2. 格式支持:
  4507. // - **第一集**
  4508. // - 第一集:
  4509. // - ###第1章 重生
  4510. // - ##第2章 相救
  4511. // - 第三章 共处一室
  4512. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  4513. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  4514. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  4515. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  4516. // 先预处理:仅在"第X集/章"位于某段正文末尾(可能因未换行粘连)时补换行使其独立成行;
  4517. // 支持正文末尾直接跟"第X集"或"第X集:标题"的粘连格式;
  4518. // 正文中间出现的"第X集"字样(如"真假千金文里第一集就被赶出厂")保持不动,避免误判为章节标题
  4519. $content = preg_replace('/([^ \t\r\f\v\n#*·\-_=])(第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场话])((?:[::][^\n]*|[ \t\r\f\v]*))$/mu', "$1\n\n$2$3", $content);
  4520. // 匹配章节标题:标题必须位于行首(前面仅允许空格/Tab 或 #*·-_= 等修饰符),避免跨行误匹配
  4521. $pattern = '/^[#*·\-_= \t]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场话]).*$/mu';
  4522. // 用正则找出所有章节标题的位置
  4523. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  4524. $titleCount = count($matches[0]);
  4525. for ($i = 0; $i < $titleCount; $i++) {
  4526. // 获取当前章节标题
  4527. $titleLine = trim($matches[0][$i][0]);
  4528. // 去除标题开头的特殊符号
  4529. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/u', '', $titleLine);
  4530. // 去除标题结尾的冒号和特殊符号
  4531. $cleanTitle = preg_replace('/[#*·::\s]+$/u', '', $cleanTitle);
  4532. $cleanTitle = trim($cleanTitle);
  4533. // 获取当前标题的结束位置
  4534. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  4535. // 获取下一个章节标题的开始位置(如果存在)
  4536. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  4537. // 提取章节内容(从标题结束到下一个标题开始)
  4538. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  4539. // 清理内容:去除前后空白和分隔线
  4540. $chapterContent = trim($chapterContent);
  4541. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  4542. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  4543. if (!empty($cleanTitle) && !empty($chapterContent)) {
  4544. $chapters[] = [
  4545. 'title' => $cleanTitle,
  4546. 'content' => $chapterContent
  4547. ];
  4548. }
  4549. }
  4550. } else {
  4551. // 如果没有匹配到章节,返回整个内容
  4552. $chapters[] = [
  4553. 'title' => '',
  4554. 'content' => $content
  4555. ];
  4556. }
  4557. return $chapters;
  4558. }
  4559. /**
  4560. * 记录日志到数据库
  4561. *
  4562. * @param string $channel 日志频道/目录名
  4563. * @param string $level 日志级别 (info, error, warning, debug)
  4564. * @param string $message 日志信息
  4565. * @param array $context 日志详细数据
  4566. * @return void
  4567. */
  4568. function logDB($channel, $level, $message, $context = []) {
  4569. try {
  4570. // 获取调用堆栈信息
  4571. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  4572. $caller = $trace[1] ?? $trace[0];
  4573. // 在 create 之前添加:
  4574. $jsonEncoded = json_encode($context, JSON_INVALID_UTF8_SUBSTITUTE);
  4575. $cleanContext = json_decode($jsonEncoded, true);
  4576. \App\Models\SystemLog::create([
  4577. 'channel' => $channel,
  4578. 'level' => $level,
  4579. 'message' => $message,
  4580. 'context' => $cleanContext,
  4581. 'file' => $caller['file'] ?? '',
  4582. 'line' => $caller['line'] ?? 0,
  4583. 'log_time' => date('Y-m-d H:i:s'),
  4584. ]);
  4585. } catch (\Exception $e) {
  4586. // 记录日志失败时不影响主流程
  4587. \Log::error('记录日志到数据库失败: ' . $e->getMessage());
  4588. }
  4589. }
  4590. function filterScriptContent($content) {
  4591. if (!$content) return '';
  4592. if (mb_substr($content, 0, 6) == '确认分镜大纲') return '确认分镜大纲';
  4593. if (mb_strlen($content) > 500) return '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。';
  4594. return $content;
  4595. }
  4596. /**
  4597. * 根据错误信息返回映射错误说明
  4598. *
  4599. * @param string $errorMessage 错误信息
  4600. * @return string 映射后的错误说明
  4601. */
  4602. function mapErrorMessage($errorMessage)
  4603. {
  4604. if (empty($errorMessage)) {
  4605. return '未知异常,请重试';
  4606. }
  4607. // 按优先级匹配错误信息
  4608. if (stripos($errorMessage, 'OutputImageSensitiveContentDetected') !== false) {
  4609. return '输出结果含有敏感词,请重试';
  4610. }
  4611. if (stripos($errorMessage, '系统繁忙,请稍后再试') !== false) {
  4612. return '系统繁忙,请稍后再试';
  4613. }
  4614. if (stripos($errorMessage, 'InternalServiceError') !== false) {
  4615. return '外部服务器网络错误,请稍后重试';
  4616. }
  4617. if (stripos($errorMessage, 'InputTextSensitiveContentDetected') !== false) {
  4618. return '输入文字含有敏感词,请调整后重试';
  4619. }
  4620. if (stripos($errorMessage, 'ServerOverloaded') !== false) {
  4621. return '当前系统过载,请稍后重试';
  4622. }
  4623. if (stripos($errorMessage, 'The request failed because the output video may be related to copyright restrictions') !== false) {
  4624. return '输出视频可能涉及版权限制,请更换内容或降低相似度后重试。';
  4625. }
  4626. // 未命中预设错误:调用模型生成友好翻译并缓存,避免轮询场景重复消耗
  4627. try {
  4628. $cacheKey = 'unknown_error_translate_' . md5((string)$errorMessage);
  4629. return Cache::remember($cacheKey, 600, function () use ($errorMessage) {
  4630. $friendlyError = app(\App\Services\DeepSeek\DeepSeekService::class)->analyzeErrorMessage($errorMessage);
  4631. return $friendlyError ?: '未知异常,请重试';
  4632. });
  4633. } catch (\Throwable $e) {
  4634. return '未知异常,请重试';
  4635. }
  4636. }
  4637. /**
  4638. * 视频超分:480p档升级到720p,720p档升级到1080p(使用FFmpeg本地超分)
  4639. * 目标分辨率按源视频方向强制为标准档位(横屏 16:9 / 竖屏 9:16)
  4640. * 可通过 $targetResolution 显式指定目标档位(720p/1080p),显式指定优先;未指定时按源档位自动识别
  4641. *
  4642. * @param string|resource $videoSource 视频URL地址或视频内容(字符串)
  4643. * @param string $prefix 上传文件夹前缀(如:'video')
  4644. * @param bool $isContent 是否为视频内容而非URL(默认false)
  4645. * @param string $targetResolution 显式目标档位:'720p' 或 '1080p',空字符串表示自动识别
  4646. * @return string 返回超分后的视频URL,失败返回原视频URL或空字符串
  4647. */
  4648. function upgrade480pTo720p($videoSource, $prefix = 'video', $isContent = false, $targetResolution = '')
  4649. {
  4650. if (env('APP_ENV') == 'local') {
  4651. return $isContent ? '' : $videoSource;
  4652. }
  4653. try {
  4654. // 创建临时目录
  4655. $tempDir = storage_path('app/temp/videos');
  4656. if (!is_dir($tempDir)) {
  4657. mkdir($tempDir, 0775, true);
  4658. chmod($tempDir, 0775);
  4659. }
  4660. // 生成唯一文件名
  4661. $uniqueId = uniqid('video_upgrade_') . bin2hex(random_bytes(4));
  4662. // 处理输入源
  4663. if ($isContent) {
  4664. // 如果是视频内容,直接写入临时文件
  4665. dLog('video_upgrade')->info('检测到视频内容,写入临时文件');
  4666. $inputFile = $tempDir . '/' . $uniqueId . '_input.mp4';
  4667. if (file_put_contents($inputFile, $videoSource) === false) {
  4668. dLog('video_upgrade')->error('视频内容写入临时文件失败');
  4669. return '';
  4670. }
  4671. $videoUrl = '视频内容';
  4672. } else {
  4673. // 如果是URL,下载视频
  4674. $videoUrl = $videoSource;
  4675. $videoExt = getVideoExtFromUrl($videoUrl);
  4676. $inputFile = $tempDir . '/' . $uniqueId . '_input' . $videoExt;
  4677. // 下载视频到本地
  4678. dLog('video_upgrade')->info('开始下载视频进行升级', ['url' => $videoUrl]);
  4679. $client = new \GuzzleHttp\Client(['timeout' => 300]);
  4680. $response = $client->get($videoUrl);
  4681. $fileContent = $response->getBody()->getContents();
  4682. if (file_put_contents($inputFile, $fileContent) === false) {
  4683. dLog('video_upgrade')->error('视频文件写入失败', [
  4684. 'url' => $videoUrl,
  4685. 'file' => $inputFile
  4686. ]);
  4687. return $videoUrl;
  4688. }
  4689. }
  4690. chmod($inputFile, 0664);
  4691. if (!file_exists($inputFile)) {
  4692. dLog('video_upgrade')->error('视频文件不存在', ['file' => $inputFile]);
  4693. return $isContent ? '' : $videoSource;
  4694. }
  4695. $inputFileSize = filesize($inputFile);
  4696. dLog('video_upgrade')->info('视频准备完成,开始超分', [
  4697. 'source' => $videoUrl,
  4698. 'size' => $inputFileSize,
  4699. 'size_mb' => round($inputFileSize / 1024 / 1024, 2) . 'MB'
  4700. ]);
  4701. // 获取视频分辨率,根据源档位选择目标档位
  4702. // 使用 ffprobe 的 JSON 输出,这是最可靠的方式
  4703. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  4704. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  4705. // 获取视频流信息,使用JSON格式输出
  4706. $probeCmd = "$ffprobePath -v quiet -print_format json -show_streams \"$inputFile\"";
  4707. $probeOutput = shell_exec($probeCmd);
  4708. $videoInfo = json_decode($probeOutput, true);
  4709. $width = 0;
  4710. $height = 0;
  4711. // 从JSON中提取视频流的宽高
  4712. if (isset($videoInfo['streams']) && is_array($videoInfo['streams'])) {
  4713. foreach ($videoInfo['streams'] as $stream) {
  4714. if (isset($stream['codec_type']) && $stream['codec_type'] === 'video') {
  4715. $width = isset($stream['width']) ? (int)$stream['width'] : 0;
  4716. $height = isset($stream['height']) ? (int)$stream['height'] : 0;
  4717. break;
  4718. }
  4719. }
  4720. }
  4721. dLog('video_upgrade')->info('ffprobe获取视频分辨率', [
  4722. 'width' => $width,
  4723. 'height' => $height,
  4724. 'json_parsed' => !empty($videoInfo)
  4725. ]);
  4726. // 根据视频方向决定目标标准分辨率
  4727. // 480p档 -> 720p(720*1280 竖屏 / 1280*720 横屏)
  4728. // 720p档 -> 1080p(1080*1920 竖屏 / 1920*1080 横屏)
  4729. $shortSide = min($width, $height);
  4730. $targetShortSide = 0;
  4731. $targetResolution = strtolower(trim($targetResolution));
  4732. if (in_array($targetResolution, ['720p', '1080p'], true)) {
  4733. // 显式指定档位优先(不允许降级:源短边超过目标档位则跳过)
  4734. $targetShortSide = $targetResolution === '720p' ? 720 : 1080;
  4735. if ($shortSide > $targetShortSide + 40) {
  4736. dLog('video_upgrade')->info('视频分辨率高于目标档位,跳过超分', [
  4737. 'width' => $width,
  4738. 'height' => $height,
  4739. 'target' => $targetResolution
  4740. ]);
  4741. @unlink($inputFile);
  4742. return $isContent ? '' : $videoSource;
  4743. }
  4744. } elseif ($shortSide > 0 && abs($shortSide - 480) <= 40) {
  4745. $targetShortSide = 720;
  4746. } elseif ($shortSide > 0 && abs($shortSide - 720) <= 40) {
  4747. $targetShortSide = 1080;
  4748. } else {
  4749. // 自动识别且非480p/720p档,无需超分,直接返回原视频
  4750. dLog('video_upgrade')->info('视频不属于480p/720p档位,跳过超分', [
  4751. 'width' => $width,
  4752. 'height' => $height,
  4753. 'short_side' => $shortSide
  4754. ]);
  4755. @unlink($inputFile);
  4756. return $isContent ? '' : $videoSource;
  4757. }
  4758. $isPortrait = $width > 0 && $height > 0 && $width < $height;
  4759. $targetWidth = $isPortrait ? $targetShortSide : (int)round($targetShortSide * 16 / 9);
  4760. $targetHeight = $isPortrait ? (int)round($targetShortSide * 16 / 9) : $targetShortSide;
  4761. $scaleFilter = "scale={$targetWidth}:{$targetHeight}:flags=lanczos:force_original_aspect_ratio=decrease,pad={$targetWidth}:{$targetHeight}:(ow-iw)/2:(oh-ih)/2";
  4762. if ($width > 0 && $height > 0) {
  4763. dLog('video_upgrade')->info('缩放计算详情', [
  4764. 'original' => "{$width}x{$height}",
  4765. 'target' => "{$targetWidth}x{$targetHeight}",
  4766. 'is_portrait' => $width < $height ? 'yes' : 'no'
  4767. ]);
  4768. dLog('video_upgrade')->info(($isPortrait ? '竖屏' : '横屏') . '视频超分', [
  4769. 'original_size' => "{$width}x{$height}",
  4770. 'target_size' => "{$targetWidth}x{$targetHeight}",
  4771. 'scale_filter' => $scaleFilter
  4772. ]);
  4773. } else {
  4774. // 无法获取分辨率,默认按横屏处理
  4775. $targetWidth = (int)round($targetShortSide * 16 / 9);
  4776. $targetHeight = $targetShortSide;
  4777. $scaleFilter = "scale={$targetWidth}:{$targetHeight}:flags=lanczos:force_original_aspect_ratio=decrease,pad={$targetWidth}:{$targetHeight}:(ow-iw)/2:(oh-ih)/2";
  4778. dLog('video_upgrade')->warning('无法获取视频分辨率,默认按横屏处理');
  4779. }
  4780. // 输出文件路径
  4781. $outputFile = $tempDir . '/' . $uniqueId . '_output.mp4';
  4782. // 使用FFmpeg超分视频,使用高质量的Lanczos算法和锐化滤镜
  4783. // 滤镜说明:
  4784. // 1. scale: 使用Lanczos算法缩放并保持宽高比,pad补边到标准分辨率(720p或1080p档)
  4785. // 2. unsharp=5:5:1.0:5:5:0.5: 锐化滤镜,增强细节
  4786. // - 5:5:1.0 表示亮度锐化(luma_msize_x:luma_msize_y:luma_amount)
  4787. // - 5:5:0.5 表示色度锐化(chroma_msize_x:chroma_msize_y:chroma_amount)
  4788. // 3. hqdn3d=1.5:1.5:6:6: 降噪滤镜,轻微降噪以改善画质
  4789. // - 参数分别为亮度空间/时间和色度空间/时间
  4790. // 编码参数:
  4791. // -c:v libx264: 使用H.264编码器
  4792. // -preset slow: 编码速度预设(ultrafast到veryslow,越慢压缩率越高)
  4793. // 可选值: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow
  4794. // 推荐: slow(平衡速度和压缩率)或 slower(更好压缩)
  4795. // -crf 23: 恒定质量模式(0-51,数值越小画质越好,文件越大)
  4796. // 推荐值: 18(高质量,大文件) 23(默认,平衡) 28(中等质量,小文件)
  4797. // 当前设置可在.env中配置 VIDEO_UPGRADE_CRF,默认23
  4798. // -tune film: 针对电影内容优化(适合AI生成的动画视频)
  4799. // -profile:v high: 使用H.264 High Profile,支持更高级的压缩特性
  4800. // -level 4.1: H.264 level 4.1,支持更高的码率和分辨率
  4801. // -pix_fmt yuv420p: 像素格式,确保兼容性
  4802. // -c:a aac -b:a 128k: 音频使用AAC编码,128kbps(比直接copy更小)
  4803. // -movflags +faststart: 优化网络播放
  4804. // 从环境变量读取编码参数,允许灵活配置
  4805. $crf = env('VIDEO_UPGRADE_CRF', 23); // CRF值: 18(高质量) 23(默认) 28(小文件)
  4806. $preset = env('VIDEO_UPGRADE_PRESET', 'slow'); // 编码速度: slow, slower, veryslow
  4807. $audioBitrate = env('VIDEO_UPGRADE_AUDIO_BITRATE', '128k'); // 音频码率
  4808. $unsharp = env('VIDEO_UPGRADE_UNSHARP', '5:5:0.5:5:5:0.2');
  4809. dLog('video_upgrade')->info('使用编码参数', [
  4810. 'crf' => $crf,
  4811. 'preset' => $preset,
  4812. 'audio_bitrate' => $audioBitrate
  4813. ]);
  4814. $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";
  4815. dLog('video_upgrade')->info('开始FFmpeg超分视频', ['command' => $ffmpegCmd]);
  4816. $output = shell_exec($ffmpegCmd);
  4817. if (!file_exists($outputFile)) {
  4818. dLog('video_upgrade')->error('视频升级失败', [
  4819. 'input' => $inputFile,
  4820. 'output' => $output
  4821. ]);
  4822. @unlink($inputFile);
  4823. return $isContent ? '' : $videoSource;
  4824. }
  4825. chmod($outputFile, 0664);
  4826. // 验证输出视频的分辨率(使用JSON格式,最可靠)
  4827. $verifyCmd = "$ffprobePath -v quiet -print_format json -show_streams \"$outputFile\"";
  4828. $verifyOutput = shell_exec($verifyCmd);
  4829. $outputVideoInfo = json_decode($verifyOutput, true);
  4830. $outputWidth = 0;
  4831. $outputHeight = 0;
  4832. if (isset($outputVideoInfo['streams']) && is_array($outputVideoInfo['streams'])) {
  4833. foreach ($outputVideoInfo['streams'] as $stream) {
  4834. if (isset($stream['codec_type']) && $stream['codec_type'] === 'video') {
  4835. $outputWidth = isset($stream['width']) ? (int)$stream['width'] : 0;
  4836. $outputHeight = isset($stream['height']) ? (int)$stream['height'] : 0;
  4837. break;
  4838. }
  4839. }
  4840. }
  4841. dLog('video_upgrade')->info('输出视频分辨率验证', [
  4842. 'input_original' => "{$width}x{$height}",
  4843. 'expected' => ($width > 0 && $height > 0) ? ($width < $height ? '720x1280' : '1280x720') : '1280x720',
  4844. 'actual_output' => "{$outputWidth}x{$outputHeight}",
  4845. 'success' => ($outputWidth > 0 && $outputHeight > 0)
  4846. ]);
  4847. $outputFileSize = filesize($outputFile);
  4848. $sizeRatio = round($outputFileSize / $inputFileSize, 2);
  4849. dLog('video_upgrade')->info('视频升级成功', [
  4850. 'input_size' => round($inputFileSize / 1024 / 1024, 2) . 'MB',
  4851. 'output_size' => round($outputFileSize / 1024 / 1024, 2) . 'MB',
  4852. 'size_ratio' => $sizeRatio
  4853. ]);
  4854. // 上传到TOS - 使用普通的文件名,不暴露是升级后的视频
  4855. $video_name = 'ai_generation_' . time() . '_' . uniqid() . '.mp4';
  4856. $uploadedUrl = uploadStreamByTos($prefix, file_get_contents($outputFile), $video_name);
  4857. // 清理临时文件
  4858. @unlink($inputFile);
  4859. @unlink($outputFile);
  4860. if (!$uploadedUrl) {
  4861. dLog('video_upgrade')->error('升级后的视频上传失败');
  4862. return $isContent ? '' : $videoSource;
  4863. }
  4864. dLog('video_upgrade')->info('升级后的视频上传成功', ['url' => $uploadedUrl]);
  4865. return $uploadedUrl;
  4866. } catch (\Exception $e) {
  4867. dLog('video_upgrade')->error('视频升级过程出错', [
  4868. 'source' => $isContent ? '视频内容' : $videoSource,
  4869. 'error' => $e->getMessage()
  4870. ]);
  4871. // 清理可能存在的临时文件
  4872. if (isset($inputFile) && file_exists($inputFile)) {
  4873. @unlink($inputFile);
  4874. }
  4875. if (isset($outputFile) && file_exists($outputFile)) {
  4876. @unlink($outputFile);
  4877. }
  4878. // 出错时返回原视频URL或空字符串
  4879. return $isContent ? '' : $videoSource;
  4880. }
  4881. }