PaliContentService.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. <?php
  2. // api-v8/app/Services/PaliContentService.php
  3. namespace App\Services;
  4. use App\Facades\RedisCache;
  5. use App\Http\Api\ChannelApi;
  6. use App\Http\Api\MdRender;
  7. use App\Http\Api\StudioApi;
  8. use App\Http\Api\SuggestionApi;
  9. use App\Http\Api\UserApi;
  10. use App\Models\Channel;
  11. use App\Models\Discussion;
  12. use App\Models\PaliSentence;
  13. use App\Models\PaliText;
  14. use App\Models\Sentence;
  15. use App\Models\SentSimIndex;
  16. use App\Models\Wbw;
  17. use App\Models\WbwBlock;
  18. use App\Services\Markup\Annotation\AnnotationSet;
  19. use App\Services\Markup\Format;
  20. use App\Services\Markup\MarkupService;
  21. use App\Services\Markup\RenderOptions;
  22. use App\Services\V3\PaliTextService;
  23. use Illuminate\Support\Arr;
  24. use Illuminate\Support\Collection;
  25. use Illuminate\Support\Facades\Log;
  26. use Illuminate\Support\Str;
  27. class PaliContentService
  28. {
  29. protected $result = [
  30. 'uid' => '',
  31. 'title' => '',
  32. 'path' => [],
  33. 'sub_title' => '',
  34. 'summary' => '',
  35. 'content' => '',
  36. 'content_type' => 'html',
  37. 'toc' => [],
  38. 'status' => 30,
  39. 'lang' => '',
  40. 'created_at' => '',
  41. 'updated_at' => '',
  42. ];
  43. protected $wbwChannels = [];
  44. // 句子需要查询的列
  45. protected $selectCol = [
  46. 'uid',
  47. 'book_id',
  48. 'paragraph',
  49. 'word_start',
  50. 'word_end',
  51. 'channel_uid',
  52. 'content',
  53. 'content_type',
  54. 'editor_uid',
  55. 'acceptor_uid',
  56. 'pr_edit_at',
  57. 'fork_at',
  58. 'create_time',
  59. 'modify_time',
  60. 'created_at',
  61. 'updated_at',
  62. ];
  63. protected $userUuid = null;
  64. protected $debug = [];
  65. public static function _sentCanReadCount($book, $para, $start, $end, $userUuid = null)
  66. {
  67. $keyCanRead = '/channel/can-read/';
  68. if ($userUuid) {
  69. $keyCanRead .= $userUuid;
  70. } else {
  71. $keyCanRead .= 'guest';
  72. }
  73. $channelCanRead = RedisCache::remember(
  74. $keyCanRead,
  75. config('mint.cache.expire'),
  76. function () use ($userUuid) {
  77. return ChannelApi::getCanReadByUser($userUuid);
  78. }
  79. );
  80. $channels = Sentence::where('book_id', $book)
  81. ->where('paragraph', $para)
  82. ->where('word_start', $start)
  83. ->where('word_end', $end)
  84. ->where('strlen', '<>', 0)
  85. ->whereIn('channel_uid', $channelCanRead)
  86. ->select('channel_uid')
  87. ->groupBy('channel_uid')
  88. ->get();
  89. $channelList = [];
  90. foreach ($channels as $key => $value) {
  91. // code...
  92. if (Str::isUuid($value->channel_uid)) {
  93. $channelList[] = $value->channel_uid;
  94. }
  95. }
  96. $simId = PaliSentence::where('book', $book)
  97. ->where('paragraph', $para)
  98. ->where('word_begin', $start)
  99. ->where('word_end', $end)
  100. ->value('id');
  101. if ($simId) {
  102. $output['simNum'] = SentSimIndex::where('sent_id', $simId)->value('count');
  103. } else {
  104. $output['simNum'] = 0;
  105. }
  106. $channelInfo = Channel::whereIn('uid', $channelList)->select('type')->get();
  107. $output['tranNum'] = 0;
  108. $output['nissayaNum'] = 0;
  109. $output['commNum'] = 0;
  110. $output['originNum'] = 0;
  111. foreach ($channelInfo as $key => $value) {
  112. // code...
  113. switch ($value->type) {
  114. case 'translation':
  115. $output['tranNum']++;
  116. break;
  117. case 'nissaya':
  118. $output['nissayaNum']++;
  119. break;
  120. case 'commentary':
  121. $output['commNum']++;
  122. break;
  123. case 'original':
  124. $output['originNum']++;
  125. break;
  126. }
  127. }
  128. return $output;
  129. }
  130. private function newSent($book, $para, $word_start, $word_end)
  131. {
  132. $sent = [
  133. 'id' => "{$book}-{$para}-{$word_start}-{$word_end}",
  134. 'book' => $book,
  135. 'para' => $para,
  136. 'wordStart' => $word_start,
  137. 'wordEnd' => $word_end,
  138. 'origin' => [],
  139. 'translation' => [],
  140. 'commentaries' => [],
  141. ];
  142. if ($book < 1000) {
  143. // 生成channel 数量列表
  144. $sentId = "{$book}-{$para}-{$word_start}-{$word_end}";
  145. $channelCount = self::_sentCanReadCount($book, $para, $word_start, $word_end, $this->userUuid);
  146. $path = json_decode(PaliText::where('book', $book)->where('paragraph', $para)->value('path'), true);
  147. $sent['path'] = [];
  148. foreach ($path as $key => $value) {
  149. // code...
  150. $value['paliTitle'] = $value['title'];
  151. $sent['path'][] = $value;
  152. }
  153. $sent['tranNum'] = $channelCount['tranNum'];
  154. $sent['nissayaNum'] = $channelCount['nissayaNum'];
  155. $sent['commNum'] = $channelCount['commNum'];
  156. $sent['originNum'] = $channelCount['originNum'];
  157. $sent['simNum'] = $channelCount['simNum'];
  158. }
  159. return $sent;
  160. }
  161. /**
  162. * 根据句子库数据生成以段落为单位的文章内容
  163. * $record 句子数据
  164. * $mode read | edit | wbw
  165. * $indexChannel channel索引
  166. * $indexedHeading 标题索引 用于给段落加标题标签 <h1> ect.
  167. */
  168. public function makeContentObj($record, $mode, $indexChannel, $format = 'react')
  169. {
  170. $content = [];
  171. // 逐词解析(wbw)默认使用第一个 translation channel 的数据。
  172. // 系统原文 channel 固定在末尾(见 CorpusController / ChapterContentController 的约定),
  173. // 这里从 indexChannel 挑出 translation channel 作为 wbw 的读写目标;
  174. // 没有 translation channel 时(如直接编辑系统原文)保持为空,回落到系统原文。
  175. $this->wbwChannels = [];
  176. foreach ($indexChannel as $channelId => $info) {
  177. if ($info->type === 'translation') {
  178. $this->wbwChannels[] = $channelId;
  179. break;
  180. }
  181. }
  182. // 获取句子编号列表
  183. $paraIndex = [];
  184. foreach ($record as $value) {
  185. $currSentId = "{$value->book_id}-{$value->paragraph}-{$value->word_start}-{$value->word_end}";
  186. $value->sid = "{$currSentId}_{$value->channel_uid}";
  187. $currParaId = "{$value->book_id}-{$value->paragraph}";
  188. if (! isset($paraIndex[$currParaId])) {
  189. $paraIndex[$currParaId] = [];
  190. }
  191. $paraIndex[$currParaId][] = $value;
  192. }
  193. $channelsId = [];
  194. foreach ($indexChannel as $channelId => $info) {
  195. $channelsId[] = $channelId;
  196. }
  197. array_pop($channelsId);
  198. // 遍历列表查找每个句子的所有channel的数据,并填充
  199. $paragraphs = [];
  200. foreach ($paraIndex as $currParaId => $sentData) {
  201. $arrParaId = explode('-', $currParaId);
  202. $sentIndex = [];
  203. foreach ($sentData as $sent) {
  204. $currSentId = "{$sent->book_id}-{$sent->paragraph}-{$sent->word_start}-{$sent->word_end}";
  205. $sentIndex[$currSentId] = [$sent->book_id, $sent->paragraph, $sent->word_start, $sent->word_end];
  206. }
  207. $sentInPara = array_values($sentIndex);
  208. $paraProps = [
  209. 'book' => $arrParaId[0],
  210. 'para' => $arrParaId[1],
  211. 'channels' => $channelsId,
  212. 'sentences' => $sentInPara,
  213. 'mode' => $mode,
  214. 'children' => [],
  215. ];
  216. // 建立段落里面的句子列表
  217. foreach ($sentIndex as $ids => $arrSentId) {
  218. $sentNode = $this->newSent($arrSentId[0], $arrSentId[1], $arrSentId[2], $arrSentId[3]);
  219. foreach ($indexChannel as $channelId => $info) {
  220. // code...
  221. $sid = "{$ids}_{$channelId}";
  222. if (isset($info->studio)) {
  223. $studioInfo = $info->studio;
  224. } else {
  225. $studioInfo = null;
  226. }
  227. $newSent = [
  228. 'content' => '',
  229. 'html' => '',
  230. 'book' => $arrSentId[0],
  231. 'para' => $arrSentId[1],
  232. 'wordStart' => $arrSentId[2],
  233. 'wordEnd' => $arrSentId[3],
  234. 'channel' => [
  235. 'name' => $info->name,
  236. 'type' => $info->type,
  237. 'id' => $info->uid,
  238. 'lang' => $info->lang,
  239. ],
  240. 'studio' => $studioInfo,
  241. 'updateAt' => '',
  242. 'suggestionCount' => SuggestionApi::getCountBySent($arrSentId[0], $arrSentId[1], $arrSentId[2], $arrSentId[3], $channelId),
  243. ];
  244. $row = Arr::first($sentData, function ($value, $key) use ($sid) {
  245. return $value->sid === $sid;
  246. });
  247. if ($row) {
  248. $newSent['id'] = $row->uid;
  249. $newSent['content'] = $row->content;
  250. $newSent['contentType'] = $row->content_type;
  251. $newSent['html'] = '';
  252. $newSent['editor'] = UserApi::getByUuid($row->editor_uid);
  253. /**
  254. * TODO 刷库改数据
  255. * 旧版api没有更新updated_at所以造成旧版的数据updated_at数据比modify_time 要晚
  256. */
  257. $newSent['forkAt'] = $row->fork_at; //
  258. $newSent['updateAt'] = $row->updated_at; //
  259. $newSent['updateAt'] = date('Y-m-d H:i:s.', $row->modify_time / 1000).($row->modify_time % 1000).' UTC';
  260. $newSent['createdAt'] = $row->created_at;
  261. if ($mode !== 'read') {
  262. if (isset($row->acceptor_uid) && ! empty($row->acceptor_uid)) {
  263. $newSent['acceptor'] = UserApi::getByUuid($row->acceptor_uid);
  264. $newSent['prEditAt'] = $row->pr_edit_at;
  265. }
  266. }
  267. switch ($info->type) {
  268. case 'wbw':
  269. case 'original':
  270. //
  271. // 在编辑模式下。
  272. // 如果是原文,查看是否有逐词解析数据,
  273. // 有的话优先显示。
  274. // 阅读模式直接显示html原文
  275. // 传过来的数据一定有一个原文channel
  276. //
  277. if ($mode === 'read') {
  278. $newSent['content'] = '';
  279. $newSent['html'] = MdRender::render(
  280. $row->content,
  281. [$row->channel_uid],
  282. null,
  283. $mode,
  284. 'translation',
  285. $row->content_type,
  286. $format
  287. );
  288. } else {
  289. if ($row->content_type === 'json') {
  290. $newSent['channel']['type'] = 'wbw';
  291. if (isset($this->wbwChannels[0])) {
  292. $newSent['channel']['name'] = $indexChannel[$this->wbwChannels[0]]->name;
  293. $newSent['channel']['lang'] = $indexChannel[$this->wbwChannels[0]]->lang;
  294. $newSent['channel']['id'] = $this->wbwChannels[0];
  295. // 存在一个translation channel
  296. // 尝试查找逐词解析数据。找到,替换现有数据
  297. $wbwData = $this->getWbw(
  298. $arrSentId[0],
  299. $arrSentId[1],
  300. $arrSentId[2],
  301. $arrSentId[3],
  302. $this->wbwChannels[0]
  303. );
  304. if ($wbwData) {
  305. $newSent['content'] = $wbwData;
  306. $newSent['contentType'] = 'json';
  307. $newSent['html'] = '';
  308. $newSent['studio'] = $indexChannel[$this->wbwChannels[0]]->studio;
  309. }
  310. }
  311. } else {
  312. $newSent['content'] = $row->content;
  313. $newSent['html'] = MdRender::render(
  314. $row->content,
  315. [$row->channel_uid],
  316. null,
  317. $mode,
  318. 'translation',
  319. $row->content_type,
  320. $format
  321. );
  322. }
  323. }
  324. break;
  325. case 'nissaya':
  326. $newSent['html'] = RedisCache::remember(
  327. "/sent/{$channelId}/{$ids}/{$format}",
  328. config('mint.cache.expire'),
  329. function () use ($row, $mode, $format) {
  330. return MdRender::render(
  331. $row->content,
  332. [$row->channel_uid],
  333. null,
  334. $mode,
  335. 'nissaya',
  336. $row->content_type,
  337. $format
  338. );
  339. }
  340. );
  341. break;
  342. case 'commentary':
  343. $options = [
  344. 'debug' => $this->debug,
  345. 'format' => $format,
  346. 'mode' => $mode,
  347. 'channelType' => 'translation',
  348. 'contentType' => $row->content_type,
  349. ];
  350. $mdRender = new MdRender($options);
  351. $newSent['html'] = $mdRender->convert($row->content, $channelsId);
  352. break;
  353. default:
  354. $options = [
  355. 'debug' => $this->debug,
  356. 'format' => $format,
  357. 'mode' => $mode,
  358. 'channelType' => 'translation',
  359. 'contentType' => $row->content_type,
  360. ];
  361. $mdRender = new MdRender($options);
  362. $newSent['html'] = $mdRender->convert($row->content, [$row->channel_uid]);
  363. // Log::debug('md render', ['content' => $row->content, 'options' => $options, 'render' => $newSent['html']]);
  364. break;
  365. }
  366. } else {
  367. Log::warning('no sentence record');
  368. }
  369. switch ($info->type) {
  370. case 'wbw':
  371. case 'original':
  372. array_push($sentNode['origin'], $newSent);
  373. break;
  374. case 'commentary':
  375. array_push($sentNode['commentaries'], $newSent);
  376. break;
  377. default:
  378. array_push($sentNode['translation'], $newSent);
  379. break;
  380. }
  381. }
  382. $paraProps['children'][] = $sentNode;
  383. }
  384. $paragraphs[] = $paraProps;
  385. }
  386. return $paragraphs;
  387. }
  388. public function getWbw($book, $para, $start, $end, $channel)
  389. {
  390. /**
  391. * 非阅读模式下。原文使用逐词解析数据。
  392. * 优先加载第一个translation channel 如果没有。加载默认逐词解析。
  393. */
  394. // 获取逐词解析数据
  395. $wbwBlock = WbwBlock::where('channel_uid', $channel)
  396. ->where('book_id', $book)
  397. ->where('paragraph', $para)
  398. ->select('uid')
  399. ->first();
  400. if (! $wbwBlock) {
  401. return false;
  402. }
  403. // 找到逐词解析数据
  404. $wbwData = Wbw::where('block_uid', $wbwBlock->uid)
  405. ->whereBetween('wid', [$start, $end])
  406. ->select(['book_id', 'paragraph', 'wid', 'data', 'uid', 'editor_id', 'created_at', 'updated_at'])
  407. ->orderBy('wid')
  408. ->get();
  409. $wbwContent = [];
  410. foreach ($wbwData as $wbwrow) {
  411. $wbw = str_replace('&nbsp;', ' ', $wbwrow->data);
  412. $wbw = str_replace('<br>', ' ', $wbw);
  413. $xmlString = '<root>'.$wbw.'</root>';
  414. try {
  415. $xmlWord = simplexml_load_string($xmlString);
  416. } catch (\Exception $e) {
  417. Log::error('corpus', ['error' => $e]);
  418. continue;
  419. }
  420. $wordsList = $xmlWord->xpath('//word');
  421. foreach ($wordsList as $word) {
  422. $case = \str_replace(['#', '.'], ['$', ''], $word->case->__toString());
  423. $case = \str_replace('$$', '$', $case);
  424. $case = trim($case);
  425. $case = trim($case, '$');
  426. $wbwId = explode('-', $word->id->__toString());
  427. $wbwData = [
  428. 'uid' => $wbwrow->uid,
  429. 'book' => $wbwrow->book_id,
  430. 'para' => $wbwrow->paragraph,
  431. 'sn' => array_slice($wbwId, 2),
  432. 'word' => ['value' => $word->pali->__toString(), 'status' => 0],
  433. 'real' => ['value' => $word->real->__toString(), 'status' => 0],
  434. 'meaning' => ['value' => $word->mean->__toString(), 'status' => 0],
  435. 'type' => ['value' => $word->type->__toString(), 'status' => 0],
  436. 'grammar' => ['value' => $word->gramma->__toString(), 'status' => 0],
  437. 'case' => ['value' => $word->case->__toString(), 'status' => 0],
  438. 'parent' => ['value' => $word->parent->__toString(), 'status' => 0],
  439. 'style' => ['value' => $word->style->__toString(), 'status' => 0],
  440. 'factors' => ['value' => $word->org->__toString(), 'status' => 0],
  441. 'factorMeaning' => ['value' => $word->om->__toString(), 'status' => 0],
  442. 'confidence' => $word->cf->__toString(),
  443. 'created_at' => $wbwrow->created_at,
  444. 'updated_at' => $wbwrow->updated_at,
  445. 'hasComment' => Discussion::where('res_id', $wbwrow->uid)->exists(),
  446. ];
  447. if (isset($word->parent2)) {
  448. $wbwData['parent2']['value'] = $word->parent2->__toString();
  449. if (isset($word->parent2['status'])) {
  450. $wbwData['parent2']['status'] = (int) $word->parent2['status'];
  451. } else {
  452. $wbwData['parent2']['status'] = 0;
  453. }
  454. }
  455. if (isset($word->pg)) {
  456. $wbwData['grammar2']['value'] = $word->pg->__toString();
  457. if (isset($word->pg['status'])) {
  458. $wbwData['grammar2']['status'] = (int) $word->pg['status'];
  459. } else {
  460. $wbwData['grammar2']['status'] = 0;
  461. }
  462. }
  463. if (isset($word->rela)) {
  464. $wbwData['relation']['value'] = $word->rela->__toString();
  465. if (isset($word->rela['status'])) {
  466. $wbwData['relation']['status'] = (int) $word->rela['status'];
  467. } else {
  468. $wbwData['relation']['status'] = 7;
  469. }
  470. }
  471. if (isset($word->bmt)) {
  472. $wbwData['bookMarkText']['value'] = $word->bmt->__toString();
  473. if (isset($word->bmt['status'])) {
  474. $wbwData['bookMarkText']['status'] = (int) $word->bmt['status'];
  475. } else {
  476. $wbwData['bookMarkText']['status'] = 7;
  477. }
  478. }
  479. if (isset($word->bmc)) {
  480. $wbwData['bookMarkColor']['value'] = $word->bmc->__toString();
  481. if (isset($word->bmc['status'])) {
  482. $wbwData['bookMarkColor']['status'] = (int) $word->bmc['status'];
  483. } else {
  484. $wbwData['bookMarkColor']['status'] = 7;
  485. }
  486. }
  487. if (isset($word->note)) {
  488. $wbwData['note']['value'] = $word->note->__toString();
  489. if (isset($word->note['status'])) {
  490. $wbwData['note']['status'] = (int) $word->note['status'];
  491. } else {
  492. $wbwData['note']['status'] = 7;
  493. }
  494. }
  495. if (isset($word->cf)) {
  496. $wbwData['confidence'] = (float) $word->cf->__toString();
  497. }
  498. if (isset($word->attachments)) {
  499. $wbwData['attachments'] = json_decode($word->attachments->__toString());
  500. }
  501. if (isset($word->pali['status'])) {
  502. $wbwData['word']['status'] = (int) $word->pali['status'];
  503. }
  504. if (isset($word->real['status'])) {
  505. $wbwData['real']['status'] = (int) $word->real['status'];
  506. }
  507. if (isset($word->mean['status'])) {
  508. $wbwData['meaning']['status'] = (int) $word->mean['status'];
  509. }
  510. if (isset($word->type['status'])) {
  511. $wbwData['type']['status'] = (int) $word->type['status'];
  512. }
  513. if (isset($word->gramma['status'])) {
  514. $wbwData['grammar']['status'] = (int) $word->gramma['status'];
  515. }
  516. if (isset($word->case['status'])) {
  517. $wbwData['case']['status'] = (int) $word->case['status'];
  518. }
  519. if (isset($word->parent['status'])) {
  520. $wbwData['parent']['status'] = (int) $word->parent['status'];
  521. }
  522. if (isset($word->org['status'])) {
  523. $wbwData['factors']['status'] = (int) $word->org['status'];
  524. }
  525. if (isset($word->om['status'])) {
  526. $wbwData['factorMeaning']['status'] = (int) $word->om['status'];
  527. }
  528. $wbwContent[] = $wbwData;
  529. }
  530. }
  531. if (count($wbwContent) === 0) {
  532. return false;
  533. }
  534. return \json_encode($wbwContent, JSON_UNESCAPED_UNICODE);
  535. }
  536. public function getChannelIndex($channels, $type = null)
  537. {
  538. // 获取channel索引表
  539. $channelInfo = Channel::whereIn('uid', $channels)
  540. ->select(['uid', 'type', 'name', 'lang', 'owner_uid'])
  541. ->get();
  542. $indexChannel = [];
  543. foreach ($channels as $key => $channelId) {
  544. $channelInfo = Channel::where('uid', $channelId)
  545. ->select(['uid', 'type', 'name', 'lang', 'owner_uid'])->first();
  546. if (! $channelInfo) {
  547. Log::error('no channel id'.$channelId);
  548. continue;
  549. }
  550. if ($type !== null && $channelInfo->type !== $type) {
  551. continue;
  552. }
  553. $indexChannel[$channelId] = $channelInfo;
  554. $indexChannel[$channelId]->studio = StudioApi::getById($channelInfo->owner_uid);
  555. }
  556. return $indexChannel;
  557. }
  558. public function sentences(array $sentenceIds, array $channelIds, string $mode)
  559. {
  560. $query = [];
  561. foreach ($sentenceIds as $id) {
  562. // code...
  563. $query[] = explode('-', $id);
  564. }
  565. $record = Sentence::select($this->selectCol)
  566. ->whereIns(['book_id', 'paragraph', 'word_start', 'word_end'], $query)
  567. ->whereIn('channel_uid', $channelIds)
  568. ->get();
  569. $indexChannel = $this->getChannelIndex($channelIds);
  570. $result = $this->makeContentObj($record, $mode, $indexChannel);
  571. return $result;
  572. }
  573. public function paragraphs(int $book, int $start, int $end, array $channelIds, array $param)
  574. {
  575. $channels = [];
  576. foreach ($channelIds as $key => $channel) {
  577. if (Str::isUuid($channel)) {
  578. $channels[] = $channel;
  579. }
  580. }
  581. $channelId = false;
  582. if ($param['original']) {
  583. if ($param['mode'] === 'read') {
  584. // 阅读模式加载html格式原文
  585. $channelId = app(ChannelService::class)->systemUid('_System_Pali_VRI_');
  586. } else {
  587. // 翻译模式加载json格式原文
  588. $channelId = app(ChannelService::class)->systemUid('_System_Wbw_VRI_');
  589. }
  590. }
  591. if ($channelId !== false) {
  592. $channels[] = $channelId;
  593. }
  594. // 获取channel索引表
  595. $tranChannels = [];
  596. $channelInfo = Channel::whereIn('uid', $channels)
  597. ->select(['uid', 'type', 'lang', 'name'])->get();
  598. foreach ($channelInfo as $key => $value) {
  599. // code...
  600. if ($value->type === 'translation') {
  601. $tranChannels[] = $value->uid;
  602. }
  603. }
  604. $indexChannel = [];
  605. $paliService = app(PaliContentService::class);
  606. $indexChannel = $paliService->getChannelIndex($channels);
  607. // the end of channel
  608. // content
  609. $record = Sentence::select($this->selectCol)
  610. ->where('book_id', $book)
  611. ->whereBetween('paragraph', [$start, $end])
  612. ->whereIn('channel_uid', $channels)
  613. ->orderBy('paragraph')
  614. ->orderBy('word_start')
  615. ->get();
  616. $result = $paliService->makeContentObj($record, $param['mode'], $indexChannel, $param['format']);
  617. return $result;
  618. }
  619. /**
  620. * 阅读模式渲染单个段落,即只给一段的 {@see self::readParagraphs()}。
  621. * 直接从 sentences 表取单个 channel 的记录。与 paragraphs() 不同:没有译文的句子不保留占位,
  622. * 有多少句子输出多少句子。
  623. *
  624. * @return array{para: int, display: string, sentences: list<array{sid: string, html: string}>}
  625. */
  626. public function readParagraph(int $book, int $para, string $channelUid, string $format = 'html'): array
  627. {
  628. return $this->readParagraphs($book, [$para], $channelUid, $format)[$para];
  629. }
  630. /**
  631. * 阅读模式渲染同一本书的多个段落。v3 阅读、Laravel 阅读器、三藏下载都从这里取正文。
  632. *
  633. * 每段的**完整结果**(含段落外壳与段后脚注列表)按 (book, para, channel, format) 缓存,
  634. * 命中时不查库;没有译文的段也缓存(display 为空)。没命中的段一起渲染
  635. * ({@see self::renderReadParagraphs()}):channel、句子、批注各查一次,全部句子一次交给 Markup,
  636. * 术语、引用句子等每类只查一次。
  637. *
  638. * 缓存由 Sentence / Discussion 的模型事件删除({@see self::paragraphChanged()}、{@see self::forgetParagraph()});术语释义、
  639. * 引用的句子、channel 名称改了没有失效信号,最多旧 `mint.cache.read_paragraph_ttl`。
  640. *
  641. * @param list<int> $paras
  642. * @return array<int, array{para: int, display: string, sentences: list<array{sid: string, html: string}>}> 段落号 => 结果,顺序同 $paras
  643. */
  644. public function readParagraphs(int $book, array $paras, string $channelUid, string $format = 'html'): array
  645. {
  646. $results = [];
  647. $misses = [];
  648. foreach (array_unique($paras) as $para) {
  649. $cached = RedisCache::get(self::paragraphCacheKey($book, $para, $channelUid, $format));
  650. $results[$para] = is_array($cached) ? $cached : null;
  651. if ($results[$para] === null) {
  652. $misses[] = $para;
  653. }
  654. }
  655. if ($misses === []) {
  656. return $results;
  657. }
  658. $ttl = (int) config('mint.cache.read_paragraph_ttl');
  659. foreach ($this->renderReadParagraphs($book, $misses, $channelUid, $format) as $para => $result) {
  660. RedisCache::put(self::paragraphCacheKey($book, $para, $channelUid, $format), $result, $ttl);
  661. $results[$para] = $result;
  662. }
  663. return $results;
  664. }
  665. /**
  666. * 区间 [start, end] 的阅读模式正文(html),阅读器按章读用。
  667. *
  668. * 按平铺章节缓存({@see PaliTextService::flatChapters()}:标题段到下一个标题段之前是一章,不嵌套),
  669. * 一章一个 key,命中时整章一次 GET、不查库。区间完整覆盖的章走章节缓存,没命中的章一起交给
  670. * {@see self::readParagraphs()}(各段多半已在段落成品缓存里)拼好回写;区间边缘没盖全的章、
  671. * 第一个标题段之前的段直接逐段取。章节缓存与段落成品一起失效({@see self::forgetParagraph()})。
  672. */
  673. public function readChapters(int $book, int $start, int $end, string $channelUid, string $format = 'html'): string
  674. {
  675. // 区间切成片:[起, 止, 是否整章]
  676. $pieces = [];
  677. $cursor = $start;
  678. foreach (app(PaliTextService::class)->flatChapters($book) as $chapterStart => $chapterEnd) {
  679. if ($chapterEnd < $cursor || $chapterStart > $end) {
  680. continue;
  681. }
  682. if ($chapterStart > $cursor) {
  683. $pieces[] = [$cursor, $chapterStart - 1, false];
  684. $cursor = $chapterStart;
  685. }
  686. $whole = $chapterStart >= $start && $chapterEnd <= $end;
  687. $pieces[] = [$cursor, min($chapterEnd, $end), $whole];
  688. $cursor = min($chapterEnd, $end) + 1;
  689. }
  690. if ($cursor <= $end) {
  691. $pieces[] = [$cursor, $end, false];
  692. }
  693. $chapters = [];
  694. $paras = [];
  695. foreach ($pieces as $i => [$from, $to, $whole]) {
  696. if ($whole) {
  697. $cached = RedisCache::get(self::chapterCacheKey($book, $from, $channelUid, $format));
  698. if (is_string($cached)) {
  699. $chapters[$i] = $cached;
  700. continue;
  701. }
  702. }
  703. array_push($paras, ...range($from, $to));
  704. }
  705. $rendered = $paras === [] ? [] : $this->readParagraphs($book, $paras, $channelUid, $format);
  706. $ttl = (int) config('mint.cache.read_paragraph_ttl');
  707. $separator = $format === 'html' ? '' : "\n";
  708. $display = [];
  709. foreach ($pieces as $i => [$from, $to, $whole]) {
  710. if (! isset($chapters[$i])) {
  711. $parts = [];
  712. foreach (range($from, $to) as $para) {
  713. if (($rendered[$para]['display'] ?? '') !== '') {
  714. $parts[] = $rendered[$para]['display'];
  715. }
  716. }
  717. $chapters[$i] = implode($separator, $parts);
  718. if ($whole) {
  719. RedisCache::put(self::chapterCacheKey($book, $from, $channelUid, $format), $chapters[$i], $ttl);
  720. }
  721. }
  722. if ($chapters[$i] !== '') {
  723. $display[] = $chapters[$i];
  724. }
  725. }
  726. return implode($separator, $display);
  727. }
  728. /**
  729. * 段落是章节标题时返回标题级别,否则 0
  730. */
  731. public function paragraphLevel(int $book, int $para): int
  732. {
  733. return app(PaliTextService::class)->headingLevel($book, $para);
  734. }
  735. /**
  736. * 阅读模式支持的全部格式。forgetParagraph 需要逐格式清除缓存 key。
  737. *
  738. * @var array<int, string>
  739. */
  740. private const FORMATS = ['html', 'markdown', 'text'];
  741. /**
  742. * 阅读格式 → App\Services\Markup 的输出格式。
  743. */
  744. private static function markupFormat(string $format): Format
  745. {
  746. return match ($format) {
  747. 'markdown' => Format::Markdown,
  748. 'text' => Format::Text,
  749. default => Format::Html,
  750. };
  751. }
  752. /**
  753. * 义注对应(commentary)批注最多渲染几句。
  754. * 一条批注可能挂着十几句义注,全铺进边注会把正文挤没,只取前几句。
  755. */
  756. private const MAX_COMMENTARY_SENTENCES = 3;
  757. /**
  758. * 段落阅读模式缓存的 key(段落成品:含外壳与脚注列表)。
  759. */
  760. public static function paragraphCacheKey(int $book, int $para, string $channelUid, string $format): string
  761. {
  762. // v4:2026-11-22 起缓存整段成品(原来只缓存句子、外壳每次现查),换前缀让旧缓存自然过期
  763. return "/read-para/v4/{$book}-{$para}/{$channelUid}/{$format}";
  764. }
  765. /**
  766. * 平铺章节的阅读正文缓存 key({@see self::readChapters()})。
  767. */
  768. public static function chapterCacheKey(int $book, int $chapter, string $channelUid, string $format): string
  769. {
  770. return "/read-chapter/v1/{$book}-{$chapter}/{$channelUid}/{$format}";
  771. }
  772. /**
  773. * 删除某个段落的阅读模式缓存(段落成品,及它所在平铺章节的章节缓存),下次读时自动重建。
  774. */
  775. public static function forgetParagraph(int $book, int $para, string $channelUid): void
  776. {
  777. $chapter = app(PaliTextService::class)->flatChapterOf($book, $para);
  778. foreach (self::FORMATS as $format) {
  779. RedisCache::forget(self::paragraphCacheKey($book, $para, $channelUid, $format));
  780. if ($chapter !== null) {
  781. RedisCache::forget(self::chapterCacheKey($book, $chapter, $channelUid, $format));
  782. }
  783. }
  784. }
  785. /**
  786. * 某段的句子变了(Sentence 的模型事件调用):删段落成品与所在章节的缓存;「有译文的段」可能变了
  787. * ($indexChanged:新建 / 删除句子、strlen 在 0 与非 0 之间变化、句子搬了家)时再删内容索引。
  788. * 书号索引的两个参数见 {@see ReadingIndexService::forget()}。
  789. */
  790. public static function paragraphChanged(int $book, int $para, string $channelUid, bool $indexChanged = false, bool $mayAddBook = false, bool $mayRemoveBook = false): void
  791. {
  792. self::forgetParagraph($book, $para, $channelUid);
  793. if ($indexChanged) {
  794. app(ReadingIndexService::class)->forget($channelUid, $book, $mayAddBook, $mayRemoveBook);
  795. }
  796. }
  797. /**
  798. * 段落批注内嵌:把锚定到该句子的批注排进句子 content,再交给 App\Services\Markup 渲染。
  799. *
  800. * 四种批注,显示方式不同(排版规则与交叠处理见 {@see AnnotationLayout}):
  801. * - `commentary`(注释书对应):content 是义注 / 复注的句子模板 `{{book-para-start-end}}`,
  802. * 渲染成这几句的译文,作为 {{note}} 边注插在锚点末尾,并追加 <cite> 跳转出处;
  803. * - `note`(普通边注):content 就是注解正文(markdown),同样插成 {{note}},没有出处;
  804. * - `glossary`(外挂术语):锚点处的原文换成 `[[title#原文]]`,渲染成术语(title 是词头);
  805. * - `issue`:锚点处的原文包一层高亮,带 discussion id,阅读器点击看内容;
  806. * 没有位置的合成一个三角叹号图标放在句尾。纯文本 / markdown 里不显示。
  807. * - `assessment`(译文评估):句尾一个对勾图标,颜色按分数分档,带 discussion id,
  808. * 阅读器点击看分数与理由。一句只有一条(有并发残留时取最近更新的)。纯文本 / markdown 里不显示。
  809. * 同段里其它没有评估的句子由 {@see self::renderReadParagraphs()} 补灰色对勾。
  810. * issue / glossary 只注入未关闭的;批注与评估没有开关状态。
  811. *
  812. * 位置按 pos_* 定位,与 quote_exact 对不上(正文改过)时按摘录重新定位。
  813. *
  814. * 插入点写的是结构化标记({@see AnnotationSet})而不是 HTML:content 里留下占位符,渲染时变成
  815. * anno-issue / anno-issue-mark / anno-assessment / note 模板节点,任意格式都能输出。
  816. *
  817. * 批注由调用方一次查好传进来({@see self::readingAnnotations()})。段后脚注列表的正文(纯文本)
  818. * 这里不渲染,只给出待渲染的源码(`text`),由调用方整块一次渲染后填进 `noteHtml`。
  819. *
  820. * @param list<Discussion> $records 挂在这句上、要注入阅读页的批注,按创建时间升序
  821. * @return array{content: string, notes: list<array{fnId: string, noteHtml: string, citeHtml: string, text: array{source: string, channels: list<string>, contentType: string}, truncated: bool}>, assessed: bool, annotations: AnnotationSet}
  822. */
  823. protected function injectAnnotationNotes(Sentence $row, string $channelType, array $records): array
  824. {
  825. $content = (string) $row->content;
  826. $annotations = new AnnotationSet;
  827. $result = ['content' => $content, 'notes' => [], 'assessed' => false, 'annotations' => $annotations];
  828. if ($records === []) {
  829. return $result;
  830. }
  831. $len = mb_strlen($content, 'UTF-8');
  832. $locate = fn (Discussion $d) => AnnotationLayout::locate(
  833. $content, $d->pos_start, $d->pos_end, $d->quote_exact, $d->quote_prefix, $d->quote_suffix
  834. );
  835. $glossaries = [];
  836. $issues = [];
  837. $notes = [];
  838. $footnotes = [];
  839. $assessment = null;
  840. foreach ($records as $record) {
  841. if ($record->type === Discussion::TYPE_ASSESSMENT) {
  842. if ($record->score !== null && ($assessment === null || $record->updated_at >= $assessment['updated_at'])) {
  843. $assessment = ['id' => $record->id, 'score' => (int) $record->score, 'updated_at' => $record->updated_at];
  844. }
  845. continue;
  846. }
  847. if ($record->type === Discussion::TYPE_GLOSSARY) {
  848. $range = $locate($record);
  849. if ($range !== null) {
  850. $glossaries[] = ['id' => $record->id, 'start' => $range[0], 'end' => $range[1], 'title' => (string) $record->title];
  851. }
  852. continue;
  853. }
  854. if ($record->type === 'issue') {
  855. $range = $locate($record);
  856. $issues[] = ['id' => $record->id, 'start' => $range[0] ?? null, 'end' => $range[1] ?? null, 'severity' => $record->severity];
  857. continue;
  858. }
  859. $note = $this->renderAnnotationNote($record, $row);
  860. if ($note === null) {
  861. continue;
  862. }
  863. // 插入点:锚点末尾;定位不到时沿用 pos_end,null / 越界都算句尾
  864. $range = $locate($record);
  865. $at = $range[1] ?? $record->pos_end;
  866. if ($at === null || $at < 0 || $at > $len) {
  867. $at = $len;
  868. }
  869. $notes[] = [
  870. 'id' => $record->id,
  871. 'at' => $at,
  872. 'order' => $note['order'],
  873. 'html' => $annotations->note($note['body'], $note['params'], $record->effectiveContentType()),
  874. ];
  875. $footnotes[$record->id] = [
  876. 'fnId' => 'fn-'.$record->id,
  877. 'noteHtml' => '',
  878. 'citeHtml' => $note['citeHtml'],
  879. 'text' => $note['text'],
  880. 'truncated' => $note['truncated'],
  881. ];
  882. }
  883. // 结构化注入:插入点写批注标记(不是 HTML),渲染时变成模板节点,各格式自己决定怎么显示
  884. $layout = AnnotationLayout::apply(
  885. $content,
  886. $glossaries,
  887. $issues,
  888. $notes,
  889. true,
  890. $assessment === null ? null : ['id' => $assessment['id'], 'score' => $assessment['score']],
  891. $annotations,
  892. );
  893. $result['content'] = $layout['content'];
  894. $result['notes'] = array_map(fn ($id) => $footnotes[$id], $layout['notes']);
  895. $result['assessed'] = $assessment !== null;
  896. return $result;
  897. }
  898. /**
  899. * 把一条批注(commentary / note)整理成要插入正文的 note 模板(正文 + 参数)与段后脚注条目。
  900. * 不合格的(正文为空、commentary 不是句子模板)返回 null,不插角标也不进脚注列表。
  901. *
  902. * 脚注条目的正文(纯文本)不在这里渲染:`text` 是待渲染的源码,`truncated` 表示义注被截断、
  903. * 渲染后要补省略号。整块一起渲染见 {@see self::renderFootnoteTexts()}。
  904. *
  905. * @return array{body: string, params: array<string, string>, text: array{source: string, channels: list<string>, contentType: string}, truncated: bool, citeHtml: string, order: array<int, int>}|null
  906. */
  907. protected function renderAnnotationNote(Discussion $note, Sentence $row): ?array
  908. {
  909. $noteContent = trim((string) $note->content);
  910. if ($noteContent === '') {
  911. return null;
  912. }
  913. $sents = [];
  914. if ($note->type === Discussion::TYPE_COMMENTARY) {
  915. // content 是一个或多个义注句子模板 {{book-para-start-end}}(一个词可能由义注
  916. // 多句解释,按顺序并列,如 {{135-404-50-54}}{{135-404-55-65}})。
  917. if (! preg_match(Discussion::COMMENTARY_PATTERN, $noteContent)) {
  918. return null;
  919. }
  920. preg_match_all('/\{\{(\d+)-(\d+)-(\d+)-(\d+)\}\}/', $noteContent, $sents, PREG_SET_ORDER);
  921. // 义注正文只需译文(不要巴利原文):把每个裸句模板 {{book-para-start-end}}
  922. // 转成 {{sent|id=…|text=translation}},让 sent 模板只输出 translation。
  923. // 句子可能有很多条,只渲染前 MAX_COMMENTARY_SENTENCES 句;
  924. // 跳转锚点仍指向第一句,点进去能看到完整义注。
  925. $source = implode(' ', array_map(
  926. fn ($s) => '{{sent|id='.$s[1].'-'.$s[2].'-'.$s[3].'-'.$s[4].'|text=translation}}',
  927. array_slice($sents, 0, self::MAX_COMMENTARY_SENTENCES)
  928. ));
  929. } else {
  930. // 普通边注:content 就是注解正文,照原样渲染。
  931. $source = $noteContent;
  932. }
  933. // 段后脚注列表用的纯文本(边注本身是结构化的 note 节点,正文照 markdown 渲染)
  934. $text = [
  935. 'source' => $source,
  936. 'channels' => [(string) $row->channel_uid],
  937. 'contentType' => $note->effectiveContentType(),
  938. ];
  939. // 义注被截断时补省略号,提示后面还有;想看全文点 <cite> 跳过去。
  940. $truncated = count($sents) > self::MAX_COMMENTARY_SENTENCES;
  941. if ($truncated) {
  942. $source .= '...';
  943. }
  944. // 出处只有 commentary 有。跳转目标(义注书-段-起-止)同时挂在 <cite> 和角标
  945. // <label> 上,前者用于「点链接跳页」,后者用于平板双栏「点角标跨栏高亮」。
  946. // 多句时跳转到第一句(义注对这个词的解释从那里开始)。
  947. $citeHtml = '';
  948. $params = [];
  949. if ($sents) {
  950. $m = $sents[0];
  951. $target = ' data-book="'.$m[1].'" data-para="'.$m[2].'" data-start="'.$m[3].'" data-end="'.$m[4].'"';
  952. $citeHtml = '<cite class="anno-jump"'.$target.'>义注</cite>';
  953. $params = ['cite' => '义注', 'citelink' => $m[1].'-'.$m[2].'-'.$m[3].'-'.$m[4]];
  954. }
  955. return [
  956. // note 模板的正文(markdown)与参数:渲染成 tufte sidenote(label + input + span.sidenote)
  957. 'body' => $source,
  958. 'params' => $params,
  959. 'text' => $text,
  960. 'truncated' => $truncated,
  961. 'citeHtml' => $citeHtml,
  962. // 同一插入点上的先后:按义注原文的先后;普通 note 没有坐标,取 0,排在义注对应之前
  963. 'order' => $sents ? [(int) $sents[0][1], (int) $sents[0][2], (int) $sents[0][3]] : [0, 0, 0],
  964. ];
  965. }
  966. /**
  967. * 段落脚注列表:把本段的注释条目逐条列在段后,每条默认收起为可配置行数(见阅读器 CSS)。
  968. *
  969. * @param list<array{fnId: string, noteHtml: string, citeHtml: string}> $notes
  970. */
  971. protected function renderFootnoteList(array $notes): string
  972. {
  973. if (empty($notes)) {
  974. return '';
  975. }
  976. $html = '<div class="anno-footnotes">';
  977. foreach ($notes as $note) {
  978. $html .= '<div class="anno-footnote">'
  979. .'<input type="checkbox" id="'.$note['fnId'].'" class="anno-fn-toggle"/>'
  980. .'<label for="'.$note['fnId'].'" class="anno-fn-label">'
  981. .'<span class="anno-fn-body">'.e($note['noteHtml']).'</span>'
  982. .'</label>'
  983. .$note['citeHtml']
  984. .'</div>';
  985. }
  986. $html .= '</div>';
  987. return $html;
  988. }
  989. /**
  990. * 一次查回这些句子上要注入阅读页的批注,按句子 uid 分组、组内按创建时间升序。
  991. *
  992. * @param Collection<int, Sentence> $records
  993. * @return array<string, list<Discussion>>
  994. */
  995. protected function readingAnnotations(Collection $records): array
  996. {
  997. $grouped = [];
  998. foreach ($records->pluck('uid')->unique()->chunk(1000) as $uids) {
  999. Discussion::where('res_type', 'sentence')
  1000. ->whereIn('res_id', $uids->values()->all())
  1001. ->whereIn('type', Discussion::READING_TYPES)
  1002. // 只注入话题本身;回复(类型跟随话题)不进阅读页
  1003. ->whereNull('parent')
  1004. ->where(fn ($q) => $q->whereIn('type', Discussion::STATELESS_TYPES)->orWhere('status', 'active'))
  1005. ->orderBy('created_at')
  1006. ->get()
  1007. ->each(function (Discussion $discussion) use (&$grouped) {
  1008. $grouped[(string) $discussion->res_id][] = $discussion;
  1009. });
  1010. }
  1011. return $grouped;
  1012. }
  1013. /**
  1014. * 整块的段后脚注正文(纯文本)一次渲染:批注里的术语、义注句子合在一起查。
  1015. *
  1016. * @param array<int, array{notes: list<array<string, mixed>>}> $injections
  1017. * @return array<string, string> "句序号:脚注序号" => 纯文本
  1018. */
  1019. protected function renderFootnoteTexts(array $injections, string $channelType): array
  1020. {
  1021. $items = [];
  1022. foreach ($injections as $i => $injected) {
  1023. foreach ($injected['notes'] as $n => $note) {
  1024. $items["{$i}:{$n}"] = $note['text'];
  1025. }
  1026. }
  1027. if ($items === []) {
  1028. return [];
  1029. }
  1030. $texts = app(MarkupService::class)->renderMany($items, new RenderOptions(format: Format::Text, channelType: $channelType));
  1031. foreach ($injections as $i => $injected) {
  1032. foreach ($injected['notes'] as $n => $note) {
  1033. $text = (string) ($texts["{$i}:{$n}"] ?? '');
  1034. $texts["{$i}:{$n}"] = $note['truncated'] ? rtrim($text).'...' : $text;
  1035. }
  1036. }
  1037. return $texts;
  1038. }
  1039. /**
  1040. * 渲染同一本书的若干段落(没命中缓存的那些),结果含段落外壳,可直接缓存。
  1041. *
  1042. * 整块只查三次库:channel、句子(按段、word_start 排序)、批注;全部句子一次交给 Markup 渲染,
  1043. * 脚注正文再一次。标题级别与段落 class 取自 {@see PaliTextService}(缓存的经文静态数据)。
  1044. *
  1045. * @param list<int> $paras
  1046. * @return array<int, array{para: int, display: string, sentences: list<array{sid: string, html: string}>}>
  1047. */
  1048. protected function renderReadParagraphs(int $book, array $paras, string $channelUid, string $format): array
  1049. {
  1050. $results = [];
  1051. foreach ($paras as $para) {
  1052. $results[$para] = ['para' => $para, 'display' => '', 'sentences' => []];
  1053. }
  1054. $channel = Channel::where('uid', $channelUid)
  1055. ->select(['uid', 'type', 'lang', 'name'])->first();
  1056. if (! $channel) {
  1057. return $results;
  1058. }
  1059. $isOrigin = $channel->type === 'original' || $channel->type === 'wbw';
  1060. $channelType = $channel->type === 'nissaya' ? 'nissaya' : 'translation';
  1061. $area = $isOrigin ? 'original' : 'translation';
  1062. $records = Sentence::select($this->selectCol)
  1063. ->where('book_id', $book)
  1064. ->where('channel_uid', $channelUid)
  1065. ->whereIn('paragraph', $paras)
  1066. ->orderBy('paragraph')
  1067. ->orderBy('word_start')
  1068. ->get()
  1069. ->values();
  1070. if ($records->isEmpty()) {
  1071. return $results;
  1072. }
  1073. $annotations = $this->readingAnnotations($records);
  1074. $injections = [];
  1075. $assessedParas = [];
  1076. foreach ($records as $i => $row) {
  1077. $injections[$i] = $this->injectAnnotationNotes($row, $channelType, $annotations[(string) $row->uid] ?? []);
  1078. if ($injections[$i]['assessed']) {
  1079. $assessedParas[(int) $row->paragraph] = true;
  1080. }
  1081. }
  1082. $sources = [];
  1083. foreach ($records as $i => $row) {
  1084. $injected = $injections[$i];
  1085. $content = $injected['content'];
  1086. // 段里有句子评估过,其余没评估的句子在句尾补灰色对勾:不然读者会把它与下一句的
  1087. // 对勾连起来,误以为是一句。整段都没评估就都不补(段落本身有分隔)。按段算,不是按整块
  1088. if (isset($assessedParas[(int) $row->paragraph]) && ! $injected['assessed'] && trim($content) !== '') {
  1089. $content .= $injected['annotations']->unassessedMark();
  1090. }
  1091. $sources[$i] = [
  1092. 'source' => $content,
  1093. 'channels' => [(string) $row->channel_uid],
  1094. 'contentType' => (string) $row->content_type,
  1095. 'annotations' => $injected['annotations'],
  1096. // 边注的 HTML id 带上句子坐标,整页唯一
  1097. 'idPrefix' => "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}",
  1098. ];
  1099. }
  1100. // 整块一起渲染:各句里的术语、句子模板(含义注对应)合在一起批量查
  1101. $rendered = app(MarkupService::class)->renderMany(
  1102. $sources,
  1103. // markdown 每句末尾附自己的脚注正文(`[^n]: …`)。编号每句从 1 起,跨句会重号,
  1104. // 整章导出时由 V3\TipitakaExportBuilder 逐句重新编号;不附正文的话 `[^n]` 无处可指
  1105. new RenderOptions(format: self::markupFormat($format), channelType: $channelType, footnote: $format === 'markdown'),
  1106. );
  1107. // 段后脚注列表只有 html 有
  1108. $noteTexts = $format === 'html' ? $this->renderFootnoteTexts($injections, $channelType) : [];
  1109. $display = [];
  1110. $notes = [];
  1111. foreach ($records as $i => $row) {
  1112. $para = (int) $row->paragraph;
  1113. foreach ($injections[$i]['notes'] as $n => $note) {
  1114. $notes[$para][] = [
  1115. 'fnId' => $note['fnId'],
  1116. 'noteHtml' => $noteTexts["{$i}:{$n}"] ?? '',
  1117. 'citeHtml' => $note['citeHtml'],
  1118. ];
  1119. }
  1120. $html = $rendered[$i] ?? '';
  1121. if (empty($html)) {
  1122. continue;
  1123. }
  1124. $sid = "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}";
  1125. $results[$para]['sentences'][] = ['sid' => $sid, 'html' => $html];
  1126. if ($format === 'html') {
  1127. $class = $isOrigin ? 'sentence origin' : 'sentence';
  1128. $display[$para][] = "<div class='{$class}' lang='{$channel->lang}' data-sid='{$sid}'>{$html}</div>";
  1129. } else {
  1130. $display[$para][] = $html;
  1131. }
  1132. }
  1133. $paliTexts = app(PaliTextService::class);
  1134. foreach ($display as $para => $lines) {
  1135. if ($format !== 'html') {
  1136. // 其他格式一行一句
  1137. $results[$para]['display'] = implode("\n", $lines);
  1138. continue;
  1139. }
  1140. // html 格式加段落外壳;段后追加段落脚注列表(本段义注/复注条目)
  1141. $content = implode('', $lines);
  1142. $level = $paliTexts->headingLevel($book, $para);
  1143. $pClass = $paliTexts->paragraph($book, $para)['class'] ?? '';
  1144. $inner = $level > 0 ? "<h{$level}>{$content}</h{$level}>" : "<div class='para-block'>{$content}</div>";
  1145. $footnoteList = $this->renderFootnoteList($notes[$para] ?? []);
  1146. $results[$para]['display'] = "<div id='para-{$para}' class='{$area} {$pClass}' data-para='{$para}'>{$inner}{$footnoteList}</div>";
  1147. }
  1148. return $results;
  1149. }
  1150. }