Helpers.php 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983
  1. <?php
  2. use GuzzleHttp\Client;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Log;
  5. use Monolog\Handler\StreamHandler;
  6. use Monolog\Logger;
  7. use OSS\OssClient;
  8. use OSS\Core\OssException;
  9. use Tos\TosClient;
  10. use Tos\Exception\TosClientException;
  11. use Tos\Exception\TosServerException;
  12. use Tos\Model\PutObjectInput;
  13. // use Imagick;
  14. /**
  15. * 截取字符串
  16. *
  17. * @param $string
  18. * @param $length
  19. * @param bool $append
  20. * @return array|string
  21. */
  22. function sysSubStr($string, $length, $append = false)
  23. {
  24. if (strlen($string) <= $length) {
  25. return $string;
  26. }
  27. $i = 0;
  28. $stringLast = [];
  29. while ($i < $length) {
  30. $stringTMP = mb_substr($string, $i, 1);
  31. if (ord($stringTMP) >= 224) {
  32. $stringTMP = mb_substr($string, $i, 3);
  33. $i += 3;
  34. } elseif (ord($stringTMP) >= 192) {
  35. $stringTMP = mb_substr($string, $i, 2);
  36. $i += 2;
  37. } else {
  38. ++$i;
  39. }
  40. $stringLast[] = $stringTMP;
  41. }
  42. $stringLast = implode('', $stringLast);
  43. if ($append) {
  44. $stringLast .= '...';
  45. }
  46. return $stringLast;
  47. }
  48. /**
  49. * 自定义日志
  50. *
  51. * @param $name
  52. * @param string $filename
  53. * @return \Illuminate\Log\Writer
  54. */
  55. function myLog($name, $filename = '')
  56. {
  57. if (!$filename) {
  58. $filename = $name;
  59. }
  60. $filename = $filename . '.log';
  61. $logger = new Logger($name);
  62. $writer = new \Illuminate\Log\Writer($logger);
  63. $writer->useDailyFiles(storage_path('logs/' . $filename));
  64. return $writer;
  65. }
  66. /**
  67. * 业务调试日志
  68. *
  69. * @return Logger
  70. */
  71. function commonLog()
  72. {
  73. $name = 'common';
  74. $filename = $name . '.log';
  75. $logger = new Logger($name);
  76. $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
  77. return $logger;
  78. }
  79. /**
  80. * @param $name
  81. * @return Logger
  82. */
  83. function dLog($name)
  84. {
  85. $filename = $name . '-' . date('Y-m-d') . '.log';
  86. $logger = new Logger($name);
  87. $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
  88. return $logger;
  89. }
  90. /**
  91. * 获取对象或数组的属性值
  92. *
  93. * @param $param
  94. * @param $key
  95. * @param string $default
  96. * @return mixed|string
  97. */
  98. function getProp($param, $key, $default = '')
  99. {
  100. $result = $default;
  101. if (is_object($param) && isset($param->$key)) {
  102. $result = $param->$key;
  103. }
  104. if (is_array($param) && isset($param[$key])) {
  105. $result = $param[$key];
  106. }
  107. return $result;
  108. }
  109. /**
  110. * @param $data
  111. * @param array $trans
  112. * @return array
  113. */
  114. function assetData($data, $trans = []): array
  115. {
  116. $result = [];
  117. if (empty($data)) {
  118. return $result;
  119. }
  120. if (empty($trans)) {
  121. return $data;
  122. }
  123. foreach ($trans as $tran) {
  124. [$originKey, $newKey, $conv, $default] = [$tran['o'], $tran['n'], $tran['conv'], $tran['default']];
  125. if (isset($data[$originKey])) {
  126. $result[$newKey] = $conv(getProp($data, $originKey, $default));
  127. }
  128. }
  129. return $result;
  130. }
  131. /**
  132. * 随机数
  133. *
  134. * @param int $num
  135. * @return string
  136. * @throws Exception
  137. */
  138. function random($num = 16)
  139. {
  140. $bytes = random_bytes($num);
  141. return bin2hex($bytes);
  142. }
  143. /**
  144. * 生成订单
  145. *
  146. * @param string $prefix 订单前缀
  147. * @return string
  148. */
  149. function generateOrderSn($prefix = '')
  150. {
  151. return $prefix . date('YmdHis') . getMillisecond() . rand(1000, 9999);
  152. }
  153. /**
  154. * 分页数据
  155. *
  156. * @param $data
  157. * @return array
  158. */
  159. function getMeta($data)
  160. {
  161. $currentPage = (int)$data->currentPage();
  162. $lastPage = (int)$data->lastPage();
  163. return [
  164. 'current_page' => $currentPage,
  165. 'next_page' => $currentPage >= $lastPage ? $lastPage : ++$currentPage,
  166. 'last_page' => $lastPage,
  167. 'per_page' => (int)$data->perPage(),
  168. 'total' => (int)$data->total(),
  169. 'is_end' => !$data->hasMorePages(),
  170. 'next_page_url' => (string)$data->nextPageUrl(),
  171. 'prev_page_url' => (string)$data->previousPageUrl()
  172. ];
  173. }
  174. /**
  175. * 钉钉通知异常
  176. *
  177. * @param $message
  178. */
  179. function sendNotice($message)
  180. {
  181. $webHook = env('DD_WEB_HOOK');
  182. $data = [
  183. 'msgtype' => 'text',
  184. 'text' => [
  185. 'content' => $message
  186. ],
  187. 'at' => [
  188. 'isAll' => true
  189. ]
  190. ];
  191. // 异步发送
  192. $client = new GuzzleHttp\Client();
  193. $client->post($webHook, ['json' => $data]);
  194. }
  195. /**
  196. * 判断数据是合法的json数据
  197. *
  198. * @param $string
  199. * @return bool
  200. */
  201. function is_json($string)
  202. {
  203. json_decode($string);
  204. return (json_last_error() == JSON_ERROR_NONE);
  205. }
  206. /**
  207. * 获取ip地址
  208. *
  209. * @return mixed|string
  210. */
  211. function getIpAddr()
  212. {
  213. $ipaddress = '';
  214. if (isset($_SERVER['HTTP_CLIENT_IP']))
  215. $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  216. else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  217. $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  218. else if (isset($_SERVER['HTTP_X_FORWARDED']))
  219. $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  220. else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
  221. $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  222. else if (isset($_SERVER['HTTP_FORWARDED']))
  223. $ipaddress = $_SERVER['HTTP_FORWARDED'];
  224. else if (isset($_SERVER['REMOTE_ADDR']))
  225. $ipaddress = $_SERVER['REMOTE_ADDR'];
  226. else
  227. $ipaddress = 'UNKNOWN';
  228. return $ipaddress;
  229. }
  230. /**
  231. * @param int $num
  232. * @return bool|string
  233. * @throws Exception
  234. */
  235. function randStr($num = 5)
  236. {
  237. $str = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm';
  238. return substr(str_shuffle($str), random_int(0, strlen($str) - 11), $num);
  239. }
  240. /**
  241. * 上传文件(火山云tos)
  242. *
  243. * @param $prefix 文件夹前缀
  244. * @param $file 文件二进制
  245. * @param $filename 文件名(不带后缀)
  246. * @return mixed
  247. */
  248. function uploadFileByTos($prefix, $file, $filename='')
  249. {
  250. if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  251. else $filename = $filename . '.' . $file->getClientOriginalExtension();
  252. try {
  253. $client = new TosClient([
  254. 'region' => env('VOLC_REGION'),
  255. 'endpoint' => env('VOLC_END_POINT'),
  256. 'ak' => env('VOLC_AK'),
  257. 'sk' => env('VOLC_SK'),
  258. ]);
  259. $stream = fopen($file->getRealPath(), 'r');
  260. $input = new PutObjectInput(env('VOLC_BUCKET'), "$prefix/$filename", $stream);
  261. $output = $client->putObject($input);
  262. if ($output->getRequestId()) {
  263. return "https://".env('VOLC_BUCKET').'.'.env('VOLC_END_POINT')."/$prefix/$filename";
  264. }
  265. } catch (TosClientException $ex) {
  266. dLog('exception')->info('saveToTos', [$ex->getMessage()]);
  267. } catch (TosServerException $ex) {
  268. dLog('exception')->info('saveToTos', [$ex->getRequestId(), $ex->getStatusCode(), $ex->getErrorCode()]);
  269. }
  270. return '';
  271. }
  272. /**
  273. * 上传文件流(火山云tos)
  274. *
  275. * @param $prefix 文件夹前缀
  276. * @param $file 文件二进制
  277. * @param $filename 文件名(带后缀)
  278. * @return mixed
  279. */
  280. function uploadStreamByTos($prefix, $stream, $filename)
  281. {
  282. try {
  283. $client = new TosClient([
  284. 'region' => env('VOLC_REGION'),
  285. 'endpoint' => env('VOLC_END_POINT'),
  286. 'ak' => env('VOLC_AK'),
  287. 'sk' => env('VOLC_SK'),
  288. ]);
  289. $input = new PutObjectInput(env('VOLC_BUCKET'), "$prefix/$filename", $stream);
  290. $output = $client->putObject($input);
  291. if ($output->getRequestId()) {
  292. return "https://".env('VOLC_BUCKET').'.'.env('VOLC_END_POINT')."/$prefix/$filename";
  293. }
  294. } catch (TosClientException $ex) {
  295. dLog('exception')->info('saveToTos', [$ex->getMessage()]);
  296. } catch (TosServerException $ex) {
  297. dLog('exception')->info('saveToTos', [$ex->getRequestId(), $ex->getStatusCode(), $ex->getErrorCode()]);
  298. }
  299. return '';
  300. }
  301. // 从图片URL获取图片扩展名
  302. function getImgExtFromUrl(string $url): ?string {
  303. $imageInfo = @getimagesize($url);
  304. if ($imageInfo !== false) {
  305. // 返回MIME类型
  306. return mimeToExt($imageInfo['mime']);
  307. // 或者返回文件扩展名
  308. // return image_type_to_extension($imageInfo[2], false);
  309. }
  310. return null;
  311. }
  312. /**
  313. * 从视频URL获取视频扩展名
  314. * 通过下载文件头部字节来识别真实的视频格式
  315. *
  316. * @param string $url 视频URL
  317. * @return string 返回扩展名(如 .mp4),默认 .mp4
  318. */
  319. function getVideoExtFromUrl(string $url): string {
  320. try {
  321. // 方法1:从URL路径中提取扩展名
  322. $parsedUrl = parse_url($url);
  323. $path = $parsedUrl['path'] ?? '';
  324. $pathInfo = pathinfo($path);
  325. $extension = $pathInfo['extension'] ?? '';
  326. if ($extension) {
  327. // 验证是否为常见视频格式
  328. $validVideoExts = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v', 'mpeg', 'mpg'];
  329. if (in_array(strtolower($extension), $validVideoExts)) {
  330. return '.' . strtolower($extension);
  331. }
  332. }
  333. // 方法2:下载文件头部字节来识别格式
  334. $client = new \GuzzleHttp\Client(['timeout' => 30]);
  335. // 先尝试HEAD请求获取Content-Type
  336. try {
  337. $response = $client->head($url);
  338. $contentType = $response->getHeader('Content-Type')[0] ?? '';
  339. // 根据Content-Type映射扩展名
  340. $mimeMap = [
  341. 'video/mp4' => '.mp4',
  342. 'video/x-msvideo' => '.avi',
  343. 'video/quicktime' => '.mov',
  344. 'video/x-ms-wmv' => '.wmv',
  345. 'video/x-flv' => '.flv',
  346. 'video/x-matroska' => '.mkv',
  347. 'video/webm' => '.webm',
  348. 'video/mpeg' => '.mpeg',
  349. ];
  350. if (isset($mimeMap[$contentType])) {
  351. return $mimeMap[$contentType];
  352. }
  353. } catch (\Exception $e) {
  354. // HEAD请求失败,继续尝试其他方法
  355. }
  356. // 方法3:下载前几个字节分析文件魔数(Magic Number)
  357. $response = $client->get($url, [
  358. 'stream' => true,
  359. 'headers' => [
  360. 'Range' => 'bytes=0-31' // 只下载前32字节
  361. ]
  362. ]);
  363. $header = $response->getBody()->read(32);
  364. // 根据文件魔数判断格式
  365. // MP4/M4V: 以 ftyp 开头(偏移4-8字节)
  366. if (strpos($header, 'ftyp') !== false) {
  367. // 进一步判断是否为 M4V
  368. if (strpos($header, 'M4V') !== false || strpos($header, 'm4v') !== false) {
  369. return '.m4v';
  370. }
  371. return '.mp4';
  372. }
  373. // AVI: 以 RIFF 开头,包含 AVI
  374. if (substr($header, 0, 4) === 'RIFF' && strpos($header, 'AVI') !== false) {
  375. return '.avi';
  376. }
  377. // MOV: 包含 moov 或 mdat
  378. if (strpos($header, 'moov') !== false || strpos($header, 'mdat') !== false) {
  379. return '.mov';
  380. }
  381. // FLV: 以 FLV 开头
  382. if (substr($header, 0, 3) === 'FLV') {
  383. return '.flv';
  384. }
  385. // WebM: 以 0x1A 0x45 0xDF 0xA3 开头
  386. if (ord($header[0]) === 0x1A && ord($header[1]) === 0x45 &&
  387. ord($header[2]) === 0xDF && ord($header[3]) === 0xA3) {
  388. return '.webm';
  389. }
  390. // MKV: 与WebM类似,但包含 matroska
  391. if (strpos($header, 'matroska') !== false) {
  392. return '.mkv';
  393. }
  394. // MPEG: 以 0x00 0x00 0x01 开头
  395. if (ord($header[0]) === 0x00 && ord($header[1]) === 0x00 && ord($header[2]) === 0x01) {
  396. return '.mpeg';
  397. }
  398. // 默认返回 .mp4(最常见的格式)
  399. return '.mp4';
  400. } catch (\Exception $e) {
  401. // 出错时返回默认格式
  402. return '.mp4';
  403. }
  404. }
  405. // 辅助 MIME 映射函数
  406. function mimeToExt(string $mime): ?string {
  407. $map = [
  408. 'audio/wav' => '.wav',
  409. 'audio/x-ms-wma' => '.wma',
  410. 'video/x-ms-wmv' => '.wmv',
  411. 'video/mp4' => '.mp4',
  412. 'audio/mpeg' => '.mp3',
  413. 'audio/amr' => '.amr',
  414. 'application/vnd.rn-realmedia' => '.rm',
  415. 'audio/mid' => '.mid',
  416. 'image/bmp' => '.bmp',
  417. 'image/gif' => '.gif',
  418. 'image/png' => '.png',
  419. 'image/tiff' => '.tiff',
  420. 'image/jpeg' => '.jpg',
  421. 'application/pdf' => '.pdf',
  422. ];
  423. return $map[$mime] ?? null;
  424. }
  425. /**
  426. * 上传文件(阿里云oss)
  427. *
  428. * @param $prefix 文件夹前缀
  429. * @param $file 文件二进制
  430. * @param $filename 文件名(不带后缀)
  431. * @return mixed
  432. */
  433. function uploadFile($prefix, $file, $filename='')
  434. {
  435. // 阿里云主账号
  436. $accessKeyId = env('OSS_ACCESS_ID');
  437. $accessKeySecret = env('OSS_ACCESS_KEY');
  438. $endpoint = env('OSS_END_POINT');
  439. $bucket = env('OSS_BUCKET');
  440. if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  441. else $filename = $filename . '.' . $file->getClientOriginalExtension();
  442. // 设置文件名称。
  443. $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
  444. $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
  445. try {
  446. $configs = [
  447. "provider" => $provider,
  448. "endpoint" => $endpoint,
  449. "signatureVersion" => 'v4',
  450. "region" => "cn-hangzhou"
  451. ];
  452. $ossClient = new OssClient($configs);
  453. $uploadRes = $ossClient->uploadFile($bucket, $object, $file->path());
  454. } catch (OssException $e) {
  455. dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
  456. return '';
  457. }
  458. // 替换域名
  459. if (!isset($uploadRes['oss-request-url'])) return '';
  460. $url = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
  461. $url = urldecode($url);
  462. return str_ireplace('http://', 'https://', $url);
  463. }
  464. /**
  465. * 上传文件流(阿里云oss)
  466. *
  467. * @param $prefix 文件夹前缀
  468. * @param $file 文件二进制
  469. * @param $filename 文件名(带后缀)
  470. * @return mixed
  471. */
  472. function uploadStreamToOss($prefix, $stream, $filename) {
  473. $accessKeyId = env('OSS_ACCESS_ID');
  474. $accessKeySecret = env('OSS_ACCESS_KEY');
  475. $endpoint = env('OSS_END_POINT');
  476. $bucket = env('OSS_BUCKET');
  477. // if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  478. // 设置文件名称。
  479. $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
  480. $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
  481. try{
  482. $configs = [
  483. "provider" => $provider,
  484. "endpoint" => $endpoint,
  485. "signatureVersion" => 'v4',
  486. "region"=> "cn-hangzhou"
  487. ];
  488. $ossClient = new OssClient($configs);
  489. $uploadRes = $ossClient->putObject($bucket, $object, $stream);
  490. } catch (OssException $e) {
  491. dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
  492. return '';
  493. }
  494. // 替换域名
  495. if (!isset($uploadRes['oss-request-url'])) return '';
  496. $url = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
  497. $url = urldecode($url);
  498. return str_ireplace('http://', 'https://', $url);
  499. }
  500. /**
  501. * 下载文件到本地
  502. *
  503. * @param $object
  504. * @param $localFile
  505. * @return string
  506. */
  507. function downloadFile($object, $localFile)
  508. {
  509. // 阿里云主账号
  510. $accessKeyId = env('OSS_ACCESS_ID');
  511. $accessKeySecret = env('OSS_ACCESS_KEY');
  512. $endpoint = env('OSS_END_POINT');
  513. $bucket = env('OSS_BUCKET');
  514. try {
  515. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  516. $ossClient->getObject($bucket, $object, [
  517. OssClient::OSS_FILE_DOWNLOAD => $localFile
  518. ]);
  519. } catch (OssException $e) {
  520. printf($e->getMessage());
  521. return '';
  522. }
  523. }
  524. /**
  525. * 上传封面
  526. *
  527. * @param $file
  528. * @return string
  529. * @throws Exception
  530. */
  531. function uploadCoverFile($file)
  532. {
  533. // 阿里云主账号
  534. $accessKeyId = env('OSS_ACCESS_ID');
  535. $accessKeySecret = env('OSS_ACCESS_KEY');
  536. $endpoint = env('OSS_END_POINT');
  537. $bucket = env('OSS_BUCKET');
  538. // 设置文件名称。
  539. $object = 'books/cover/' . randStr(10) . '.' . $file->getClientOriginalExtension();
  540. try {
  541. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  542. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  543. } catch (OssException $e) {
  544. printf($e->getMessage());
  545. return '';
  546. }
  547. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  548. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  549. }
  550. function uploadAgreementFile($file)
  551. {
  552. // 阿里云主账号
  553. $accessKeyId = env('OSS_ACCESS_ID');
  554. $accessKeySecret = env('OSS_ACCESS_KEY');
  555. $endpoint = env('OSS_END_POINT');
  556. $bucket = env('OSS_BUCKET');
  557. $file_name = $file->getClientOriginalName();
  558. $file_name = str_replace('.' . $file->getClientOriginalExtension(), '', $file_name);
  559. // 设置文件名称。
  560. $object = 'books/contract/' . $file_name . '-' . date('YmdHi') . '.' . $file->getClientOriginalExtension();
  561. try {
  562. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  563. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file);
  564. } catch (OssException $e) {
  565. printf($e->getMessage());
  566. return '';
  567. }
  568. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  569. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . urldecode(getProp($urlArr, 'path')) : '';
  570. }
  571. /**
  572. * 上传wap推荐图片
  573. *
  574. * @param $file
  575. * @param $filename
  576. * @return string
  577. * @throws Exception
  578. */
  579. function uploadWapRecommendPic($file, $filename)
  580. {
  581. // 阿里云主账号
  582. $accessKeyId = env('OSS_ACCESS_ID');
  583. $accessKeySecret = env('OSS_ACCESS_KEY');
  584. $endpoint = env('OSS_END_POINT');
  585. $bucket = env('OSS_BUCKET_YCSD');
  586. // 设置文件名称。
  587. $object = 'ycsd_web_3nd/images/homebanners/' . $filename . '.' . $file->getClientOriginalExtension();
  588. try {
  589. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  590. $options = array(
  591. OssClient::OSS_HEADERS => array(
  592. 'Content-Type' => 'image/jpeg',
  593. 'Content-Disposition' => 'inline'
  594. ),
  595. );
  596. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path(), $options);
  597. } catch (OssException $e) {
  598. printf($e->getMessage());
  599. return '';
  600. }
  601. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  602. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  603. }
  604. /**
  605. * @param $path
  606. * @return Generator
  607. */
  608. function readFileContent($path)
  609. {
  610. if ($handle = fopen($path, 'r')) {
  611. while (!feof($handle)) {
  612. yield trim(fgets($handle));
  613. }
  614. fclose($handle);
  615. }
  616. }
  617. function exportFileCsv(array $headers, array $data, string $filename)
  618. {
  619. header("Content-type:application/vnd.ms-excel");
  620. header("Content-Disposition:attachment;filename=" . $filename . ".csv");
  621. $headers = collect($headers)->map(function ($item) {
  622. return "\"" . mb_convert_encoding($item, "GBK", "UTF-8") . "\"";
  623. })->all();
  624. echo implode(",", $headers);
  625. echo "\r\n";
  626. foreach ($data as $item) {
  627. $rows = collect($item)->map(function ($row) {
  628. return "\"" . mb_convert_encoding(is_numeric($row) && strlen($row) > 12 ? "'" . $row : $row, "GBK", "UTF-8") . "\"";
  629. })->all();
  630. echo implode(",", $rows);
  631. echo "\r\n";
  632. }
  633. exit();
  634. }
  635. //function exportFileCsv(array $header, array $data, string $filename) {
  636. // header('Content-Encoding: UTF-8');
  637. // header("Content-type:application/vnd.ms-excel;charset=UTF-8");
  638. // header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
  639. //
  640. // //打开php标准输出流
  641. // $fp = fopen('php://output', 'a');
  642. //
  643. // //添加BOM头,以UTF8编码导出CSV文件,如果文件头未添加BOM头,打开会出现乱码。
  644. // fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
  645. // //添加导出标题
  646. // fputcsv($fp, $header);
  647. //
  648. // foreach ($data as $k => $item) {
  649. // fputcsv($fp, $item);
  650. // if ($k % 5000 == 0) {
  651. // //每1万条数据就刷新缓冲区
  652. // ob_flush();
  653. // flush();
  654. // }
  655. // }
  656. // exit();
  657. //}
  658. //function exportFileCsv(array $header, array $data, string $filename) {
  659. //
  660. // header('Content-Type: application/vnd.ms-excel');
  661. // header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
  662. // header('Cache-Control: max-age=0');
  663. //
  664. // //打开PHP文件句柄,php://output 表示直接输出到浏览器
  665. // $fp = fopen('php://output', 'a');
  666. //
  667. // //输出Excel列名信息
  668. // foreach ($header as $key => $value) {
  669. // //CSV的Excel支持GBK编码,一定要转换,否则乱码
  670. // $header[$key] = iconv('utf-8', 'gbk', $value);
  671. // }
  672. //
  673. // //将数据通过fputcsv写到文件句柄
  674. // fputcsv($fp, $header);
  675. //
  676. // //计数器
  677. // $num = 0;
  678. //
  679. // //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
  680. // $limit = 10000;
  681. //
  682. // //逐行取出数据,不浪费内存
  683. // $count = count($data);
  684. // for ($i = 0; $i < $count; $i++) {
  685. //
  686. // $num++;
  687. //
  688. // //刷新一下输出buffer,防止由于数据过多造成问题
  689. // if ($limit == $num) {
  690. // ob_flush();
  691. // flush();
  692. // $num = 0;
  693. // }
  694. //
  695. // $row = $data[$i];
  696. // foreach ($row as $key => $value) {
  697. // $row[$key] = iconv('utf-8', 'gbk', $value);
  698. // }
  699. //
  700. // fputcsv($fp, $row);
  701. // }
  702. // exit();
  703. //}
  704. // 获取除空格外的字数
  705. function getSize(string $content)
  706. {
  707. $content = preg_replace('/\s+/', '', $content);
  708. return mb_strlen($content, 'utf-8');
  709. }
  710. // 获取word字符数(不计空格)
  711. function getChargeSize(string $content)
  712. {
  713. //判断是否存在替换字符
  714. $is_replace_count = substr_count($content, "龘");
  715. try {
  716. //先将回车换行符做特殊处理
  717. $str = preg_replace('/(\r\n+|\s+| +)/', "龘", $content);
  718. //处理英文字符数字,连续字母、数字、英文符号视为一个单词
  719. $str = preg_replace('/[a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",\'<>~`\?:;|]/', "m", $str);
  720. //合并字符m,连续字母、数字、英文符号视为一个单词
  721. $str = preg_replace('/m+/', "*", $str);
  722. //去掉回车换行符
  723. $str = preg_replace('/龘+/', "", $str);
  724. //返回字数
  725. return mb_strlen($str) + $is_replace_count;
  726. } catch (\Exception $e) {
  727. return 0;
  728. }
  729. }
  730. // 将阿拉伯数字转换成中文
  731. function chineseNum($figure, $capital = false, $mode = true)
  732. {
  733. if ($figure == '0') return '零';
  734. $numberChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  735. $unitChar = ['', '十', '百', '千', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
  736. if ($capital !== false) {
  737. $numberChar = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  738. $unitChar = ['', '拾', '佰', '仟', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
  739. }
  740. $dec = "点";
  741. $target = '';
  742. $matches = [];
  743. if ($mode) {
  744. preg_match("/^0*(\d*)\.?(\d*)/", $figure, $matches);
  745. } else {
  746. preg_match("/(\d*)\.?(\d*)/", $figure, $matches);
  747. }
  748. list(, $number, $point) = $matches;
  749. if ($point) {
  750. $target = $dec . chineseNum($point, $capital, false);
  751. }
  752. if (!$number) {
  753. return $target;
  754. }
  755. $str = strrev($number);
  756. for ($i = 0; $i < strlen($str); $i++) {
  757. $out[$i] = $numberChar[$str[$i]];
  758. if ($mode === false) {
  759. continue;
  760. }
  761. $out[$i] .= $str[$i] != '0' ? $unitChar[$i % 4] : '';
  762. if ($i > 0 && $str[$i] + $str[$i - 1] == 0) {
  763. $out[$i] = '';
  764. }
  765. if ($i % 4 == 0) {
  766. $temp = substr($str, $i, 4);
  767. $out[$i] = str_replace($numberChar[0], '', $out[$i]);
  768. if (strrev($temp) > 0) {
  769. $out[$i] .= $unitChar[4 + floor($i / 4)];
  770. } else {
  771. $out[$i] .= $numberChar[0];
  772. }
  773. }
  774. }
  775. $result = join('', array_reverse($out)) . $target;
  776. return mb_substr($result, 0, 2) == '一十' ? mb_substr($result, 1) : $result;
  777. }
  778. function addPrefix($str)
  779. {
  780. if (!$str) return '';
  781. if (mb_substr($str, 0, 4) == 'http') return $str;
  782. if (mb_substr($str, 0, 5) == 'https') return $str;
  783. if (mb_substr($str, 0, 7) == '/books/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  784. if (mb_substr($str, 0, 6) == '/card/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  785. if (mb_substr($str, 0, 15) == 'uploader/idcard') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com/' . $str;
  786. if (mb_substr($str, 0, 6) == '/cover') return 'https://cdn-newyc.ycsd.cn/ycsd_cover/covermiddle' . mb_substr($str, 6);
  787. if (mb_substr($str, 0, 8) == '/images/') return 'https://cdn-newyc.ycsd.cn/ycsd_cover' . $str;
  788. }
  789. /**
  790. * 章节内容排版
  791. *
  792. * @param $content
  793. * @return string
  794. */
  795. function filterContent($content)
  796. {
  797. if (!$content) return '';
  798. $content = str_replace(
  799. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  800. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  801. $content);
  802. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  803. // 段落首字母前加两个中文空格
  804. $string = explode(PHP_EOL, $content);
  805. foreach ($string as $line => $text) {
  806. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' '], '', $string[$line]);
  807. if (!$string[$line]) {
  808. unset($string[$line]);
  809. } else {
  810. $string[$line] = $string[$line] . PHP_EOL;
  811. // if (mb_substr($string[$line], 0, 1) == ' ') {
  812. // $string[$line] = str_replace(' ', '', $string[$line]); // 去除多个空格
  813. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  814. // }
  815. // if (mb_substr($string[$line], 0, 2) != '  ') {
  816. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  817. // }
  818. // if (mb_substr($string[$line], 0, 2) == '  ' && str_replace(' ', '', $string[$line])) {
  819. // $string[$line] .= PHP_EOL;
  820. // }
  821. }
  822. }
  823. $content = implode(PHP_EOL, $string);
  824. return $content;
  825. }
  826. /**
  827. * 书籍简介排版
  828. *
  829. * @param $content
  830. * @return string
  831. */
  832. function filterContent2($content)
  833. {
  834. if (!$content) return '';
  835. $content = str_replace(
  836. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  837. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  838. $content);
  839. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  840. // 段落首字母前加两个中文空格
  841. $string = explode(PHP_EOL, $content);
  842. $content = '';
  843. foreach ($string as $line => $text) {
  844. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  845. if (!$string[$line]) {
  846. unset($string[$line]);
  847. } else {
  848. $string[$line] = '  ' . $string[$line] . '<br />';
  849. $content .= $string[$line];
  850. }
  851. }
  852. $content = trim($content, '<br />');
  853. return $content;
  854. }
  855. /**
  856. * 书籍简介排版-抖音版
  857. *
  858. * @param $content
  859. * @return string
  860. */
  861. function filterIntro($content)
  862. {
  863. if (!$content) return '';
  864. $content = str_replace(
  865. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  866. [' ', ' ', ' ', ' ', ' ', '', ' ', '“', '”', '...', '‘', '’', '-'],
  867. $content);
  868. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  869. // 段落首字母前加两个中文空格
  870. $string = explode(PHP_EOL, $content);
  871. $content = '';
  872. foreach ($string as $line => $text) {
  873. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  874. if (!$string[$line]) {
  875. unset($string[$line]);
  876. } else {
  877. $content .= $string[$line];
  878. }
  879. }
  880. $content = trim($content, '<br />');
  881. return $content;
  882. }
  883. function sensitiveStr($list, $string)
  884. {
  885. $count = 0; //违规词的个数
  886. $sensitiveWord = ''; //违规词
  887. $stringAfter = $string; //替换后的内容
  888. $total = count($list);
  889. $size = 500;
  890. $last = ceil($total / $size);
  891. $patternList = [];
  892. for ($page = 1; $page <= $last; $page++) {
  893. $arr = array_slice($list, $size * ($page - 1), $size);
  894. $filter = [];
  895. foreach ($arr as $v) {
  896. if (preg_match('/[^a-zA-Z0-9\|\p{Han}\·]/u', $v)) continue;
  897. $filter[] = $v;
  898. // $a = preg_replace('/[^a-zA-Z0-9\|\p{Han}]/u', '', $v);
  899. // if ($a) $filter[] = $a;
  900. }
  901. $pattern = "/" . implode("|", $filter) . "/i"; //定义正则表达式
  902. if (preg_match_all($pattern, $string, $matches)) { //匹配到了结果
  903. $patternList = array_merge($patternList, $matches[0]); //匹配到的数组
  904. }
  905. }
  906. $sensitiveWord = '';
  907. if ($patternList) {
  908. $count = count($patternList);
  909. // $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
  910. $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '*')); //把匹配到的数组进行合并,替换使用
  911. $stringAfter = strtr($string, $replaceArray); //结果替换
  912. // 将敏感词合并
  913. $return_pattern = [];
  914. foreach ($patternList as $v) {
  915. if (!isset($return_pattern[$v])) {
  916. $return_pattern[$v] = [
  917. 'word' => $v,
  918. 'count' => 1,
  919. ];
  920. } else {
  921. $return_pattern[$v]['count'] += 1;
  922. }
  923. }
  924. foreach ($return_pattern as $v) {
  925. $sensitiveWord .= $v['word'] . ',';
  926. }
  927. }
  928. return [
  929. 'count' => $count,
  930. 'sensitive_words' => trim($sensitiveWord, ','),
  931. 'content' => $stringAfter
  932. ];
  933. }
  934. /**
  935. * 转换时间格式
  936. *
  937. * @param $date
  938. * @param string $format
  939. * @return false|string
  940. */
  941. function transDate($date, $format = 'Y-m-d H:i:s')
  942. {
  943. return strtotime($date) > 0 ? date($format, strtotime($date)) : '';
  944. }
  945. /**
  946. * 根据网段获取计算所有IP
  947. *
  948. * @param string $segment 网段 '139.217.0.1/24'
  949. * @return array [网络地址:139.217.0.1 广播地址:139.217.0.255 IP列表: ['139.217.0.2','139.217.0.3'……'139.217.0.254']]
  950. */
  951. function getIpBySegment($segment)
  952. {
  953. $segmentInfo = explode("/", $segment);
  954. $beginIpArray = explode(".", $segmentInfo[0]);
  955. $mask = intval($segmentInfo['1']);
  956. $endIp = array();
  957. foreach ($beginIpArray as $ipKey => $item) {
  958. $beginFlag = 8 * ($ipKey); //0 8 16 24
  959. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  960. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  961. $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));
  962. }
  963. $ipArray = array();
  964. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0]++) {
  965. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1]++) {
  966. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2]++) {
  967. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3]++) {
  968. $ipArray[] = implode(".", $beginIp);
  969. }
  970. }
  971. }
  972. }
  973. $network_ip_addr = $beginIpArray[0] . '.' . $beginIpArray[1] . '.' . $beginIpArray[2] . '.' . '0'; // 网络地址
  974. $broadcast_ip_addr = end($ipArray); // 广播地址
  975. if ($ipArray[0] == $network_ip_addr) { // 如果是网络地址则删掉
  976. unset($ipArray[0]);
  977. }
  978. $last = count($ipArray);
  979. unset($ipArray[$last]);
  980. return [$network_ip_addr, $broadcast_ip_addr, $ipArray];
  981. }
  982. /**
  983. * 在指定网段中分配子网段
  984. *
  985. * @param string $segment 指定网段
  986. * @param int $ipNum 需要的IP数
  987. * @param array $usedIpArray 不可用(已经使用)的IP,默认为空数组
  988. * @return bool|string 成功则返回分配的网段
  989. */
  990. function allocateSegment($segment, $ipNum, $usedIpArray = [])
  991. {
  992. $usedIpArray = empty($usedIpArray) ? [] : array_flip($usedIpArray);
  993. //计算需要多少个IP
  994. $i = 0;
  995. $ipCount = pow(2, $i);
  996. while ($ipCount < $ipNum) {
  997. $i++;
  998. $ipCount = pow(2, $i);
  999. }
  1000. $newMask = 32 - $i;
  1001. //大网段的开始和结束IP
  1002. $segmentInfo = explode("/", $segment); //['139.217.0.1',24]
  1003. $beginIpArray = explode(".", $segmentInfo[0]);//[139,217,0,1]
  1004. $mask = intval($segmentInfo['1']); //24
  1005. if ($newMask < $mask) {
  1006. return false;
  1007. }
  1008. $endIp = array();
  1009. $step = [];
  1010. foreach ($beginIpArray as $ipKey => $item) {
  1011. $beginFlag = 8 * ($ipKey); //0 8 16 24
  1012. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  1013. $step[$ipKey] = $newMask > $endFlag ? 1 : ($endFlag - $newMask < 8 ? pow(2, $endFlag - $newMask) : pow(2, 8));
  1014. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  1015. $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));
  1016. }
  1017. //遍历生成网段
  1018. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0] += $step[0]) {
  1019. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1] += $step[1]) {
  1020. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2] += $step[2]) {
  1021. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3] += $step[3]) {
  1022. $newSegment = implode('.', $beginIp) . '/' . $newMask;
  1023. //获取该网段所有的IP
  1024. $ipArray = getIpBySegment($newSegment);
  1025. $canUse = true;
  1026. //判断该网段是否可用
  1027. if (!empty($usedIpArray)) {
  1028. foreach ($ipArray as $ip) {
  1029. if (isset($usedIpArray[$ip])) {
  1030. $canUse = false;
  1031. break;
  1032. }
  1033. }
  1034. }
  1035. if ($canUse) {
  1036. return $newSegment;
  1037. }
  1038. }
  1039. }
  1040. }
  1041. }
  1042. return false;
  1043. }
  1044. function remove_xss($val)
  1045. {
  1046. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  1047. // this prevents some character re-spacing such as <java\0script>
  1048. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
  1049. $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
  1050. // straight replacements, the user should never need these since they're normal characters
  1051. // this prevents like <IMG SRC=@avascript:alert('XSS')>
  1052. $search = 'abcdefghijklmnopqrstuvwxyz';
  1053. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1054. $search .= '1234567890!@#$%^&*()';
  1055. $search .= '~`";:?+/={}[]-_|\'\\';
  1056. for ($i = 0; $i < strlen($search); $i++) {
  1057. // ;? matches the ;, which is optional
  1058. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  1059. // @ @ search for the hex values
  1060. $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
  1061. // @ @ 0{0,7} matches '0' zero to seven times
  1062. $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
  1063. }
  1064. // now the only remaining whitespace attacks are \t, \n, and \r
  1065. $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  1066. $ra2 = array(
  1067. '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'
  1068. );
  1069. $ra = array_merge($ra1, $ra2);
  1070. $found = true; // keep replacing as long as the previous round replaced something
  1071. while ($found == true) {
  1072. $val_before = $val;
  1073. for ($i = 0; $i < sizeof($ra); $i++) {
  1074. $pattern = '/';
  1075. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  1076. if ($j > 0) {
  1077. $pattern .= '(';
  1078. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  1079. $pattern .= '|';
  1080. $pattern .= '|(�{0,8}([9|10|13]);)';
  1081. $pattern .= ')*';
  1082. }
  1083. $pattern .= $ra[$i][$j];
  1084. }
  1085. $pattern .= '/i';
  1086. $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
  1087. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  1088. if ($val_before == $val) {
  1089. // no replacements were made, so exit the loop
  1090. $found = false;
  1091. }
  1092. }
  1093. }
  1094. return $val;
  1095. }
  1096. /**
  1097. * 计算作者积分等级
  1098. *
  1099. * @param $score
  1100. */
  1101. function calcAuthorLevel($score): int
  1102. {
  1103. switch (true) {
  1104. case $score <= 0:
  1105. $level = 0;
  1106. break;
  1107. case $score <= 5000:
  1108. $level = 1;
  1109. break;
  1110. case $score <= 50000:
  1111. $level = 2;
  1112. break;
  1113. case $score <= 100000:
  1114. $level = 3;
  1115. break;
  1116. case $score <= 300000:
  1117. $level = 4;
  1118. break;
  1119. case $score <= 800000:
  1120. $level = 5;
  1121. break;
  1122. case $score <= 1500000:
  1123. $level = 6;
  1124. break;
  1125. case $score <= 2500000:
  1126. $level = 7;
  1127. break;
  1128. case $score <= 5000000:
  1129. $level = 8;
  1130. break;
  1131. case $score <= 10000000:
  1132. $level = 9;
  1133. break;
  1134. default:
  1135. $level = 10;
  1136. break;
  1137. }
  1138. return $level;
  1139. }
  1140. /**
  1141. * 运营数据(上传附件)
  1142. *
  1143. * @param $file
  1144. * @return string
  1145. * @throws Exception
  1146. */
  1147. function uploadEnclosureFile($file)
  1148. {
  1149. // 阿里云主账号
  1150. $accessKeyId = env('OSS_ACCESS_ID');
  1151. $accessKeySecret = env('OSS_ACCESS_KEY');
  1152. $endpoint = env('OSS_END_POINT');
  1153. $bucket = env('OSS_BUCKET');
  1154. // 设置文件名称。
  1155. $object = 'books/enclosure/' . randStr(10) . '--' . $file->getClientOriginalName();
  1156. try {
  1157. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  1158. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  1159. } catch (OssException $e) {
  1160. printf($e->getMessage());
  1161. return '';
  1162. }
  1163. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  1164. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  1165. }
  1166. // 获取当前域名是http还是https
  1167. function getHttpType()
  1168. {
  1169. return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
  1170. }
  1171. // 根据id生成唯一邀请码
  1172. function enCodeId($user_id)
  1173. {
  1174. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1175. $num = strlen($key);
  1176. $code = ''; // 邀请码
  1177. while ($user_id > 0) { // 转进制
  1178. $mod = $user_id % $num; // 求模
  1179. $user_id = ($user_id - $mod) / $num;
  1180. $code = $key[$mod] . $code;
  1181. }
  1182. $code = str_pad($code, 6, 'A', STR_PAD_LEFT); // 不足用0补充
  1183. return $code;
  1184. }
  1185. // 根据邀请码解密为id
  1186. function deCodeId($code)
  1187. {
  1188. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1189. $num = strlen($key);
  1190. if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0') + 1);
  1191. $len = strlen($code);
  1192. $code = strrev($code);
  1193. $user_id = 0;
  1194. for ($i = 0; $i < $len; $i++) {
  1195. $user_id += strpos($key, $code[$i]) * pow($num, $i);
  1196. }
  1197. return $user_id;
  1198. }
  1199. /**
  1200. * 将二维数组按其中的某个数组排序(此方法适用于将数据库数据按数组取出后自动按ID排序的情况 ps:即未按该数组排序)
  1201. *
  1202. * @param array $array 二维数组
  1203. * @param array $sort 排序数组
  1204. * @param string $field 排序字段(二维数组和排序数组相同的字段)
  1205. * @return array
  1206. */
  1207. function sortByArray(array $array, array $sort, string $field): array
  1208. {
  1209. $data = [];
  1210. if (is_array($array) && is_array($sort)) {
  1211. foreach ($sort as $v) {
  1212. foreach ($array as $key => $val) {
  1213. if ($v == $val[$field]) {
  1214. array_push($data, $array[$key]);
  1215. }
  1216. }
  1217. }
  1218. }
  1219. return $data;
  1220. }
  1221. /**
  1222. * 将二维数组按其中的字段排序(正序或倒序)
  1223. *
  1224. * @param array $array 二维数组
  1225. * @param string $field 排序字段
  1226. * @param mixed $type 排序方式(3倒序,4正序)
  1227. * @return array|mixed
  1228. */
  1229. function sortByField(array $array, string $field, $type): array
  1230. {
  1231. if (is_array($array)) {
  1232. array_multisort(array_column($array, $field), $type, $array);
  1233. }
  1234. return $array;
  1235. }
  1236. // 生成用户邀请码
  1237. function setUserInviteCode($id)
  1238. {
  1239. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->encode($id);
  1240. }
  1241. // 解密用户邀请码
  1242. function decodeUserInviteCode($code)
  1243. {
  1244. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->decode($code);
  1245. }
  1246. function getMillisecond()
  1247. {
  1248. list($microsecond, $time) = explode(' ', microtime());
  1249. return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
  1250. }
  1251. function get_client_ip($type = 0, $adv = false)
  1252. {
  1253. $type = $type ? 1 : 0;
  1254. static $ip = null;
  1255. if (null !== $ip) {
  1256. return $ip[$type];
  1257. }
  1258. if ($adv) {
  1259. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1260. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1261. $pos = array_search('unknown', $arr);
  1262. if (false !== $pos) {
  1263. unset($arr[$pos]);
  1264. }
  1265. $ip = trim($arr[0]);
  1266. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1267. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1268. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1269. $ip = $_SERVER['REMOTE_ADDR'];
  1270. }
  1271. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1272. $ip = $_SERVER['REMOTE_ADDR'];
  1273. }
  1274. // IP地址合法验证
  1275. $long = sprintf("%u", ip2long($ip));
  1276. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  1277. return $ip[$type];
  1278. }
  1279. /**
  1280. * 获取真实IP
  1281. */
  1282. function _getIp()
  1283. {
  1284. if (getenv('HTTP_X_FORWARDED_FOR')) {
  1285. $ip = getenv('HTTP_X_FORWARDED_FOR');
  1286. } else if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  1287. $ip = getenv("HTTP_CLIENT_IP");
  1288. else if (getenv("HTTP_X_FORWARD_FOR") && strcasecmp(getenv("HTTP_X_FORWARD_FOR"), "unknown"))
  1289. $ip = getenv("HTTP_X_FORWARD_FOR");
  1290. else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  1291. $ip = getenv("REMOTE_ADDR");
  1292. else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  1293. $ip = $_SERVER['REMOTE_ADDR'];
  1294. else
  1295. $ip = "unknown";
  1296. return ($ip);
  1297. }
  1298. /**
  1299. * 数组 转 对象
  1300. *
  1301. * @param array $arr 数组
  1302. * @return object
  1303. */
  1304. function array_to_object($arr)
  1305. {
  1306. if (gettype($arr) != 'array') {
  1307. return;
  1308. }
  1309. foreach ($arr as $k => $v) {
  1310. if (gettype($v) == 'array' || getType($v) == 'object') {
  1311. $arr[$k] = (object)array_to_object($v);
  1312. }
  1313. }
  1314. return (object)$arr;
  1315. }
  1316. /**
  1317. * 对象 转 数组
  1318. *
  1319. * @param object $obj 对象
  1320. * @return array
  1321. */
  1322. function object_to_array($obj)
  1323. {
  1324. $obj = (array)$obj;
  1325. foreach ($obj as $k => $v) {
  1326. if (gettype($v) == 'resource') {
  1327. return;
  1328. }
  1329. if (gettype($v) == 'object' || gettype($v) == 'array') {
  1330. $obj[$k] = (array)object_to_array($v);
  1331. }
  1332. }
  1333. return $obj;
  1334. }
  1335. /**
  1336. * 检查是否为手机号码
  1337. */
  1338. function _isPhone($number)
  1339. {
  1340. return preg_match("/^1[34578][0-9]{9}$/", $number);
  1341. }
  1342. /**
  1343. * 判断所传的参数是否缺少,如果缺少返回渠道的字段,正确返回0
  1344. *
  1345. * @param array $param
  1346. * @param array $must
  1347. * @return int|mixed
  1348. */
  1349. function checkParam(array $param, array $must)
  1350. {
  1351. foreach ($must as $item) {
  1352. if (array_key_exists($item, $param) && $param[$item] != '') {
  1353. } else {
  1354. return $item;
  1355. }
  1356. }
  1357. return 0;
  1358. }
  1359. /**
  1360. * 对象 转 数组
  1361. *
  1362. * @param object $obj 对象
  1363. * @return array
  1364. */
  1365. function ignoreKeyInArray($targetArray, $delete_keys = [], $changes = [])
  1366. {
  1367. $change_keys = array_keys($changes);
  1368. foreach ($targetArray as $key => $value) {
  1369. if (in_array($key, $delete_keys) && isset($targetArray[$key])) unset($targetArray[$key]);
  1370. if (in_array($key, $change_keys) && isset($targetArray[$key])) $targetArray[$key] = $changes[$key];
  1371. if (is_array($value)) ignoreKeyInArray($value, $delete_keys, $change_keys);
  1372. }
  1373. return $targetArray;
  1374. }
  1375. function itemTransform($trans, $data)
  1376. {
  1377. if ($data) {
  1378. return $trans->transform($data);
  1379. } else {
  1380. return [];
  1381. }
  1382. }
  1383. function collectionTransform($trans, $data)
  1384. {
  1385. $ret_data = [];
  1386. if ($data) {
  1387. foreach ($data as $item) {
  1388. $ret_data[] = $trans->transform($item);
  1389. }
  1390. }
  1391. return $ret_data;
  1392. }
  1393. function paginationTransform($trans, $paginator)
  1394. {
  1395. $ret = [];
  1396. $ret['list'] = [];
  1397. if ($paginator) {
  1398. foreach ($paginator as $item) {
  1399. $ret['list'][] = $trans->transform($item);
  1400. }
  1401. $ret['meta'] = [
  1402. 'total' => (int)$paginator->total(),
  1403. 'per_page' => (int)$paginator->perPage(),
  1404. 'current_page' => (int)$paginator->currentPage(),
  1405. 'last_page' => (int)$paginator->lastPage(),
  1406. 'next_page_url' => (string)$paginator->nextPageUrl(),
  1407. 'prev_page_url' => (string)$paginator->previousPageUrl()
  1408. ];
  1409. }
  1410. return $ret;
  1411. }
  1412. /**
  1413. * 加密site id
  1414. */
  1415. function encodeDistributionChannelId($id)
  1416. {
  1417. $encrypt_pool = [
  1418. ];
  1419. if (isset($encrypt_pool[$id])) {
  1420. return $encrypt_pool[$id];
  1421. }
  1422. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1423. return $hashids->encode($id);
  1424. }
  1425. /**
  1426. * 解密密site id
  1427. */
  1428. function decodeDistributionChannelId($code)
  1429. {
  1430. $encrypt_pool = [
  1431. ];
  1432. if (isset($encrypt_pool[$code])) {
  1433. return $encrypt_pool[$code];
  1434. }
  1435. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1436. $res = $hashids->decode($code);
  1437. if ($res && isset($res[0])) {
  1438. return $res[0];
  1439. }
  1440. return null;
  1441. }
  1442. //bid加密
  1443. function book_hash_encode($bid)
  1444. {
  1445. return Vinkla\Hashids\Facades\Hashids::encode($bid);
  1446. }
  1447. function decodeBid($encode_bid)
  1448. {
  1449. $bid = 0;
  1450. try {
  1451. $bid_arr = \Hashids::decode($encode_bid);
  1452. if (isset($bid_arr[0])) {
  1453. $bid = $bid_arr[0];
  1454. }
  1455. } catch (\Exception $e) {
  1456. return null;
  1457. }
  1458. return $bid;
  1459. }
  1460. /**
  1461. * 获取当前域名
  1462. */
  1463. function _domain()
  1464. {
  1465. return str_replace('https://', '', str_replace('http://', '', url('/')));
  1466. }
  1467. /**
  1468. * 字符串转*
  1469. *
  1470. * @param $str // 待转的字符串
  1471. * @param $start // 转*起始位置
  1472. * @param int $end // 转*结束位置
  1473. * @param string $dot // 转换的字符(必须是单字符,默认是*)
  1474. * @param string $charset // 编码方式
  1475. * @param string $end_char // 特殊字符(碰到此字符则确定end位置)
  1476. * @return string
  1477. */
  1478. function trans_pass($str, $start, $end = 0, $dot = "*", $charset = "UTF-8", $end_char = '@'): string
  1479. {
  1480. $len = mb_strlen($str, $charset);
  1481. if ($start == 0 || $start > $len) {
  1482. $start = 1;
  1483. }
  1484. if ($end != 0 && $end > $len) {
  1485. $end = $len - 2;
  1486. }
  1487. if (strstr($str, $end_char)) {
  1488. $end = $len - strrpos($str, $end_char);
  1489. }
  1490. $endStart = $len - $end;
  1491. $top = mb_substr($str, 0, $start, $charset);
  1492. $bottom = "";
  1493. if ($endStart > 0) {
  1494. $bottom = mb_substr($str, $endStart, $end, $charset);
  1495. }
  1496. $len -= mb_strlen($top, $charset);
  1497. $len -= mb_strlen($bottom, $charset);
  1498. $newStr = $top;
  1499. for ($i = 0; $i < $len; $i++) {
  1500. $newStr .= $dot;
  1501. }
  1502. $newStr .= $bottom;
  1503. return $newStr;
  1504. }
  1505. /**
  1506. * 格式化章节内容
  1507. *
  1508. * @param $content
  1509. * @return false|string
  1510. */
  1511. function formatContent($content)
  1512. {
  1513. if (!$content) return '';
  1514. $content = str_replace(
  1515. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p >', '&ldquo;', '&rdquo;', '&hellip;'],
  1516. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...'],
  1517. $content);
  1518. $content = str_replace(["&nbsp;", '&ldquo;', '&hellip;', '&rdquo;', '<p>'], '', $content);
  1519. // 段落首字母前加两个中文空格
  1520. $string = explode(PHP_EOL, $content);
  1521. foreach ($string as $line => $text) {
  1522. if (mb_substr($text, 0, 2) != '  ') $string[$line] = '  ' . $text;
  1523. }
  1524. $content = implode(PHP_EOL, $string);
  1525. $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8,GBK,GB2312');
  1526. $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);
  1527. return $content;
  1528. }
  1529. /**
  1530. * 筛选出有效的id集合
  1531. *
  1532. * @param array $ids
  1533. * @return array
  1534. */
  1535. function filterValidIds(array $ids): array
  1536. {
  1537. // 传参
  1538. if (empty($ids)) {
  1539. return [];
  1540. }
  1541. $result = [];
  1542. foreach ($ids as $id) {
  1543. if (in_array($id, $result) || !is_numeric($id) || (int)$id < 1) {
  1544. continue;
  1545. }
  1546. $result[] = (int)$id;
  1547. }
  1548. return $result;
  1549. }
  1550. function arrayToStr($map)
  1551. {
  1552. $isMap = isArrMap($map);
  1553. $result = "";
  1554. if ($isMap) {
  1555. $result = "map[";
  1556. }
  1557. $keyArr = array_keys($map);
  1558. if ($isMap) {
  1559. sort($keyArr);
  1560. }
  1561. $paramsArr = array();
  1562. foreach ($keyArr as $k) {
  1563. $v = $map[$k];
  1564. if ($isMap) {
  1565. if (is_array($v)) {
  1566. $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
  1567. } else {
  1568. $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
  1569. }
  1570. } else {
  1571. if (is_array($v)) {
  1572. $paramsArr[] = arrayToStr($v);
  1573. } else {
  1574. $paramsArr[] = trim(strval($v));
  1575. }
  1576. }
  1577. }
  1578. $result = sprintf("%s%s", $result, join(" ", $paramsArr));
  1579. if (!$isMap) {
  1580. $result = sprintf("[%s]", $result);
  1581. } else {
  1582. $result = sprintf("%s]", $result);
  1583. }
  1584. return $result;
  1585. }
  1586. function isArrMap($map)
  1587. {
  1588. foreach ($map as $k => $v) {
  1589. if (is_string($k)) {
  1590. return true;
  1591. }
  1592. }
  1593. return false;
  1594. }
  1595. /**
  1596. * 随机字符串
  1597. *
  1598. * @param $length
  1599. * @return string
  1600. */
  1601. function makeRandStr($length): string
  1602. {
  1603. // 密码字符集,可任意添加你需要的字符
  1604. $str = [
  1605. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  1606. 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  1607. 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
  1608. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  1609. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  1610. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  1611. ];
  1612. // 在 $str 中随机取 $length 个数组元素键名
  1613. $keys = array_rand($str, $length);
  1614. $password = '';
  1615. for ($i = 0; $i < $length; $i++) {
  1616. // 将 $length 个数组元素连接成字符串
  1617. $password .= $str[$keys[$i]];
  1618. }
  1619. return $password;
  1620. }
  1621. /**
  1622. * 导出数据为excel表格
  1623. *
  1624. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1625. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1626. * @param $filename 下载的文件名
  1627. * @examlpe10
  1628. */
  1629. function exportExcel($data = [], $title = [], $filename = 'report')
  1630. {
  1631. ob_end_clean();
  1632. ob_start();
  1633. header("Content-type:application/octet-stream");
  1634. header("Accept-Ranges:bytes");
  1635. header("Content-type:application/vnd.ms-excel");
  1636. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1637. header("Pragma: no-cache");
  1638. header("Expires: 0");
  1639. //导出xls 开始
  1640. if (!empty($title)) {
  1641. foreach ($title as $k => $v) {
  1642. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1643. }
  1644. $title = implode("\t", $title);
  1645. echo "$title\n";
  1646. }
  1647. if (!empty($data)) {
  1648. foreach ($data as $key => $val) {
  1649. foreach ($val as $ck => $cv) {
  1650. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1651. }
  1652. $data[$key] = implode("\t", $data[$key]);
  1653. }
  1654. echo implode("\n", $data);
  1655. }
  1656. }
  1657. /**
  1658. * 导出csv文件
  1659. * @param string $name
  1660. * @param array $headers
  1661. * @param array $data
  1662. * @return void
  1663. */
  1664. function exportCsv(string $name, array $headers, array $data = [])
  1665. {
  1666. header('Content-Description: File Transfer');
  1667. header('Content-Type: application/csv');
  1668. header("Content-Disposition: attachment; filename=".$name.".csv");
  1669. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  1670. $handle = fopen('php://output', 'w');
  1671. ob_clean();
  1672. fputcsv($handle, $headers);
  1673. if ($data) {
  1674. foreach ($data as $row) {
  1675. fputcsv($handle, $row);
  1676. }
  1677. }
  1678. ob_flush();
  1679. fclose($handle);
  1680. die();
  1681. }
  1682. // 树状分类
  1683. function buildCategoryTree($categories, $pid = 0) {
  1684. $tree = [];
  1685. foreach ($categories as $category) {
  1686. if ($category['pid'] == $pid) {
  1687. $children = buildCategoryTree($categories, $category['category_id']);
  1688. if ($children) {
  1689. $category['children'] = $children;
  1690. }
  1691. $tree[] = $category;
  1692. }
  1693. }
  1694. return $tree;
  1695. }
  1696. // 获取文件的md5值
  1697. function getFileContentMD5($filePath){
  1698. //获取文件MD5的128位二进制数组
  1699. $md5Bytes = md5_file($filePath,true);
  1700. //计算文件的Content-MD5
  1701. $contentMD5 = base64_encode($md5Bytes);
  1702. return $contentMD5;
  1703. }
  1704. function getTextTokens($text) {
  1705. // 方法1:按空格分词(西文较准)
  1706. $words = preg_split('/\s+/', $text);
  1707. $wordCount = count($words);
  1708. // 方法2:按字符数估算(中文较准:1个汉字 ≈ 1.5-2 tokens)
  1709. $charCount = mb_strlen($text);
  1710. // 综合估算(根据语言调整权重)
  1711. $tokenCount = $wordCount + $charCount * 0.5; // 示例公式
  1712. // 更简单:直接按字符数 * 系数(中文推荐)
  1713. // $tokenCount = $charCount * 1.8; // 经验系数
  1714. return (int)ceil($tokenCount);
  1715. }
  1716. // 处理小说剧本文本
  1717. function handleScriptWords($text, $enable_emotion=1) {
  1718. $text = preg_replace('/[\r\n]+/', PHP_EOL, $text);
  1719. $text_arr = explode(PHP_EOL, $text);
  1720. $roles = [];
  1721. $words = [];
  1722. $role_gender = [];
  1723. // $sequence = 0;
  1724. foreach ($text_arr as $line) {
  1725. $line = trim($line);
  1726. if ($enable_emotion) {
  1727. $match_rule = '/^(.*?)\:(.*?)\{(.*?)\}$/';
  1728. $count = 4;
  1729. } else {
  1730. $match_rule = '/^(.*?)\:(.*?)$/';
  1731. $count = 3;
  1732. }
  1733. preg_match($match_rule, $line, $matches);
  1734. if (count($matches) == $count) {
  1735. $gender = '0';
  1736. // 角色部分拆分
  1737. preg_match('/^(.*?)\((.*?)\)$/', $matches[1], $matches2);
  1738. if (count($matches2) == 3) {
  1739. $role = $matches2[1];
  1740. $gender_arr = ['男'=>'1', '女'=>'2'];
  1741. $gender = isset($gender_arr[$matches2[2]]) ? $gender_arr[$matches2[2]] : '0';
  1742. }else {
  1743. $role = $matches[1];
  1744. }
  1745. if (!in_array($role, $roles)) {
  1746. $roles[] = $role; // 记录角色
  1747. $role_gender[$role] = $gender;
  1748. }
  1749. $words[] = [
  1750. 'role' => $role,
  1751. 'gender' => $gender,
  1752. 'text' => $matches[2],
  1753. 'emotion' => $enable_emotion ? $matches[3] : '中性',
  1754. ];
  1755. }
  1756. }
  1757. $new_words = [];
  1758. $tmp = '';
  1759. $tmp_arr = [];
  1760. $tmp_text = '';
  1761. // 将words数组按照role和emotion合并相邻的text内容,不相邻则跳过合并
  1762. foreach ($words as $word) {
  1763. if(!$tmp) $tmp = $word['role'].'-'.$word['emotion'];
  1764. if($tmp == $word['role'].'-'.$word['emotion']) {
  1765. $tmp_text .= PHP_EOL.$word['text'];
  1766. $tmp_arr = [
  1767. 'role' => $word['role'],
  1768. 'gender' => $word['gender'],
  1769. 'text' => trim($tmp_text, PHP_EOL),
  1770. 'emotion' => $word['emotion'],
  1771. ];
  1772. }else {
  1773. // $sequence++;
  1774. // $tmp_arr['sequence'] = $sequence;
  1775. $new_words[] = $tmp_arr;
  1776. $tmp = $word['role'].'-'.$word['emotion'];
  1777. $tmp_text = $word['text'];
  1778. $tmp_arr = [
  1779. 'role' => $word['role'],
  1780. 'gender' => $word['gender'],
  1781. 'text' => trim($tmp_text, PHP_EOL),
  1782. 'emotion' => $word['emotion'],
  1783. ];
  1784. }
  1785. }
  1786. if ($tmp_arr) {
  1787. // $sequence++;
  1788. // $tmp_arr['sequence'] = $sequence;
  1789. $new_words[] = $tmp_arr;
  1790. }
  1791. return [
  1792. 'roles' => $roles,
  1793. 'role_gender' => $role_gender,
  1794. 'words' => $new_words,
  1795. ];
  1796. }
  1797. /**
  1798. * 处理剧本内容
  1799. */
  1800. function handleScriptContent($originalContent) {
  1801. if (!$originalContent) return [];
  1802. // 使用更精确的正则表达式分割内容
  1803. $parts = [];
  1804. // // 确保内容使用UTF-8编码
  1805. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  1806. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  1807. // }
  1808. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  1809. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  1810. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  1811. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  1812. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  1813. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  1814. // 提取剧本亮点(支持多个空格)
  1815. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  1816. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  1817. // 提取人物关系(支持多个空格)
  1818. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  1819. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  1820. // 提取核心矛盾(支持多个空格)
  1821. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  1822. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  1823. // 提取主体列表(支持多个空格)
  1824. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  1825. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  1826. $parts['roles'] = parseRolesFromText($rolesText);
  1827. // 提取美术风格(支持多个空格)
  1828. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  1829. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  1830. // 提取场景列表(支持多个空格)
  1831. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  1832. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  1833. $parts['scenes'] = parseScenesFromText($scenesText);
  1834. // 提取分集详细内容(多剧集模式,支持多个空格)
  1835. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  1836. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  1837. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  1838. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  1839. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  1840. // 优先使用原文内容,其次使用分集详细内容
  1841. $parts['content'] = $generatedContent ?: $detailedContent;
  1842. $parts['episode_title'] = '';
  1843. $parts['acts'] = [];
  1844. // 单剧集格式:顶层是大纲信息,分镜部分采用 handleEpisodeContent 的结构标准
  1845. $singleStoryboard = '';
  1846. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  1847. $singleStoryboard = trim($singleStoryboardMatch[1]);
  1848. }
  1849. if ($singleStoryboard !== '') {
  1850. $episodeContent = $singleStoryboard;
  1851. if (!preg_match('/第\d+集[::\s]+/u', $episodeContent)) {
  1852. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  1853. $episodeContent = $defaultEpisodeTitle . "\n\n" . $episodeContent;
  1854. }
  1855. $episodeSections = [];
  1856. $episodeSections[] = $episodeContent;
  1857. if ($parts['intro'] !== '') {
  1858. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  1859. }
  1860. if ($parts['art_style'] !== '') {
  1861. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  1862. }
  1863. if ($rolesText !== '') {
  1864. $episodeSections[] = "###主体列表\n" . $rolesText;
  1865. }
  1866. if ($scenesText !== '') {
  1867. $episodeSections[] = "###场景列表\n" . $scenesText;
  1868. }
  1869. if (strpos($episodeContent, '###分镜剧本') === false) {
  1870. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  1871. }
  1872. $episode_arr = handleEpisodeContent(implode("\n\n", $episodeSections));
  1873. if (!empty($episode_arr['acts'])) {
  1874. $parts['episode_title'] = getProp($episode_arr, 'episode_title');
  1875. $parts['acts'] = getProp($episode_arr, 'acts', []);
  1876. if (empty($parts['roles'])) {
  1877. $parts['roles'] = getProp($episode_arr, 'roles', []);
  1878. }
  1879. if (empty($parts['scenes'])) {
  1880. $parts['scenes'] = getProp($episode_arr, 'scenes', []);
  1881. }
  1882. }
  1883. }
  1884. if (empty($parts['acts'])) {
  1885. $fallbackEpisodeArr = handleEpisodeContent($originalContent);
  1886. if (!empty($fallbackEpisodeArr['acts'])) {
  1887. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title');
  1888. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  1889. if (empty($parts['intro'])) {
  1890. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro');
  1891. }
  1892. if (empty($parts['art_style'])) {
  1893. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style');
  1894. }
  1895. if (empty($parts['roles'])) {
  1896. $parts['roles'] = getProp($fallbackEpisodeArr, 'roles', []);
  1897. }
  1898. if (empty($parts['scenes'])) {
  1899. $parts['scenes'] = getProp($fallbackEpisodeArr, 'scenes', []);
  1900. }
  1901. }
  1902. }
  1903. // 多剧集格式:继续兼容旧的分集剧本结构
  1904. $fullScript = '';
  1905. if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  1906. $fullScript = trim($storyboardMatch[1]);
  1907. } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  1908. $fullScript = trim($storyboardMatch[1]);
  1909. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  1910. $fullScript = trim($storyboardMatch[1]);
  1911. }
  1912. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  1913. $fullScript = trim($fallbackMatch[1]);
  1914. }
  1915. $episodes = [];
  1916. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  1917. foreach ($matches as $match) {
  1918. $episodeNumber = (int)trim($match[1]);
  1919. $episodeName = trim($match[2]);
  1920. $episodeContent = trim($match[3]);
  1921. $segments = [];
  1922. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  1923. foreach ($segmentMatches as $segMatch) {
  1924. $segmentNumber = (int)trim($segMatch[1]);
  1925. $segmentContent = trim($segMatch[2]);
  1926. $segments[] = [
  1927. 'segment_number' => $segmentNumber,
  1928. 'segment_content' => $segmentContent,
  1929. ];
  1930. }
  1931. $episodes[] = [
  1932. 'episode_number' => $episodeNumber,
  1933. 'title' => $episodeName,
  1934. 'content' => $episodeContent,
  1935. 'segments' => $segments,
  1936. ];
  1937. }
  1938. if (empty($episodes) && !empty($parts['acts'])) {
  1939. $singleSegments = [];
  1940. foreach ($parts['acts'] as $act) {
  1941. $actSegments = getProp($act, 'segments', []);
  1942. if (!is_array($actSegments)) {
  1943. continue;
  1944. }
  1945. foreach ($actSegments as $segment) {
  1946. $singleSegments[] = [
  1947. 'segment_number' => getProp($segment, 'segment_number'),
  1948. 'segment_content' => getProp($segment, 'segment_content'),
  1949. ];
  1950. }
  1951. }
  1952. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  1953. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  1954. $episodes[] = [
  1955. 'episode_number' => 1,
  1956. 'title' => $episodeName,
  1957. 'content' => $singleStoryboard,
  1958. 'segments' => $singleSegments,
  1959. ];
  1960. }
  1961. $parts['episodes'] = $episodes;
  1962. return $parts;
  1963. }
  1964. function handleEpisodeContent($originalContent) {
  1965. if (!$originalContent) return [];
  1966. // $originalContent = '好的,作为您的专业文档分析助手及资深编剧,我将根据您提供的本章剧情内容、历史对话记录以及本次修改要求,严格按照您的要求完成第1集分镜剧本的创作。
  1967. // 第1集:重生与隐形的拯救
  1968. // ###故事梗概
  1969. // 内容梗概:重生在悲剧发生前一个月的徐清遥,提前与许家真千金交换了身份,回到了原生家庭徐家。在悲剧发生日(双十一),她听从徐母安排,放学后没有回家,而是选择在网吧包夜以避开危险。在网吧煎熬一夜后,次日清晨因疲惫过马路时险些遭遇车祸,千钧一发之际被一股无形的力量拉开。她意识到是上辈子那个为她收尸、为她复仇、并付出代价换她重生的“隐形守护者”再次出手相救。劫后余生的徐清遥在人群中徒劳地寻找他的踪迹,心中涌起复杂的情感。
  1970. // ###美术风格
  1971. // 基础画风风格词:韩漫二次元
  1972. // 视觉风格描述:采用细腻的韩漫厚涂风格,以冷灰色调和低饱和度为主,营造重生后的疏离感与命运未卜的紧张氛围。回忆片段采用高对比度的黑白或单色处理,强调过往的惨痛与不真实感。现实场景中,网吧的昏暗浑浊与清晨街道的清冷形成对比,车祸瞬间运用动态模糊和慢镜头特写,突出“隐形守护者”介入时的超现实感与宿命牵引。人物面部表情刻画精细,着重展现徐清遥眼神中的沧桑、坚韧以及对无形守护的复杂情感。
  1973. // ###主体列表
  1974. // 徐清遥-重生后(17岁): 身高约162cm,面容清秀但带着长期营养不良的苍白与疲惫。眼神坚韧,偶尔流露出超越年龄的沧桑。常穿着黄色T恤加蓝色牛仔裤。回到徐家后,手上常有干活留下的细微伤痕。{{甜心小美}}
  1975. // “空气人”(隐形守护者): 存在但不可见。通过间接信息推测为同龄或稍长男性,身材应较为高大(能提起女主角躲避车祸),经济拮据(住阁楼),爱干净(阁楼有皂角味),可能为学生(桌上有高中课本试卷)。{{阳光青年}}
  1976. // 卞大伟(20岁): 身高约175cm,体型偏瘦但力气不小。眼神阴鸷,面色因长期混迹网吧而泛着油光与不健康的青白。常穿廉价的紧身T恤和牛仔裤,身上有烟味和厨房的油腻味。{{广州德哥}}
  1977. // 徐母(45岁左右): 身材干瘦,颧骨高突,眉眼间总带着不耐烦与算计。穿着廉价的花衬衫和黑裤子,嗓门洪亮,动作粗鲁。{{邻居阿姨}}
  1978. // 徐父(48岁左右): 背微驼,面容愁苦,眼神躲闪。穿着沾有污渍的工装,身上有淡淡的酒气,整体气质怯懦。{{广州德哥}}
  1979. // 老奶奶(70岁左右): 头发花白,身形佝偻,拄着拐杖,面容慈祥但带着老年人特有的迟缓与关切。{{邻居阿姨}}
  1980. // 许芸-大学生/成年: 20-30岁,气质逐渐成熟温婉,衣着简约大方,笑容增多,眼中有了被爱滋养的光彩。{{爽快思思}}
  1981. // ###场景列表
  1982. // 徐家馄饨店后间: 通往后院的狭窄房间,兼做厨房和部分家庭成员活动区。墙面油腻发黄,堆满杂物。中间一张旧方桌,几张塑料凳。灯光昏暗,空气中弥漫着馄饨馅和煤球炉的味道。
  1983. // 网吧包夜区: 环境昏暗,空气混浊,弥漫着烟味与泡面味。一排排电脑屏幕闪着幽光,键盘鼠标声杂乱。徐清遥所在的角落相对安静。
  1984. // 车祸路口: 城市普通街道十字路口,人行道狭窄,车流匆忙。背景是略显老旧的居民楼商铺。
  1985. // 学校门口: 普通高中校门,上下学时间人流密集。有家长、学生和小贩,背景是教学楼。
  1986. // ###分镜剧本
  1987. // ##第1幕:徐家老旧厨房 白天 室内
  1988. // 分镜1
  1989. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  1990. // 场景:徐家老旧厨房
  1991. // 构图设计:全景,低角度仰视
  1992. // 运镜调度:手持拍摄
  1993. // 配音角色:旁白
  1994. // 出镜角色:许芸-校服装、徐母
  1995. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  1996. // 画面类型:普通画面
  1997. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  1998. // 分镜2
  1999. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2000. // 场景:徐家老旧厨房
  2001. // 构图设计:近景,徐母面部特写
  2002. // 运镜调度:固定镜头
  2003. // 配音角色:徐母
  2004. // 出镜角色:徐母
  2005. // 台词内容:问我夜不归宿死哪儿去了。
  2006. // 画面类型:对口型
  2007. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2008. // ##第2幕:徐家简陋客厅 黄昏 室内
  2009. // 分镜3
  2010. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2011. // 场景:徐家简陋客厅
  2012. // 构图设计:全景,景深虚化
  2013. // 运镜调度:固定镜头
  2014. // 配音角色:旁白
  2015. // 出镜角色:无
  2016. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2017. // 画面类型:普通画面
  2018. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2019. // 分镜4
  2020. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2021. // 场景:徐家简陋客厅
  2022. // 构图设计:特写,火车票
  2023. // 运镜调度:固定镜头
  2024. // 配音角色:旁白
  2025. // 出镜角色:无
  2026. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2027. // 画面类型:普通画面
  2028. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  2029. // \n\n';
  2030. // 解析剧集内容
  2031. $result = [
  2032. 'episode_title' => '',
  2033. 'intro' => '',
  2034. 'art_style' => '',
  2035. 'roles' => [],
  2036. 'scenes' => [],
  2037. 'acts' => []
  2038. ];
  2039. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  2040. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  2041. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  2042. }
  2043. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  2044. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  2045. $result['intro'] = trim($summaryMatch[1]);
  2046. }
  2047. // 提取美术风格 - 兼容多种格式
  2048. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  2049. $result['art_style'] = trim($styleMatch[1]);
  2050. }
  2051. // 提取主体列表 - 兼容多种格式
  2052. if (preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  2053. $charactersText = trim($charactersMatch[1]);
  2054. $characterLines = explode("\n", $charactersText);
  2055. foreach ($characterLines as $line) {
  2056. $line = trim($line);
  2057. if (empty($line)) continue;
  2058. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  2059. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2060. $role = trim($charMatch[1]);
  2061. $description = trim($charMatch[2]);
  2062. $timbreName = null;
  2063. // 检查描述末尾是否有{{音色名}}格式
  2064. if (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2065. $description = trim($timbreMatch[1]);
  2066. $timbreName = trim($timbreMatch[2]);
  2067. }
  2068. $roleData = [
  2069. 'role' => $role,
  2070. 'description' => $description
  2071. ];
  2072. // 如果有音色信息,添加到数组中
  2073. if ($timbreName) {
  2074. $timbre = DB::table('mp_timbres')->where('is_enabled', 1)->where('timbre_name', 'like', "%{$timbreName}%")->orderBy('id')->select('timbre_type', 'audio_url')->first();
  2075. if ($timbre) {
  2076. $roleData['voice_name'] = $timbreName;
  2077. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2078. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');;
  2079. }
  2080. }
  2081. $result['roles'][] = $roleData;
  2082. }
  2083. }
  2084. // 加入旁白角色
  2085. $result['roles'][] = [
  2086. 'role' => '旁白',
  2087. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2088. 'voice_name' => '旁白',
  2089. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2090. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2091. ];
  2092. }
  2093. // 提取场景列表 - 兼容多种格式
  2094. if (preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  2095. $scenesText = trim($scenesMatch[1]);
  2096. $sceneLines = explode("\n", $scenesText);
  2097. foreach ($sceneLines as $line) {
  2098. $line = trim($line);
  2099. if (empty($line)) continue;
  2100. // 兼容中文冒号:和英文冒号:
  2101. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  2102. $result['scenes'][] = [
  2103. 'scene' => trim($sceneMatch[1]),
  2104. 'description' => trim($sceneMatch[2])
  2105. ];
  2106. }
  2107. }
  2108. }
  2109. // 提取分镜剧本 - 兼容多种格式
  2110. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $storyboardMatch)) {
  2111. $storyboardText = trim($storyboardMatch[1]);
  2112. // 按幕分割 - 修复第1幕识别和乱码问题
  2113. $acts = [];
  2114. // 先在开头添加换行符,确保第1幕也能被正确分割
  2115. $normalizedText = "\n" . $storyboardText;
  2116. $parts = preg_split('/\n\s*##/', $normalizedText);
  2117. foreach ($parts as $part) {
  2118. $part = trim($part);
  2119. if (empty($part)) continue;
  2120. // 如果不是以"第"开头,跳过
  2121. if (!preg_match('/^第\d+幕/', $part)) {
  2122. continue;
  2123. }
  2124. // 分离标题和内容
  2125. $lines = explode("\n", $part, 2);
  2126. $actTitle = trim($lines[0]);
  2127. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  2128. // 解析幕标题,提取序号和详细信息 - 修复乱码问题
  2129. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  2130. $actNumber = intval($actTitleMatch[1]);
  2131. $actDetails = trim($actTitleMatch[2]);
  2132. // 如果详细信息为空或者就是冒号,使用完整标题
  2133. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  2134. $actDetails = $actTitle;
  2135. }
  2136. } else {
  2137. $actNumber = count($acts) + 1;
  2138. $actDetails = $actTitle;
  2139. }
  2140. // 解析该幕下的分镜
  2141. $segments = [];
  2142. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  2143. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  2144. foreach ($segmentMatches as $segmentMatch) {
  2145. $segmentNumber = intval($segmentMatch[1]);
  2146. $segmentContent = trim($segmentMatch[2]);
  2147. // 解析分镜详细信息
  2148. $segmentData = [
  2149. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT), // 生成唯一ID(后续可在生成任务里查看历史版本)
  2150. 'segment_number' => $segmentNumber,
  2151. 'segment_content' => $segmentContent,
  2152. 'description' => '',
  2153. 'composition' => '',
  2154. 'camera_movement' => '',
  2155. 'voice_actor' => '',
  2156. 'dialogue' => '',
  2157. 'frame_type' => '',
  2158. 'scene' => '', // 新增:场景
  2159. 'characters' => '', // 新增:出镜角色
  2160. 'tail_frame' => '', // 新增:尾帧描述
  2161. // 新增字段
  2162. 'emotion' => '中性', // 新增: 情感
  2163. 'gender' => '0', // 新增: 性别(0未知,1男,2女)
  2164. 'speed_ratio' => 0, // 新增: 语速
  2165. 'loudness_ratio' => 0, // 新增: 音量
  2166. 'emotion_scale' => 4, // 新增: 语调
  2167. 'pitch' => 0, // 新增: 音调
  2168. ];
  2169. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  2170. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  2171. $segmentData['description'] = trim($descMatch[1]);
  2172. }
  2173. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  2174. $segmentData['composition'] = trim($compMatch[1]);
  2175. }
  2176. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  2177. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  2178. }
  2179. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  2180. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  2181. }
  2182. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  2183. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  2184. }
  2185. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  2186. $segmentData['frame_type'] = trim($frameMatch[1]);
  2187. }
  2188. // 新增:场景字段
  2189. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  2190. $segmentData['scene'] = trim($sceneMatch[1]);
  2191. }
  2192. // 新增:出镜角色字段
  2193. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  2194. $segmentData['characters'] = trim($charactersMatch[1]);
  2195. }
  2196. // 新增:尾帧描述字段
  2197. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  2198. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  2199. }
  2200. $replaceEmptyArr = [];
  2201. // 新增:情感字段
  2202. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  2203. $replaceEmptyArr[] = trim($emotionMatch[0]);
  2204. $segmentData['emotion'] = trim($emotionMatch[1]);
  2205. }
  2206. // 新增:性别字段
  2207. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  2208. $replaceEmptyArr[] = trim($genderMatch[0]);
  2209. $genderStr = trim($genderMatch[1]);
  2210. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  2211. $segmentData['gender'] = '1';
  2212. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  2213. $segmentData['gender'] = '2';
  2214. } else {
  2215. $segmentData['gender'] = '0';
  2216. }
  2217. }
  2218. // 新增:语速字段
  2219. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  2220. $replaceEmptyArr[] = trim($speedMatch[0]);
  2221. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  2222. }
  2223. // 新增:音量字段
  2224. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  2225. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  2226. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  2227. }
  2228. // 新增:情感强度字段
  2229. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  2230. $replaceEmptyArr[] = trim($scaleMatch[0]);
  2231. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  2232. }
  2233. // 新增:音调字段
  2234. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  2235. $replaceEmptyArr[] = trim($pitchMatch[0]);
  2236. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  2237. }
  2238. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  2239. $segments[] = $segmentData;
  2240. }
  2241. $acts[] = [
  2242. 'act_number' => $actNumber,
  2243. 'act_title' => $actTitle,
  2244. 'act_details' => $actDetails,
  2245. 'segments' => $segments
  2246. ];
  2247. }
  2248. $result['acts'] = $acts;
  2249. }
  2250. return $result;
  2251. }
  2252. /**
  2253. * 远程图片压缩(尽可能保持原图 fidelity,压缩到不超过 maxBytes 字节)
  2254. * 采用有损/无损组合策略:保留原始格式尽量不失真,若需要则通过尺寸缩放和质量调节来降低体积。
  2255. *
  2256. * @param string $url 远程图片 URL
  2257. * @param int $maxBytes 最大字节数,默认 3MB
  2258. * @param string|null $aspectRatio 目标长宽比,如 "16:9"、"4:3"、"1:1" 等,null 则保持原图比例
  2259. * @return string|null 返回压缩后的图片二进制数据,失败时返回 null
  2260. */
  2261. function compressRemoteImageUrlToSize(string $url, int $maxBytes = 3 * 1024 * 1024, ?string $aspectRatio = null): ?string
  2262. {
  2263. // 1) 下载图片数据(使用 Guzzle 以避免 allow_url_fopen 依赖)
  2264. try {
  2265. $client = new Client(['timeout' => 30]);
  2266. $response = $client->get($url, ['stream' => true]);
  2267. if ($response->getStatusCode() !== 200) {
  2268. return null;
  2269. }
  2270. $data = $response->getBody()->getContents();
  2271. } catch (\Exception $e) {
  2272. return null;
  2273. }
  2274. if (!$data) return null;
  2275. // 2) 识别图片类型
  2276. $imgInfo = @getimagesizefromstring($data);
  2277. $mime = $imgInfo['mime'] ?? '';
  2278. if ($mime == 'image/jpeg') return null; // JPEG 不做有损压缩
  2279. // 3) 载入图像对象
  2280. $srcImg = @imagecreatefromstring($data);
  2281. if (!$srcImg) {
  2282. return null;
  2283. }
  2284. $origW = imagesx($srcImg);
  2285. $origH = imagesy($srcImg);
  2286. // 3.2) 计算目标尺寸(根据长宽比调整)
  2287. $targetW = $origW;
  2288. $targetH = $origH;
  2289. if ($aspectRatio !== null) {
  2290. // 解析长宽比,如 "16:9" -> [16, 9]
  2291. $validRatios = ["16:9", "4:3", "1:1", "3:4", "9:16", "21:9"];
  2292. if (in_array($aspectRatio, $validRatios)) {
  2293. list($ratioW, $ratioH) = explode(':', $aspectRatio);
  2294. $ratioW = (float)$ratioW;
  2295. $ratioH = (float)$ratioH;
  2296. $targetRatio = $ratioW / $ratioH;
  2297. $currentRatio = $origW / $origH;
  2298. // 根据目标比例裁剪图片
  2299. if ($currentRatio > $targetRatio) {
  2300. // 原图更宽,需要裁剪宽度
  2301. $targetW = (int)round($origH * $targetRatio);
  2302. $targetH = $origH;
  2303. } else {
  2304. // 原图更高,需要裁剪高度
  2305. $targetW = $origW;
  2306. $targetH = (int)round($origW / $targetRatio);
  2307. }
  2308. }
  2309. }
  2310. // 如果需要裁剪,创建裁剪后的图像
  2311. if ($targetW !== $origW || $targetH !== $origH) {
  2312. $croppedImg = imagecreatetruecolor($targetW, $targetH);
  2313. imagealphablending($croppedImg, false);
  2314. imagesavealpha($croppedImg, true);
  2315. // 处理透明背景
  2316. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  2317. $transparent = imagecolorallocatealpha($croppedImg, 0, 0, 0, 127);
  2318. imagefill($croppedImg, 0, 0, $transparent);
  2319. }
  2320. // 居中裁剪
  2321. $srcX = (int)(($origW - $targetW) / 2);
  2322. $srcY = (int)(($origH - $targetH) / 2);
  2323. imagecopy($croppedImg, $srcImg, 0, 0, $srcX, $srcY, $targetW, $targetH);
  2324. // 替换原图
  2325. safeDestroyImage($srcImg);
  2326. $srcImg = $croppedImg;
  2327. $origW = $targetW;
  2328. $origH = $targetH;
  2329. }
  2330. // 3.1) 内部渲染成不同格式的字符串
  2331. $render = function($srcRes, string $mimeType, int $quality) {
  2332. ob_start();
  2333. switch (strtolower($mimeType)) {
  2334. case 'image/jpeg':
  2335. case 'image/jpg':
  2336. case 'image/pjpeg':
  2337. // 输出 JPEG
  2338. imagejpeg($srcRes, null, $quality);
  2339. break;
  2340. case 'image/png':
  2341. // 将 quality 映射到 PNG 的 compression level (0-9)
  2342. $level = (int)round((100 - $quality) / 11.11);
  2343. if ($level < 0) $level = 0;
  2344. if ($level > 9) $level = 9;
  2345. imagepng($srcRes, null, $level);
  2346. break;
  2347. case 'image/webp':
  2348. if (function_exists('imagewebp')) {
  2349. imagewebp($srcRes, null, $quality);
  2350. } else {
  2351. imagejpeg($srcRes, null, $quality);
  2352. }
  2353. break;
  2354. default:
  2355. imagejpeg($srcRes, null, $quality);
  2356. break;
  2357. }
  2358. $out = ob_get_contents();
  2359. ob_end_clean();
  2360. return $out;
  2361. };
  2362. // 4) 尝试策略:尽量保留原图尺寸,逐步降维/降质量,直到 <= maxBytes
  2363. $tryList = [];
  2364. // 原始尺寸,尽量保留
  2365. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>100];
  2366. // 逐步缩小尺寸
  2367. for ($s = 0.9; $s >= 0.2; $s -= 0.1) {
  2368. $tryList[] = ['scale'=>$s, 'mime'=>$mime, 'quality'=>90];
  2369. }
  2370. // 一系列质量等级(用于 JPEG/WebP)
  2371. $qualityLevels = [95, 90, 85, 75, 60, 50, 40, 30];
  2372. foreach ($qualityLevels as $q) {
  2373. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>$q];
  2374. }
  2375. $bestData = null;
  2376. foreach ($tryList as $cand) {
  2377. $scale = isset($cand['scale']) ? (float)$cand['scale'] : 1.0;
  2378. $mimeT = $cand['mime'] ?? $mime;
  2379. $quality = isset($cand['quality']) ? (int)$cand['quality'] : 90;
  2380. $w = (int)round($origW * $scale);
  2381. $h = (int)round($origH * $scale);
  2382. $src = $srcImg;
  2383. $tempImg = null;
  2384. if ($scale < 1.0) {
  2385. $tempImg = imagecreatetruecolor($w, $h);
  2386. // 处理透明通道
  2387. imagealphablending($tempImg, false);
  2388. imagesavealpha($tempImg, true);
  2389. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  2390. $transparent = imagecolorallocatealpha($tempImg, 0, 0, 0, 127);
  2391. imagefill($tempImg, 0, 0, $transparent);
  2392. }
  2393. // 确保 $srcImg 有效
  2394. if (!$srcImg || (!is_resource($srcImg) && !($srcImg instanceof \GdImage))) {
  2395. safeDestroyImage($tempImg);
  2396. continue;
  2397. }
  2398. imagecopyresampled($tempImg, $srcImg, 0, 0, 0, 0, $w, $h, $origW, $origH);
  2399. $src = $tempImg;
  2400. }
  2401. $imageBytes = $render($src, $mimeT, $quality);
  2402. if ($tempImg !== null) {
  2403. safeDestroyImage($tempImg);
  2404. }
  2405. if ($imageBytes !== false && strlen($imageBytes) <= $maxBytes) {
  2406. $bestData = $imageBytes;
  2407. break;
  2408. }
  2409. }
  2410. // 5) 回退策略:若仍未达到要求,尝试更大幅度降解到一个合理的小尺寸 JPEG
  2411. if ($bestData === null) {
  2412. $tmpW = max(1, (int)round($origW * 0.5));
  2413. $tmpH = max(1, (int)round($origH * 0.5));
  2414. $tmpImg = imagecreatetruecolor($tmpW, $tmpH);
  2415. imagealphablending($tmpImg, false);
  2416. imagesavealpha($tmpImg, true);
  2417. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  2418. $transparent = imagecolorallocatealpha($tmpImg, 0, 0, 0, 127);
  2419. imagefill($tmpImg, 0, 0, $transparent);
  2420. }
  2421. imagecopyresampled($tmpImg, $srcImg, 0, 0, 0, 0, $tmpW, $tmpH, $origW, $origH);
  2422. ob_start();
  2423. if (in_array(strtolower($mime), ['image/jpeg','image/jpg','image/pjpeg'])) {
  2424. imagejpeg($tmpImg, null, 75);
  2425. } elseif (strtolower($mime) === 'image/png') {
  2426. imagepng($tmpImg, null, 6);
  2427. } elseif (function_exists('imagewebp')) {
  2428. imagewebp($tmpImg, null, 75);
  2429. } else {
  2430. imagejpeg($tmpImg, null, 75);
  2431. }
  2432. $tmpBytes = ob_get_contents();
  2433. ob_end_clean();
  2434. safeDestroyImage($tmpImg);
  2435. if ($tmpBytes !== '' && strlen($tmpBytes) <= $maxBytes) {
  2436. $bestData = $tmpBytes;
  2437. }
  2438. }
  2439. // 6) 清理
  2440. safeDestroyImage($srcImg);
  2441. return $bestData;
  2442. }
  2443. /**
  2444. * 安全销毁 GD 图像资源(兼容 PHP7.4+ 的资源管理)
  2445. * 通过引用传递并在销毁后置空变量,避免未定义变量的问题
  2446. *
  2447. * @param resource|\GdImage|null &$img GD 图像资源或对象(PHP7.4 为 resource,PHP8.0+ 为 GdImage)
  2448. */
  2449. function safeDestroyImage(&$img)
  2450. {
  2451. if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
  2452. @imagedestroy($img);
  2453. }
  2454. $img = null;
  2455. }
  2456. // /**
  2457. // * 使用 Imagick 将远程图片压缩至不超过 maxBytes(默认3MB)内
  2458. // * 目标:在尽量保留原始格式和质量的前提下进行压缩,避免内存暴涨
  2459. // * 依赖:Imagick 扩展与 ImageMagick 库,下载使用 Guzzle 获取图片 blob
  2460. // *
  2461. // * @param string $url
  2462. // * @param int $maxBytes 最大字节数,默认 3*1024*1024
  2463. // * @return string|null 经过压缩后的图片 blob,失败返回 null
  2464. // */
  2465. // function compressRemoteImageUrlToSizeImagick(string $url, int $maxBytes = 3 * 1024 * 1024): ?string
  2466. // {
  2467. // // 兼容性检查
  2468. // if (!extension_loaded('imagick') || !class_exists('Imagick')) {
  2469. // return null;
  2470. // }
  2471. // try {
  2472. // $client = new Client(['timeout' => 30]);
  2473. // // 使用流式下载,将数据写入临时文件,避免一次性加载到内存
  2474. // $response = $client->get($url, ['stream' => true]);
  2475. // if ($response->getStatusCode() !== 200) {
  2476. // return null;
  2477. // }
  2478. // $body = $response->getBody();
  2479. // $tmp = tmpfile();
  2480. // if ($tmp === false) {
  2481. // return null;
  2482. // }
  2483. // stream_copy_to_stream($body, $tmp);
  2484. // rewind($tmp);
  2485. // $imagick = new Imagick();
  2486. // $imagick->readImageFile($tmp);
  2487. // $origW = $imagick->getImageWidth();
  2488. // $origH = $imagick->getImageHeight();
  2489. // $format = strtolower($imagick->getImageFormat());
  2490. // // 尝试序列:尺寸缩放 + 质量调节
  2491. // $scales = [1.0, 0.9, 0.8, 0.6, 0.4, 0.25];
  2492. // $qualities = [95, 90, 85, 75, 60, 40, 30, 20];
  2493. // $bestBlob = null;
  2494. // foreach ($scales as $scale) {
  2495. // foreach ($qualities as $q) {
  2496. // $clone = clone $imagick;
  2497. // if ($scale < 1.0) {
  2498. // $w = (int)round($origW * $scale);
  2499. // $h = (int)round($origH * $scale);
  2500. // if ($w < 1 || $h < 1) {
  2501. // $clone->destroy();
  2502. // continue;
  2503. // }
  2504. // $clone->resizeImage($w, $h, Imagick::FILTER_LANCZOS, 1);
  2505. // }
  2506. // $clone->setImageFormat($format);
  2507. // $clone->setImageCompressionQuality($q);
  2508. // $blob = $clone->getImageBlob();
  2509. // $clone->destroy();
  2510. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  2511. // $bestBlob = $blob;
  2512. // break 2;
  2513. // }
  2514. // }
  2515. // }
  2516. // if ($bestBlob !== null) {
  2517. // $imagick->destroy();
  2518. // fclose($tmp);
  2519. // return $bestBlob;
  2520. // }
  2521. // // 回退:尝试强制输出为当前格式的一个中等质量版本
  2522. // $fallback = clone $imagick;
  2523. // $fallback->setImageFormat($format);
  2524. // $fallback->setImageCompressionQuality(75);
  2525. // $blob = $fallback->getImageBlob();
  2526. // $fallback->destroy();
  2527. // $imagick->destroy();
  2528. // fclose($tmp);
  2529. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  2530. // return $blob;
  2531. // }
  2532. // } catch (\Exception $e) {
  2533. // return null;
  2534. // }
  2535. // return null;
  2536. // }
  2537. /**
  2538. * 将主体列表文本拆分为主体数组
  2539. *
  2540. * @param string $rolesText 主体列表文本内容
  2541. * @return array 主体名称数组
  2542. */
  2543. function parseRolesFromText(string $rolesText): array
  2544. {
  2545. if (empty($rolesText)) {
  2546. return [];
  2547. }
  2548. $roles = [];
  2549. // 按行分割文本
  2550. $lines = explode("\n", $rolesText);
  2551. foreach ($lines as $line) {
  2552. $line = trim($line);
  2553. if (empty($line)) {
  2554. continue;
  2555. }
  2556. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2557. $role = trim($charMatch[1]);
  2558. $description = trim($charMatch[2]);
  2559. $timbreName = null;
  2560. if (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2561. $description = trim($timbreMatch[1]);
  2562. $timbreName = trim($timbreMatch[2]);
  2563. }
  2564. $roleData = [
  2565. 'role' => $role,
  2566. 'description' => $description,
  2567. ];
  2568. if ($timbreName) {
  2569. $timbre = DB::table('mp_timbres')
  2570. ->where('is_enabled', 1)
  2571. ->where('timbre_name', 'like', "%{$timbreName}%")
  2572. ->orderBy('id')
  2573. ->select('timbre_type', 'audio_url')
  2574. ->first();
  2575. if ($timbre) {
  2576. $roleData['voice_name'] = $timbreName;
  2577. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2578. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2579. }
  2580. }
  2581. $roles[] = $roleData;
  2582. }
  2583. }
  2584. $hasNarrator = false;
  2585. foreach ($roles as $role) {
  2586. if (getProp($role, 'role') === '旁白') {
  2587. $hasNarrator = true;
  2588. break;
  2589. }
  2590. }
  2591. if (!$hasNarrator) {
  2592. $roles[] = [
  2593. 'role' => '旁白',
  2594. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2595. 'voice_name' => '旁白',
  2596. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2597. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2598. ];
  2599. }
  2600. return $roles;
  2601. }
  2602. /**
  2603. * 将场景列表文本拆分为主体数组
  2604. *
  2605. * @param string $rolesText 场景列表列表文本内容
  2606. * @return array 场景名称数组
  2607. */
  2608. function parseScenesFromText(string $scenesText): array
  2609. {
  2610. if (empty($scenesText)) {
  2611. return [];
  2612. }
  2613. $scenes = [];
  2614. // 按行分割文本
  2615. $lines = explode("\n", $scenesText);
  2616. foreach ($lines as $line) {
  2617. $line = trim($line);
  2618. if (empty($line)) {
  2619. continue;
  2620. }
  2621. $line = str_replace(':', ':', $line);
  2622. if (strstr($line, ':')) {
  2623. $line_arr = explode(':', $line);
  2624. if (count($line_arr) == 2) {
  2625. $scenes[] = [
  2626. 'scene' => $line_arr[0],
  2627. 'description' => $line_arr[1],
  2628. ];
  2629. }
  2630. }
  2631. }
  2632. return $scenes;
  2633. }
  2634. /**
  2635. * 记录日志到数据库
  2636. *
  2637. * @param string $channel 日志频道/目录名
  2638. * @param string $level 日志级别 (info, error, warning, debug)
  2639. * @param string $message 日志信息
  2640. * @param array $context 日志详细数据
  2641. * @return void
  2642. */
  2643. function logDB($channel, $level, $message, $context = []) {
  2644. try {
  2645. // 获取调用堆栈信息
  2646. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  2647. $caller = $trace[1] ?? $trace[0];
  2648. \App\Models\SystemLog::create([
  2649. 'channel' => $channel,
  2650. 'level' => $level,
  2651. 'message' => $message,
  2652. 'context' => $context,
  2653. 'file' => $caller['file'] ?? '',
  2654. 'line' => $caller['line'] ?? 0,
  2655. 'log_time' => date('Y-m-d H:i:s'),
  2656. ]);
  2657. } catch (\Exception $e) {
  2658. // 记录日志失败时不影响主流程
  2659. \Log::error('记录日志到数据库失败: ' . $e->getMessage());
  2660. }
  2661. }