PaliContentService.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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. * 段落阅读模式缓存的 key
  660. */
  661. public static function paragraphCacheKey(int $book, int $para, string $channelUid, string $format): string
  662. {
  663. return "/read-para/{$book}-{$para}/{$channelUid}/{$format}";
  664. }
  665. /**
  666. * 删除某个段落的阅读模式缓存。句子有增改删时调用,下次 readParagraph 自动重建。
  667. */
  668. public static function forgetParagraph(int $book, int $para, string $channelUid): void
  669. {
  670. foreach (self::FORMATS as $format) {
  671. Cache::forget(self::paragraphCacheKey($book, $para, $channelUid, $format));
  672. }
  673. }
  674. /**
  675. * 段落注释(义注/复注内嵌):把锚定到该句子的注释记录渲染成 {{note}} 模板,
  676. * 按位置插入句子内容,并在其后追加 <cite> 作为跳转锚点。
  677. *
  678. * 同一句可能有多条注释,按 pos_end 倒序插入 —— 先插靠后的,避免先插入的
  679. * 模板改变后面位置的字符偏移(见 docs/reading-annotations.md §4)。
  680. */
  681. protected function injectAnnotationNotes(Sentence $row, string $channelType): array
  682. {
  683. $content = (string) $row->content;
  684. $result = ['content' => $content, 'notes' => []];
  685. $notes = Discussion::where('res_type', 'sentence')
  686. ->where('res_id', $row->uid)
  687. ->where('type', 'note')
  688. ->get();
  689. if ($notes->isEmpty()) {
  690. return $result;
  691. }
  692. $sid = "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}";
  693. $len = mb_strlen($content, 'UTF-8');
  694. // 插入顺序:按插入点倒序(先插靠后的,免得前面的插入改变后面的偏移);
  695. // 插入点相同的,按义注原文的先后倒序——同一位置后插入的排在前面,
  696. // 倒序插入后读起来就是义注原文顺序。插入点与下面的越界处理口径一致
  697. //(null / 越界都算句尾)。义注坐标取 content 第一句的 book-para-start。
  698. $notes = $notes->sort(function ($a, $b) use ($len) {
  699. $key = function ($note) use ($len) {
  700. $pos = $note->pos_end;
  701. if ($pos === null || $pos < 0 || $pos > $len) {
  702. $pos = $len;
  703. }
  704. preg_match('/\{\{(\d+)-(\d+)-(\d+)-\d+\}\}/', (string) $note->content, $m);
  705. return [$pos, (int) ($m[1] ?? 0), (int) ($m[2] ?? 0), (int) ($m[3] ?? 0)];
  706. };
  707. return $key($b) <=> $key($a);
  708. })->values();
  709. $collected = [];
  710. foreach ($notes as $note) {
  711. // content 是一个或多个义注句子模板 {{book-para-start-end}}(一个词可能由义注
  712. // 多句解释,按顺序并列,如 {{135-404-50-54}}{{135-404-55-65}})。
  713. // 不是这种格式的记录不认,跳过——不插角标,也不进脚注列表。
  714. $noteContent = trim((string) $note->content);
  715. if (! preg_match('/^(?:\{\{\d+-\d+-\d+-\d+\}\}\s*)+$/', $noteContent)) {
  716. continue;
  717. }
  718. preg_match_all('/\{\{(\d+)-(\d+)-(\d+)-(\d+)\}\}/', $noteContent, $sents, PREG_SET_ORDER);
  719. // 义注实际内容:先用 MdRender 渲染义注句子模板得到,
  720. // 再放进 {{note|text=…}} —— 直接嵌套 {{…}} 会被 wiki2xml 的平铺替换破坏。
  721. // 用 text 格式渲染义注内容:避免「1.」被 markdown 解释成有序列表,
  722. // 产生 <ol></p></p> 这类坏 HTML 把 sidenote 的闭合结构破坏、吞掉后续正文。
  723. // 义注正文只需译文(不要巴利原文):把每个裸句模板 {{book-para-start-end}}
  724. // 转成 {{sent|id=…|text=translation}},让 sent 模板只输出 translation。
  725. $noteTpl = implode(' ', array_map(
  726. fn ($s) => '{{sent|id='.$s[1].'-'.$s[2].'-'.$s[3].'-'.$s[4].'|text=translation}}',
  727. $sents
  728. ));
  729. $noteHtml = MdRender::render(
  730. $noteTpl,
  731. [$row->channel_uid],
  732. null,
  733. 'read',
  734. $channelType,
  735. 'markdown',
  736. 'text'
  737. );
  738. $pos = $note->pos_end;
  739. if ($pos === null || $pos < 0 || $pos > $len) {
  740. $pos = $len;
  741. }
  742. // 跳转目标(义注书-段-起-止):同时挂在 <cite> 和角标 <label> 上,
  743. // 前者用于「点链接跳页」,后者用于平板双栏「点角标跨栏高亮」。
  744. // 用 {{note}} 模板渲染 tufte sidenote(label + input + span.sidenote),
  745. // 复用 render_note() 的结构,不再手拼 sidenote HTML。
  746. // text 传已预渲染的纯文本译文(嵌套 {{…}} 会被 wiki2xml 平铺替换破坏)。
  747. // 多句时跳转到第一句(义注对这个词的解释从那里开始)。
  748. $m = $sents[0];
  749. $target = ' data-book="'.$m[1].'" data-para="'.$m[2].'" data-start="'.$m[3].'" data-end="'.$m[4].'"';
  750. $citeHtml = '<cite class="anno-jump"'.$target.'>义注</cite>';
  751. $noteTplInline = '{{note|text='.$noteHtml
  752. .'|cite=义注'
  753. .'|citelink='.$m[1].'-'.$m[2].'-'.$m[3].'-'.$m[4].'}}';
  754. $content = mb_substr($content, 0, $pos, 'UTF-8')
  755. .$noteTplInline
  756. .mb_substr($content, $pos, null, 'UTF-8');
  757. // 收集脚注列表条目(倒序插入,最后反转回阅读顺序)
  758. $collected[] = [
  759. 'fnId' => 'fn-'.$note->id,
  760. 'noteHtml' => $noteHtml,
  761. 'citeHtml' => $citeHtml,
  762. ];
  763. }
  764. $result['notes'] = array_reverse($collected);
  765. $result['content'] = $content;
  766. Log::info('reading-annotations: inject', [
  767. 'sid' => $sid,
  768. 'count' => $notes->count(),
  769. 'content' => $content,
  770. ]);
  771. return $result;
  772. }
  773. /**
  774. * 段落脚注列表:把本段的注释条目逐条列在段后,每条默认收起为可配置行数(见阅读器 CSS)。
  775. */
  776. protected function renderFootnoteList(array $notes): string
  777. {
  778. if (empty($notes)) {
  779. return '';
  780. }
  781. $html = '<div class="anno-footnotes">';
  782. foreach ($notes as $note) {
  783. $html .= '<div class="anno-footnote">'
  784. .'<input type="checkbox" id="'.$note['fnId'].'" class="anno-fn-toggle"/>'
  785. .'<label for="'.$note['fnId'].'" class="anno-fn-label">'
  786. .'<span class="anno-fn-body">'.e($note['noteHtml']).'</span>'
  787. .'</label>'
  788. .$note['citeHtml']
  789. .'</div>';
  790. }
  791. $html .= '</div>';
  792. return $html;
  793. }
  794. /**
  795. * 渲染段落里的句子。不含段落外壳,可直接缓存。
  796. *
  797. * @return array{area: string, display: array<int, string>, sentences: array<int, array{sid: string, html: string}>}
  798. */
  799. protected function renderReadSentences(int $book, int $para, string $channelUid, string $format): array
  800. {
  801. $result = ['area' => 'translation', 'display' => [], 'sentences' => []];
  802. $channel = Channel::where('uid', $channelUid)
  803. ->select(['uid', 'type', 'lang', 'name'])->first();
  804. if (! $channel) {
  805. return $result;
  806. }
  807. $isOrigin = $channel->type === 'original' || $channel->type === 'wbw';
  808. $channelType = $channel->type === 'nissaya' ? 'nissaya' : 'translation';
  809. $result['area'] = $isOrigin ? 'original' : 'translation';
  810. $records = Sentence::select($this->selectCol)
  811. ->where('book_id', $book)
  812. ->where('paragraph', $para)
  813. ->where('channel_uid', $channelUid)
  814. ->orderBy('word_start')
  815. ->get();
  816. $allNotes = [];
  817. foreach ($records as $row) {
  818. $injected = $this->injectAnnotationNotes($row, $channelType);
  819. $content = $injected['content'];
  820. $allNotes = array_merge($allNotes, $injected['notes']);
  821. $html = MdRender::render(
  822. $content,
  823. [$row->channel_uid],
  824. null,
  825. 'read',
  826. $channelType,
  827. $row->content_type,
  828. $format
  829. );
  830. if (empty($html)) {
  831. continue;
  832. }
  833. $sid = "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}";
  834. $result['sentences'][] = ['sid' => $sid, 'html' => $html];
  835. if ($format === 'html') {
  836. $class = $isOrigin ? 'sentence origin' : 'sentence';
  837. $result['display'][] = "<div class='{$class}' data-sid='{$sid}'>{$html}</div>";
  838. } else {
  839. $result['display'][] = $html;
  840. }
  841. }
  842. $result['notes'] = $allNotes;
  843. return $result;
  844. }
  845. }