WikiService.php 11 KB

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