Helpers.php 203 KB

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