PaliContentService.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. <?php
  2. // api-v8/app/Services/PaliContentService.php
  3. namespace App\Services;
  4. use App\Http\Api\ChannelApi;
  5. use App\Http\Api\MdRender;
  6. use App\Http\Api\StudioApi;
  7. use App\Http\Api\SuggestionApi;
  8. use App\Http\Api\UserApi;
  9. use App\Models\Channel;
  10. use App\Models\Discussion;
  11. use App\Models\PaliSentence;
  12. use App\Models\PaliText;
  13. use App\Models\Sentence;
  14. use App\Models\SentSimIndex;
  15. use App\Models\Wbw;
  16. use App\Models\WbwBlock;
  17. use Illuminate\Support\Arr;
  18. use Illuminate\Support\Facades\Cache;
  19. use Illuminate\Support\Facades\Log;
  20. use Illuminate\Support\Str;
  21. class PaliContentService
  22. {
  23. protected $result = [
  24. 'uid' => '',
  25. 'title' => '',
  26. 'path' => [],
  27. 'sub_title' => '',
  28. 'summary' => '',
  29. 'content' => '',
  30. 'content_type' => 'html',
  31. 'toc' => [],
  32. 'status' => 30,
  33. 'lang' => '',
  34. 'created_at' => '',
  35. 'updated_at' => '',
  36. ];
  37. protected $wbwChannels = [];
  38. // 句子需要查询的列
  39. protected $selectCol = [
  40. 'uid',
  41. 'book_id',
  42. 'paragraph',
  43. 'word_start',
  44. 'word_end',
  45. 'channel_uid',
  46. 'content',
  47. 'content_type',
  48. 'editor_uid',
  49. 'acceptor_uid',
  50. 'pr_edit_at',
  51. 'fork_at',
  52. 'create_time',
  53. 'modify_time',
  54. 'created_at',
  55. 'updated_at',
  56. ];
  57. protected $userUuid = null;
  58. protected $debug = [];
  59. public static function _sentCanReadCount($book, $para, $start, $end, $userUuid = null)
  60. {
  61. $keyCanRead = '/channel/can-read/';
  62. if ($userUuid) {
  63. $keyCanRead .= $userUuid;
  64. } else {
  65. $keyCanRead .= 'guest';
  66. }
  67. $channelCanRead = Cache::remember(
  68. $keyCanRead,
  69. config('mint.cache.expire'),
  70. function () use ($userUuid) {
  71. return ChannelApi::getCanReadByUser($userUuid);
  72. }
  73. );
  74. $channels = Sentence::where('book_id', $book)
  75. ->where('paragraph', $para)
  76. ->where('word_start', $start)
  77. ->where('word_end', $end)
  78. ->where('strlen', '<>', 0)
  79. ->whereIn('channel_uid', $channelCanRead)
  80. ->select('channel_uid')
  81. ->groupBy('channel_uid')
  82. ->get();
  83. $channelList = [];
  84. foreach ($channels as $key => $value) {
  85. // code...
  86. if (Str::isUuid($value->channel_uid)) {
  87. $channelList[] = $value->channel_uid;
  88. }
  89. }
  90. $simId = PaliSentence::where('book', $book)
  91. ->where('paragraph', $para)
  92. ->where('word_begin', $start)
  93. ->where('word_end', $end)
  94. ->value('id');
  95. if ($simId) {
  96. $output['simNum'] = SentSimIndex::where('sent_id', $simId)->value('count');
  97. } else {
  98. $output['simNum'] = 0;
  99. }
  100. $channelInfo = Channel::whereIn('uid', $channelList)->select('type')->get();
  101. $output['tranNum'] = 0;
  102. $output['nissayaNum'] = 0;
  103. $output['commNum'] = 0;
  104. $output['originNum'] = 0;
  105. foreach ($channelInfo as $key => $value) {
  106. // code...
  107. switch ($value->type) {
  108. case 'translation':
  109. $output['tranNum']++;
  110. break;
  111. case 'nissaya':
  112. $output['nissayaNum']++;
  113. break;
  114. case 'commentary':
  115. $output['commNum']++;
  116. break;
  117. case 'original':
  118. $output['originNum']++;
  119. break;
  120. }
  121. }
  122. return $output;
  123. }
  124. private function newSent($book, $para, $word_start, $word_end)
  125. {
  126. $sent = [
  127. 'id' => "{$book}-{$para}-{$word_start}-{$word_end}",
  128. 'book' => $book,
  129. 'para' => $para,
  130. 'wordStart' => $word_start,
  131. 'wordEnd' => $word_end,
  132. 'origin' => [],
  133. 'translation' => [],
  134. 'commentaries' => [],
  135. ];
  136. if ($book < 1000) {
  137. // 生成channel 数量列表
  138. $sentId = "{$book}-{$para}-{$word_start}-{$word_end}";
  139. $channelCount = self::_sentCanReadCount($book, $para, $word_start, $word_end, $this->userUuid);
  140. $path = json_decode(PaliText::where('book', $book)->where('paragraph', $para)->value('path'), true);
  141. $sent['path'] = [];
  142. foreach ($path as $key => $value) {
  143. // code...
  144. $value['paliTitle'] = $value['title'];
  145. $sent['path'][] = $value;
  146. }
  147. $sent['tranNum'] = $channelCount['tranNum'];
  148. $sent['nissayaNum'] = $channelCount['nissayaNum'];
  149. $sent['commNum'] = $channelCount['commNum'];
  150. $sent['originNum'] = $channelCount['originNum'];
  151. $sent['simNum'] = $channelCount['simNum'];
  152. }
  153. return $sent;
  154. }
  155. /**
  156. * 根据句子库数据生成以段落为单位的文章内容
  157. * $record 句子数据
  158. * $mode read | edit | wbw
  159. * $indexChannel channel索引
  160. * $indexedHeading 标题索引 用于给段落加标题标签 <h1> ect.
  161. */
  162. public function makeContentObj($record, $mode, $indexChannel, $format = 'react')
  163. {
  164. $content = [];
  165. // 获取句子编号列表
  166. $paraIndex = [];
  167. foreach ($record as $value) {
  168. $currSentId = "{$value->book_id}-{$value->paragraph}-{$value->word_start}-{$value->word_end}";
  169. $value->sid = "{$currSentId}_{$value->channel_uid}";
  170. $currParaId = "{$value->book_id}-{$value->paragraph}";
  171. if (! isset($paraIndex[$currParaId])) {
  172. $paraIndex[$currParaId] = [];
  173. }
  174. $paraIndex[$currParaId][] = $value;
  175. }
  176. $channelsId = [];
  177. foreach ($indexChannel as $channelId => $info) {
  178. $channelsId[] = $channelId;
  179. }
  180. array_pop($channelsId);
  181. // 遍历列表查找每个句子的所有channel的数据,并填充
  182. $paragraphs = [];
  183. foreach ($paraIndex as $currParaId => $sentData) {
  184. $arrParaId = explode('-', $currParaId);
  185. $sentIndex = [];
  186. foreach ($sentData as $sent) {
  187. $currSentId = "{$sent->book_id}-{$sent->paragraph}-{$sent->word_start}-{$sent->word_end}";
  188. $sentIndex[$currSentId] = [$sent->book_id, $sent->paragraph, $sent->word_start, $sent->word_end];
  189. }
  190. $sentInPara = array_values($sentIndex);
  191. $paraProps = [
  192. 'book' => $arrParaId[0],
  193. 'para' => $arrParaId[1],
  194. 'channels' => $channelsId,
  195. 'sentences' => $sentInPara,
  196. 'mode' => $mode,
  197. 'children' => [],
  198. ];
  199. // 建立段落里面的句子列表
  200. foreach ($sentIndex as $ids => $arrSentId) {
  201. $sentNode = $this->newSent($arrSentId[0], $arrSentId[1], $arrSentId[2], $arrSentId[3]);
  202. foreach ($indexChannel as $channelId => $info) {
  203. // code...
  204. $sid = "{$ids}_{$channelId}";
  205. if (isset($info->studio)) {
  206. $studioInfo = $info->studio;
  207. } else {
  208. $studioInfo = null;
  209. }
  210. $newSent = [
  211. 'content' => '',
  212. 'html' => '',
  213. 'book' => $arrSentId[0],
  214. 'para' => $arrSentId[1],
  215. 'wordStart' => $arrSentId[2],
  216. 'wordEnd' => $arrSentId[3],
  217. 'channel' => [
  218. 'name' => $info->name,
  219. 'type' => $info->type,
  220. 'id' => $info->uid,
  221. 'lang' => $info->lang,
  222. ],
  223. 'studio' => $studioInfo,
  224. 'updateAt' => '',
  225. 'suggestionCount' => SuggestionApi::getCountBySent($arrSentId[0], $arrSentId[1], $arrSentId[2], $arrSentId[3], $channelId),
  226. ];
  227. $row = Arr::first($sentData, function ($value, $key) use ($sid) {
  228. return $value->sid === $sid;
  229. });
  230. if ($row) {
  231. $newSent['id'] = $row->uid;
  232. $newSent['content'] = $row->content;
  233. $newSent['contentType'] = $row->content_type;
  234. $newSent['html'] = '';
  235. $newSent['editor'] = UserApi::getByUuid($row->editor_uid);
  236. /**
  237. * TODO 刷库改数据
  238. * 旧版api没有更新updated_at所以造成旧版的数据updated_at数据比modify_time 要晚
  239. */
  240. $newSent['forkAt'] = $row->fork_at; //
  241. $newSent['updateAt'] = $row->updated_at; //
  242. $newSent['updateAt'] = date('Y-m-d H:i:s.', $row->modify_time / 1000).($row->modify_time % 1000).' UTC';
  243. $newSent['createdAt'] = $row->created_at;
  244. if ($mode !== 'read') {
  245. if (isset($row->acceptor_uid) && ! empty($row->acceptor_uid)) {
  246. $newSent['acceptor'] = UserApi::getByUuid($row->acceptor_uid);
  247. $newSent['prEditAt'] = $row->pr_edit_at;
  248. }
  249. }
  250. switch ($info->type) {
  251. case 'wbw':
  252. case 'original':
  253. //
  254. // 在编辑模式下。
  255. // 如果是原文,查看是否有逐词解析数据,
  256. // 有的话优先显示。
  257. // 阅读模式直接显示html原文
  258. // 传过来的数据一定有一个原文channel
  259. //
  260. if ($mode === 'read') {
  261. $newSent['content'] = '';
  262. $newSent['html'] = MdRender::render(
  263. $row->content,
  264. [$row->channel_uid],
  265. null,
  266. $mode,
  267. 'translation',
  268. $row->content_type,
  269. $format
  270. );
  271. } else {
  272. if ($row->content_type === 'json') {
  273. $newSent['channel']['type'] = 'wbw';
  274. if (isset($this->wbwChannels[0])) {
  275. $newSent['channel']['name'] = $indexChannel[$this->wbwChannels[0]]->name;
  276. $newSent['channel']['lang'] = $indexChannel[$this->wbwChannels[0]]->lang;
  277. $newSent['channel']['id'] = $this->wbwChannels[0];
  278. // 存在一个translation channel
  279. // 尝试查找逐词解析数据。找到,替换现有数据
  280. $wbwData = $this->getWbw(
  281. $arrSentId[0],
  282. $arrSentId[1],
  283. $arrSentId[2],
  284. $arrSentId[3],
  285. $this->wbwChannels[0]
  286. );
  287. if ($wbwData) {
  288. $newSent['content'] = $wbwData;
  289. $newSent['contentType'] = 'json';
  290. $newSent['html'] = '';
  291. $newSent['studio'] = $indexChannel[$this->wbwChannels[0]]->studio;
  292. }
  293. }
  294. } else {
  295. $newSent['content'] = $row->content;
  296. $newSent['html'] = MdRender::render(
  297. $row->content,
  298. [$row->channel_uid],
  299. null,
  300. $mode,
  301. 'translation',
  302. $row->content_type,
  303. $format
  304. );
  305. }
  306. }
  307. break;
  308. case 'nissaya':
  309. $newSent['html'] = Cache::remember(
  310. "/sent/{$channelId}/{$ids}/{$format}",
  311. config('mint.cache.expire'),
  312. function () use ($row, $mode, $format) {
  313. return MdRender::render(
  314. $row->content,
  315. [$row->channel_uid],
  316. null,
  317. $mode,
  318. 'nissaya',
  319. $row->content_type,
  320. $format
  321. );
  322. }
  323. );
  324. break;
  325. case 'commentary':
  326. $options = [
  327. 'debug' => $this->debug,
  328. 'format' => $format,
  329. 'mode' => $mode,
  330. 'channelType' => 'translation',
  331. 'contentType' => $row->content_type,
  332. ];
  333. $mdRender = new MdRender($options);
  334. $newSent['html'] = $mdRender->convert($row->content, $channelsId);
  335. break;
  336. default:
  337. $options = [
  338. 'debug' => $this->debug,
  339. 'format' => $format,
  340. 'mode' => $mode,
  341. 'channelType' => 'translation',
  342. 'contentType' => $row->content_type,
  343. ];
  344. $mdRender = new MdRender($options);
  345. $newSent['html'] = $mdRender->convert($row->content, [$row->channel_uid]);
  346. // Log::debug('md render', ['content' => $row->content, 'options' => $options, 'render' => $newSent['html']]);
  347. break;
  348. }
  349. } else {
  350. Log::warning('no sentence record');
  351. }
  352. switch ($info->type) {
  353. case 'wbw':
  354. case 'original':
  355. array_push($sentNode['origin'], $newSent);
  356. break;
  357. case 'commentary':
  358. array_push($sentNode['commentaries'], $newSent);
  359. break;
  360. default:
  361. array_push($sentNode['translation'], $newSent);
  362. break;
  363. }
  364. }
  365. $paraProps['children'][] = $sentNode;
  366. }
  367. $paragraphs[] = $paraProps;
  368. }
  369. return $paragraphs;
  370. }
  371. public function getWbw($book, $para, $start, $end, $channel)
  372. {
  373. /**
  374. * 非阅读模式下。原文使用逐词解析数据。
  375. * 优先加载第一个translation channel 如果没有。加载默认逐词解析。
  376. */
  377. // 获取逐词解析数据
  378. $wbwBlock = WbwBlock::where('channel_uid', $channel)
  379. ->where('book_id', $book)
  380. ->where('paragraph', $para)
  381. ->select('uid')
  382. ->first();
  383. if (! $wbwBlock) {
  384. return false;
  385. }
  386. // 找到逐词解析数据
  387. $wbwData = Wbw::where('block_uid', $wbwBlock->uid)
  388. ->whereBetween('wid', [$start, $end])
  389. ->select(['book_id', 'paragraph', 'wid', 'data', 'uid', 'editor_id', 'created_at', 'updated_at'])
  390. ->orderBy('wid')
  391. ->get();
  392. $wbwContent = [];
  393. foreach ($wbwData as $wbwrow) {
  394. $wbw = str_replace('&nbsp;', ' ', $wbwrow->data);
  395. $wbw = str_replace('<br>', ' ', $wbw);
  396. $xmlString = '<root>'.$wbw.'</root>';
  397. try {
  398. $xmlWord = simplexml_load_string($xmlString);
  399. } catch (\Exception $e) {
  400. Log::error('corpus', ['error' => $e]);
  401. continue;
  402. }
  403. $wordsList = $xmlWord->xpath('//word');
  404. foreach ($wordsList as $word) {
  405. $case = \str_replace(['#', '.'], ['$', ''], $word->case->__toString());
  406. $case = \str_replace('$$', '$', $case);
  407. $case = trim($case);
  408. $case = trim($case, '$');
  409. $wbwId = explode('-', $word->id->__toString());
  410. $wbwData = [
  411. 'uid' => $wbwrow->uid,
  412. 'book' => $wbwrow->book_id,
  413. 'para' => $wbwrow->paragraph,
  414. 'sn' => array_slice($wbwId, 2),
  415. 'word' => ['value' => $word->pali->__toString(), 'status' => 0],
  416. 'real' => ['value' => $word->real->__toString(), 'status' => 0],
  417. 'meaning' => ['value' => $word->mean->__toString(), 'status' => 0],
  418. 'type' => ['value' => $word->type->__toString(), 'status' => 0],
  419. 'grammar' => ['value' => $word->gramma->__toString(), 'status' => 0],
  420. 'case' => ['value' => $word->case->__toString(), 'status' => 0],
  421. 'parent' => ['value' => $word->parent->__toString(), 'status' => 0],
  422. 'style' => ['value' => $word->style->__toString(), 'status' => 0],
  423. 'factors' => ['value' => $word->org->__toString(), 'status' => 0],
  424. 'factorMeaning' => ['value' => $word->om->__toString(), 'status' => 0],
  425. 'confidence' => $word->cf->__toString(),
  426. 'created_at' => $wbwrow->created_at,
  427. 'updated_at' => $wbwrow->updated_at,
  428. 'hasComment' => Discussion::where('res_id', $wbwrow->uid)->exists(),
  429. ];
  430. if (isset($word->parent2)) {
  431. $wbwData['parent2']['value'] = $word->parent2->__toString();
  432. if (isset($word->parent2['status'])) {
  433. $wbwData['parent2']['status'] = (int) $word->parent2['status'];
  434. } else {
  435. $wbwData['parent2']['status'] = 0;
  436. }
  437. }
  438. if (isset($word->pg)) {
  439. $wbwData['grammar2']['value'] = $word->pg->__toString();
  440. if (isset($word->pg['status'])) {
  441. $wbwData['grammar2']['status'] = (int) $word->pg['status'];
  442. } else {
  443. $wbwData['grammar2']['status'] = 0;
  444. }
  445. }
  446. if (isset($word->rela)) {
  447. $wbwData['relation']['value'] = $word->rela->__toString();
  448. if (isset($word->rela['status'])) {
  449. $wbwData['relation']['status'] = (int) $word->rela['status'];
  450. } else {
  451. $wbwData['relation']['status'] = 7;
  452. }
  453. }
  454. if (isset($word->bmt)) {
  455. $wbwData['bookMarkText']['value'] = $word->bmt->__toString();
  456. if (isset($word->bmt['status'])) {
  457. $wbwData['bookMarkText']['status'] = (int) $word->bmt['status'];
  458. } else {
  459. $wbwData['bookMarkText']['status'] = 7;
  460. }
  461. }
  462. if (isset($word->bmc)) {
  463. $wbwData['bookMarkColor']['value'] = $word->bmc->__toString();
  464. if (isset($word->bmc['status'])) {
  465. $wbwData['bookMarkColor']['status'] = (int) $word->bmc['status'];
  466. } else {
  467. $wbwData['bookMarkColor']['status'] = 7;
  468. }
  469. }
  470. if (isset($word->note)) {
  471. $wbwData['note']['value'] = $word->note->__toString();
  472. if (isset($word->note['status'])) {
  473. $wbwData['note']['status'] = (int) $word->note['status'];
  474. } else {
  475. $wbwData['note']['status'] = 7;
  476. }
  477. }
  478. if (isset($word->cf)) {
  479. $wbwData['confidence'] = (float) $word->cf->__toString();
  480. }
  481. if (isset($word->attachments)) {
  482. $wbwData['attachments'] = json_decode($word->attachments->__toString());
  483. }
  484. if (isset($word->pali['status'])) {
  485. $wbwData['word']['status'] = (int) $word->pali['status'];
  486. }
  487. if (isset($word->real['status'])) {
  488. $wbwData['real']['status'] = (int) $word->real['status'];
  489. }
  490. if (isset($word->mean['status'])) {
  491. $wbwData['meaning']['status'] = (int) $word->mean['status'];
  492. }
  493. if (isset($word->type['status'])) {
  494. $wbwData['type']['status'] = (int) $word->type['status'];
  495. }
  496. if (isset($word->gramma['status'])) {
  497. $wbwData['grammar']['status'] = (int) $word->gramma['status'];
  498. }
  499. if (isset($word->case['status'])) {
  500. $wbwData['case']['status'] = (int) $word->case['status'];
  501. }
  502. if (isset($word->parent['status'])) {
  503. $wbwData['parent']['status'] = (int) $word->parent['status'];
  504. }
  505. if (isset($word->org['status'])) {
  506. $wbwData['factors']['status'] = (int) $word->org['status'];
  507. }
  508. if (isset($word->om['status'])) {
  509. $wbwData['factorMeaning']['status'] = (int) $word->om['status'];
  510. }
  511. $wbwContent[] = $wbwData;
  512. }
  513. }
  514. if (count($wbwContent) === 0) {
  515. return false;
  516. }
  517. return \json_encode($wbwContent, JSON_UNESCAPED_UNICODE);
  518. }
  519. public function getChannelIndex($channels, $type = null)
  520. {
  521. // 获取channel索引表
  522. $channelInfo = Channel::whereIn('uid', $channels)
  523. ->select(['uid', 'type', 'name', 'lang', 'owner_uid'])
  524. ->get();
  525. $indexChannel = [];
  526. foreach ($channels as $key => $channelId) {
  527. $channelInfo = Channel::where('uid', $channelId)
  528. ->select(['uid', 'type', 'name', 'lang', 'owner_uid'])->first();
  529. if (! $channelInfo) {
  530. Log::error('no channel id'.$channelId);
  531. continue;
  532. }
  533. if ($type !== null && $channelInfo->type !== $type) {
  534. continue;
  535. }
  536. $indexChannel[$channelId] = $channelInfo;
  537. $indexChannel[$channelId]->studio = StudioApi::getById($channelInfo->owner_uid);
  538. }
  539. return $indexChannel;
  540. }
  541. public function sentences(array $sentenceIds, array $channelIds, string $mode)
  542. {
  543. $query = [];
  544. foreach ($sentenceIds as $id) {
  545. // code...
  546. $query[] = explode('-', $id);
  547. }
  548. $record = Sentence::select($this->selectCol)
  549. ->whereIns(['book_id', 'paragraph', 'word_start', 'word_end'], $query)
  550. ->whereIn('channel_uid', $channelIds)
  551. ->get();
  552. $indexChannel = $this->getChannelIndex($channelIds);
  553. $result = $this->makeContentObj($record, $mode, $indexChannel);
  554. return $result;
  555. }
  556. public function paragraphs(int $book, int $start, int $end, array $channelIds, array $param)
  557. {
  558. $channels = [];
  559. foreach ($channelIds as $key => $channel) {
  560. if (Str::isUuid($channel)) {
  561. $channels[] = $channel;
  562. }
  563. }
  564. $channelId = false;
  565. if ($param['original']) {
  566. if ($param['mode'] === 'read') {
  567. // 阅读模式加载html格式原文
  568. $channelId = ChannelApi::getSysChannel('_System_Pali_VRI_');
  569. } else {
  570. // 翻译模式加载json格式原文
  571. $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
  572. }
  573. }
  574. if ($channelId !== false) {
  575. $channels[] = $channelId;
  576. }
  577. // 获取channel索引表
  578. $tranChannels = [];
  579. $channelInfo = Channel::whereIn('uid', $channels)
  580. ->select(['uid', 'type', 'lang', 'name'])->get();
  581. foreach ($channelInfo as $key => $value) {
  582. // code...
  583. if ($value->type === 'translation') {
  584. $tranChannels[] = $value->uid;
  585. }
  586. }
  587. $indexChannel = [];
  588. $paliService = app(PaliContentService::class);
  589. $indexChannel = $paliService->getChannelIndex($channels);
  590. // the end of channel
  591. // content
  592. $record = Sentence::select($this->selectCol)
  593. ->where('book_id', $book)
  594. ->whereBetween('paragraph', [$start, $end])
  595. ->whereIn('channel_uid', $channels)
  596. ->orderBy('paragraph')
  597. ->orderBy('word_start')
  598. ->get();
  599. $result = $paliService->makeContentObj($record, $param['mode'], $indexChannel, $param['format']);
  600. return $result;
  601. }
  602. /**
  603. * 阅读模式渲染单个段落。
  604. * 直接从 sentences 表取单个 channel 的记录,渲染成 html。
  605. * 与 paragraphs() 不同:没有译文的句子不保留占位,有多少句子输出多少句子。
  606. *
  607. * @return array{para: int, display: string, sentences: array<int, array{sid: string, html: string}>}
  608. */
  609. public function readParagraph(int $book, int $para, string $channelUid, string $format = 'html'): array
  610. {
  611. $level = $this->paragraphLevel($book, $para);
  612. // 缓存句子,段落外壳与标题级别有关,不进缓存
  613. $key = self::paragraphCacheKey($book, $para, $channelUid, $format);
  614. $cached = Cache::remember(
  615. $key,
  616. config('mint.cache.expire'),
  617. function () use ($book, $para, $channelUid, $format) {
  618. return $this->renderReadSentences($book, $para, $channelUid, $format);
  619. }
  620. );
  621. $result = [
  622. 'para' => $para,
  623. 'display' => '',
  624. 'sentences' => $cached['sentences'],
  625. ];
  626. if (count($cached['display']) === 0) {
  627. return $result;
  628. }
  629. if ($format === 'html') {
  630. // html 格式加段落外壳;段后追加段落脚注列表(本段义注/复注条目)
  631. $content = implode('', $cached['display']);
  632. $inner = $level > 0 ? "<h{$level}>{$content}</h{$level}>" : "<div class='para-block'>{$content}</div>";
  633. $footnoteList = $this->renderFootnoteList($cached['notes'] ?? []);
  634. $result['display'] = "<div id='para-{$para}' class='{$cached['area']}' data-para='{$para}'>{$inner}{$footnoteList}</div>";
  635. } else {
  636. // 其他格式一行一句
  637. $result['display'] = implode("\n", $cached['display']);
  638. }
  639. return $result;
  640. }
  641. /**
  642. * 段落是章节标题时返回标题级别,否则 0
  643. */
  644. public function paragraphLevel(int $book, int $para): int
  645. {
  646. $level = PaliText::where('book', $book)
  647. ->where('paragraph', $para)
  648. ->where('level', '<', 8)
  649. ->value('level');
  650. return $level ? (int) $level : 0;
  651. }
  652. /**
  653. * 阅读模式支持的全部格式。forgetParagraph 需要逐格式清除缓存 key。
  654. *
  655. * @var array<int, string>
  656. */
  657. private const FORMATS = ['html', 'markdown', 'react', 'text'];
  658. /**
  659. * 义注对应(commentary)批注最多渲染几句。
  660. * 一条批注可能挂着十几句义注,全铺进边注会把正文挤没,只取前几句。
  661. */
  662. private const MAX_COMMENTARY_SENTENCES = 3;
  663. /**
  664. * 段落阅读模式缓存的 key
  665. */
  666. public static function paragraphCacheKey(int $book, int $para, string $channelUid, string $format): string
  667. {
  668. return "/read-para/{$book}-{$para}/{$channelUid}/{$format}";
  669. }
  670. /**
  671. * 删除某个段落的阅读模式缓存。句子有增改删时调用,下次 readParagraph 自动重建。
  672. */
  673. public static function forgetParagraph(int $book, int $para, string $channelUid): void
  674. {
  675. foreach (self::FORMATS as $format) {
  676. Cache::forget(self::paragraphCacheKey($book, $para, $channelUid, $format));
  677. }
  678. }
  679. /**
  680. * 段落批注内嵌:把锚定到该句子的批注渲染成 {{note}} 模板,按位置插入句子内容。
  681. *
  682. * 两种批注一起注入,除出处外处理完全一样:
  683. * - `type='commentary'`(注释书对应):content 是义注 / 复注的句子模板
  684. * `{{book-para-start-end}}`,渲染成这几句的译文,并追加 <cite> 作为跳转锚点;
  685. * - `type='note'`(普通边注):content 就是注解正文(markdown),没有出处,不出 <cite>。
  686. *
  687. * 同一句可能有多条批注,按 pos_end 倒序插入 —— 先插靠后的,避免先插入的
  688. * 模板改变后面位置的字符偏移(见 docs/reading-annotations.md §4)。
  689. */
  690. protected function injectAnnotationNotes(Sentence $row, string $channelType): array
  691. {
  692. $content = (string) $row->content;
  693. $result = ['content' => $content, 'notes' => []];
  694. $notes = Discussion::where('res_type', 'sentence')
  695. ->where('res_id', $row->uid)
  696. ->whereIn('type', Discussion::INJECTED_TYPES)
  697. ->get();
  698. if ($notes->isEmpty()) {
  699. return $result;
  700. }
  701. $sid = "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}";
  702. $len = mb_strlen($content, 'UTF-8');
  703. // 插入顺序:按插入点倒序(先插靠后的,免得前面的插入改变后面的偏移);
  704. // 插入点相同的,按义注原文的先后倒序——同一位置后插入的排在前面,
  705. // 倒序插入后读起来就是义注原文顺序。插入点与下面的越界处理口径一致
  706. // (null / 越界都算句尾)。义注坐标取 content 第一句的 book-para-start;
  707. // 普通 note 没有坐标,取 0,同一插入点上读起来排在义注对应之前。
  708. $notes = $notes->sort(function ($a, $b) use ($len) {
  709. $key = function ($note) use ($len) {
  710. $pos = $note->pos_end;
  711. if ($pos === null || $pos < 0 || $pos > $len) {
  712. $pos = $len;
  713. }
  714. preg_match('/\{\{(\d+)-(\d+)-(\d+)-\d+\}\}/', (string) $note->content, $m);
  715. return [$pos, (int) ($m[1] ?? 0), (int) ($m[2] ?? 0), (int) ($m[3] ?? 0)];
  716. };
  717. return $key($b) <=> $key($a);
  718. })->values();
  719. $collected = [];
  720. foreach ($notes as $note) {
  721. $noteContent = trim((string) $note->content);
  722. if ($noteContent === '') {
  723. continue;
  724. }
  725. $sents = [];
  726. if ($note->type === Discussion::TYPE_COMMENTARY) {
  727. // content 是一个或多个义注句子模板 {{book-para-start-end}}(一个词可能由义注
  728. // 多句解释,按顺序并列,如 {{135-404-50-54}}{{135-404-55-65}})。
  729. // 不是这种格式的记录不认,跳过——不插角标,也不进脚注列表。
  730. if (! preg_match('/^(?:\{\{\d+-\d+-\d+-\d+\}\}\s*)+$/', $noteContent)) {
  731. continue;
  732. }
  733. preg_match_all('/\{\{(\d+)-(\d+)-(\d+)-(\d+)\}\}/', $noteContent, $sents, PREG_SET_ORDER);
  734. // 义注正文只需译文(不要巴利原文):把每个裸句模板 {{book-para-start-end}}
  735. // 转成 {{sent|id=…|text=translation}},让 sent 模板只输出 translation。
  736. // 句子可能有很多条,只渲染前 MAX_COMMENTARY_SENTENCES 句;
  737. // 跳转锚点仍指向第一句,点进去能看到完整义注。
  738. $source = implode(' ', array_map(
  739. fn ($s) => '{{sent|id='.$s[1].'-'.$s[2].'-'.$s[3].'-'.$s[4].'|text=translation}}',
  740. array_slice($sents, 0, self::MAX_COMMENTARY_SENTENCES)
  741. ));
  742. } else {
  743. // 普通边注:content 就是注解正文,照原样渲染。
  744. $source = $noteContent;
  745. }
  746. // 边注实际内容:先用 MdRender 渲染出来,再放进 {{note|text=…}} ——
  747. // 直接嵌套 {{…}} 会被 wiki2xml 的平铺替换破坏。
  748. // 用 text 格式渲染:避免「1.」被 markdown 解释成有序列表,
  749. // 产生 <ol></p></p> 这类坏 HTML 把 sidenote 的闭合结构破坏、吞掉后续正文。
  750. $noteHtml = MdRender::render(
  751. $source,
  752. [$row->channel_uid],
  753. null,
  754. 'read',
  755. $channelType,
  756. 'markdown',
  757. 'text'
  758. );
  759. // 义注被截断时补省略号,提示后面还有;想看全文点 <cite> 跳过去。
  760. if (count($sents) > self::MAX_COMMENTARY_SENTENCES) {
  761. $noteHtml = rtrim($noteHtml).'...';
  762. }
  763. $pos = $note->pos_end;
  764. if ($pos === null || $pos < 0 || $pos > $len) {
  765. $pos = $len;
  766. }
  767. // 出处只有 commentary 有。跳转目标(义注书-段-起-止)同时挂在 <cite> 和角标
  768. // <label> 上,前者用于「点链接跳页」,后者用于平板双栏「点角标跨栏高亮」。
  769. // 多句时跳转到第一句(义注对这个词的解释从那里开始)。
  770. $citeHtml = '';
  771. $citeParam = '';
  772. if ($sents) {
  773. $m = $sents[0];
  774. $target = ' data-book="'.$m[1].'" data-para="'.$m[2].'" data-start="'.$m[3].'" data-end="'.$m[4].'"';
  775. $citeHtml = '<cite class="anno-jump"'.$target.'>义注</cite>';
  776. $citeParam = '|cite=义注'
  777. .'|citelink='.$m[1].'-'.$m[2].'-'.$m[3].'-'.$m[4];
  778. }
  779. // 用 {{note}} 模板渲染 tufte sidenote(label + input + span.sidenote),
  780. // 复用 render_note() 的结构,不再手拼 sidenote HTML。
  781. // text 传已预渲染的纯文本(嵌套 {{…}} 会被 wiki2xml 平铺替换破坏)。
  782. $noteTplInline = '{{note|text='.$noteHtml.$citeParam.'}}';
  783. $content = mb_substr($content, 0, $pos, 'UTF-8')
  784. .$noteTplInline
  785. .mb_substr($content, $pos, null, 'UTF-8');
  786. // 收集脚注列表条目(倒序插入,最后反转回阅读顺序)
  787. $collected[] = [
  788. 'fnId' => 'fn-'.$note->id,
  789. 'noteHtml' => $noteHtml,
  790. 'citeHtml' => $citeHtml,
  791. ];
  792. }
  793. $result['notes'] = array_reverse($collected);
  794. $result['content'] = $content;
  795. Log::info('reading-annotations: inject', [
  796. 'sid' => $sid,
  797. 'count' => $notes->count(),
  798. 'content' => $content,
  799. ]);
  800. return $result;
  801. }
  802. /**
  803. * 段落脚注列表:把本段的注释条目逐条列在段后,每条默认收起为可配置行数(见阅读器 CSS)。
  804. */
  805. protected function renderFootnoteList(array $notes): string
  806. {
  807. if (empty($notes)) {
  808. return '';
  809. }
  810. $html = '<div class="anno-footnotes">';
  811. foreach ($notes as $note) {
  812. $html .= '<div class="anno-footnote">'
  813. .'<input type="checkbox" id="'.$note['fnId'].'" class="anno-fn-toggle"/>'
  814. .'<label for="'.$note['fnId'].'" class="anno-fn-label">'
  815. .'<span class="anno-fn-body">'.e($note['noteHtml']).'</span>'
  816. .'</label>'
  817. .$note['citeHtml']
  818. .'</div>';
  819. }
  820. $html .= '</div>';
  821. return $html;
  822. }
  823. /**
  824. * 渲染段落里的句子。不含段落外壳,可直接缓存。
  825. *
  826. * @return array{area: string, display: array<int, string>, sentences: array<int, array{sid: string, html: string}>}
  827. */
  828. protected function renderReadSentences(int $book, int $para, string $channelUid, string $format): array
  829. {
  830. $result = ['area' => 'translation', 'display' => [], 'sentences' => []];
  831. $channel = Channel::where('uid', $channelUid)
  832. ->select(['uid', 'type', 'lang', 'name'])->first();
  833. if (! $channel) {
  834. return $result;
  835. }
  836. $isOrigin = $channel->type === 'original' || $channel->type === 'wbw';
  837. $channelType = $channel->type === 'nissaya' ? 'nissaya' : 'translation';
  838. $result['area'] = $isOrigin ? 'original' : 'translation';
  839. $records = Sentence::select($this->selectCol)
  840. ->where('book_id', $book)
  841. ->where('paragraph', $para)
  842. ->where('channel_uid', $channelUid)
  843. ->orderBy('word_start')
  844. ->get();
  845. $allNotes = [];
  846. foreach ($records as $row) {
  847. $injected = $this->injectAnnotationNotes($row, $channelType);
  848. $content = $injected['content'];
  849. $allNotes = array_merge($allNotes, $injected['notes']);
  850. $html = MdRender::render(
  851. $content,
  852. [$row->channel_uid],
  853. null,
  854. 'read',
  855. $channelType,
  856. $row->content_type,
  857. $format
  858. );
  859. if (empty($html)) {
  860. continue;
  861. }
  862. $sid = "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}";
  863. $result['sentences'][] = ['sid' => $sid, 'html' => $html];
  864. if ($format === 'html') {
  865. $class = $isOrigin ? 'sentence origin' : 'sentence';
  866. $result['display'][] = "<div class='{$class}' data-sid='{$sid}'>{$html}</div>";
  867. } else {
  868. $result['display'][] = $html;
  869. }
  870. }
  871. $result['notes'] = $allNotes;
  872. return $result;
  873. }
  874. }