Helpers.php 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219
  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. try {
  895. // 创建临时目录
  896. $tempDir = storage_path('app/temp/videos');
  897. if (!is_dir($tempDir)) {
  898. mkdir($tempDir, 0755, true);
  899. }
  900. // 生成唯一文件名
  901. $uniqueId = uniqid('video_', true);
  902. $videoExt = getVideoExtFromUrl($videoUrl);
  903. $inputFile = $tempDir . '/' . $uniqueId . '_input' . $videoExt;
  904. $outputFile = $tempDir . '/' . $uniqueId . '_output.mp4';
  905. // 下载视频到本地
  906. dLog('video_compress')->info('开始下载视频', ['url' => $videoUrl]);
  907. $client = new \GuzzleHttp\Client(['timeout' => 300]);
  908. $response = $client->get($videoUrl);
  909. file_put_contents($inputFile, $response->getBody()->getContents());
  910. if (!file_exists($inputFile)) {
  911. dLog('video_compress')->error('视频下载失败', ['url' => $videoUrl]);
  912. return '';
  913. }
  914. $inputFileSize = filesize($inputFile);
  915. dLog('video_compress')->info('视频下载成功', [
  916. 'url' => $videoUrl,
  917. 'size' => $inputFileSize,
  918. 'size_mb' => round($inputFileSize / 1024 / 1024, 2) . 'MB'
  919. ]);
  920. // 获取视频时长(秒)
  921. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  922. $durationCmd = "$ffprobePath -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 \"$inputFile\"";
  923. $duration = (float)trim(shell_exec($durationCmd));
  924. if ($duration <= 0) {
  925. dLog('video_compress')->error('无法获取视频时长', ['file' => $inputFile]);
  926. @unlink($inputFile);
  927. return '';
  928. }
  929. // 计算目标码率
  930. // 目标:3秒视频 = 1~1.5MB,即每秒约 0.33~0.5MB = 2730~4096 kbps
  931. // 使用中间值:3500 kbps
  932. $targetBitrate = 3500; // kbps
  933. // 根据视频时长动态调整码率,确保文件大小合理
  934. // 目标文件大小 = duration * 0.4MB/s = duration * 400KB/s
  935. $targetFileSizeKB = $duration * 400; // KB
  936. $targetBitrateCalculated = (int)(($targetFileSizeKB * 8) / $duration); // kbps
  937. // 使用计算出的码率,但不低于1500kbps,不高于5000kbps
  938. $targetBitrate = max(1500, min(5000, $targetBitrateCalculated));
  939. dLog('video_compress')->info('视频信息', [
  940. 'duration' => $duration . 's',
  941. 'target_bitrate' => $targetBitrate . 'kbps',
  942. 'estimated_size' => round($targetFileSizeKB / 1024, 2) . 'MB'
  943. ]);
  944. // 使用FFmpeg压缩视频
  945. // -c:v libx264: 使用H.264编码器
  946. // -b:v: 视频码率
  947. // -c:a aac: 音频编码器
  948. // -b:a 128k: 音频码率
  949. // -movflags +faststart: 优化网络播放
  950. // -preset medium: 编码速度与质量平衡
  951. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  952. $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";
  953. dLog('video_compress')->info('开始压缩视频', ['command' => $ffmpegCmd]);
  954. $output = shell_exec($ffmpegCmd);
  955. if (!file_exists($outputFile)) {
  956. dLog('video_compress')->error('视频压缩失败', [
  957. 'input' => $inputFile,
  958. 'output' => $output
  959. ]);
  960. @unlink($inputFile);
  961. return '';
  962. }
  963. $outputFileSize = filesize($outputFile);
  964. $compressionRatio = round((1 - $outputFileSize / $inputFileSize) * 100, 2);
  965. dLog('video_compress')->info('视频压缩成功', [
  966. 'input_size' => round($inputFileSize / 1024 / 1024, 2) . 'MB',
  967. 'output_size' => round($outputFileSize / 1024 / 1024, 2) . 'MB',
  968. 'compression_ratio' => $compressionRatio . '%',
  969. 'duration' => $duration . 's',
  970. 'size_per_second' => round($outputFileSize / $duration / 1024 / 1024, 2) . 'MB/s'
  971. ]);
  972. // 上传压缩后的视频到云存储
  973. $stream = fopen($outputFile, 'r');
  974. if (!$stream) {
  975. dLog('video_compress')->error('无法打开压缩后的视频文件', ['file' => $outputFile]);
  976. @unlink($inputFile);
  977. @unlink($outputFile);
  978. return '';
  979. }
  980. $filename = $uniqueId . '.mp4';
  981. // 根据环境变量选择上传方式
  982. $uploadMethod = env('VIDEO_UPLOAD_METHOD', 'tos'); // 默认使用火山云
  983. if ($uploadMethod === 'oss') {
  984. $compressedUrl = uploadStreamToOss($prefix, $stream, $filename);
  985. } else {
  986. $compressedUrl = uploadStreamByTos($prefix, $stream, $filename);
  987. }
  988. // 安全关闭文件流
  989. if (is_resource($stream)) {
  990. fclose($stream);
  991. }
  992. // 清理临时文件
  993. @unlink($inputFile);
  994. @unlink($outputFile);
  995. if (!$compressedUrl) {
  996. dLog('video_compress')->error('压缩视频上传失败');
  997. return '';
  998. }
  999. dLog('video_compress')->info('压缩视频上传成功', [
  1000. 'original_url' => $videoUrl,
  1001. 'compressed_url' => $compressedUrl
  1002. ]);
  1003. return $compressedUrl;
  1004. } catch (\Exception $e) {
  1005. dLog('video_compress')->error('视频压缩异常', [
  1006. 'url' => $videoUrl,
  1007. 'error' => $e->getMessage(),
  1008. 'trace' => $e->getTraceAsString()
  1009. ]);
  1010. // 安全关闭文件流(如果存在)
  1011. if (isset($stream) && is_resource($stream)) {
  1012. @fclose($stream);
  1013. }
  1014. // 清理可能存在的临时文件
  1015. if (isset($inputFile) && file_exists($inputFile)) {
  1016. @unlink($inputFile);
  1017. }
  1018. if (isset($outputFile) && file_exists($outputFile)) {
  1019. @unlink($outputFile);
  1020. }
  1021. return ''; // 出错时返回空字符串
  1022. }
  1023. }
  1024. function sensitiveStr($list, $string)
  1025. {
  1026. $count = 0; //违规词的个数
  1027. $sensitiveWord = ''; //违规词
  1028. $stringAfter = $string; //替换后的内容
  1029. $total = count($list);
  1030. $size = 500;
  1031. $last = ceil($total / $size);
  1032. $patternList = [];
  1033. for ($page = 1; $page <= $last; $page++) {
  1034. $arr = array_slice($list, $size * ($page - 1), $size);
  1035. $filter = [];
  1036. foreach ($arr as $v) {
  1037. if (preg_match('/[^a-zA-Z0-9\|\p{Han}\·]/u', $v)) continue;
  1038. $filter[] = $v;
  1039. // $a = preg_replace('/[^a-zA-Z0-9\|\p{Han}]/u', '', $v);
  1040. // if ($a) $filter[] = $a;
  1041. }
  1042. $pattern = "/" . implode("|", $filter) . "/i"; //定义正则表达式
  1043. if (preg_match_all($pattern, $string, $matches)) { //匹配到了结果
  1044. $patternList = array_merge($patternList, $matches[0]); //匹配到的数组
  1045. }
  1046. }
  1047. $sensitiveWord = '';
  1048. if ($patternList) {
  1049. $count = count($patternList);
  1050. // $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
  1051. $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '*')); //把匹配到的数组进行合并,替换使用
  1052. $stringAfter = strtr($string, $replaceArray); //结果替换
  1053. // 将敏感词合并
  1054. $return_pattern = [];
  1055. foreach ($patternList as $v) {
  1056. if (!isset($return_pattern[$v])) {
  1057. $return_pattern[$v] = [
  1058. 'word' => $v,
  1059. 'count' => 1,
  1060. ];
  1061. } else {
  1062. $return_pattern[$v]['count'] += 1;
  1063. }
  1064. }
  1065. foreach ($return_pattern as $v) {
  1066. $sensitiveWord .= $v['word'] . ',';
  1067. }
  1068. }
  1069. return [
  1070. 'count' => $count,
  1071. 'sensitive_words' => trim($sensitiveWord, ','),
  1072. 'content' => $stringAfter
  1073. ];
  1074. }
  1075. /**
  1076. * 转换时间格式
  1077. *
  1078. * @param $date
  1079. * @param string $format
  1080. * @return false|string
  1081. */
  1082. function transDate($date, $format = 'Y-m-d H:i:s')
  1083. {
  1084. return strtotime($date) > 0 ? date($format, strtotime($date)) : '';
  1085. }
  1086. /**
  1087. * 根据网段获取计算所有IP
  1088. *
  1089. * @param string $segment 网段 '139.217.0.1/24'
  1090. * @return array [网络地址:139.217.0.1 广播地址:139.217.0.255 IP列表: ['139.217.0.2','139.217.0.3'……'139.217.0.254']]
  1091. */
  1092. function getIpBySegment($segment)
  1093. {
  1094. $segmentInfo = explode("/", $segment);
  1095. $beginIpArray = explode(".", $segmentInfo[0]);
  1096. $mask = intval($segmentInfo['1']);
  1097. $endIp = array();
  1098. foreach ($beginIpArray as $ipKey => $item) {
  1099. $beginFlag = 8 * ($ipKey); //0 8 16 24
  1100. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  1101. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  1102. $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));
  1103. }
  1104. $ipArray = array();
  1105. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0]++) {
  1106. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1]++) {
  1107. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2]++) {
  1108. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3]++) {
  1109. $ipArray[] = implode(".", $beginIp);
  1110. }
  1111. }
  1112. }
  1113. }
  1114. $network_ip_addr = $beginIpArray[0] . '.' . $beginIpArray[1] . '.' . $beginIpArray[2] . '.' . '0'; // 网络地址
  1115. $broadcast_ip_addr = end($ipArray); // 广播地址
  1116. if ($ipArray[0] == $network_ip_addr) { // 如果是网络地址则删掉
  1117. unset($ipArray[0]);
  1118. }
  1119. $last = count($ipArray);
  1120. unset($ipArray[$last]);
  1121. return [$network_ip_addr, $broadcast_ip_addr, $ipArray];
  1122. }
  1123. /**
  1124. * 在指定网段中分配子网段
  1125. *
  1126. * @param string $segment 指定网段
  1127. * @param int $ipNum 需要的IP数
  1128. * @param array $usedIpArray 不可用(已经使用)的IP,默认为空数组
  1129. * @return bool|string 成功则返回分配的网段
  1130. */
  1131. function allocateSegment($segment, $ipNum, $usedIpArray = [])
  1132. {
  1133. $usedIpArray = empty($usedIpArray) ? [] : array_flip($usedIpArray);
  1134. //计算需要多少个IP
  1135. $i = 0;
  1136. $ipCount = pow(2, $i);
  1137. while ($ipCount < $ipNum) {
  1138. $i++;
  1139. $ipCount = pow(2, $i);
  1140. }
  1141. $newMask = 32 - $i;
  1142. //大网段的开始和结束IP
  1143. $segmentInfo = explode("/", $segment); //['139.217.0.1',24]
  1144. $beginIpArray = explode(".", $segmentInfo[0]);//[139,217,0,1]
  1145. $mask = intval($segmentInfo['1']); //24
  1146. if ($newMask < $mask) {
  1147. return false;
  1148. }
  1149. $endIp = array();
  1150. $step = [];
  1151. foreach ($beginIpArray as $ipKey => $item) {
  1152. $beginFlag = 8 * ($ipKey); //0 8 16 24
  1153. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  1154. $step[$ipKey] = $newMask > $endFlag ? 1 : ($endFlag - $newMask < 8 ? pow(2, $endFlag - $newMask) : pow(2, 8));
  1155. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  1156. $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));
  1157. }
  1158. //遍历生成网段
  1159. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0] += $step[0]) {
  1160. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1] += $step[1]) {
  1161. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2] += $step[2]) {
  1162. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3] += $step[3]) {
  1163. $newSegment = implode('.', $beginIp) . '/' . $newMask;
  1164. //获取该网段所有的IP
  1165. $ipArray = getIpBySegment($newSegment);
  1166. $canUse = true;
  1167. //判断该网段是否可用
  1168. if (!empty($usedIpArray)) {
  1169. foreach ($ipArray as $ip) {
  1170. if (isset($usedIpArray[$ip])) {
  1171. $canUse = false;
  1172. break;
  1173. }
  1174. }
  1175. }
  1176. if ($canUse) {
  1177. return $newSegment;
  1178. }
  1179. }
  1180. }
  1181. }
  1182. }
  1183. return false;
  1184. }
  1185. function remove_xss($val)
  1186. {
  1187. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  1188. // this prevents some character re-spacing such as <java\0script>
  1189. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
  1190. $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
  1191. // straight replacements, the user should never need these since they're normal characters
  1192. // this prevents like <IMG SRC=@avascript:alert('XSS')>
  1193. $search = 'abcdefghijklmnopqrstuvwxyz';
  1194. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1195. $search .= '1234567890!@#$%^&*()';
  1196. $search .= '~`";:?+/={}[]-_|\'\\';
  1197. for ($i = 0; $i < strlen($search); $i++) {
  1198. // ;? matches the ;, which is optional
  1199. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  1200. // @ @ search for the hex values
  1201. $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
  1202. // @ @ 0{0,7} matches '0' zero to seven times
  1203. $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
  1204. }
  1205. // now the only remaining whitespace attacks are \t, \n, and \r
  1206. $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  1207. $ra2 = array(
  1208. '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'
  1209. );
  1210. $ra = array_merge($ra1, $ra2);
  1211. $found = true; // keep replacing as long as the previous round replaced something
  1212. while ($found == true) {
  1213. $val_before = $val;
  1214. for ($i = 0; $i < sizeof($ra); $i++) {
  1215. $pattern = '/';
  1216. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  1217. if ($j > 0) {
  1218. $pattern .= '(';
  1219. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  1220. $pattern .= '|';
  1221. $pattern .= '|(�{0,8}([9|10|13]);)';
  1222. $pattern .= ')*';
  1223. }
  1224. $pattern .= $ra[$i][$j];
  1225. }
  1226. $pattern .= '/i';
  1227. $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
  1228. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  1229. if ($val_before == $val) {
  1230. // no replacements were made, so exit the loop
  1231. $found = false;
  1232. }
  1233. }
  1234. }
  1235. return $val;
  1236. }
  1237. /**
  1238. * 计算作者积分等级
  1239. *
  1240. * @param $score
  1241. */
  1242. function calcAuthorLevel($score): int
  1243. {
  1244. switch (true) {
  1245. case $score <= 0:
  1246. $level = 0;
  1247. break;
  1248. case $score <= 5000:
  1249. $level = 1;
  1250. break;
  1251. case $score <= 50000:
  1252. $level = 2;
  1253. break;
  1254. case $score <= 100000:
  1255. $level = 3;
  1256. break;
  1257. case $score <= 300000:
  1258. $level = 4;
  1259. break;
  1260. case $score <= 800000:
  1261. $level = 5;
  1262. break;
  1263. case $score <= 1500000:
  1264. $level = 6;
  1265. break;
  1266. case $score <= 2500000:
  1267. $level = 7;
  1268. break;
  1269. case $score <= 5000000:
  1270. $level = 8;
  1271. break;
  1272. case $score <= 10000000:
  1273. $level = 9;
  1274. break;
  1275. default:
  1276. $level = 10;
  1277. break;
  1278. }
  1279. return $level;
  1280. }
  1281. /**
  1282. * 运营数据(上传附件)
  1283. *
  1284. * @param $file
  1285. * @return string
  1286. * @throws Exception
  1287. */
  1288. function uploadEnclosureFile($file)
  1289. {
  1290. // 阿里云主账号
  1291. $accessKeyId = env('OSS_ACCESS_ID');
  1292. $accessKeySecret = env('OSS_ACCESS_KEY');
  1293. $endpoint = env('OSS_END_POINT');
  1294. $bucket = env('OSS_BUCKET');
  1295. // 设置文件名称。
  1296. $object = 'books/enclosure/' . randStr(10) . '--' . $file->getClientOriginalName();
  1297. try {
  1298. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  1299. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  1300. } catch (OssException $e) {
  1301. printf($e->getMessage());
  1302. return '';
  1303. }
  1304. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  1305. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  1306. }
  1307. // 获取当前域名是http还是https
  1308. function getHttpType()
  1309. {
  1310. return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
  1311. }
  1312. // 根据id生成唯一邀请码
  1313. function enCodeId($user_id)
  1314. {
  1315. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1316. $num = strlen($key);
  1317. $code = ''; // 邀请码
  1318. while ($user_id > 0) { // 转进制
  1319. $mod = $user_id % $num; // 求模
  1320. $user_id = ($user_id - $mod) / $num;
  1321. $code = $key[$mod] . $code;
  1322. }
  1323. $code = str_pad($code, 6, 'A', STR_PAD_LEFT); // 不足用0补充
  1324. return $code;
  1325. }
  1326. // 根据邀请码解密为id
  1327. function deCodeId($code)
  1328. {
  1329. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1330. $num = strlen($key);
  1331. if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0') + 1);
  1332. $len = strlen($code);
  1333. $code = strrev($code);
  1334. $user_id = 0;
  1335. for ($i = 0; $i < $len; $i++) {
  1336. $user_id += strpos($key, $code[$i]) * pow($num, $i);
  1337. }
  1338. return $user_id;
  1339. }
  1340. /**
  1341. * 将二维数组按其中的某个数组排序(此方法适用于将数据库数据按数组取出后自动按ID排序的情况 ps:即未按该数组排序)
  1342. *
  1343. * @param array $array 二维数组
  1344. * @param array $sort 排序数组
  1345. * @param string $field 排序字段(二维数组和排序数组相同的字段)
  1346. * @return array
  1347. */
  1348. function sortByArray(array $array, array $sort, string $field): array
  1349. {
  1350. $data = [];
  1351. if (is_array($array) && is_array($sort)) {
  1352. foreach ($sort as $v) {
  1353. foreach ($array as $key => $val) {
  1354. if ($v == $val[$field]) {
  1355. array_push($data, $array[$key]);
  1356. }
  1357. }
  1358. }
  1359. }
  1360. return $data;
  1361. }
  1362. /**
  1363. * 将二维数组按其中的字段排序(正序或倒序)
  1364. *
  1365. * @param array $array 二维数组
  1366. * @param string $field 排序字段
  1367. * @param mixed $type 排序方式(3倒序,4正序)
  1368. * @return array|mixed
  1369. */
  1370. function sortByField(array $array, string $field, $type): array
  1371. {
  1372. if (is_array($array)) {
  1373. array_multisort(array_column($array, $field), $type, $array);
  1374. }
  1375. return $array;
  1376. }
  1377. // 生成用户邀请码
  1378. function setUserInviteCode($id)
  1379. {
  1380. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->encode($id);
  1381. }
  1382. // 解密用户邀请码
  1383. function decodeUserInviteCode($code)
  1384. {
  1385. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->decode($code);
  1386. }
  1387. function getMillisecond()
  1388. {
  1389. list($microsecond, $time) = explode(' ', microtime());
  1390. return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
  1391. }
  1392. function get_client_ip($type = 0, $adv = false)
  1393. {
  1394. $type = $type ? 1 : 0;
  1395. static $ip = null;
  1396. if (null !== $ip) {
  1397. return $ip[$type];
  1398. }
  1399. if ($adv) {
  1400. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1401. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1402. $pos = array_search('unknown', $arr);
  1403. if (false !== $pos) {
  1404. unset($arr[$pos]);
  1405. }
  1406. $ip = trim($arr[0]);
  1407. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1408. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1409. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1410. $ip = $_SERVER['REMOTE_ADDR'];
  1411. }
  1412. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1413. $ip = $_SERVER['REMOTE_ADDR'];
  1414. }
  1415. // IP地址合法验证
  1416. $long = sprintf("%u", ip2long($ip));
  1417. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  1418. return $ip[$type];
  1419. }
  1420. /**
  1421. * 获取真实IP
  1422. */
  1423. function _getIp()
  1424. {
  1425. if (getenv('HTTP_X_FORWARDED_FOR')) {
  1426. $ip = getenv('HTTP_X_FORWARDED_FOR');
  1427. } else if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  1428. $ip = getenv("HTTP_CLIENT_IP");
  1429. else if (getenv("HTTP_X_FORWARD_FOR") && strcasecmp(getenv("HTTP_X_FORWARD_FOR"), "unknown"))
  1430. $ip = getenv("HTTP_X_FORWARD_FOR");
  1431. else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  1432. $ip = getenv("REMOTE_ADDR");
  1433. else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  1434. $ip = $_SERVER['REMOTE_ADDR'];
  1435. else
  1436. $ip = "unknown";
  1437. return ($ip);
  1438. }
  1439. /**
  1440. * 数组 转 对象
  1441. *
  1442. * @param array $arr 数组
  1443. * @return object
  1444. */
  1445. function array_to_object($arr)
  1446. {
  1447. if (gettype($arr) != 'array') {
  1448. return;
  1449. }
  1450. foreach ($arr as $k => $v) {
  1451. if (gettype($v) == 'array' || getType($v) == 'object') {
  1452. $arr[$k] = (object)array_to_object($v);
  1453. }
  1454. }
  1455. return (object)$arr;
  1456. }
  1457. /**
  1458. * 对象 转 数组
  1459. *
  1460. * @param object $obj 对象
  1461. * @return array
  1462. */
  1463. function object_to_array($obj)
  1464. {
  1465. $obj = (array)$obj;
  1466. foreach ($obj as $k => $v) {
  1467. if (gettype($v) == 'resource') {
  1468. return;
  1469. }
  1470. if (gettype($v) == 'object' || gettype($v) == 'array') {
  1471. $obj[$k] = (array)object_to_array($v);
  1472. }
  1473. }
  1474. return $obj;
  1475. }
  1476. /**
  1477. * 检查是否为手机号码
  1478. */
  1479. function _isPhone($number)
  1480. {
  1481. return preg_match("/^1[34578][0-9]{9}$/", $number);
  1482. }
  1483. /**
  1484. * 判断所传的参数是否缺少,如果缺少返回渠道的字段,正确返回0
  1485. *
  1486. * @param array $param
  1487. * @param array $must
  1488. * @return int|mixed
  1489. */
  1490. function checkParam(array $param, array $must)
  1491. {
  1492. foreach ($must as $item) {
  1493. if (array_key_exists($item, $param) && $param[$item] != '') {
  1494. } else {
  1495. return $item;
  1496. }
  1497. }
  1498. return 0;
  1499. }
  1500. /**
  1501. * 对象 转 数组
  1502. *
  1503. * @param object $obj 对象
  1504. * @return array
  1505. */
  1506. function ignoreKeyInArray($targetArray, $delete_keys = [], $changes = [])
  1507. {
  1508. $change_keys = array_keys($changes);
  1509. foreach ($targetArray as $key => $value) {
  1510. if (in_array($key, $delete_keys) && isset($targetArray[$key])) unset($targetArray[$key]);
  1511. if (in_array($key, $change_keys) && isset($targetArray[$key])) $targetArray[$key] = $changes[$key];
  1512. if (is_array($value)) ignoreKeyInArray($value, $delete_keys, $change_keys);
  1513. }
  1514. return $targetArray;
  1515. }
  1516. function itemTransform($trans, $data)
  1517. {
  1518. if ($data) {
  1519. return $trans->transform($data);
  1520. } else {
  1521. return [];
  1522. }
  1523. }
  1524. function collectionTransform($trans, $data)
  1525. {
  1526. $ret_data = [];
  1527. if ($data) {
  1528. foreach ($data as $item) {
  1529. $ret_data[] = $trans->transform($item);
  1530. }
  1531. }
  1532. return $ret_data;
  1533. }
  1534. function paginationTransform($trans, $paginator)
  1535. {
  1536. $ret = [];
  1537. $ret['list'] = [];
  1538. if ($paginator) {
  1539. foreach ($paginator as $item) {
  1540. $ret['list'][] = $trans->transform($item);
  1541. }
  1542. $ret['meta'] = [
  1543. 'total' => (int)$paginator->total(),
  1544. 'per_page' => (int)$paginator->perPage(),
  1545. 'current_page' => (int)$paginator->currentPage(),
  1546. 'last_page' => (int)$paginator->lastPage(),
  1547. 'next_page_url' => (string)$paginator->nextPageUrl(),
  1548. 'prev_page_url' => (string)$paginator->previousPageUrl()
  1549. ];
  1550. }
  1551. return $ret;
  1552. }
  1553. /**
  1554. * 加密site id
  1555. */
  1556. function encodeDistributionChannelId($id)
  1557. {
  1558. $encrypt_pool = [
  1559. ];
  1560. if (isset($encrypt_pool[$id])) {
  1561. return $encrypt_pool[$id];
  1562. }
  1563. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1564. return $hashids->encode($id);
  1565. }
  1566. /**
  1567. * 解密密site id
  1568. */
  1569. function decodeDistributionChannelId($code)
  1570. {
  1571. $encrypt_pool = [
  1572. ];
  1573. if (isset($encrypt_pool[$code])) {
  1574. return $encrypt_pool[$code];
  1575. }
  1576. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1577. $res = $hashids->decode($code);
  1578. if ($res && isset($res[0])) {
  1579. return $res[0];
  1580. }
  1581. return null;
  1582. }
  1583. //bid加密
  1584. function book_hash_encode($bid)
  1585. {
  1586. return Vinkla\Hashids\Facades\Hashids::encode($bid);
  1587. }
  1588. function decodeBid($encode_bid)
  1589. {
  1590. $bid = 0;
  1591. try {
  1592. $bid_arr = \Hashids::decode($encode_bid);
  1593. if (isset($bid_arr[0])) {
  1594. $bid = $bid_arr[0];
  1595. }
  1596. } catch (\Exception $e) {
  1597. return null;
  1598. }
  1599. return $bid;
  1600. }
  1601. /**
  1602. * 获取当前域名
  1603. */
  1604. function _domain()
  1605. {
  1606. return str_replace('https://', '', str_replace('http://', '', url('/')));
  1607. }
  1608. /**
  1609. * 字符串转*
  1610. *
  1611. * @param $str // 待转的字符串
  1612. * @param $start // 转*起始位置
  1613. * @param int $end // 转*结束位置
  1614. * @param string $dot // 转换的字符(必须是单字符,默认是*)
  1615. * @param string $charset // 编码方式
  1616. * @param string $end_char // 特殊字符(碰到此字符则确定end位置)
  1617. * @return string
  1618. */
  1619. function trans_pass($str, $start, $end = 0, $dot = "*", $charset = "UTF-8", $end_char = '@'): string
  1620. {
  1621. $len = mb_strlen($str, $charset);
  1622. if ($start == 0 || $start > $len) {
  1623. $start = 1;
  1624. }
  1625. if ($end != 0 && $end > $len) {
  1626. $end = $len - 2;
  1627. }
  1628. if (strstr($str, $end_char)) {
  1629. $end = $len - strrpos($str, $end_char);
  1630. }
  1631. $endStart = $len - $end;
  1632. $top = mb_substr($str, 0, $start, $charset);
  1633. $bottom = "";
  1634. if ($endStart > 0) {
  1635. $bottom = mb_substr($str, $endStart, $end, $charset);
  1636. }
  1637. $len -= mb_strlen($top, $charset);
  1638. $len -= mb_strlen($bottom, $charset);
  1639. $newStr = $top;
  1640. for ($i = 0; $i < $len; $i++) {
  1641. $newStr .= $dot;
  1642. }
  1643. $newStr .= $bottom;
  1644. return $newStr;
  1645. }
  1646. /**
  1647. * 格式化章节内容
  1648. *
  1649. * @param $content
  1650. * @return false|string
  1651. */
  1652. function formatContent($content)
  1653. {
  1654. if (!$content) return '';
  1655. $content = str_replace(
  1656. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p >', '&ldquo;', '&rdquo;', '&hellip;'],
  1657. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...'],
  1658. $content);
  1659. $content = str_replace(["&nbsp;", '&ldquo;', '&hellip;', '&rdquo;', '<p>'], '', $content);
  1660. // 段落首字母前加两个中文空格
  1661. $string = explode(PHP_EOL, $content);
  1662. foreach ($string as $line => $text) {
  1663. if (mb_substr($text, 0, 2) != '  ') $string[$line] = '  ' . $text;
  1664. }
  1665. $content = implode(PHP_EOL, $string);
  1666. $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8,GBK,GB2312');
  1667. $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);
  1668. return $content;
  1669. }
  1670. /**
  1671. * 筛选出有效的id集合
  1672. *
  1673. * @param array $ids
  1674. * @return array
  1675. */
  1676. function filterValidIds(array $ids): array
  1677. {
  1678. // 传参
  1679. if (empty($ids)) {
  1680. return [];
  1681. }
  1682. $result = [];
  1683. foreach ($ids as $id) {
  1684. if (in_array($id, $result) || !is_numeric($id) || (int)$id < 1) {
  1685. continue;
  1686. }
  1687. $result[] = (int)$id;
  1688. }
  1689. return $result;
  1690. }
  1691. function arrayToStr($map)
  1692. {
  1693. $isMap = isArrMap($map);
  1694. $result = "";
  1695. if ($isMap) {
  1696. $result = "map[";
  1697. }
  1698. $keyArr = array_keys($map);
  1699. if ($isMap) {
  1700. sort($keyArr);
  1701. }
  1702. $paramsArr = array();
  1703. foreach ($keyArr as $k) {
  1704. $v = $map[$k];
  1705. if ($isMap) {
  1706. if (is_array($v)) {
  1707. $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
  1708. } else {
  1709. $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
  1710. }
  1711. } else {
  1712. if (is_array($v)) {
  1713. $paramsArr[] = arrayToStr($v);
  1714. } else {
  1715. $paramsArr[] = trim(strval($v));
  1716. }
  1717. }
  1718. }
  1719. $result = sprintf("%s%s", $result, join(" ", $paramsArr));
  1720. if (!$isMap) {
  1721. $result = sprintf("[%s]", $result);
  1722. } else {
  1723. $result = sprintf("%s]", $result);
  1724. }
  1725. return $result;
  1726. }
  1727. function isArrMap($map)
  1728. {
  1729. foreach ($map as $k => $v) {
  1730. if (is_string($k)) {
  1731. return true;
  1732. }
  1733. }
  1734. return false;
  1735. }
  1736. /**
  1737. * 随机字符串
  1738. *
  1739. * @param $length
  1740. * @return string
  1741. */
  1742. function makeRandStr($length): string
  1743. {
  1744. // 密码字符集,可任意添加你需要的字符
  1745. $str = [
  1746. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  1747. 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  1748. 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
  1749. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  1750. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  1751. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  1752. ];
  1753. // 在 $str 中随机取 $length 个数组元素键名
  1754. $keys = array_rand($str, $length);
  1755. $password = '';
  1756. for ($i = 0; $i < $length; $i++) {
  1757. // 将 $length 个数组元素连接成字符串
  1758. $password .= $str[$keys[$i]];
  1759. }
  1760. return $password;
  1761. }
  1762. /**
  1763. * 导出数据为excel表格
  1764. *
  1765. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1766. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1767. * @param $filename 下载的文件名
  1768. * @examlpe10
  1769. */
  1770. function exportExcel($data = [], $title = [], $filename = 'report')
  1771. {
  1772. ob_end_clean();
  1773. ob_start();
  1774. header("Content-type:application/octet-stream");
  1775. header("Accept-Ranges:bytes");
  1776. header("Content-type:application/vnd.ms-excel");
  1777. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1778. header("Pragma: no-cache");
  1779. header("Expires: 0");
  1780. //导出xls 开始
  1781. if (!empty($title)) {
  1782. foreach ($title as $k => $v) {
  1783. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1784. }
  1785. $title = implode("\t", $title);
  1786. echo "$title\n";
  1787. }
  1788. if (!empty($data)) {
  1789. foreach ($data as $key => $val) {
  1790. foreach ($val as $ck => $cv) {
  1791. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1792. }
  1793. $data[$key] = implode("\t", $data[$key]);
  1794. }
  1795. echo implode("\n", $data);
  1796. }
  1797. }
  1798. /**
  1799. * 导出csv文件
  1800. * @param string $name
  1801. * @param array $headers
  1802. * @param array $data
  1803. * @return void
  1804. */
  1805. function exportCsv(string $name, array $headers, array $data = [])
  1806. {
  1807. header('Content-Description: File Transfer');
  1808. header('Content-Type: application/csv');
  1809. header("Content-Disposition: attachment; filename=".$name.".csv");
  1810. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  1811. $handle = fopen('php://output', 'w');
  1812. ob_clean();
  1813. fputcsv($handle, $headers);
  1814. if ($data) {
  1815. foreach ($data as $row) {
  1816. fputcsv($handle, $row);
  1817. }
  1818. }
  1819. ob_flush();
  1820. fclose($handle);
  1821. die();
  1822. }
  1823. // 树状分类
  1824. function buildCategoryTree($categories, $pid = 0) {
  1825. $tree = [];
  1826. foreach ($categories as $category) {
  1827. if ($category['pid'] == $pid) {
  1828. $children = buildCategoryTree($categories, $category['category_id']);
  1829. if ($children) {
  1830. $category['children'] = $children;
  1831. }
  1832. $tree[] = $category;
  1833. }
  1834. }
  1835. return $tree;
  1836. }
  1837. // 获取文件的md5值
  1838. function getFileContentMD5($filePath){
  1839. //获取文件MD5的128位二进制数组
  1840. $md5Bytes = md5_file($filePath,true);
  1841. //计算文件的Content-MD5
  1842. $contentMD5 = base64_encode($md5Bytes);
  1843. return $contentMD5;
  1844. }
  1845. function getTextTokens($text) {
  1846. // 方法1:按空格分词(西文较准)
  1847. $words = preg_split('/\s+/', $text);
  1848. $wordCount = count($words);
  1849. // 方法2:按字符数估算(中文较准:1个汉字 ≈ 1.5-2 tokens)
  1850. $charCount = mb_strlen($text);
  1851. // 综合估算(根据语言调整权重)
  1852. $tokenCount = $wordCount + $charCount * 0.5; // 示例公式
  1853. // 更简单:直接按字符数 * 系数(中文推荐)
  1854. // $tokenCount = $charCount * 1.8; // 经验系数
  1855. return (int)ceil($tokenCount);
  1856. }
  1857. // 处理小说剧本文本
  1858. function handleScriptWords($text, $enable_emotion=1) {
  1859. $text = preg_replace('/[\r\n]+/', PHP_EOL, $text);
  1860. $text_arr = explode(PHP_EOL, $text);
  1861. $roles = [];
  1862. $words = [];
  1863. $role_gender = [];
  1864. // $sequence = 0;
  1865. foreach ($text_arr as $line) {
  1866. $line = trim($line);
  1867. if ($enable_emotion) {
  1868. $match_rule = '/^(.*?)\:(.*?)\{(.*?)\}$/';
  1869. $count = 4;
  1870. } else {
  1871. $match_rule = '/^(.*?)\:(.*?)$/';
  1872. $count = 3;
  1873. }
  1874. preg_match($match_rule, $line, $matches);
  1875. if (count($matches) == $count) {
  1876. $gender = '0';
  1877. // 角色部分拆分
  1878. preg_match('/^(.*?)\((.*?)\)$/', $matches[1], $matches2);
  1879. if (count($matches2) == 3) {
  1880. $role = $matches2[1];
  1881. $gender_arr = ['男'=>'1', '女'=>'2'];
  1882. $gender = isset($gender_arr[$matches2[2]]) ? $gender_arr[$matches2[2]] : '0';
  1883. }else {
  1884. $role = $matches[1];
  1885. }
  1886. if (!in_array($role, $roles)) {
  1887. $roles[] = $role; // 记录角色
  1888. $role_gender[$role] = $gender;
  1889. }
  1890. $words[] = [
  1891. 'role' => $role,
  1892. 'gender' => $gender,
  1893. 'text' => $matches[2],
  1894. 'emotion' => $enable_emotion ? $matches[3] : '中性',
  1895. ];
  1896. }
  1897. }
  1898. $new_words = [];
  1899. $tmp = '';
  1900. $tmp_arr = [];
  1901. $tmp_text = '';
  1902. // 将words数组按照role和emotion合并相邻的text内容,不相邻则跳过合并
  1903. foreach ($words as $word) {
  1904. if(!$tmp) $tmp = $word['role'].'-'.$word['emotion'];
  1905. if($tmp == $word['role'].'-'.$word['emotion']) {
  1906. $tmp_text .= PHP_EOL.$word['text'];
  1907. $tmp_arr = [
  1908. 'role' => $word['role'],
  1909. 'gender' => $word['gender'],
  1910. 'text' => trim($tmp_text, PHP_EOL),
  1911. 'emotion' => $word['emotion'],
  1912. ];
  1913. }else {
  1914. // $sequence++;
  1915. // $tmp_arr['sequence'] = $sequence;
  1916. $new_words[] = $tmp_arr;
  1917. $tmp = $word['role'].'-'.$word['emotion'];
  1918. $tmp_text = $word['text'];
  1919. $tmp_arr = [
  1920. 'role' => $word['role'],
  1921. 'gender' => $word['gender'],
  1922. 'text' => trim($tmp_text, PHP_EOL),
  1923. 'emotion' => $word['emotion'],
  1924. ];
  1925. }
  1926. }
  1927. if ($tmp_arr) {
  1928. // $sequence++;
  1929. // $tmp_arr['sequence'] = $sequence;
  1930. $new_words[] = $tmp_arr;
  1931. }
  1932. return [
  1933. 'roles' => $roles,
  1934. 'role_gender' => $role_gender,
  1935. 'words' => $new_words,
  1936. ];
  1937. }
  1938. function extractScriptContent($originalContent) {
  1939. if (!$originalContent) return [];
  1940. // 使用更精确的正则表达式分割内容
  1941. $parts = [];
  1942. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  1943. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  1944. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  1945. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  1946. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  1947. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  1948. // 提取剧本亮点(支持多个空格)
  1949. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  1950. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  1951. // 提取人物关系(支持多个空格)
  1952. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  1953. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  1954. // 提取核心矛盾(支持多个空格)
  1955. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  1956. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  1957. // 提取主体列表(支持多个空格)
  1958. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  1959. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  1960. $parts['roles'] = parseRolesFromText($rolesText);
  1961. // 提取美术风格(支持多个空格)
  1962. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  1963. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  1964. // 提取场景列表(支持多个空格)
  1965. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  1966. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  1967. $parts['scenes'] = parseScenesFromText($scenesText);
  1968. // 提取分集详细内容(多剧集模式,支持多个空格)
  1969. preg_match('/###\s*分集剧本\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  1970. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  1971. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  1972. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  1973. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  1974. // 优先使用原文内容,其次使用分集详细内容
  1975. // $parts['content'] = $generatedContent ?: $detailedContent;
  1976. // 解析分集剧本内容
  1977. $episodes = [];
  1978. if ($detailedContent) {
  1979. // 按 ##分集 分割
  1980. preg_match_all('/##\s*分集(\d+)\s*\n(.*?)(?=\n\s*##分集|\z)/s', $detailedContent, $episodeMatches, PREG_SET_ORDER);
  1981. foreach ($episodeMatches as $episodeMatch) {
  1982. $episodeNum = $episodeMatch[1];
  1983. $episodeContent = trim($episodeMatch[2]);
  1984. $episode = [
  1985. 'episode_number' => $episodeNum,
  1986. 'episode_content' => $episodeContent,
  1987. 'episode_name' => '',
  1988. 'scene_description' => '',
  1989. 'camera_movement' => '',
  1990. 'characters' => '',
  1991. 'dialogues' => []
  1992. ];
  1993. // 提取分集名(格式:##分集01第一集: 第一集的标题)
  1994. if (preg_match('/^第.*?集\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $nameMatch)) {
  1995. $episode['episode_name'] = trim($nameMatch[1]);
  1996. }
  1997. // 提取场景描述
  1998. if (preg_match('/场景描述\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $sceneMatch)) {
  1999. $episode['scene_description'] = trim($sceneMatch[1]);
  2000. }
  2001. // 提取运镜
  2002. if (preg_match('/运镜\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $cameraMatch)) {
  2003. $episode['camera_movement'] = trim($cameraMatch[1]);
  2004. }
  2005. // 提取出场角色
  2006. if (preg_match('/出场角色\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $charactersMatch)) {
  2007. $episode['characters'] = trim($charactersMatch[1]);
  2008. }
  2009. // 提取台词内容
  2010. if (preg_match('/台词内容\s*[::]\s*\n(.*?)$/su', $episodeContent, $dialoguesMatch)) {
  2011. $dialoguesText = trim($dialoguesMatch[1]);
  2012. $dialogueLines = explode("\n", $dialoguesText);
  2013. foreach ($dialogueLines as $line) {
  2014. $line = trim($line);
  2015. if (empty($line)) {
  2016. continue;
  2017. }
  2018. // 匹配格式:角色名: 对话内容 或 角色名:对话内容
  2019. if (preg_match('/^(.+?)\s*[::]\s*(.+)$/u', $line, $dialogueMatch)) {
  2020. $episode['dialogues'][] = [
  2021. 'character' => trim($dialogueMatch[1]),
  2022. 'text' => trim($dialogueMatch[2])
  2023. ];
  2024. }
  2025. }
  2026. }
  2027. $episodes[] = $episode;
  2028. }
  2029. }
  2030. $parts['episodes'] = $episodes;
  2031. return $parts;
  2032. }
  2033. /**
  2034. * 处理剧本内容
  2035. */
  2036. function handleScriptContent($originalContent) {
  2037. if (!$originalContent) return [];
  2038. // 使用更精确的正则表达式分割内容
  2039. $parts = [];
  2040. // // 确保内容使用UTF-8编码
  2041. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  2042. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  2043. // }
  2044. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2045. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2046. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2047. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2048. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2049. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2050. // 提取剧本亮点(支持多个空格)
  2051. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2052. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2053. // 提取人物关系(支持多个空格)
  2054. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2055. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2056. // 提取核心矛盾(支持多个空格)
  2057. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2058. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2059. // 提取主体列表(支持多个空格)
  2060. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2061. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2062. $parts['roles'] = parseRolesFromText($rolesText);
  2063. // 提取美术风格(支持多个空格)
  2064. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2065. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2066. // 提取场景列表(支持多个空格)
  2067. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2068. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2069. $parts['scenes'] = parseScenesFromText($scenesText);
  2070. // 提取分集详细内容(多剧集模式,支持多个空格)
  2071. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2072. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2073. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2074. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2075. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2076. // 优先使用原文内容,其次使用分集详细内容
  2077. $parts['content'] = $generatedContent ?: $detailedContent;
  2078. $parts['episode_title'] = '';
  2079. $parts['acts'] = [];
  2080. // 单剧集格式:顶层是大纲信息,分镜部分采用 handleEpisodeContent 的结构标准
  2081. $singleStoryboard = '';
  2082. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2083. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2084. }
  2085. if ($singleStoryboard !== '') {
  2086. $episodeContent = $singleStoryboard;
  2087. if (!preg_match('/第\d+集[::\s]+/u', $episodeContent)) {
  2088. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  2089. $episodeContent = $defaultEpisodeTitle . "\n\n" . $episodeContent;
  2090. }
  2091. $episodeSections = [];
  2092. $episodeSections[] = $episodeContent;
  2093. if ($parts['intro'] !== '') {
  2094. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  2095. }
  2096. if ($parts['art_style'] !== '') {
  2097. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  2098. }
  2099. if ($rolesText !== '') {
  2100. $episodeSections[] = "###主体列表\n" . $rolesText;
  2101. }
  2102. if ($scenesText !== '') {
  2103. $episodeSections[] = "###场景列表\n" . $scenesText;
  2104. }
  2105. if (strpos($episodeContent, '###分镜剧本') === false) {
  2106. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  2107. }
  2108. $episode_arr = handleEpisodeContent(implode("\n\n", $episodeSections));
  2109. if (!empty($episode_arr['acts'])) {
  2110. $parts['episode_title'] = getProp($episode_arr, 'episode_title');
  2111. $parts['acts'] = getProp($episode_arr, 'acts', []);
  2112. if (empty($parts['roles'])) {
  2113. $parts['roles'] = getProp($episode_arr, 'roles', []);
  2114. }
  2115. if (empty($parts['scenes'])) {
  2116. $parts['scenes'] = getProp($episode_arr, 'scenes', []);
  2117. }
  2118. }
  2119. }
  2120. if (empty($parts['acts'])) {
  2121. $fallbackEpisodeArr = handleEpisodeContent($originalContent);
  2122. if (!empty($fallbackEpisodeArr['acts'])) {
  2123. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title');
  2124. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  2125. if (empty($parts['intro'])) {
  2126. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro');
  2127. }
  2128. if (empty($parts['art_style'])) {
  2129. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style');
  2130. }
  2131. if (empty($parts['roles'])) {
  2132. $parts['roles'] = getProp($fallbackEpisodeArr, 'roles', []);
  2133. }
  2134. if (empty($parts['scenes'])) {
  2135. $parts['scenes'] = getProp($fallbackEpisodeArr, 'scenes', []);
  2136. }
  2137. }
  2138. }
  2139. // 多剧集格式:继续兼容旧的分集剧本结构
  2140. $fullScript = '';
  2141. if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2142. $fullScript = trim($storyboardMatch[1]);
  2143. } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2144. $fullScript = trim($storyboardMatch[1]);
  2145. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2146. $fullScript = trim($storyboardMatch[1]);
  2147. }
  2148. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  2149. $fullScript = trim($fallbackMatch[1]);
  2150. }
  2151. $episodes = [];
  2152. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  2153. foreach ($matches as $match) {
  2154. $episodeNumber = (int)trim($match[1]);
  2155. $episodeName = trim($match[2]);
  2156. $episodeContent = trim($match[3]);
  2157. $segments = [];
  2158. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  2159. foreach ($segmentMatches as $segMatch) {
  2160. $segmentNumber = (int)trim($segMatch[1]);
  2161. $segmentContent = trim($segMatch[2]);
  2162. $segments[] = [
  2163. 'segment_number' => $segmentNumber,
  2164. 'segment_content' => $segmentContent,
  2165. ];
  2166. }
  2167. $episodes[] = [
  2168. 'episode_number' => $episodeNumber,
  2169. 'title' => $episodeName,
  2170. 'content' => $episodeContent,
  2171. 'segments' => $segments,
  2172. ];
  2173. }
  2174. if (empty($episodes) && !empty($parts['acts'])) {
  2175. $singleSegments = [];
  2176. foreach ($parts['acts'] as $act) {
  2177. $actSegments = getProp($act, 'segments', []);
  2178. if (!is_array($actSegments)) {
  2179. continue;
  2180. }
  2181. foreach ($actSegments as $segment) {
  2182. $singleSegments[] = [
  2183. 'segment_number' => getProp($segment, 'segment_number'),
  2184. 'segment_content' => getProp($segment, 'segment_content'),
  2185. ];
  2186. }
  2187. }
  2188. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  2189. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  2190. $episodes[] = [
  2191. 'episode_number' => 1,
  2192. 'title' => $episodeName,
  2193. 'content' => $singleStoryboard,
  2194. 'segments' => $singleSegments,
  2195. ];
  2196. }
  2197. $parts['episodes'] = $episodes;
  2198. return $parts;
  2199. }
  2200. function handleEpisodeContent($originalContent) {
  2201. if (!$originalContent) return [];
  2202. // 解析剧集内容
  2203. $result = [
  2204. 'episode_title' => '',
  2205. 'intro' => '',
  2206. 'art_style' => '',
  2207. 'roles' => [],
  2208. 'scenes' => [],
  2209. 'acts' => []
  2210. ];
  2211. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  2212. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  2213. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  2214. }
  2215. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  2216. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  2217. $result['intro'] = trim($summaryMatch[1]);
  2218. }
  2219. // 提取美术风格 - 兼容多种格式
  2220. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  2221. $result['art_style'] = trim($styleMatch[1]);
  2222. }
  2223. // 提取主体列表 - 兼容多种格式
  2224. if (preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  2225. $charactersText = trim($charactersMatch[1]);
  2226. $characterLines = explode("\n", $charactersText);
  2227. foreach ($characterLines as $line) {
  2228. $line = trim($line);
  2229. if (empty($line)) continue;
  2230. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  2231. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2232. $role = trim($charMatch[1]);
  2233. $description = trim($charMatch[2]);
  2234. $timbreName = null;
  2235. // 检查描述末尾是否有{{音色名}}格式
  2236. if (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2237. $description = trim($timbreMatch[1]);
  2238. $timbreName = trim($timbreMatch[2]);
  2239. }
  2240. $roleData = [
  2241. 'role' => $role,
  2242. 'description' => $description
  2243. ];
  2244. // 如果有音色信息,添加到数组中
  2245. if ($timbreName) {
  2246. $timbre = DB::table('mp_timbres')->where('is_enabled', 1)->where('timbre_name', 'like', "%{$timbreName}%")->orderBy('id')->select('timbre_type', 'audio_url')->first();
  2247. if ($timbre) {
  2248. $roleData['voice_name'] = $timbreName;
  2249. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2250. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');;
  2251. }
  2252. }
  2253. $result['roles'][] = $roleData;
  2254. }
  2255. }
  2256. // 加入旁白角色(如果不存在)
  2257. $hasNarrator = false;
  2258. foreach ($result['roles'] as $role) {
  2259. if (isset($role['role']) && $role['role'] === '旁白') {
  2260. $hasNarrator = true;
  2261. break;
  2262. }
  2263. }
  2264. if (!$hasNarrator) {
  2265. $result['roles'][] = [
  2266. 'role' => '旁白',
  2267. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2268. 'voice_name' => '旁白',
  2269. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2270. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2271. ];
  2272. }
  2273. }
  2274. // 提取场景列表 - 兼容多种格式
  2275. if (preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  2276. $scenesText = trim($scenesMatch[1]);
  2277. $sceneLines = explode("\n", $scenesText);
  2278. foreach ($sceneLines as $line) {
  2279. $line = trim($line);
  2280. if (empty($line)) continue;
  2281. // 兼容中文冒号:和英文冒号:
  2282. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  2283. $result['scenes'][] = [
  2284. 'scene' => trim($sceneMatch[1]),
  2285. 'description' => trim($sceneMatch[2])
  2286. ];
  2287. }
  2288. }
  2289. }
  2290. // 提取分镜剧本 - 兼容多种格式
  2291. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $storyboardMatch)) {
  2292. $storyboardText = trim($storyboardMatch[1]);
  2293. // 按幕分割 - 修复第1幕识别和乱码问题
  2294. $acts = [];
  2295. // 先在开头添加换行符,确保第1幕也能被正确分割
  2296. $normalizedText = "\n" . $storyboardText;
  2297. $parts = preg_split('/\n\s*##/', $normalizedText);
  2298. foreach ($parts as $part) {
  2299. $part = trim($part);
  2300. if (empty($part)) continue;
  2301. // 如果不是以"第"开头,跳过
  2302. if (!preg_match('/^第\d+幕/', $part)) {
  2303. continue;
  2304. }
  2305. // 分离标题和内容
  2306. $lines = explode("\n", $part, 2);
  2307. $actTitle = trim($lines[0]);
  2308. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  2309. // 解析幕标题,提取序号和详细信息 - 修复乱码问题
  2310. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  2311. $actNumber = intval($actTitleMatch[1]);
  2312. $actDetails = trim($actTitleMatch[2]);
  2313. // 如果详细信息为空或者就是冒号,使用完整标题
  2314. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  2315. $actDetails = $actTitle;
  2316. }
  2317. } else {
  2318. $actNumber = count($acts) + 1;
  2319. $actDetails = $actTitle;
  2320. }
  2321. // 解析该幕下的分镜
  2322. $segments = [];
  2323. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  2324. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  2325. foreach ($segmentMatches as $segmentMatch) {
  2326. $segmentNumber = intval($segmentMatch[1]);
  2327. $segmentContent = trim($segmentMatch[2]);
  2328. // 解析分镜详细信息
  2329. $segmentData = [
  2330. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT), // 生成唯一ID(后续可在生成任务里查看历史版本)
  2331. 'segment_number' => $segmentNumber,
  2332. 'segment_content' => $segmentContent,
  2333. 'description' => '',
  2334. 'composition' => '',
  2335. 'camera_movement' => '',
  2336. 'voice_actor' => '',
  2337. 'dialogue' => '',
  2338. 'frame_type' => '',
  2339. 'scene' => '', // 新增:场景
  2340. 'characters' => '', // 新增:出镜角色
  2341. 'tail_frame' => '', // 新增:尾帧描述
  2342. // 新增字段
  2343. 'emotion' => '中性', // 新增: 情感
  2344. 'gender' => '0', // 新增: 性别(0未知,1男,2女)
  2345. 'speed_ratio' => 0, // 新增: 语速
  2346. 'loudness_ratio' => 0, // 新增: 音量
  2347. 'emotion_scale' => 4, // 新增: 语调
  2348. 'pitch' => 0, // 新增: 音调
  2349. ];
  2350. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  2351. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  2352. $segmentData['description'] = trim($descMatch[1]);
  2353. }
  2354. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  2355. $segmentData['composition'] = trim($compMatch[1]);
  2356. }
  2357. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  2358. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  2359. }
  2360. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  2361. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  2362. }
  2363. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  2364. $segmentData['dialogue'] = trim($dialogueMatch[1]) == '无' ? '' : trim($dialogueMatch[1]);
  2365. }
  2366. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  2367. $segmentData['frame_type'] = trim($frameMatch[1]);
  2368. }
  2369. // 新增:场景字段
  2370. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  2371. $segmentData['scene'] = trim($sceneMatch[1]);
  2372. }
  2373. // 新增:出镜角色字段
  2374. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  2375. $segmentData['characters'] = trim($charactersMatch[1]);
  2376. }
  2377. // 新增:尾帧描述字段
  2378. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  2379. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  2380. }
  2381. $replaceEmptyArr = [];
  2382. // 新增:情感字段
  2383. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  2384. $replaceEmptyArr[] = trim($emotionMatch[0]);
  2385. $segmentData['emotion'] = trim($emotionMatch[1]);
  2386. }
  2387. // 新增:性别字段
  2388. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  2389. $replaceEmptyArr[] = trim($genderMatch[0]);
  2390. $genderStr = trim($genderMatch[1]);
  2391. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  2392. $segmentData['gender'] = '1';
  2393. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  2394. $segmentData['gender'] = '2';
  2395. } else {
  2396. $segmentData['gender'] = '0';
  2397. }
  2398. }
  2399. // 新增:语速字段
  2400. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  2401. $replaceEmptyArr[] = trim($speedMatch[0]);
  2402. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  2403. }
  2404. // 新增:音量字段
  2405. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  2406. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  2407. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  2408. }
  2409. // 新增:情感强度字段
  2410. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  2411. $replaceEmptyArr[] = trim($scaleMatch[0]);
  2412. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  2413. }
  2414. // 新增:音调字段
  2415. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  2416. $replaceEmptyArr[] = trim($pitchMatch[0]);
  2417. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  2418. }
  2419. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  2420. $segments[] = $segmentData;
  2421. }
  2422. $acts[] = [
  2423. 'act_number' => $actNumber,
  2424. 'act_title' => $actTitle,
  2425. 'act_details' => $actDetails,
  2426. 'segments' => $segments
  2427. ];
  2428. }
  2429. $result['acts'] = $acts;
  2430. }
  2431. return $result;
  2432. }
  2433. /**
  2434. * 远程图片压缩(尽可能保持原图 fidelity,压缩到不超过 maxBytes 字节)
  2435. * 采用有损/无损组合策略:保留原始格式尽量不失真,若需要则通过尺寸缩放和质量调节来降低体积。
  2436. *
  2437. * @param string $url 远程图片 URL
  2438. * @param int $maxBytes 最大字节数,默认 3MB
  2439. * @param string|null $aspectRatio 目标长宽比,如 "16:9"、"4:3"、"1:1" 等,null 则保持原图比例
  2440. * @return string|null 返回压缩后的图片二进制数据,失败时返回 null
  2441. */
  2442. function compressRemoteImageUrlToSize(string $url, int $maxBytes = 3 * 1024 * 1024, ?string $aspectRatio = null): ?string
  2443. {
  2444. // 1) 下载图片数据(使用 Guzzle 以避免 allow_url_fopen 依赖)
  2445. try {
  2446. $client = new Client(['timeout' => 30]);
  2447. $response = $client->get($url, ['stream' => true]);
  2448. if ($response->getStatusCode() !== 200) {
  2449. return null;
  2450. }
  2451. $data = $response->getBody()->getContents();
  2452. } catch (\Exception $e) {
  2453. return null;
  2454. }
  2455. if (!$data) return null;
  2456. // 2) 识别图片类型
  2457. $imgInfo = @getimagesizefromstring($data);
  2458. $mime = $imgInfo['mime'] ?? '';
  2459. if ($mime == 'image/jpeg') return null; // JPEG 不做有损压缩
  2460. // 3) 载入图像对象
  2461. $srcImg = @imagecreatefromstring($data);
  2462. if (!$srcImg) {
  2463. return null;
  2464. }
  2465. $origW = imagesx($srcImg);
  2466. $origH = imagesy($srcImg);
  2467. // 3.2) 计算目标尺寸(根据长宽比调整)
  2468. $targetW = $origW;
  2469. $targetH = $origH;
  2470. if ($aspectRatio !== null) {
  2471. // 解析长宽比,如 "16:9" -> [16, 9]
  2472. $validRatios = array_keys(BaseConst::IMAGE_RATIOS);
  2473. if (in_array($aspectRatio, $validRatios)) {
  2474. list($ratioW, $ratioH) = explode(':', $aspectRatio);
  2475. $ratioW = (float)$ratioW;
  2476. $ratioH = (float)$ratioH;
  2477. $targetRatio = $ratioW / $ratioH;
  2478. $currentRatio = $origW / $origH;
  2479. // 根据目标比例裁剪图片
  2480. if ($currentRatio > $targetRatio) {
  2481. // 原图更宽,需要裁剪宽度
  2482. $targetW = (int)round($origH * $targetRatio);
  2483. $targetH = $origH;
  2484. } else {
  2485. // 原图更高,需要裁剪高度
  2486. $targetW = $origW;
  2487. $targetH = (int)round($origW / $targetRatio);
  2488. }
  2489. }
  2490. }
  2491. // 如果需要裁剪,创建裁剪后的图像
  2492. if ($targetW !== $origW || $targetH !== $origH) {
  2493. $croppedImg = imagecreatetruecolor($targetW, $targetH);
  2494. imagealphablending($croppedImg, false);
  2495. imagesavealpha($croppedImg, true);
  2496. // 处理透明背景
  2497. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  2498. $transparent = imagecolorallocatealpha($croppedImg, 0, 0, 0, 127);
  2499. imagefill($croppedImg, 0, 0, $transparent);
  2500. }
  2501. // 居中裁剪
  2502. $srcX = (int)(($origW - $targetW) / 2);
  2503. $srcY = (int)(($origH - $targetH) / 2);
  2504. imagecopy($croppedImg, $srcImg, 0, 0, $srcX, $srcY, $targetW, $targetH);
  2505. // 替换原图
  2506. safeDestroyImage($srcImg);
  2507. $srcImg = $croppedImg;
  2508. $origW = $targetW;
  2509. $origH = $targetH;
  2510. }
  2511. // 3.1) 内部渲染成不同格式的字符串
  2512. $render = function($srcRes, string $mimeType, int $quality) {
  2513. ob_start();
  2514. switch (strtolower($mimeType)) {
  2515. case 'image/jpeg':
  2516. case 'image/jpg':
  2517. case 'image/pjpeg':
  2518. // 输出 JPEG
  2519. imagejpeg($srcRes, null, $quality);
  2520. break;
  2521. case 'image/png':
  2522. // 将 quality 映射到 PNG 的 compression level (0-9)
  2523. $level = (int)round((100 - $quality) / 11.11);
  2524. if ($level < 0) $level = 0;
  2525. if ($level > 9) $level = 9;
  2526. imagepng($srcRes, null, $level);
  2527. break;
  2528. case 'image/webp':
  2529. if (function_exists('imagewebp')) {
  2530. imagewebp($srcRes, null, $quality);
  2531. } else {
  2532. imagejpeg($srcRes, null, $quality);
  2533. }
  2534. break;
  2535. default:
  2536. imagejpeg($srcRes, null, $quality);
  2537. break;
  2538. }
  2539. $out = ob_get_contents();
  2540. ob_end_clean();
  2541. return $out;
  2542. };
  2543. // 4) 尝试策略:尽量保留原图尺寸,逐步降维/降质量,直到 <= maxBytes
  2544. $tryList = [];
  2545. // 原始尺寸,尽量保留
  2546. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>100];
  2547. // 逐步缩小尺寸
  2548. for ($s = 0.9; $s >= 0.2; $s -= 0.1) {
  2549. $tryList[] = ['scale'=>$s, 'mime'=>$mime, 'quality'=>90];
  2550. }
  2551. // 一系列质量等级(用于 JPEG/WebP)
  2552. $qualityLevels = [95, 90, 85, 75, 60, 50, 40, 30];
  2553. foreach ($qualityLevels as $q) {
  2554. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>$q];
  2555. }
  2556. $bestData = null;
  2557. foreach ($tryList as $cand) {
  2558. $scale = isset($cand['scale']) ? (float)$cand['scale'] : 1.0;
  2559. $mimeT = $cand['mime'] ?? $mime;
  2560. $quality = isset($cand['quality']) ? (int)$cand['quality'] : 90;
  2561. $w = (int)round($origW * $scale);
  2562. $h = (int)round($origH * $scale);
  2563. $src = $srcImg;
  2564. $tempImg = null;
  2565. if ($scale < 1.0) {
  2566. $tempImg = imagecreatetruecolor($w, $h);
  2567. // 处理透明通道
  2568. imagealphablending($tempImg, false);
  2569. imagesavealpha($tempImg, true);
  2570. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  2571. $transparent = imagecolorallocatealpha($tempImg, 0, 0, 0, 127);
  2572. imagefill($tempImg, 0, 0, $transparent);
  2573. }
  2574. // 确保 $srcImg 有效
  2575. if (!$srcImg || (!is_resource($srcImg) && !($srcImg instanceof \GdImage))) {
  2576. safeDestroyImage($tempImg);
  2577. continue;
  2578. }
  2579. imagecopyresampled($tempImg, $srcImg, 0, 0, 0, 0, $w, $h, $origW, $origH);
  2580. $src = $tempImg;
  2581. }
  2582. $imageBytes = $render($src, $mimeT, $quality);
  2583. if ($tempImg !== null) {
  2584. safeDestroyImage($tempImg);
  2585. }
  2586. if ($imageBytes !== false && strlen($imageBytes) <= $maxBytes) {
  2587. $bestData = $imageBytes;
  2588. break;
  2589. }
  2590. }
  2591. // 5) 回退策略:若仍未达到要求,尝试更大幅度降解到一个合理的小尺寸 JPEG
  2592. if ($bestData === null) {
  2593. $tmpW = max(1, (int)round($origW * 0.5));
  2594. $tmpH = max(1, (int)round($origH * 0.5));
  2595. $tmpImg = imagecreatetruecolor($tmpW, $tmpH);
  2596. imagealphablending($tmpImg, false);
  2597. imagesavealpha($tmpImg, true);
  2598. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  2599. $transparent = imagecolorallocatealpha($tmpImg, 0, 0, 0, 127);
  2600. imagefill($tmpImg, 0, 0, $transparent);
  2601. }
  2602. imagecopyresampled($tmpImg, $srcImg, 0, 0, 0, 0, $tmpW, $tmpH, $origW, $origH);
  2603. ob_start();
  2604. if (in_array(strtolower($mime), ['image/jpeg','image/jpg','image/pjpeg'])) {
  2605. imagejpeg($tmpImg, null, 75);
  2606. } elseif (strtolower($mime) === 'image/png') {
  2607. imagepng($tmpImg, null, 6);
  2608. } elseif (function_exists('imagewebp')) {
  2609. imagewebp($tmpImg, null, 75);
  2610. } else {
  2611. imagejpeg($tmpImg, null, 75);
  2612. }
  2613. $tmpBytes = ob_get_contents();
  2614. ob_end_clean();
  2615. safeDestroyImage($tmpImg);
  2616. if ($tmpBytes !== '' && strlen($tmpBytes) <= $maxBytes) {
  2617. $bestData = $tmpBytes;
  2618. }
  2619. }
  2620. // 6) 清理
  2621. safeDestroyImage($srcImg);
  2622. return $bestData;
  2623. }
  2624. /**
  2625. * 安全销毁 GD 图像资源(兼容 PHP7.4+ 的资源管理)
  2626. * 通过引用传递并在销毁后置空变量,避免未定义变量的问题
  2627. *
  2628. * @param resource|\GdImage|null &$img GD 图像资源或对象(PHP7.4 为 resource,PHP8.0+ 为 GdImage)
  2629. */
  2630. function safeDestroyImage(&$img)
  2631. {
  2632. if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
  2633. @imagedestroy($img);
  2634. }
  2635. $img = null;
  2636. }
  2637. // /**
  2638. // * 使用 Imagick 将远程图片压缩至不超过 maxBytes(默认3MB)内
  2639. // * 目标:在尽量保留原始格式和质量的前提下进行压缩,避免内存暴涨
  2640. // * 依赖:Imagick 扩展与 ImageMagick 库,下载使用 Guzzle 获取图片 blob
  2641. // *
  2642. // * @param string $url
  2643. // * @param int $maxBytes 最大字节数,默认 3*1024*1024
  2644. // * @return string|null 经过压缩后的图片 blob,失败返回 null
  2645. // */
  2646. // function compressRemoteImageUrlToSizeImagick(string $url, int $maxBytes = 3 * 1024 * 1024): ?string
  2647. // {
  2648. // // 兼容性检查
  2649. // if (!extension_loaded('imagick') || !class_exists('Imagick')) {
  2650. // return null;
  2651. // }
  2652. // try {
  2653. // $client = new Client(['timeout' => 30]);
  2654. // // 使用流式下载,将数据写入临时文件,避免一次性加载到内存
  2655. // $response = $client->get($url, ['stream' => true]);
  2656. // if ($response->getStatusCode() !== 200) {
  2657. // return null;
  2658. // }
  2659. // $body = $response->getBody();
  2660. // $tmp = tmpfile();
  2661. // if ($tmp === false) {
  2662. // return null;
  2663. // }
  2664. // stream_copy_to_stream($body, $tmp);
  2665. // rewind($tmp);
  2666. // $imagick = new Imagick();
  2667. // $imagick->readImageFile($tmp);
  2668. // $origW = $imagick->getImageWidth();
  2669. // $origH = $imagick->getImageHeight();
  2670. // $format = strtolower($imagick->getImageFormat());
  2671. // // 尝试序列:尺寸缩放 + 质量调节
  2672. // $scales = [1.0, 0.9, 0.8, 0.6, 0.4, 0.25];
  2673. // $qualities = [95, 90, 85, 75, 60, 40, 30, 20];
  2674. // $bestBlob = null;
  2675. // foreach ($scales as $scale) {
  2676. // foreach ($qualities as $q) {
  2677. // $clone = clone $imagick;
  2678. // if ($scale < 1.0) {
  2679. // $w = (int)round($origW * $scale);
  2680. // $h = (int)round($origH * $scale);
  2681. // if ($w < 1 || $h < 1) {
  2682. // $clone->destroy();
  2683. // continue;
  2684. // }
  2685. // $clone->resizeImage($w, $h, Imagick::FILTER_LANCZOS, 1);
  2686. // }
  2687. // $clone->setImageFormat($format);
  2688. // $clone->setImageCompressionQuality($q);
  2689. // $blob = $clone->getImageBlob();
  2690. // $clone->destroy();
  2691. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  2692. // $bestBlob = $blob;
  2693. // break 2;
  2694. // }
  2695. // }
  2696. // }
  2697. // if ($bestBlob !== null) {
  2698. // $imagick->destroy();
  2699. // fclose($tmp);
  2700. // return $bestBlob;
  2701. // }
  2702. // // 回退:尝试强制输出为当前格式的一个中等质量版本
  2703. // $fallback = clone $imagick;
  2704. // $fallback->setImageFormat($format);
  2705. // $fallback->setImageCompressionQuality(75);
  2706. // $blob = $fallback->getImageBlob();
  2707. // $fallback->destroy();
  2708. // $imagick->destroy();
  2709. // fclose($tmp);
  2710. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  2711. // return $blob;
  2712. // }
  2713. // } catch (\Exception $e) {
  2714. // return null;
  2715. // }
  2716. // return null;
  2717. // }
  2718. /**
  2719. * 将主体列表文本拆分为主体数组
  2720. *
  2721. * @param string $rolesText 主体列表文本内容
  2722. * @return array 主体名称数组
  2723. */
  2724. function parseRolesFromText(string $rolesText): array
  2725. {
  2726. if (empty($rolesText)) {
  2727. return [];
  2728. }
  2729. $roles = [];
  2730. // 按行分割文本
  2731. $lines = explode("\n", $rolesText);
  2732. foreach ($lines as $line) {
  2733. $line = trim($line);
  2734. if (empty($line)) {
  2735. continue;
  2736. }
  2737. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2738. $role = trim($charMatch[1]);
  2739. $description = trim($charMatch[2]);
  2740. $timbreName = null;
  2741. if (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2742. $description = trim($timbreMatch[1]);
  2743. $timbreName = trim($timbreMatch[2]);
  2744. }
  2745. $roleData = [
  2746. 'role' => $role,
  2747. 'description' => $description,
  2748. ];
  2749. if ($timbreName) {
  2750. $timbre = DB::table('mp_timbres')
  2751. ->where('is_enabled', 1)
  2752. ->where('timbre_name', 'like', "%{$timbreName}%")
  2753. ->orderBy('id')
  2754. ->select('timbre_type', 'audio_url')
  2755. ->first();
  2756. if ($timbre) {
  2757. $roleData['voice_name'] = $timbreName;
  2758. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2759. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2760. }
  2761. }
  2762. $roles[] = $roleData;
  2763. }
  2764. }
  2765. $hasNarrator = false;
  2766. foreach ($roles as $role) {
  2767. if (getProp($role, 'role') === '旁白') {
  2768. $hasNarrator = true;
  2769. break;
  2770. }
  2771. }
  2772. if (!$hasNarrator) {
  2773. $roles[] = [
  2774. 'role' => '旁白',
  2775. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2776. 'voice_name' => '旁白',
  2777. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2778. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2779. ];
  2780. }
  2781. return $roles;
  2782. }
  2783. /**
  2784. * 将场景列表文本拆分为主体数组
  2785. *
  2786. * @param string $rolesText 场景列表列表文本内容
  2787. * @return array 场景名称数组
  2788. */
  2789. function parseScenesFromText(string $scenesText): array
  2790. {
  2791. if (empty($scenesText)) {
  2792. return [];
  2793. }
  2794. $scenes = [];
  2795. // 按行分割文本
  2796. $lines = explode("\n", $scenesText);
  2797. foreach ($lines as $line) {
  2798. $line = trim($line);
  2799. if (empty($line)) {
  2800. continue;
  2801. }
  2802. $line = str_replace(':', ':', $line);
  2803. if (strstr($line, ':')) {
  2804. $line_arr = explode(':', $line);
  2805. if (count($line_arr) == 2) {
  2806. $scenes[] = [
  2807. 'scene' => $line_arr[0],
  2808. 'description' => $line_arr[1],
  2809. ];
  2810. }
  2811. }
  2812. }
  2813. return $scenes;
  2814. }
  2815. /**
  2816. * 记录日志到数据库
  2817. *
  2818. * @param string $channel 日志频道/目录名
  2819. * @param string $level 日志级别 (info, error, warning, debug)
  2820. * @param string $message 日志信息
  2821. * @param array $context 日志详细数据
  2822. * @return void
  2823. */
  2824. function logDB($channel, $level, $message, $context = []) {
  2825. try {
  2826. // 获取调用堆栈信息
  2827. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  2828. $caller = $trace[1] ?? $trace[0];
  2829. \App\Models\SystemLog::create([
  2830. 'channel' => $channel,
  2831. 'level' => $level,
  2832. 'message' => $message,
  2833. 'context' => $context,
  2834. 'file' => $caller['file'] ?? '',
  2835. 'line' => $caller['line'] ?? 0,
  2836. 'log_time' => date('Y-m-d H:i:s'),
  2837. ]);
  2838. } catch (\Exception $e) {
  2839. // 记录日志失败时不影响主流程
  2840. \Log::error('记录日志到数据库失败: ' . $e->getMessage());
  2841. }
  2842. }
  2843. function filterScriptContent($content) {
  2844. if (!$content) return '';
  2845. if (mb_substr($content, 0, 6) == '确认分镜大纲') return '确认分镜大纲';
  2846. if (mb_strlen($content) > 500) return '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。';
  2847. return $content;
  2848. }