TagDAO.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 (is_array($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:int|numeric-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 (is_array($row = $stm->fetch(PDO::FETCH_ASSOC))) {
  128. /** @var array{id_tag:int,id_entry:int|numeric-string} $row */
  129. yield $row;
  130. }
  131. }
  132. public function updateEntryTag(int $oldTagId, int $newTagId): int|false {
  133. $sql = <<<'SQL'
  134. DELETE FROM `_entrytag` WHERE EXISTS (
  135. SELECT 1 FROM `_entrytag` AS e
  136. WHERE e.id_entry = `_entrytag`.id_entry AND e.id_tag = ? AND `_entrytag`.id_tag = ?)
  137. SQL;
  138. $stm = $this->pdo->prepare($sql);
  139. if ($stm === false || !$stm->execute([$newTagId, $oldTagId])) {
  140. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  141. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  142. return false;
  143. }
  144. $sql = 'UPDATE `_entrytag` SET id_tag = ? WHERE id_tag = ?';
  145. $stm = $this->pdo->prepare($sql);
  146. if ($stm !== false && $stm->execute([$newTagId, $oldTagId])) {
  147. return $stm->rowCount();
  148. }
  149. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  150. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  151. return false;
  152. }
  153. public function searchById(int $id): ?FreshRSS_Tag {
  154. $res = $this->fetchAssoc('SELECT * FROM `_tag` WHERE id=:id', [':id' => $id]);
  155. /** @var list<array{id:int,name:string,attributes?:string}>|null $res */
  156. return $res === null ? null : (current(self::daoToTags($res)) ?: null);
  157. }
  158. public function searchByName(string $name): ?FreshRSS_Tag {
  159. $res = $this->fetchAssoc('SELECT * FROM `_tag` WHERE name=:name', [':name' => $name]);
  160. /** @var list<array{id:int,name:string,attributes?:string}>|null $res */
  161. return $res === null ? null : (current(self::daoToTags($res)) ?: null);
  162. }
  163. /** @return array<int,FreshRSS_Tag> where the key is the label ID */
  164. public function listTags(bool $precounts = false): array {
  165. if ($precounts) {
  166. $sql = <<<'SQL'
  167. SELECT t.id, t.name, count(e.id) AS unreads
  168. FROM `_tag` t
  169. LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id
  170. LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id AND e.is_read = 0
  171. GROUP BY t.id
  172. ORDER BY t.name
  173. SQL;
  174. } else {
  175. $sql = 'SELECT * FROM `_tag` ORDER BY name';
  176. }
  177. $stm = $this->pdo->query($sql);
  178. if ($stm !== false && ($res = $stm->fetchAll(PDO::FETCH_ASSOC)) !== false) {
  179. /** @var list<array{id:int,name:string,unreads:int}> $res */
  180. return self::daoToTags($res);
  181. } else {
  182. $info = $this->pdo->errorInfo();
  183. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  184. return [];
  185. }
  186. }
  187. /** @return array<string,string> */
  188. public function listTagsNewestItemUsec(?int $id_tag = null): array {
  189. $sql = <<<'SQL'
  190. SELECT t.id AS id_tag, MAX(e.id) AS newest_item_us
  191. FROM `_tag` t
  192. LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id
  193. LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id
  194. SQL;
  195. if ($id_tag === null) {
  196. $sql .= ' GROUP BY t.id';
  197. } else {
  198. $sql .= ' WHERE t.id=' . $id_tag;
  199. }
  200. $res = $this->fetchAssoc($sql);
  201. if ($res == null) {
  202. return [];
  203. }
  204. $newestItemUsec = [];
  205. foreach ($res as $line) {
  206. $newestItemUsec['t_' . $line['id_tag']] = (string)($line['newest_item_us']);
  207. }
  208. return $newestItemUsec;
  209. }
  210. public function count(): int {
  211. $sql = 'SELECT COUNT(*) AS count FROM `_tag`';
  212. $stm = $this->pdo->query($sql);
  213. if ($stm !== false) {
  214. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  215. /** @var list<array{count:int|numeric-string}> $res */
  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 iterable<array{id_tag:int,id_entry:numeric-string|int}> $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(iterable $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 && (is_int($id_entry) || 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 list<array{id:int,name:string,checked:bool}>
  291. */
  292. public function getTagsForEntry(string $id_entry): array {
  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) && ($lines = $stm->fetchAll(PDO::FETCH_ASSOC)) !== false) {
  302. $result = [];
  303. foreach ($lines as $line) {
  304. /** @var array{id:int,name:string,checked:int} $line */
  305. $result[] = [
  306. 'id' => (int)($line['id']),
  307. 'name' => $line['name'],
  308. 'checked' => !empty($line['checked']),
  309. ];
  310. }
  311. return $result;
  312. }
  313. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  314. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  315. return [];
  316. }
  317. /**
  318. * @param list<FreshRSS_Entry|numeric-string> $entries
  319. * @return list<array{id_entry:int|numeric-string,id_tag:int,name:string}>|null
  320. */
  321. public function getTagsForEntries(array $entries): array|null {
  322. $sql = <<<'SQL'
  323. SELECT et.id_entry, et.id_tag, t.name
  324. FROM `_tag` t
  325. INNER JOIN `_entrytag` et ON et.id_tag = t.id
  326. SQL;
  327. $values = [];
  328. if (count($entries) > 0) {
  329. if (count($entries) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  330. // Split a query with too many variables parameters
  331. $idsChunks = array_chunk($entries, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  332. foreach ($idsChunks as $idsChunk) {
  333. $valuesChunk = $this->getTagsForEntries($idsChunk);
  334. if (!is_array($valuesChunk)) {
  335. return null;
  336. }
  337. $values = array_merge($values, $valuesChunk);
  338. }
  339. return $values;
  340. }
  341. $sql .= ' AND et.id_entry IN (' . str_repeat('?,', count($entries) - 1) . '?)';
  342. foreach ($entries as $entry) {
  343. $values[] = is_object($entry) ? $entry->id() : $entry;
  344. }
  345. }
  346. $stm = $this->pdo->prepare($sql);
  347. if ($stm !== false && $stm->execute($values)) {
  348. $result = $stm->fetchAll(PDO::FETCH_ASSOC);
  349. /** @var list<array{id_entry:int|numeric-string,id_tag:int,name:string}> $result; */
  350. return $result;
  351. }
  352. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  353. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  354. return null;
  355. }
  356. /**
  357. * Produces an array: for each entry ID (prefixed by `e_`), associate a list of labels.
  358. * 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).
  359. * @param list<FreshRSS_Entry|numeric-string> $entries the list of entries for which to retrieve the labels.
  360. * @return array<string,array<string>> An array of the shape `[e_id_entry => ["label 1", "label 2"]]`
  361. */
  362. public function getEntryIdsTagNames(array $entries): array {
  363. $result = [];
  364. foreach ($this->getTagsForEntries($entries) ?? [] as $line) {
  365. $entryId = 'e_' . $line['id_entry'];
  366. $tagName = $line['name'];
  367. if (empty($result[$entryId])) {
  368. $result[$entryId] = [];
  369. }
  370. $result[$entryId][] = $tagName;
  371. }
  372. return $result;
  373. }
  374. /**
  375. * @param iterable<array{id:int,name:string,attributes?:string,unreads?:int}> $listDAO
  376. * @return array<int,FreshRSS_Tag> where the key is the label ID
  377. */
  378. private static function daoToTags(iterable $listDAO): array {
  379. $list = [];
  380. foreach ($listDAO as $dao) {
  381. if (empty($dao['id']) || empty($dao['name'])) {
  382. continue;
  383. }
  384. $tag = new FreshRSS_Tag($dao['name']);
  385. $tag->_id($dao['id']);
  386. if (!empty($dao['attributes'])) {
  387. $tag->_attributes($dao['attributes']);
  388. }
  389. if (isset($dao['unreads'])) {
  390. $tag->_nbUnread($dao['unreads']);
  391. }
  392. $list[$tag->id()] = $tag;
  393. }
  394. return $list;
  395. }
  396. }