WikiService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Channel;
  4. use App\Models\DhammaTerm;
  5. use App\Models\TermCategory;
  6. use App\Services\Markup\Format;
  7. use App\Services\Markup\MarkupService;
  8. use App\Services\Markup\RenderOptions;
  9. use App\Services\V3\ChannelAbilityService;
  10. use Illuminate\Auth\Access\AuthorizationException;
  11. use Illuminate\Database\Eloquent\Builder;
  12. use Illuminate\Database\Eloquent\ModelNotFoundException;
  13. use Illuminate\Support\Collection;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Str;
  16. /**
  17. * library 百科页(`/library/wiki/*`)的数据:按分类列词条、词条详情、相关词条、其它版本。
  18. *
  19. * 直接查库,不经 OpenSearch:质量取 dhamma_terms.quality,分类取 term_categories(v3 写入时从正文
  20. * `{{category|…}}` 抽出),摘要取 summary 或正文第一段。正文用新渲染器({@see MarkupService})出 HTML。
  21. *
  22. * 列表、相关词条、其它版本只列公开的:所在 channel 会被列出(status 30 或系统 channel,
  23. * {@see ChannelAbilityService::scopeListable()}),或 studio 级术语(不属于任何 channel)。
  24. * 按 guid 打开的词条页按「能访问」判(公开不列出的也能看,私有 403)。
  25. */
  26. class WikiService
  27. {
  28. /** 质量等级,数值越小越高;空按 pending */
  29. public const QUALITY_RANK = ['featured' => 1, 'standard' => 2, 'draft' => 3, 'pending' => 4];
  30. public function __construct(
  31. private readonly ChannelAbilityService $channels,
  32. private readonly MarkupService $markup,
  33. ) {}
  34. /**
  35. * 某组分类下的词条,质量不低于 $minQuality。同一个「词 + 释义」只留质量最高的一条。
  36. *
  37. * @param list<string> $categories
  38. * @return list<array{id: string, word: string, zh: string, quality: string}>
  39. */
  40. public function categoryEntries(array $categories, string $lang, string $minQuality): array
  41. {
  42. if ($categories === []) {
  43. return [];
  44. }
  45. $maxRank = self::QUALITY_RANK[$minQuality] ?? 4;
  46. $terms = $this->publicTerms($lang)
  47. ->whereIn('guid', TermCategory::query()->selectRaw('term_guid::text')->whereIn('category', $categories))
  48. ->orderBy('word')
  49. ->limit(1000)
  50. ->get(['guid', 'word', 'meaning', 'quality']);
  51. $unique = [];
  52. foreach ($terms as $term) {
  53. $quality = $term->quality ?? 'pending';
  54. $rank = self::QUALITY_RANK[$quality] ?? 4;
  55. if ($rank > $maxRank) {
  56. continue;
  57. }
  58. $key = mb_strtolower(trim($term->word).'|'.trim($term->meaning));
  59. if (isset($unique[$key]) && (self::QUALITY_RANK[$unique[$key]['quality']] ?? 4) <= $rank) {
  60. continue;
  61. }
  62. $unique[$key] = ['id' => (string) $term->guid, 'word' => (string) $term->word, 'zh' => (string) $term->meaning, 'quality' => $quality];
  63. }
  64. return array_values($unique);
  65. }
  66. /**
  67. * 按 guid 或词找要显示的词条。
  68. *
  69. * - guid:这一条,拿到链接就能看(公开不列出的也行),私有 channel 的 403
  70. * - 词:先找该语言社区 channel(`_community_translation_{lang}_`)里的,没有就取公开词条里质量最高、最近更新的
  71. *
  72. * @throws AuthorizationException guid 指向私有 channel 的术语
  73. */
  74. public function find(string $lang, string $wordOrId): ?DhammaTerm
  75. {
  76. if (Str::isUuid($wordOrId)) {
  77. return $this->accessibleTerm($wordOrId);
  78. }
  79. $community = Channel::where('name', '_community_translation_'.strtolower($lang).'_')
  80. ->where('owner_uid', config('mint.admin.root_uuid'))
  81. ->value('uid');
  82. if ($community) {
  83. $term = DhammaTerm::where('channal', $community)->where('word', $wordOrId)->first();
  84. if ($term) {
  85. return $term;
  86. }
  87. }
  88. return $this->publicTerms($lang)
  89. ->where('word', $wordOrId)
  90. ->orderByRaw("case coalesce(quality, 'pending') when 'featured' then 1 when 'standard' then 2 when 'draft' then 3 else 4 end")
  91. ->orderByDesc('updated_at')
  92. ->first();
  93. }
  94. /**
  95. * 按 guid 取一条:拿到链接就能看,与「会不会被列出」无关。
  96. *
  97. * channel 是公开(30)或公开不列出(20)、系统 channel、或 studio 级术语都能看;
  98. * library 没有登录态,私有 channel 的一律 403({@see ChannelAbilityService::assertReadable()}),
  99. * 术语或它所在的 channel 不存在(含软删)返回 null(404)。
  100. *
  101. * @throws AuthorizationException
  102. */
  103. private function accessibleTerm(string $guid): ?DhammaTerm
  104. {
  105. $term = DhammaTerm::where('guid', $guid)->first();
  106. if ($term === null) {
  107. return null;
  108. }
  109. $channelUid = $term->channelUid();
  110. if ($channelUid !== null) {
  111. try {
  112. $this->channels->assertReadable($channelUid, null);
  113. } catch (ModelNotFoundException) {
  114. return null;
  115. }
  116. }
  117. return $term;
  118. }
  119. /**
  120. * 重定向的目标(`word` 或 `word@tag`):先在同一 channel(studio 级的在同一 owner 的 studio 级术语)里找,
  121. * 找不到返回 null(读者停在原词条上)。
  122. */
  123. public function redirectTarget(DhammaTerm $term): ?DhammaTerm
  124. {
  125. $redirect = trim((string) $term->redirect);
  126. if ($redirect === '') {
  127. return null;
  128. }
  129. [$word, $tag] = array_pad(explode('@', $redirect, 2), 2, '');
  130. $query = DhammaTerm::query()->where('word', $word);
  131. $tag === ''
  132. ? $query->where(fn (Builder $q) => $q->whereNull('tag')->orWhere('tag', ''))
  133. : $query->where('tag', $tag);
  134. $term->channelUid() !== null
  135. ? $query->where('channal', $term->channelUid())
  136. : $query->studioLevel()->where('owner', $term->owner);
  137. $target = $query->first();
  138. return $target && $target->guid !== $term->guid ? $target : null;
  139. }
  140. /**
  141. * 正文 HTML:摘要 + 正文(摘要在前,不加分隔),用词条所在 channel 解析模板。
  142. *
  143. * 正文里的分类(`{{category|…}}`,渲染器输出 `span.tpl-category[data-category]`)换成指向
  144. * 该分类词条列表的链接,$lang 是当前百科页的语言。
  145. */
  146. public function contentHtml(DhammaTerm $term, string $lang): string
  147. {
  148. $source = trim(trim((string) $term->summary)."\n\n".(string) $term->note);
  149. $html = (string) $this->markup->render($source, new RenderOptions(
  150. format: Format::Html,
  151. channels: $term->channal ? [$term->channal] : [],
  152. contentType: $term->effectiveContentType(),
  153. lang: $term->language ?: 'zh-Hans',
  154. ));
  155. return (string) preg_replace_callback(
  156. '#<span class="tpl-category" data-category="([^"]*)">(.*?)</span>#u',
  157. function (array $m) use ($lang) {
  158. $name = html_entity_decode($m[1], ENT_QUOTES | ENT_HTML5);
  159. $url = route('library.wiki.index', ['lang' => $lang, 'category' => $name]);
  160. return '<a class="tpl-category" href="'.e($url).'">'.$m[2].'</a>';
  161. },
  162. $html,
  163. );
  164. }
  165. /**
  166. * 这条词条的分类(按正文里出现的顺序)。
  167. *
  168. * @return list<string>
  169. */
  170. public function categoriesOf(DhammaTerm $term): array
  171. {
  172. return TermCategory::where('term_guid', $term->guid)->orderBy('position')->pluck('category')->all();
  173. }
  174. /**
  175. * 与它共享分类的其它公开词条,最多 $limit 条,共享分类越多越靠前。
  176. *
  177. * @param list<string> $categories
  178. * @return list<array{word: string, zh: string, lang: string}>
  179. */
  180. public function related(DhammaTerm $term, array $categories, int $limit = 5): array
  181. {
  182. if ($categories === []) {
  183. return [];
  184. }
  185. $shared = TermCategory::query()
  186. ->selectRaw('term_guid::text as guid, count(*) as shared')
  187. ->whereIn('category', $categories)
  188. ->where('term_guid', '<>', $term->guid)
  189. ->groupBy('term_guid');
  190. return $this->publicTerms(null)
  191. ->joinSub($shared, 'shared', 'shared.guid', '=', 'dhamma_terms.guid')
  192. ->orderByDesc('shared.shared')
  193. ->orderBy('dhamma_terms.word')
  194. ->limit($limit)
  195. ->get(['dhamma_terms.word', 'dhamma_terms.meaning', 'dhamma_terms.language'])
  196. ->map(fn (DhammaTerm $t) => ['word' => (string) $t->word, 'zh' => (string) $t->meaning, 'lang' => (string) $t->language])
  197. ->all();
  198. }
  199. /**
  200. * 同一个词的其它公开版本(其它 channel、其它语言),最多 $limit 条。摘要是纯文本。
  201. *
  202. * @return list<array{type: string, id: string, lang: string, title: string, quality: string, category: string, snippet: string, updated: string}>
  203. */
  204. public function otherVersions(DhammaTerm $term, int $limit = 10): array
  205. {
  206. $versions = $this->publicTerms(null)
  207. ->where('word', $term->word)
  208. ->where('guid', '<>', $term->guid)
  209. ->orderByDesc('updated_at')
  210. ->limit($limit)
  211. ->get(['guid', 'word', 'meaning', 'language', 'quality', 'summary', 'note', 'content_type', 'channal', 'updated_at']);
  212. return $this->withSnippets($versions)->map(fn (DhammaTerm $t) => [
  213. 'type' => 'term',
  214. 'id' => (string) $t->guid,
  215. 'lang' => (string) $t->language,
  216. 'title' => (string) $t->meaning,
  217. 'quality' => $t->quality ?? 'pending',
  218. 'category' => '法义术语',
  219. 'snippet' => (string) $t->snippet,
  220. 'updated' => $t->updated_at?->toIso8601String() ?? '',
  221. ])->all();
  222. }
  223. /**
  224. * 公开的词条:所在 channel 会被列出,或 studio 级术语。$lang 给了就只要这种语言的。
  225. *
  226. * @return Builder<DhammaTerm>
  227. */
  228. private function publicTerms(?string $lang): Builder
  229. {
  230. $query = DhammaTerm::query()->where(function (Builder $q) {
  231. $q->studioLevel()->orWhereIn('channal', function ($sub) {
  232. $sub->selectRaw('uid::text')->from('channels')->whereNull('deleted_at');
  233. $this->channels->scopeListable($sub, null);
  234. });
  235. });
  236. if ($lang !== null) {
  237. $query->whereIn(DB::raw('lower(language)'), $this->languageVariants($lang));
  238. }
  239. return $query;
  240. }
  241. /**
  242. * 库里的语言写法不统一(zh-Hans / zh-hans / zh)。
  243. *
  244. * @return list<string>
  245. */
  246. private function languageVariants(string $lang): array
  247. {
  248. $lang = strtolower($lang);
  249. return match ($lang) {
  250. 'zh-hans', 'zh-cn', 'zh' => ['zh-hans', 'zh-cn', 'zh'],
  251. 'zh-hant', 'zh-tw' => ['zh-hant', 'zh-tw'],
  252. default => [$lang],
  253. };
  254. }
  255. /**
  256. * 给每条挂上纯文本摘要(`snippet`):有 summary 用它,没有取正文第一段。整批渲染一次。
  257. *
  258. * @param Collection<int, DhammaTerm> $terms
  259. * @return Collection<int, DhammaTerm>
  260. */
  261. private function withSnippets(Collection $terms): Collection
  262. {
  263. $items = [];
  264. foreach ($terms as $term) {
  265. $summary = trim((string) $term->summary);
  266. $items[$term->guid] = [
  267. 'source' => $summary !== '' ? $summary : (string) $term->note,
  268. 'channels' => $term->channal ? [$term->channal] : [],
  269. 'contentType' => $term->effectiveContentType(),
  270. ];
  271. }
  272. $texts = $items === [] ? [] : $this->markup->renderMany($items, new RenderOptions(format: Format::Text));
  273. return $terms->each(function (DhammaTerm $term) use ($texts) {
  274. $text = (string) ($texts[$term->guid] ?? '');
  275. $first = '';
  276. foreach (preg_split('/\n/u', $text) ?: [] as $line) {
  277. if (trim($line) !== '') {
  278. $first = trim($line);
  279. break;
  280. }
  281. }
  282. $term->snippet = Str::limit($first, 200);
  283. });
  284. }
  285. }