TermService.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Exceptions\BusinessException;
  4. use App\Facades\RedisCache;
  5. use App\Models\Channel;
  6. use App\Models\DhammaTerm;
  7. use App\Models\TermCategory;
  8. use App\Services\ChannelService;
  9. use App\Services\Markup\Format;
  10. use App\Services\Markup\MarkupService;
  11. use App\Services\Markup\RenderOptions;
  12. use App\Services\OpenSearchService;
  13. use App\Services\TermIndexService;
  14. use App\Services\UserService;
  15. use App\Tools\Tools;
  16. use Illuminate\Auth\Access\AuthorizationException;
  17. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  18. use Illuminate\Database\Eloquent\Builder;
  19. use Illuminate\Database\Eloquent\Collection as EloquentCollection;
  20. use Illuminate\Support\Collection;
  21. use Illuminate\Support\Facades\DB;
  22. use Illuminate\Support\Facades\Log;
  23. use Illuminate\Support\Str;
  24. use Illuminate\Validation\ValidationException;
  25. /**
  26. * 术语 / 百科词条(只给 v3 用):查看、按 channel / studio 列出、按词查、建、改、删。
  27. *
  28. * 取代 v2 `DhammaTermController`(show、index 的 channel / studio / word、store、update、destroy)。
  29. * v2 那份原地保留不动(铁律 2),不共用代码。
  30. *
  31. * 权限:
  32. * - 挂在 channel 下的术语跟 channel 走({@see ChannelAbilityService}):能读 channel 就能读,能写 channel 内容就能建、改
  33. * - studio 级术语(channal 为空,owner 名下所有 channel 共用):谁都能读;建要 owner 的 create,改要 update
  34. * ({@see GroupAbilityService}:团队 owner / manager 能建,editor 也能改)
  35. * - 删:owner 本人或团队 owner(GroupAbilityService 的 delete);只给人类
  36. *
  37. * 写入方(`$actor`)由 {@see AgentGrantService::actor()} 给出:AI 模型凭人类授权代写时 editor 是授权人、
  38. * co_editor 是模型,权限按 editor 判,且只能写授权覆盖的 channel(按 book 限定的授权不覆盖术语)。
  39. *
  40. * 分类不是入参:写入时从正文的 `{{category|…}}` 抽出存进 term_categories(内容多由 LLM 生成,分类不做限制)。
  41. * word + tag 建立后不准改(引用方写 `[[word@tag]]`),要改就新建一条、把旧的 redirect 过去。
  42. * 修改带乐观锁:If-Match 必须等于当前 ETag({@see DhammaTerm::etag()}),否则 412;不带 428。
  43. */
  44. class TermService
  45. {
  46. /** 列表可排序的字段 */
  47. public const ORDERS = ['updated_at', 'created_at', 'word'];
  48. /** 改了这些字段算「改内容」:co_editor 跟着这次写入走(人改清空、AI 改换成该模型) */
  49. private const CONTENT_FIELDS = ['meaning', 'other_meaning', 'note', 'summary', 'quality', 'content_type', 'redirect', 'language'];
  50. /** @var array<string, array<string, bool>> 请求内缓存:用户|owner → 能力 */
  51. private array $groupAbilities = [];
  52. public function __construct(
  53. private readonly ChannelAbilityService $channels,
  54. private readonly GroupAbilityService $groups,
  55. private readonly AgentGrantService $agents,
  56. private readonly MarkupService $markup,
  57. private readonly UserService $users,
  58. private readonly ChannelService $channelSummaries,
  59. ) {}
  60. /* ------------------------------------------------------------------ 读 */
  61. /**
  62. * 单条,带渲染后的正文(摘要 + 正文)。
  63. *
  64. * 正文默认按术语所在 channel 解析模板;$render 可以指定按哪些 channel 解析(阅读器右栏选版本)
  65. * 与 read / edit 模式。指定的 channel 只认查看者看得见的,一个都看不见就退回术语所在 channel。
  66. * format=html 时正文输出 HTML(挂在 html 上,给用 WebView 显示的客户端),否则输出节点树(body)。
  67. *
  68. * @param array{channels?: list<string>, mode?: string, format?: string} $render
  69. *
  70. * @throws AuthorizationException 看不见
  71. */
  72. public function show(DhammaTerm $term, ?string $viewerUid, array $render = []): DhammaTerm
  73. {
  74. $abilities = $this->abilitiesMany(collect([$term]), $viewerUid)[$term->guid];
  75. if (! $abilities['read']) {
  76. throw new AuthorizationException(__('messages.term_forbidden'));
  77. }
  78. $this->loadRelations(new EloquentCollection([$term]));
  79. $this->decorate(collect([$term]), $viewerUid, withBody: true, render: [
  80. 'channels' => $this->readableChannels($render['channels'] ?? [], $viewerUid),
  81. 'mode' => $render['mode'] ?? 'read',
  82. 'format' => $render['format'] ?? 'tree',
  83. ]);
  84. return $term;
  85. }
  86. /**
  87. * 这些 channel 里查看者看得见的,保持传入顺序。
  88. *
  89. * @param list<string> $uids
  90. * @return list<string>
  91. */
  92. private function readableChannels(array $uids, ?string $viewerUid): array
  93. {
  94. if ($uids === []) {
  95. return [];
  96. }
  97. $channels = Channel::whereIn('uid', $uids)->get(['uid', 'owner_uid', 'status', 'is_system']);
  98. $abilities = $this->channels->abilitiesMany($channels, $viewerUid);
  99. return array_values(array_filter($uids, fn (string $uid) => $abilities[$uid]['read'] ?? false));
  100. }
  101. /**
  102. * 某个 channel 的术语。
  103. *
  104. * @param array{search?: string|null, quality?: string, category?: string, order?: string, dir?: string} $filters
  105. * @return LengthAwarePaginator<int, DhammaTerm>
  106. *
  107. * @throws AuthorizationException 看不见这个 channel
  108. */
  109. public function listInChannel(Channel $channel, array $filters, ?string $viewerUid, int $perPage): LengthAwarePaginator
  110. {
  111. return $this->paginate($this->channelQuery($channel, $viewerUid), $filters, $viewerUid, $perPage);
  112. }
  113. /**
  114. * 某个 channel 的术语查询(列表、导出共用)。
  115. *
  116. * @return Builder<DhammaTerm>
  117. *
  118. * @throws AuthorizationException 看不见这个 channel
  119. */
  120. public function channelQuery(Channel $channel, ?string $viewerUid): Builder
  121. {
  122. if (! $this->channels->abilities($channel, $viewerUid)['read']) {
  123. throw new AuthorizationException(__('messages.channel_forbidden'));
  124. }
  125. return DhammaTerm::query()->where('channal', $channel->uid);
  126. }
  127. /**
  128. * 某个 studio(本人或团队)名下的术语:它的 channel 里的与 studio 级的。`general=true` 只要 studio 级的。
  129. *
  130. * @param array{search?: string|null, quality?: string, category?: string, general?: bool, order?: string, dir?: string} $filters
  131. * @return LengthAwarePaginator<int, DhammaTerm>
  132. *
  133. * @throws AuthorizationException 不是本人,也不是这个团队的成员
  134. */
  135. public function listInStudio(string $studioUid, array $filters, string $viewerUid, int $perPage): LengthAwarePaginator
  136. {
  137. return $this->paginate($this->studioQuery($studioUid, $filters, $viewerUid), $filters, $viewerUid, $perPage);
  138. }
  139. /**
  140. * 某个 studio 名下术语的查询(列表、导出共用)。`general=true` 只要 studio 级的。
  141. *
  142. * @param array{general?: bool} $filters
  143. * @return Builder<DhammaTerm>
  144. *
  145. * @throws AuthorizationException 不是本人,也不是这个团队的成员
  146. */
  147. public function studioQuery(string $studioUid, array $filters, string $viewerUid): Builder
  148. {
  149. if (! $this->groups->can($viewerUid, $studioUid, GroupAbilityService::READ)) {
  150. throw new AuthorizationException(__('messages.channel_studio_forbidden'));
  151. }
  152. $query = DhammaTerm::query()->where('owner', $studioUid);
  153. if (! empty($filters['general'])) {
  154. $query->studioLevel();
  155. }
  156. return $query;
  157. }
  158. /**
  159. * 列表的过滤与排序(不分页),导出用。
  160. *
  161. * @param Builder<DhammaTerm> $query
  162. * @param array<string, mixed> $filters
  163. * @return Builder<DhammaTerm>
  164. */
  165. public function filtered(Builder $query, array $filters): Builder
  166. {
  167. $this->applyFilters($query, $filters);
  168. return $query->orderBy('word')->orderBy('guid');
  169. }
  170. /**
  171. * 按词查:这些词在所有看得见的 channel 与 studio 级术语里的词条(编辑时看同词的其它义项、社区译法)。
  172. *
  173. * `with_body` 时每条都带渲染后的正文(同一个词通常只有几条)。
  174. *
  175. * @param array{word: string, tag?: string|null, channel?: string, language?: string, with_body?: bool} $filters
  176. * @return LengthAwarePaginator<int, DhammaTerm>
  177. */
  178. public function lookup(array $filters, ?string $viewerUid, int $perPage): LengthAwarePaginator
  179. {
  180. $words = array_values(array_filter(array_map('trim', explode(',', $filters['word']))));
  181. $query = DhammaTerm::query()->whereIn('word', $words);
  182. if (array_key_exists('tag', $filters)) {
  183. $this->whereTag($query, $filters['tag']);
  184. }
  185. if (! empty($filters['channel'])) {
  186. $query->where('channal', $filters['channel']);
  187. }
  188. if (! empty($filters['language'])) {
  189. $query->where('language', $filters['language']);
  190. }
  191. // 看得见的:studio 级术语,或所在 channel 会被列出给查看者
  192. $query->where(function (Builder $q) use ($viewerUid) {
  193. $q->studioLevel()->orWhereIn('channal', function ($sub) use ($viewerUid) {
  194. $sub->selectRaw('uid::text')->from('channels')->whereNull('deleted_at');
  195. $this->channels->scopeListable($sub, $viewerUid);
  196. });
  197. });
  198. return $this->paginate($query, ['order' => 'updated_at'] + $filters, $viewerUid, $perPage, ! empty($filters['with_body']));
  199. }
  200. /* ------------------------------------------------------------------ 写 */
  201. /**
  202. * 在 channel 里新建。owner 与语言跟 channel。
  203. *
  204. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  205. * @param array<string, mixed> $data
  206. *
  207. * @throws AuthorizationException
  208. * @throws BusinessException 同一 channel 里已有这个 word@tag(409)
  209. */
  210. public function createInChannel(Channel $channel, array $actor, array $data): DhammaTerm
  211. {
  212. if (! $this->agents->covers($actor['scope'], $channel->uid, null)
  213. || ! $this->channels->abilities($channel, $actor['editor'])['write']) {
  214. throw new AuthorizationException(__('messages.term_forbidden'));
  215. }
  216. $this->guardUnique(DhammaTerm::query()->where('channal', $channel->uid), $data);
  217. return $this->create($actor, $data + [
  218. 'channel' => $channel->uid,
  219. 'owner' => $channel->owner_uid,
  220. 'language' => $channel->lang,
  221. ]);
  222. }
  223. /**
  224. * 在 studio 名下新建 studio 级术语(不属于任何 channel)。只给人类:agent 授权只覆盖 channel。
  225. *
  226. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  227. * @param array<string, mixed> $data
  228. *
  229. * @throws AuthorizationException
  230. * @throws BusinessException 同一 studio、同一语言已有这个 word@tag(409)
  231. */
  232. public function createInStudio(string $studioUid, array $actor, array $data): DhammaTerm
  233. {
  234. if ($actor['scope'] !== null || ! $this->groups->can($actor['editor'], $studioUid, GroupAbilityService::CREATE)) {
  235. throw new AuthorizationException(__('messages.term_forbidden'));
  236. }
  237. $this->guardUnique(
  238. DhammaTerm::query()->where('owner', $studioUid)->studioLevel()->where('language', $data['language']),
  239. $data,
  240. );
  241. return $this->create($actor, $data + ['channel' => null, 'owner' => $studioUid]);
  242. }
  243. /**
  244. * 改(只改传了的字段)。word / tag 不准改(FormRequest 已拦)。带乐观锁:$ifMatch 必须等于当前 ETag。
  245. *
  246. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  247. * @param array<string, mixed> $data
  248. *
  249. * @throws AuthorizationException
  250. * @throws BusinessException 428 没带 If-Match;412 这条在你编辑期间被改过
  251. * @throws ValidationException
  252. */
  253. public function update(DhammaTerm $term, array $actor, array $data, ?string $ifMatch): DhammaTerm
  254. {
  255. if (! $this->agents->covers($actor['scope'], $term->channelUid(), null) || ! $this->can($term, $actor['editor'], 'update')) {
  256. throw new AuthorizationException(__('messages.term_forbidden'));
  257. }
  258. if ($ifMatch === null || $ifMatch === '') {
  259. throw new BusinessException(__('messages.term_if_match_required'), 428, 'precondition-required', [], 'Precondition Required');
  260. }
  261. if ($term->channelUid() !== null && array_key_exists('language', $data)) {
  262. throw ValidationException::withMessages(['language' => __('messages.term_language_follows_channel')]);
  263. }
  264. $this->guardRedirect($term->word, $term->tag, $data);
  265. $changes = array_intersect_key($data, array_flip(self::CONTENT_FIELDS));
  266. if (array_key_exists('note', $changes) || array_key_exists('content_type', $changes)) {
  267. $changes['content_type'] ??= $term->effectiveContentType();
  268. }
  269. $etag = $term->etag();
  270. if ($ifMatch !== $etag) {
  271. throw $this->modified($term);
  272. }
  273. if (! $this->applyChanges($term, $actor, $changes)) {
  274. throw $this->modified($term->fresh() ?? $term);
  275. }
  276. return $this->show($term->fresh(), $actor['editor']);
  277. }
  278. /**
  279. * 写入修改(比较并交换:版本与 modify_time 都没变才写),改了 note 就重抽分类,写完清缓存。
  280. * 不查权限、不渲染——由调用方负责(单条修改、导入共用)。$index=false 时不立即重建搜索索引。
  281. *
  282. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  283. * @param array<string, mixed> $changes 只含要改的内容字段
  284. * @return bool 在别人之后写的(期间被改过)返回 false,什么都没写
  285. */
  286. public function applyChanges(DhammaTerm $term, array $actor, array $changes, bool $index = true): bool
  287. {
  288. $changed = DB::transaction(function () use ($term, $actor, $changes) {
  289. $updates = $changes + [
  290. 'editor_uid' => $actor['editor'],
  291. 'editor_id' => $this->users->intIdByUuid($actor['editor']) ?? 0,
  292. 'co_editor_uid' => $actor['co_editor'],
  293. 'modify_time' => time() * 1000,
  294. 'version' => (int) $term->version + 1,
  295. 'updated_at' => now(),
  296. ];
  297. // 比较并交换:版本与 modify_time 都没变才写(v2 的修改只动 modify_time)
  298. $affected = DhammaTerm::query()
  299. ->where('guid', $term->guid)
  300. ->where('version', (int) $term->version)
  301. ->where('modify_time', (int) $term->modify_time)
  302. ->update($updates);
  303. if ($affected === 0) {
  304. return false;
  305. }
  306. if (array_key_exists('note', $changes)) {
  307. $this->syncCategories($term->guid, $changes['note']);
  308. }
  309. return true;
  310. });
  311. if ($changed) {
  312. $this->afterWrite($term->fresh(), $index);
  313. }
  314. return $changed;
  315. }
  316. /**
  317. * 软删除,返回被删的术语(AIP-164)。分类留着,恢复时还在。
  318. *
  319. * @throws AuthorizationException
  320. */
  321. public function delete(DhammaTerm $term, string $actorUid): DhammaTerm
  322. {
  323. $this->agents->assertHuman($actorUid);
  324. if (! $this->can($term, $actorUid, 'delete')) {
  325. throw new AuthorizationException(__('messages.term_forbidden'));
  326. }
  327. $term->delete();
  328. $this->forgetCache($term);
  329. try {
  330. app(OpenSearchService::class)->delete("term_{$term->guid}");
  331. } catch (\Throwable $e) {
  332. Log::warning('Failed to remove deleted term from index', ['guid' => $term->guid, 'error' => $e->getMessage()]);
  333. }
  334. $this->loadRelations(new EloquentCollection([$term]));
  335. $this->decorate(collect([$term]), $actorUid, withBody: false);
  336. return $term;
  337. }
  338. /* ------------------------------------------------------------------ 权限 */
  339. /**
  340. * 本人对这批术语能做什么。channel 的能力整批算一次;studio 级与删除按 owner 算,同一 owner 只查一次。
  341. *
  342. * @param Collection<int, DhammaTerm> $terms
  343. * @return array<string, array{read: bool, update: bool, delete: bool}>
  344. */
  345. public function abilitiesMany(Collection $terms, ?string $userUid): array
  346. {
  347. $channelUids = $terms->pluck('channal')->filter()->unique()->values();
  348. $channelModels = $channelUids->isEmpty()
  349. ? collect()
  350. : Channel::whereIn('uid', $channelUids)->get(['uid', 'owner_uid', 'status', 'is_system']);
  351. $channelAbilities = $this->channels->abilitiesMany($channelModels, $userUid);
  352. $result = [];
  353. foreach ($terms as $term) {
  354. if ($term->channelUid() !== null) {
  355. $ch = $channelAbilities[$term->channelUid()] ?? ['read' => false, 'write' => false];
  356. $read = $ch['read'];
  357. $update = $userUid !== null && $ch['write'];
  358. } else {
  359. $read = true;
  360. $update = $userUid !== null && $this->groupCan($userUid, $term->owner, GroupAbilityService::UPDATE);
  361. }
  362. $delete = $userUid !== null && $this->groupCan($userUid, $term->owner, GroupAbilityService::DELETE);
  363. $result[$term->guid] = ['read' => $read, 'update' => $update, 'delete' => $delete];
  364. }
  365. return $result;
  366. }
  367. private function can(DhammaTerm $term, string $userUid, string $ability): bool
  368. {
  369. return $this->abilitiesMany(collect([$term]), $userUid)[$term->guid][$ability];
  370. }
  371. private function groupCan(string $userUid, string $ownerUid, string $ability): bool
  372. {
  373. return $this->groupAbilities["{$userUid}|{$ownerUid}"][$ability]
  374. ??= $this->groups->can($userUid, $ownerUid, $ability);
  375. }
  376. /* ------------------------------------------------------------------ 内部 */
  377. /**
  378. * @param Builder<DhammaTerm> $query
  379. * @param array<string, mixed> $filters
  380. * @return LengthAwarePaginator<int, DhammaTerm>
  381. */
  382. private function paginate(Builder $query, array $filters, ?string $viewerUid, int $perPage, bool $withBody = false): LengthAwarePaginator
  383. {
  384. $this->applyFilters($query, $filters);
  385. $order = $filters['order'] ?? 'updated_at';
  386. $dir = $filters['dir'] ?? ($order === 'word' ? 'asc' : 'desc');
  387. $page = $query
  388. ->orderBy($order, $dir)
  389. ->orderBy('guid')
  390. ->paginate($perPage);
  391. $this->loadRelations($page->getCollection());
  392. $this->decorate($page->getCollection(), $viewerUid, withBody: $withBody);
  393. return $page;
  394. }
  395. /**
  396. * @param Builder<DhammaTerm> $query
  397. * @param array<string, mixed> $filters
  398. */
  399. private function applyFilters(Builder $query, array $filters): void
  400. {
  401. if (! empty($filters['search'])) {
  402. $like = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['search']).'%';
  403. $query->where(fn (Builder $q) => $q->where('word', 'ilike', $like)
  404. ->orWhere('word_en', 'ilike', $like)
  405. ->orWhere('meaning', 'ilike', $like)
  406. ->orWhere('other_meaning', 'ilike', $like));
  407. }
  408. if (! empty($filters['quality'])) {
  409. $filters['quality'] === 'pending'
  410. ? $query->where(fn (Builder $q) => $q->where('quality', 'pending')->orWhereNull('quality'))
  411. : $query->where('quality', $filters['quality']);
  412. }
  413. if (! empty($filters['category'])) {
  414. // term_categories.term_guid 是 uuid,dhamma_terms.guid 是 varchar
  415. $query->whereIn('guid', TermCategory::query()->selectRaw('term_guid::text')->where('category', $filters['category']));
  416. }
  417. }
  418. /**
  419. * @return list<string>
  420. */
  421. private function relations(): array
  422. {
  423. return [
  424. ...UserService::eagerLoadActor(),
  425. UserService::eagerLoadAssistant('coEditor'),
  426. // 只取分类名(与外键、排序);term_categories.id 不对外,也用不到
  427. 'categories:term_guid,category,position',
  428. ];
  429. }
  430. /**
  431. * 预加载 {@see self::relations()},并挂上所属 channel 的摘要 `channel_summary`({@see ChannelService::summaries()},
  432. * 整批一次查询;studio 级术语与 channel 已不存在的是 null)。
  433. *
  434. * @param EloquentCollection<int, DhammaTerm> $terms
  435. */
  436. private function loadRelations(EloquentCollection $terms): void
  437. {
  438. $terms->load($this->relations());
  439. $summaries = $this->channelSummaries->summaries($terms->map(fn (DhammaTerm $term) => $term->channelUid())->all());
  440. $terms->values()->each(function (DhammaTerm $term, int $i) use ($summaries) {
  441. $term->channel_summary = $summaries[$i] ?: null;
  442. });
  443. }
  444. /**
  445. * 挂上 abilities、摘要纯文本,详情另挂渲染后的正文。整批渲染一次。
  446. *
  447. * 正文 = 摘要 + 正文(摘要放在前面,不加分隔)。摘要纯文本:有摘要用摘要,没有取正文第一段。
  448. * $render 只用于正文:channels 非空时代替术语所在 channel,mode 为 read / edit,
  449. * format 为 tree(挂 body)/ html(挂 html)。
  450. *
  451. * @param Collection<int, DhammaTerm> $terms
  452. * @param array{channels?: list<string>, mode?: string, format?: string} $render
  453. */
  454. private function decorate(Collection $terms, ?string $viewerUid, bool $withBody, array $render = []): void
  455. {
  456. if ($terms->isEmpty()) {
  457. return;
  458. }
  459. $abilities = $this->abilitiesMany($terms, $viewerUid);
  460. $items = [];
  461. foreach ($terms as $term) {
  462. $base = [
  463. 'channels' => $term->channal ? [$term->channal] : [],
  464. 'contentType' => $term->effectiveContentType(),
  465. ];
  466. $summary = trim((string) $term->summary);
  467. $items["{$term->guid}|summary"] = $base + ['source' => $summary !== '' ? $summary : $this->firstParagraph((string) $term->note)];
  468. if ($withBody) {
  469. $bodyChannels = ! empty($render['channels']) ? $render['channels'] : $base['channels'];
  470. $items["{$term->guid}|body"] = ['channels' => $bodyChannels] + $base + ['source' => trim($summary."\n\n".(string) $term->note)];
  471. }
  472. }
  473. $bodyFormat = ($render['format'] ?? 'tree') === 'html' ? Format::Html : Format::Tree;
  474. $rendered = $this->markup->renderManyAs(
  475. $items,
  476. new RenderOptions(mode: $render['mode'] ?? 'read'),
  477. $withBody ? [Format::Text, $bodyFormat] : [Format::Text],
  478. );
  479. foreach ($terms as $term) {
  480. $term->abilities = $abilities[$term->guid];
  481. $text = (string) $rendered[Format::Text->value]["{$term->guid}|summary"];
  482. $term->summary_text = trim($text);
  483. if ($withBody && $bodyFormat === Format::Html) {
  484. $term->html = (string) $rendered[Format::Html->value]["{$term->guid}|body"];
  485. } elseif ($withBody) {
  486. $term->body = $rendered[Format::Tree->value]["{$term->guid}|body"];
  487. }
  488. }
  489. }
  490. /**
  491. * 正文源码(markdown / markdown-e2)的第一个自然段,渲染前在源码上取。
  492. *
  493. * 不能渲染后再切:纯文本渲染里段落之间与段内换行都只是一个 `\n`,分不出段。
  494. * 自然段以空行分隔(两种方言相同),围栏(```)内的空行不算;跳过标题、围栏、分隔线、
  495. * 以及只由模板组成的段(`{{toc}}` 等);段首只由模板组成的行(如 `{{ai}}` 提示)去掉。
  496. * 一段也没有时退回整篇。
  497. */
  498. private function firstParagraph(string $source): string
  499. {
  500. $blocks = [];
  501. $lines = [];
  502. $fenced = false;
  503. foreach (preg_split('/\R/u', $source) ?: [] as $line) {
  504. if (preg_match('/^\s*(```|~~~)/u', $line) === 1) {
  505. $fenced = ! $fenced;
  506. }
  507. if (! $fenced && trim($line) === '') {
  508. $blocks[] = $lines;
  509. $lines = [];
  510. continue;
  511. }
  512. $lines[] = $line;
  513. }
  514. $blocks[] = $lines;
  515. $templateOnly = '/^\s*(?:(?<t>\{\{(?:[^{}]++|(?&t))*\}\})\s*)+$/u';
  516. foreach ($blocks as $lines) {
  517. while ($lines !== [] && preg_match($templateOnly, $lines[0]) === 1) {
  518. array_shift($lines);
  519. }
  520. if ($lines === [] || preg_match('/^\s*(#|```|~~~|([-*_])\s*\2\s*\2[\s\-*_]*$)/u', $lines[0]) === 1) {
  521. continue;
  522. }
  523. return implode("\n", $lines);
  524. }
  525. return $source;
  526. }
  527. /**
  528. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  529. * @param array<string, mixed> $data 已含 channel / owner / language
  530. */
  531. private function create(array $actor, array $data): DhammaTerm
  532. {
  533. $this->guardRedirect($data['word'], $data['tag'] ?? null, $data);
  534. return $this->show($this->insert($actor, $data), $actor['editor']);
  535. }
  536. /**
  537. * 写入一条新术语并抽分类、清缓存。不查权限、不查重、不渲染——由调用方负责(单条新建、导入共用)。
  538. * $index=false 时不立即重建搜索索引。
  539. *
  540. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  541. * @param array<string, mixed> $data 已含 channel / owner / language
  542. */
  543. public function insert(array $actor, array $data, bool $index = true): DhammaTerm
  544. {
  545. $now = time() * 1000;
  546. $term = new DhammaTerm;
  547. $term->forceFill([
  548. 'id' => app('snowflake')->id(),
  549. 'guid' => (string) Str::uuid(),
  550. 'word' => $data['word'],
  551. 'word_en' => Tools::getWordEn($data['word']),
  552. 'tag' => $this->normalizeTag($data['tag'] ?? null),
  553. 'meaning' => $data['meaning'],
  554. 'other_meaning' => $data['other_meaning'] ?? null,
  555. 'note' => $data['note'] ?? null,
  556. 'summary' => $data['summary'] ?? null,
  557. 'quality' => $data['quality'] ?? null,
  558. 'content_type' => $data['content_type'] ?? DhammaTerm::CONTENT_TYPE_V3,
  559. 'redirect' => $data['redirect'] ?? null,
  560. 'channal' => $data['channel'],
  561. 'language' => $data['language'],
  562. 'owner' => $data['owner'],
  563. 'editor_uid' => $actor['editor'],
  564. 'editor_id' => $this->users->intIdByUuid($actor['editor']) ?? 0,
  565. 'co_editor_uid' => $actor['co_editor'],
  566. 'version' => 1,
  567. 'create_time' => $now,
  568. 'modify_time' => $now,
  569. ]);
  570. DB::transaction(function () use ($term) {
  571. $term->save();
  572. $this->syncCategories($term->guid, $term->note);
  573. });
  574. $this->afterWrite($term, $index);
  575. return $term->fresh();
  576. }
  577. /**
  578. * 同一范围里 word + tag 唯一(tag 空串与 null 视为相同)。
  579. *
  580. * @param Builder<DhammaTerm> $scope
  581. * @param array<string, mixed> $data
  582. *
  583. * @throws BusinessException
  584. */
  585. private function guardUnique(Builder $scope, array $data): void
  586. {
  587. $existing = $this->findExisting($scope, $data['word'], $data['tag'] ?? null)?->guid;
  588. if ($existing !== null) {
  589. throw new BusinessException(__('messages.term_exists'), 409, 'term-exists', ['existing' => $existing]);
  590. }
  591. }
  592. /**
  593. * 范围内同 word + tag 的那一条(tag 空串与 null 视为相同)。
  594. *
  595. * @param Builder<DhammaTerm> $scope
  596. */
  597. public function findExisting(Builder $scope, string $word, ?string $tag): ?DhammaTerm
  598. {
  599. $query = $scope->where('word', $word);
  600. $this->whereTag($query, $tag);
  601. return $query->first();
  602. }
  603. /**
  604. * redirect 写成 word 或 word@tag,不能指向自己。目标是否存在不查(内容多由 LLM 生成,批量写入时目标可能还没建)。
  605. *
  606. * @param array<string, mixed> $data
  607. *
  608. * @throws ValidationException
  609. */
  610. public function guardRedirect(string $word, ?string $tag, array $data): void
  611. {
  612. $redirect = $data['redirect'] ?? null;
  613. if ($redirect === null || $redirect === '') {
  614. return;
  615. }
  616. [$targetWord, $targetTag] = array_pad(explode('@', $redirect, 2), 2, '');
  617. if ($targetWord === $word && $targetTag === (string) $this->normalizeTag($tag)) {
  618. throw ValidationException::withMessages(['redirect' => __('messages.term_redirect_self')]);
  619. }
  620. }
  621. /**
  622. * @param Builder<DhammaTerm> $query
  623. */
  624. private function whereTag(Builder $query, ?string $tag): void
  625. {
  626. $tag = $this->normalizeTag($tag);
  627. $tag === null
  628. ? $query->where(fn (Builder $q) => $q->whereNull('tag')->orWhere('tag', ''))
  629. : $query->where('tag', $tag);
  630. }
  631. public function normalizeTag(?string $tag): ?string
  632. {
  633. $tag = trim((string) $tag);
  634. return $tag === '' ? null : $tag;
  635. }
  636. /**
  637. * 从正文抽出 {{category|…}},整体替换这条术语的分类。同名的只留第一个。
  638. */
  639. private function syncCategories(string $guid, ?string $note): void
  640. {
  641. preg_match_all('/\{\{category\|([^}|]+)\}\}/u', (string) $note, $matches);
  642. $names = array_values(array_unique(array_filter(array_map(
  643. fn (string $name) => mb_substr(trim($name), 0, 128),
  644. $matches[1] ?? [],
  645. ))));
  646. TermCategory::where('term_guid', $guid)->delete();
  647. foreach ($names as $position => $name) {
  648. TermCategory::create(['term_guid' => $guid, 'category' => $name, 'position' => $position]);
  649. }
  650. }
  651. public function modified(DhammaTerm $term): BusinessException
  652. {
  653. return new BusinessException(
  654. __('messages.term_modified'),
  655. 412,
  656. 'term-modified',
  657. ['etag' => $term->etag()],
  658. 'Precondition Failed',
  659. );
  660. }
  661. /**
  662. * 写入后:清 v2 的术语缓存(v4 / v6 的旧渲染还在读),重建 OpenSearch 索引(全站搜索用;失败不阻断写入)。
  663. * $index=false 时只清缓存,索引由每周的 `opensearch:index-term` 补上(大批导入用)。
  664. */
  665. public function afterWrite(DhammaTerm $term, bool $index = true): void
  666. {
  667. $this->forgetCache($term);
  668. if (! $index) {
  669. return;
  670. }
  671. try {
  672. app(TermIndexService::class)->index($term->guid);
  673. } catch (\Throwable $e) {
  674. Log::warning('Failed to index term after write', ['guid' => $term->guid, 'error' => $e->getMessage()]);
  675. }
  676. }
  677. /**
  678. * v2 的缓存键是 `/term/{channel uid}/{word}`;studio 级术语要清 owner 名下每个 channel 的
  679. * (v2 自己那份清不掉:拿模型而不是 uid 拼键,见 DhammaTermController::deleteCache 的 FIXME)。
  680. */
  681. private function forgetCache(DhammaTerm $term): void
  682. {
  683. $channels = $term->channelUid() !== null
  684. ? [$term->channelUid()]
  685. : Channel::where('owner_uid', $term->owner)->pluck('uid')->all();
  686. foreach ($channels as $uid) {
  687. RedisCache::forget("/term/{$uid}/{$term->word}");
  688. }
  689. }
  690. }