TagDAO.php 14 KB

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