Helpers.php 169 KB

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