TagDAO.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_TagDAO extends Minz_ModelPdo {
  4. public function sqlIgnore(): string {
  5. return 'IGNORE';
  6. }
  7. public function sqlResetSequence(): bool {
  8. return true; // Nothing to do for MySQL
  9. }
  10. /**
  11. * @param array{id?:int,name:string,attributes?:array<string,mixed>} $valuesTmp
  12. */
  13. public function addTag(array $valuesTmp): int|false {
  14. if (empty($valuesTmp['id'])) { // Auto-generated ID
  15. $sql = <<<'SQL'
  16. INSERT INTO `_tag`(name, attributes)
  17. SELECT * FROM (SELECT :name1 AS name, :attributes AS attributes) t2
  18. SQL;
  19. } else {
  20. $sql = <<<'SQL'
  21. INSERT INTO `_tag`(id, name, attributes)
  22. SELECT * FROM (SELECT 1*:id AS id, :name1 AS name, :attributes AS attributes) t2
  23. SQL;
  24. }
  25. // No category of the same name
  26. $sql .= "\n" . <<<'SQL'
  27. WHERE NOT EXISTS (SELECT 1 FROM `_category` WHERE name = :name2)
  28. SQL;
  29. $stm = $this->pdo->prepare($sql);
  30. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  31. if (!isset($valuesTmp['attributes'])) {
  32. $valuesTmp['attributes'] = [];
  33. }
  34. if ($stm !== false &&
  35. (empty($valuesTmp['id']) || $stm->bindValue(':id', $valuesTmp['id'], PDO::PARAM_INT)) &&
  36. $stm->bindValue(':name1', $valuesTmp['name'], PDO::PARAM_STR) &&
  37. $stm->bindValue(':name2', $valuesTmp['name'], PDO::PARAM_STR) &&
  38. $stm->bindValue(':attributes', is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] :
  39. json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PDO::PARAM_STR) &&
  40. $stm->execute() && $stm->rowCount() > 0) {
  41. if (empty($valuesTmp['id'])) {
  42. // Auto-generated ID
  43. $tagId = $this->pdo->lastInsertId('`_tag_id_seq`');
  44. return $tagId === false ? false : (int)$tagId;
  45. }
  46. $this->sqlResetSequence();
  47. return $valuesTmp['id'];
  48. } else {
  49. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  50. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  51. return false;
  52. }
  53. }
  54. public function addTagObject(FreshRSS_Tag $tag): int|false {
  55. $tag0 = $this->searchByName($tag->name());
  56. if ($tag0 === null) {
  57. $values = [
  58. 'name' => $tag->name(),
  59. 'attributes' => $tag->attributes(),
  60. ];
  61. return $this->addTag($values);
  62. }
  63. return $tag->id();
  64. }
  65. public function updateTagName(int $id, string $name): int|false {
  66. // No category of the same name
  67. $sql = <<<'SQL'
  68. UPDATE `_tag` SET name = :name1 WHERE id = :id
  69. AND NOT EXISTS (SELECT 1 FROM `_category` WHERE name = :name2)
  70. SQL;
  71. $name = mb_strcut(trim($name), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  72. $stm = $this->pdo->prepare($sql);
  73. if ($stm !== false &&
  74. $stm->bindValue(':id', $id, PDO::PARAM_INT) &&
  75. $stm->bindValue(':name1', $name, PDO::PARAM_STR) &&
  76. $stm->bindValue(':name2', $name, PDO::PARAM_STR) &&
  77. $stm->execute()) {
  78. return $stm->rowCount();
  79. } else {
  80. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  81. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  82. return false;
  83. }
  84. }
  85. /**
  86. * @param array<string,mixed> $attributes
  87. */
  88. public function updateTagAttributes(int $id, array $attributes): int|false {
  89. $sql = <<<'SQL'
  90. UPDATE `_tag` SET attributes=:attributes WHERE id=:id
  91. SQL;
  92. $stm = $this->pdo->prepare($sql);
  93. if ($stm !== false &&
  94. $stm->bindValue(':id', $id, PDO::PARAM_INT) &&
  95. $stm->bindValue(':attributes', json_encode($attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PDO::PARAM_STR) &&
  96. $stm->execute()) {
  97. return $stm->rowCount();
  98. }
  99. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  100. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  101. return false;
  102. }
  103. /**
  104. * @param non-empty-string $key
  105. */
  106. public function updateTagAttribute(FreshRSS_Tag $tag, string $key, mixed $value): int|false {
  107. $tag->_attribute($key, $value);
  108. return $this->updateTagAttributes($tag->id(), $tag->attributes());
  109. }
  110. public function deleteTag(int $id): int|false {
  111. if ($id <= 0) {
  112. return false;
  113. }
  114. $sql = <<<'SQL'
  115. DELETE FROM `_tag` WHERE id=:id
  116. SQL;
  117. $stm = $this->pdo->prepare($sql);
  118. if ($stm !== false &&
  119. $stm->bindValue(':id', $id, PDO::PARAM_INT) &&
  120. $stm->execute()) {
  121. return $stm->rowCount();
  122. } else {
  123. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  124. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  125. return false;
  126. }
  127. }
  128. /** @return Traversable<array{id:int,name:string,attributes?:array<string,mixed>}> */
  129. public function selectAll(): Traversable {
  130. $sql = <<<'SQL'
  131. SELECT id, name, attributes FROM `_tag`
  132. SQL;
  133. $stm = $this->pdo->query($sql);
  134. if ($stm === false) {
  135. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($this->pdo->errorInfo()));
  136. return;
  137. }
  138. while (is_array($row = $stm->fetch(PDO::FETCH_ASSOC))) {
  139. /** @var array{id:int,name:string,attributes?:array<string,mixed>} $row */
  140. yield $row;
  141. }
  142. }
  143. /** @return Traversable<array{id_tag:int,id_entry:int|numeric-string}> */
  144. public function selectEntryTag(): Traversable {
  145. $sql = <<<'SQL'
  146. SELECT id_tag, id_entry FROM `_entrytag`
  147. SQL;
  148. $stm = $this->pdo->query($sql);
  149. if ($stm === false) {
  150. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($this->pdo->errorInfo()));
  151. return;
  152. }
  153. while (is_array($row = $stm->fetch(PDO::FETCH_ASSOC))) {
  154. /** @var array{id_tag:int,id_entry:int|numeric-string} $row */
  155. yield $row;
  156. }
  157. }
  158. public function updateEntryTag(int $oldTagId, int $newTagId): int|false {
  159. $sql = <<<'SQL'
  160. DELETE FROM `_entrytag` WHERE EXISTS (
  161. SELECT 1 FROM `_entrytag` AS e
  162. WHERE e.id_entry = `_entrytag`.id_entry AND e.id_tag = :new_tag_id AND `_entrytag`.id_tag = :old_tag_id)
  163. SQL;
  164. $stm = $this->pdo->prepare($sql);
  165. if ($stm === false ||
  166. !$stm->bindValue(':new_tag_id', $newTagId, PDO::PARAM_INT) ||
  167. !$stm->bindValue(':old_tag_id', $oldTagId, PDO::PARAM_INT) ||
  168. !$stm->execute()) {
  169. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  170. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  171. return false;
  172. }
  173. $sql = <<<'SQL'
  174. UPDATE `_entrytag` SET id_tag = :new_tag_id WHERE id_tag = :old_tag_id
  175. SQL;
  176. $stm = $this->pdo->prepare($sql);
  177. if ($stm !== false &&
  178. $stm->bindValue(':new_tag_id', $newTagId, PDO::PARAM_INT) &&
  179. $stm->bindValue(':old_tag_id', $oldTagId, PDO::PARAM_INT) &&
  180. $stm->execute()) {
  181. return $stm->rowCount();
  182. }
  183. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  184. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  185. return false;
  186. }
  187. public function searchById(int $id): ?FreshRSS_Tag {
  188. $res = $this->fetchAssoc('SELECT * FROM `_tag` WHERE id=:id', [':id' => $id]);
  189. /** @var list<array{id:int,name:string,attributes?:string}>|null $res */
  190. return $res === null ? null : (current(self::daoToTags($res)) ?: null);
  191. }
  192. public function searchByName(string $name): ?FreshRSS_Tag {
  193. $res = $this->fetchAssoc('SELECT * FROM `_tag` WHERE name=:name', [':name' => $name]);
  194. /** @var list<array{id:int,name:string,attributes?:string}>|null $res */
  195. return $res === null ? null : (current(self::daoToTags($res)) ?: null);
  196. }
  197. /** @return array<int,FreshRSS_Tag> where the key is the label ID */
  198. public function listTags(bool $precounts = false): array {
  199. if ($precounts) {
  200. $sql = <<<'SQL'
  201. SELECT t.id, t.name, count(e.id) AS unreads
  202. FROM `_tag` t
  203. LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id
  204. LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id AND e.is_read = 0
  205. GROUP BY t.id
  206. ORDER BY t.name
  207. SQL;
  208. } else {
  209. $sql = <<<'SQL'
  210. SELECT * FROM `_tag` ORDER BY name
  211. SQL;
  212. }
  213. $res = $this->fetchAssoc($sql);
  214. if ($res !== null) {
  215. /** @var list<array{id:int,name:string,unreads:int}> $res */
  216. return self::daoToTags($res);
  217. } else {
  218. $info = $this->pdo->errorInfo();
  219. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  220. return [];
  221. }
  222. }
  223. /** @return array<string,string> */
  224. public function listTagsNewestItemUsec(?int $id_tag = null): array {
  225. $sql = <<<'SQL'
  226. SELECT t.id AS id_tag, MAX(e.id) AS newest_item_us
  227. FROM `_tag` t
  228. LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id
  229. LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id
  230. SQL;
  231. if ($id_tag === null) {
  232. $sql .= "\n" . <<<'SQL'
  233. GROUP BY t.id
  234. SQL;
  235. } else {
  236. $sql .= "\n" . <<<SQL
  237. WHERE t.id={$id_tag}
  238. SQL;
  239. }
  240. $res = $this->fetchAssoc($sql);
  241. if ($res == null) {
  242. return [];
  243. }
  244. $newestItemUsec = [];
  245. foreach ($res as $line) {
  246. $newestItemUsec['t_' . $line['id_tag']] = (string)($line['newest_item_us']);
  247. }
  248. return $newestItemUsec;
  249. }
  250. public function count(): int {
  251. $sql = <<<'SQL'
  252. SELECT COUNT(*) AS count FROM `_tag`
  253. SQL;
  254. return $this->fetchInt($sql) ?? -1;
  255. }
  256. public function countEntries(int $id): int {
  257. $sql = <<<'SQL'
  258. SELECT COUNT(*) AS count FROM `_entrytag` WHERE id_tag=:id_tag
  259. SQL;
  260. return $this->fetchInt($sql, [':id_tag' => $id]) ?? -1;
  261. }
  262. public function countNotRead(?int $id = null): int {
  263. $sql = <<<'SQL'
  264. SELECT COUNT(*) AS count FROM `_entrytag` et
  265. INNER JOIN `_entry` e ON et.id_entry=e.id
  266. WHERE e.is_read=0
  267. SQL;
  268. $values = [];
  269. if (null !== $id) {
  270. $sql .= "\n" . <<<'SQL'
  271. AND et.id_tag=:id_tag
  272. SQL;
  273. $values[':id_tag'] = $id;
  274. }
  275. return $this->fetchInt($sql, $values) ?? -1;
  276. }
  277. public function tagEntry(int $id_tag, string $id_entry, bool $checked = true): bool {
  278. if ($checked) {
  279. $ignore = $this->sqlIgnore();
  280. $sql = <<<SQL
  281. INSERT {$ignore} INTO `_entrytag`(id_tag, id_entry) VALUES(:id_tag, :id_entry)
  282. SQL;
  283. } else {
  284. $sql = <<<'SQL'
  285. DELETE FROM `_entrytag` WHERE id_tag=:id_tag AND id_entry=:id_entry
  286. SQL;
  287. }
  288. $stm = $this->pdo->prepare($sql);
  289. if ($stm !== false &&
  290. $stm->bindValue(':id_tag', $id_tag, PDO::PARAM_INT) &&
  291. $stm->bindValue(':id_entry', $id_entry, PDO::PARAM_STR) &&
  292. $stm->execute()) {
  293. return true;
  294. }
  295. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  296. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  297. return false;
  298. }
  299. /**
  300. * @param iterable<array{id_tag:int,id_entry:numeric-string|int}> $addLabels Labels to insert as batch
  301. * @return int|false Number of new entries or false in case of error
  302. */
  303. public function tagEntries(iterable $addLabels): int|false {
  304. $hasValues = false;
  305. $ignore = $this->sqlIgnore();
  306. $sql = <<<SQL
  307. INSERT {$ignore} INTO `_entrytag`(id_tag, id_entry) VALUES
  308. SQL;
  309. foreach ($addLabels as $addLabel) {
  310. $id_tag = (int)($addLabel['id_tag'] ?? 0);
  311. $id_entry = $addLabel['id_entry'] ?? '';
  312. if ($id_tag > 0 && (is_int($id_entry) || ctype_digit($id_entry))) {
  313. $sql .= "({$id_tag},{$id_entry}),";
  314. $hasValues = true;
  315. }
  316. }
  317. $sql = rtrim($sql, ',');
  318. if (!$hasValues) {
  319. return false;
  320. }
  321. $affected = $this->pdo->exec($sql);
  322. if ($affected !== false) {
  323. return $affected;
  324. }
  325. $info = $this->pdo->errorInfo();
  326. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  327. return false;
  328. }
  329. /**
  330. * @return list<array{id:int,name:string,checked:bool}>
  331. */
  332. public function getTagsForEntry(string $id_entry): array {
  333. $sql = <<<'SQL'
  334. SELECT t.id, t.name, et.id_entry IS NOT NULL as checked
  335. FROM `_tag` t
  336. LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id AND et.id_entry=:id_entry
  337. ORDER BY t.name
  338. SQL;
  339. $lines = $this->fetchAssoc($sql, [':id_entry' => $id_entry]);
  340. if ($lines !== null) {
  341. $result = [];
  342. foreach ($lines as $line) {
  343. /** @var array{id:int,name:string,checked:int} $line */
  344. $result[] = [
  345. 'id' => (int)($line['id']),
  346. 'name' => $line['name'],
  347. 'checked' => !empty($line['checked']),
  348. ];
  349. }
  350. return $result;
  351. }
  352. $info = $this->pdo->errorInfo();
  353. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  354. return [];
  355. }
  356. /**
  357. * @param list<FreshRSS_Entry|numeric-string> $entries
  358. * @return list<array{id_entry:int|numeric-string,id_tag:int,name:string}>|null
  359. */
  360. public function getTagsForEntries(array $entries): array|null {
  361. $sql = <<<'SQL'
  362. SELECT et.id_entry, et.id_tag, t.name
  363. FROM `_tag` t
  364. INNER JOIN `_entrytag` et ON et.id_tag = t.id
  365. SQL;
  366. $values = [];
  367. if (count($entries) > 0) {
  368. if (count($entries) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  369. // Split a query with too many variables parameters
  370. $idsChunks = array_chunk($entries, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  371. foreach ($idsChunks as $idsChunk) {
  372. $valuesChunk = $this->getTagsForEntries($idsChunk);
  373. if (!is_array($valuesChunk)) {
  374. return null;
  375. }
  376. $values = array_merge($values, $valuesChunk);
  377. }
  378. return $values;
  379. }
  380. $idPlaceholders = str_repeat('?,', count($entries) - 1) . '?';
  381. $sql .= "\n" . <<<SQL
  382. AND et.id_entry IN ({$idPlaceholders})
  383. SQL;
  384. foreach ($entries as $entry) {
  385. $values[] = is_object($entry) ? $entry->id() : $entry;
  386. }
  387. }
  388. $stm = $this->pdo->prepare($sql);
  389. if ($stm !== false && $stm->execute($values)) {
  390. $result = $stm->fetchAll(PDO::FETCH_ASSOC);
  391. /** @var list<array{id_entry:int|numeric-string,id_tag:int,name:string}> $result; */
  392. return $result;
  393. }
  394. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  395. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  396. return null;
  397. }
  398. /**
  399. * Produces an array: for each entry ID (prefixed by `e_`), associate a list of labels.
  400. * Used by API and by JSON export, to speed up queries (would be very expensive to perform a label look-up on each entry individually).
  401. * @param list<FreshRSS_Entry|numeric-string> $entries the list of entries for which to retrieve the labels.
  402. * @return array<string,array<string>> An array of the shape `[e_id_entry => ["label 1", "label 2"]]`
  403. */
  404. public function getEntryIdsTagNames(array $entries): array {
  405. $result = [];
  406. foreach ($this->getTagsForEntries($entries) ?? [] as $line) {
  407. $entryId = 'e_' . $line['id_entry'];
  408. $tagName = $line['name'];
  409. if (empty($result[$entryId])) {
  410. $result[$entryId] = [];
  411. }
  412. $result[$entryId][] = $tagName;
  413. }
  414. return $result;
  415. }
  416. /**
  417. * @param iterable<array{id:int,name:string,attributes?:string,unreads?:int}> $listDAO
  418. * @return array<int,FreshRSS_Tag> where the key is the label ID
  419. */
  420. private static function daoToTags(iterable $listDAO): array {
  421. $list = [];
  422. foreach ($listDAO as $dao) {
  423. if (empty($dao['id']) || empty($dao['name'])) {
  424. continue;
  425. }
  426. $tag = new FreshRSS_Tag($dao['name']);
  427. $tag->_id($dao['id']);
  428. if (!empty($dao['attributes'])) {
  429. $tag->_attributes($dao['attributes']);
  430. }
  431. if (isset($dao['unreads'])) {
  432. $tag->_nbUnread($dao['unreads']);
  433. }
  434. $list[$tag->id()] = $tag;
  435. }
  436. return $list;
  437. }
  438. }