2
0

UserDictController.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Api\DictApi;
  4. use App\Http\Api\StudioApi;
  5. use App\Http\Resources\UserDictResource;
  6. use App\Models\DictInfo;
  7. use App\Models\UserDict;
  8. use App\Services\AuthService;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Support\Facades\Redis;
  11. use Illuminate\Support\Str;
  12. class UserDictController extends Controller
  13. {
  14. /**
  15. * 列出用户词典条目
  16. *
  17. * 按 view 指定的口径返回 user_dict 记录,支持按单词、词根、词典过滤,以及分页与排序。
  18. * 需要登录的口径:all、studio;studio 口径还要求 name 指定的 studio 属于当前用户,否则返回 auth.failed。
  19. * community 口径只返回 status>5 且来源为 _USER_WBW_/_USER_DICT_ 的社区公开数据。
  20. * 返回 rows 与 count(过滤后总数)。
  21. *
  22. * @queryParam view string required 查询口径。all=全部;studio=某 studio 创建者的用户词条;user=cookie 中用户的词条(排除系统汇总);word=按单词查全部;community=社区公开词条;compound=复合词机器人词典;dict=指定词典。Enum: all,studio,user,word,community,compound,dict
  23. * @queryParam name string studio 口径为 studio 名;dict 口径为系统词典短名。Example: robot_compound
  24. * @queryParam id string dict 口径下直接指定的词典 uid(与 name 二选一)
  25. * @queryParam word string 要查询的单词,word/community/compound 口径必填;其他口径传入时也会追加过滤
  26. * @queryParam parent string 按词根(parent)过滤
  27. * @queryParam dict string 按词典短名(dict_info.shortname)过滤,解析为 uuid 后才生效
  28. * @queryParam search string 按单词前缀模糊搜索
  29. * @queryParam order string 排序字段。Default: updated_at
  30. * @queryParam dir string 排序方向。Enum: asc,desc Default: desc
  31. * @queryParam offset integer 跳过的记录数。Default: 0
  32. * @queryParam limit integer 返回条数上限。Default: 200
  33. */
  34. public function index(Request $request)
  35. {
  36. //
  37. $result = false;
  38. $indexCol = [
  39. 'id',
  40. 'word',
  41. 'type',
  42. 'grammar',
  43. 'mean',
  44. 'parent',
  45. 'note',
  46. 'status',
  47. 'factors',
  48. 'confidence',
  49. 'dict_id',
  50. 'source',
  51. 'updated_at',
  52. 'creator_id',
  53. ];
  54. switch ($request->input('view')) {
  55. case 'all':
  56. // 获取studio内所有channel
  57. $user = AuthService::current($request);
  58. if (! $user) {
  59. return $this->error(__('auth.failed'));
  60. }
  61. $table = UserDict::select($indexCol);
  62. break;
  63. case 'studio':
  64. // 获取studio内所有channel
  65. $user = AuthService::current($request);
  66. if (! $user) {
  67. return $this->error(__('auth.failed'));
  68. }
  69. // 判断当前用户是否有指定的studio的权限
  70. if ($user['user_uid'] !== StudioApi::getIdByName($request->input('name'))) {
  71. return $this->error(__('auth.failed'));
  72. }
  73. $table = UserDict::select($indexCol)
  74. ->where('creator_id', $user['user_id'])
  75. ->whereIn('source', ['_USER_WBW_', '_USER_DICT_']);
  76. break;
  77. case 'user':
  78. // 原先凭据取自 $_COOKIE['user_id'](v1 遗留的认证绕过)。同一个 switch
  79. // 上面的 studio 分支早就用的是 $user['user_id'],这条是漏改的。
  80. // $user 是各分支各自解析的(case 之间不共享),这里要自己解一次。
  81. $user = AuthService::current($request);
  82. if (! $user) {
  83. return $this->error(__('auth.failed'));
  84. }
  85. $table = UserDict::select($indexCol)
  86. ->where('creator_id', $user['user_id'])
  87. ->where('source', '<>', '_SYS_USER_WBW_');
  88. break;
  89. case 'word':
  90. $table = UserDict::select($indexCol)
  91. ->where('word', $request->input('word'));
  92. break;
  93. case 'community':
  94. $table = UserDict::select($indexCol)
  95. ->where('word', $request->input('word'))
  96. ->where('status', '>', 5)
  97. ->where(function ($query) {
  98. $query->where('source', '_USER_WBW_')
  99. ->orWhere('source', '_USER_DICT_');
  100. });
  101. break;
  102. case 'compound':
  103. $dict_id = DictApi::getSysDict('robot_compound');
  104. // FIXME: $this->error(...) 没有 return,取不到词典时不会中断,会继续用 false 去查询。应改为 return $this->error(...)。
  105. if ($dict_id === false) {
  106. $this->error('no robot_compound');
  107. }
  108. $table = UserDict::where('dict_id', $dict_id)->where('word', $request->input('word'));
  109. break;
  110. case 'dict':
  111. $dict_id = false;
  112. if ($request->has('name')) {
  113. $dict_id = DictApi::getSysDict($request->input('name'));
  114. } elseif ($request->has('id')) {
  115. $dict_id = $request->input('id');
  116. }
  117. // FIXME: $this->error(...) 没有 return,词典不存在时不会中断,会继续用 false 去查询。应改为 return $this->error(...)。
  118. if ($dict_id === false) {
  119. $this->error('no dict', [], 404);
  120. }
  121. $table = UserDict::select($indexCol)
  122. ->where('dict_id', $dict_id);
  123. // FIXME: 这里缺 break,会贯穿到 default(当前恰好无副作用,但属于隐患)。应补上 break;。
  124. default:
  125. // code...
  126. break;
  127. }
  128. // FIXME: view 不在枚举内(含缺省)时 $table 从未被赋值,下面的 $table->count() 会 fatal error。
  129. // 建议 default 分支直接 return $this->error('无法识别的参数view', 400, 400)。
  130. if ($request->has('search')) {
  131. $table->where('word', 'like', $request->input('search').'%');
  132. }
  133. if (($request->has('word'))) {
  134. $table = $table->where('word', $request->input('word'));
  135. }
  136. if (($request->has('parent'))) {
  137. $table = $table->where('parent', $request->input('parent'));
  138. }
  139. if (($request->has('dict'))) {
  140. $dictId = DictInfo::where('shortname', $request->input('dict'))->value('id');
  141. if (Str::isUuid($dictId)) {
  142. $table = $table->where('dict_id', $dictId);
  143. }
  144. }
  145. $count = $table->count();
  146. $table->orderBy(
  147. $request->input('order', 'updated_at'),
  148. $request->input('dir', 'desc')
  149. );
  150. $table->skip($request->input('offset', 0))
  151. ->take($request->input('limit', 200));
  152. $result = $table->get();
  153. return $this->ok(['rows' => UserDictResource::collection($result), 'count' => $count]);
  154. }
  155. /**
  156. * 批量新增/更新用户词典条目
  157. *
  158. * 需要登录。data 是 JSON 字符串,解码后逐条处理:以 creator_id + word 以及请求中给出的
  159. * type/grammar/parent/mean/factors 组合判重,不存在则插入(自动生成雪花 id、按 view 写入 source、
  160. * 记录 create_time 与 creator_id),已存在则只更新 note 与 confidence。
  161. * 新增且 status>5 时会同步刷新系统汇总词典 _SYS_USER_WBW_;每次新增都会刷新该单词的 Redis 缓存 dict/user。
  162. * 返回 [新增条数, 汇总表更新结果]。
  163. *
  164. * @bodyParam view string required 数据来源口径,决定写入的 source:dict=_USER_DICT_,wbw=_USER_WBW_。Enum: dict,wbw
  165. * @bodyParam data string required 词条数组的 JSON 字符串,每项含 word(必填)及可选 type、grammar、parent、mean、factors、factormean、note、confidence、status、language
  166. */
  167. public function store(Request $request)
  168. {
  169. //
  170. $user = AuthService::current($request);
  171. // FIXME: $this->error('not login') 没有 return,未登录时会继续往下执行并在 $user['user_id'] 处 fatal error。
  172. // 应改为 return $this->error(__('auth.failed'), [], 401)。
  173. if (! $user) {
  174. $this->error('not login');
  175. }
  176. $_data = json_decode($request->input('data'), true);
  177. switch ($request->input('view')) {
  178. case 'dict':
  179. $src = '_USER_DICT_';
  180. break;
  181. case 'wbw':
  182. $src = '_USER_WBW_';
  183. break;
  184. default:
  185. $this->error('not view');
  186. break;
  187. }
  188. // 查询用户重复的数据
  189. $iOk = 0;
  190. $updateOk = 0;
  191. foreach ($_data as $key => $word) {
  192. // code...
  193. $table = UserDict::where('creator_id', $user['user_id'])
  194. ->where('word', $word['word']);
  195. if (isset($word['type'])) {
  196. $table = $table->where('type', $word['type']);
  197. }
  198. if (isset($word['grammar'])) {
  199. $table = $table->where('grammar', $word['grammar']);
  200. }
  201. if (isset($word['parent'])) {
  202. $table = $table->where('parent', $word['parent']);
  203. }
  204. if (isset($word['mean'])) {
  205. $table = $table->where('mean', $word['mean']);
  206. }
  207. if (isset($word['factors'])) {
  208. $table = $table->where('factors', $word['factors']);
  209. }
  210. $isDoesntExist = $table->doesntExist();
  211. if ($isDoesntExist) {
  212. // 不存在插入数据
  213. $word['id'] = app('snowflake')->id();
  214. $word['source'] = $src;
  215. $word['create_time'] = time() * 1000;
  216. $word['creator_id'] = $user['user_id'];
  217. $id = UserDict::insert($word);
  218. if (isset($word['status']) && $word['status'] > 5) {
  219. $updateOk = $this->update_sys_wbw($word);
  220. } else {
  221. $updateOk = true;
  222. }
  223. $this->update_redis($word);
  224. $iOk++;
  225. } else {
  226. // 存在,修改数据
  227. $origin = $table->first();
  228. if (isset($word['note'])) {
  229. $origin->note = $word['note'];
  230. }
  231. if (isset($word['confidence'])) {
  232. $origin->confidence = $word['confidence'];
  233. }
  234. $origin->save();
  235. }
  236. }
  237. return $this->ok([$iOk, $updateOk]);
  238. }
  239. /**
  240. * 查询单条用户词典记录
  241. *
  242. * 按主键查找,不做登录与权限校验;查不到返回「没有查询到数据」。
  243. *
  244. * @urlParam userdict string required 词条 id
  245. */
  246. public function show($id)
  247. {
  248. //
  249. $result = UserDict::find($id);
  250. if ($result) {
  251. return $this->ok($result);
  252. } else {
  253. return $this->error('没有查询到数据');
  254. }
  255. }
  256. /**
  257. * 更新单条用户词典记录
  258. *
  259. * 把请求体中的全部字段直接写入该记录(未做字段白名单与权限校验)。
  260. * 更新成功后同步刷新系统汇总词典 _SYS_USER_WBW_ 与该单词的 Redis 缓存 dict/user。
  261. * 没有记录被更新时返回「没有查询到数据」。
  262. *
  263. * @urlParam userdict string required 词条 id
  264. *
  265. * @bodyParam word string 单词
  266. * @bodyParam type string 词性
  267. * @bodyParam grammar string 语法属性
  268. * @bodyParam parent string 词根
  269. * @bodyParam mean string 词义
  270. * @bodyParam factors string 复合词拆分
  271. * @bodyParam factormean string 复合词各部分词义
  272. * @bodyParam note string 备注
  273. * @bodyParam confidence integer 置信度
  274. * @bodyParam status integer 状态,大于 5 表示公开到社区
  275. * @bodyParam language string 语言代码
  276. */
  277. public function update(Request $request, $id)
  278. {
  279. //
  280. // FIXME: 安全问题。直接把 $request->all() 整体落库,既无字段白名单(可改 creator_id、source、dict_id 等)
  281. // 也无登录与创建者校验,任何人都能改任意词条。应先鉴权并只允许更新白名单字段。
  282. $newData = $request->all();
  283. $result = UserDict::where('id', $id)
  284. ->update($newData);
  285. if ($result) {
  286. $updateOk = $this->update_sys_wbw($newData);
  287. $this->update_redis($newData);
  288. return $this->ok([$result, $updateOk]);
  289. } else {
  290. return $this->error('没有查询到数据');
  291. }
  292. }
  293. /**
  294. * 删除用户词典记录(支持批量)
  295. *
  296. * 需要登录,未登录返回 403。传了查询参数 id(JSON 数组)时走批量分支,逐条只删除 creator_id
  297. * 等于当前用户的记录,返回 [实际删除条数, 汇总表更新结果];否则删除路径参数指定的单条记录,
  298. * 非本人创建返回 auth.failed。两种分支都会同步刷新 _SYS_USER_WBW_ 汇总与 Redis 缓存 dict/user。
  299. *
  300. * @urlParam userdict string required 要删除的词条 id(未传查询参数 id 时使用)
  301. *
  302. * @queryParam id string 要批量删除的词条 id 数组的 JSON 字符串。Example: ["123","456"]
  303. */
  304. public function destroy(Request $request, $id)
  305. {
  306. //
  307. $user = AuthService::current($request);
  308. if (! $user) {
  309. return $this->error(__('auth.failed'), [], 403);
  310. }
  311. $user_id = $user['user_id'];
  312. if ($request->has('id')) {
  313. $arrId = json_decode($request->input('id'), true);
  314. $count = 0;
  315. $updateOk = false;
  316. foreach ($arrId as $key => $id) {
  317. // 找到对应数据
  318. // FIXME: find() 可能返回 null,下一行对 null 取属性会 fatal error。应先判空再处理。
  319. $data = UserDict::find($id);
  320. // 查看是否有权限删除
  321. if ($data->creator_id == $user_id) {
  322. $result = UserDict::where('id', $id)
  323. ->delete();
  324. $count += $result;
  325. $updateOk = $this->update_sys_wbw($data);
  326. $this->update_redis($data);
  327. }
  328. }
  329. return $this->ok([$count, $updateOk]);
  330. } else {
  331. // 删除单个单词
  332. $userDict = UserDict::find($id);
  333. // 判断当前用户是否有指定的studio的权限
  334. // FIXME: $userDict 可能为 null(fatal error);且用 (int) 与 creator_id 做 !== 严格比较,
  335. // creator_id 若是字符串列则永远不相等,会误判为无权限。建议先判空并改用 == 或统一类型。
  336. if ((int) $user_id !== $userDict->creator_id) {
  337. return $this->error(__('auth.failed'));
  338. }
  339. $delete = $userDict->delete();
  340. return $this->ok($delete);
  341. }
  342. }
  343. /**
  344. * 批量删除用户词典记录(旧接口)
  345. *
  346. * 不走 AuthService,凭据取自 cookie 中的 user_id,只删除该用户创建的记录。
  347. * 每删一条都会同步刷新 _SYS_USER_WBW_ 汇总与该单词的 Redis 缓存 dict/user。
  348. * 返回 deleted(实际删除条数)。
  349. *
  350. * @queryParam id string required 要删除的词条 id 数组的 JSON 字符串。Example: ["123","456"]
  351. */
  352. public function delete(Request $request)
  353. {
  354. // 原先凭据取自 $_COOKIE['user_id'](v1 遗留的认证绕过),未登录时还会
  355. // undefined array key。前端的删除走的是 DELETE /v2/userdict/{id}(destroy),
  356. // 没人调这条,但既然留着就得让它是安全的。
  357. //
  358. // FIXME: 这条端点是死的(两个前端都无调用),而且成功路径本来就是坏的——
  359. // 2026-09-24 第一次真跑它,update_sys_wbw() 往 user_dicts 插入时
  360. // dict_id / editor_id(uuid 列)拿到 "0",直接 500。修它超出「清除 cookie
  361. // 绕过」的范围,没有读懂那段汇总逻辑之前不动。要么补对那两列,要么整条删掉。
  362. $user = AuthService::current($request);
  363. if (! $user) {
  364. return $this->error(__('auth.failed'));
  365. }
  366. $arrId = json_decode($request->input('id'), true);
  367. $count = 0;
  368. $updateOk = false;
  369. foreach ($arrId as $key => $id) {
  370. $data = UserDict::where('id', $id)->first();
  371. if ($data) {
  372. // 找到对应数据
  373. $param = [
  374. 'id' => $id,
  375. 'creator_id' => $user['user_id'],
  376. ];
  377. $del = UserDict::where($param)->delete();
  378. $count += $del;
  379. $updateOk = $this->update_sys_wbw($data);
  380. $this->update_redis($data);
  381. }
  382. }
  383. return $this->ok(['deleted' => $count]);
  384. }
  385. /*
  386. 更新系统wbw汇总表
  387. */
  388. private function update_sys_wbw($data)
  389. {
  390. // 查询用户重复的数据
  391. if (! isset($data['type'])) {
  392. $data['type'] = null;
  393. }
  394. if (! isset($data['grammar'])) {
  395. $data['grammar'] = null;
  396. }
  397. if (! isset($data['parent'])) {
  398. $data['parent'] = null;
  399. }
  400. if (! isset($data['mean'])) {
  401. $data['mean'] = null;
  402. }
  403. if (! isset($data['factors'])) {
  404. $data['factors'] = null;
  405. }
  406. if (! isset($data['factormean'])) {
  407. $data['factormean'] = null;
  408. }
  409. $count = UserDict::where('word', $data['word'])
  410. ->where('type', $data['type'])
  411. ->where('grammar', $data['grammar'])
  412. ->where('parent', $data['parent'])
  413. ->where('mean', $data['mean'])
  414. ->where('factors', $data['factors'])
  415. ->where('factormean', $data['factormean'])
  416. ->where('source', $data['source'])
  417. ->count();
  418. if ($count === 0) {
  419. // 没有任何用户有这个数据
  420. // 删除数据
  421. $result = UserDict::where('word', $data['word'])
  422. ->where('type', $data['type'])
  423. ->where('grammar', $data['grammar'])
  424. ->where('parent', $data['parent'])
  425. ->where('mean', $data['mean'])
  426. ->where('factors', $data['factors'])
  427. ->where('factormean', $data['factormean'])
  428. ->where('source', '_SYS_USER_WBW_')
  429. ->delete();
  430. return $result;
  431. } else {
  432. // 更新或新增
  433. // 查询最早上传这个数据的用户
  434. $creator_id = UserDict::where('word', $data['word'])
  435. ->where('type', $data['type'])
  436. ->where('grammar', $data['grammar'])
  437. ->where('parent', $data['parent'])
  438. ->where('mean', $data['mean'])
  439. ->where('factors', $data['factors'])
  440. ->where('factormean', $data['factormean'])
  441. ->whereIn('source', ['_USER_WBW_', '_USER_DICT_'])
  442. ->orderby('created_at', 'asc')
  443. ->value('creator_id');
  444. $count = UserDict::where('word', $data['word'])
  445. ->where('type', $data['type'])
  446. ->where('grammar', $data['grammar'])
  447. ->where('parent', $data['parent'])
  448. ->where('mean', $data['mean'])
  449. ->where('factors', $data['factors'])
  450. ->where('factormean', $data['factormean'])
  451. ->where('source', '_SYS_USER_WBW_')
  452. ->count();
  453. if ($count === 0) {
  454. // 社区字典没有 新增
  455. $result = UserDict::insert(
  456. [
  457. 'id' => app('snowflake')->id(),
  458. 'word' => $data['word'],
  459. 'type' => $data['type'],
  460. 'grammar' => $data['grammar'],
  461. 'parent' => $data['parent'],
  462. 'mean' => $data['mean'],
  463. 'factors' => $data['factors'],
  464. 'factormean' => $data['factormean'],
  465. 'language' => $data['language'],
  466. 'source' => '_SYS_USER_WBW_',
  467. 'creator_id' => $data['creator_id'],
  468. 'ref_counter' => 1,
  469. 'dict_id' => DictApi::getSysDict('community_extract'),
  470. 'create_time' => time() * 1000,
  471. ]
  472. );
  473. } else {
  474. // 有,更新
  475. $result = UserDict::where('word', $data['word'])
  476. ->where('type', $data['type'])
  477. ->where('grammar', $data['grammar'])
  478. ->where('parent', $data['parent'])
  479. ->where('mean', $data['mean'])
  480. ->where('factors', $data['factors'])
  481. ->where('factormean', $data['factormean'])
  482. ->where('source', '_SYS_USER_WBW_')
  483. ->update(
  484. [
  485. 'creator_id' => $creator_id,
  486. 'ref_counter' => $count,
  487. ]
  488. );
  489. }
  490. return $result;
  491. }
  492. }
  493. private function update_redis($word)
  494. {
  495. // 更新 redis
  496. $Fetch = UserDict::where(['word' => $word['word'], 'source' => '_USER_WBW_'])->get();
  497. $redisWord = [];
  498. foreach ($Fetch as $one) {
  499. // code...
  500. $redisWord[] = [
  501. $one['id'],
  502. $one['word'],
  503. $one['type'],
  504. $one['grammar'],
  505. $one['parent'],
  506. $one['mean'],
  507. $one['note'],
  508. $one['factors'],
  509. $one['factormean'],
  510. $one['status'],
  511. $one['confidence'],
  512. $one['creator_id'],
  513. $one['source'],
  514. $one['language'],
  515. ];
  516. }
  517. $redisData = json_encode($redisWord, JSON_UNESCAPED_UNICODE);
  518. Redis::hSet('dict/user', $word['word'], $redisData);
  519. $redisData1 = Redis::hGet('dict/user', $word['word']);
  520. // 更新redis结束
  521. }
  522. }