4
0

TagDAO.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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; // @phpstan-ignore generator.valueType
  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. return self::daoToTags($res);
  180. } else {
  181. $info = $this->pdo->errorInfo();
  182. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  183. return [];
  184. }
  185. }
  186. /** @return array<string,string> */
  187. public function listTagsNewestItemUsec(?int $id_tag = null): array {
  188. $sql = <<<'SQL'
  189. SELECT t.id AS id_tag, MAX(e.id) AS newest_item_us
  190. FROM `_tag` t
  191. LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id
  192. LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id
  193. SQL;
  194. if ($id_tag === null) {
  195. $sql .= ' GROUP BY t.id';
  196. } else {
  197. $sql .= ' WHERE t.id=' . $id_tag;
  198. }
  199. $res = $this->fetchAssoc($sql);
  200. if ($res == null) {
  201. return [];
  202. }
  203. $newestItemUsec = [];
  204. foreach ($res as $line) {
  205. $newestItemUsec['t_' . $line['id_tag']] = (string)($line['newest_item_us']);
  206. }
  207. return $newestItemUsec;
  208. }
  209. public function count(): int {
  210. $sql = 'SELECT COUNT(*) AS count FROM `_tag`';
  211. $stm = $this->pdo->query($sql);
  212. if ($stm !== false) {
  213. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  214. return (int)$res[0]['count'];
  215. }
  216. $info = $this->pdo->errorInfo();
  217. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  218. return -1;
  219. }
  220. public function countEntries(int $id): int {
  221. $sql = 'SELECT COUNT(*) AS count FROM `_entrytag` WHERE id_tag=:id_tag';
  222. $res = $this->fetchAssoc($sql, [':id_tag' => $id]);
  223. if ($res == null || !isset($res[0]['count'])) {
  224. return -1;
  225. }
  226. return (int)$res[0]['count'];
  227. }
  228. public function countNotRead(?int $id = null): int {
  229. $sql = <<<'SQL'
  230. SELECT COUNT(*) AS count FROM `_entrytag` et
  231. INNER JOIN `_entry` e ON et.id_entry=e.id
  232. WHERE e.is_read=0
  233. SQL;
  234. $values = [];
  235. if (null !== $id) {
  236. $sql .= ' AND et.id_tag=:id_tag';
  237. $values[':id_tag'] = $id;
  238. }
  239. $res = $this->fetchAssoc($sql, $values);
  240. if ($res == null || !isset($res[0]['count'])) {
  241. return -1;
  242. }
  243. return (int)$res[0]['count'];
  244. }
  245. public function tagEntry(int $id_tag, string $id_entry, bool $checked = true): bool {
  246. if ($checked) {
  247. $sql = 'INSERT ' . $this->sqlIgnore() . ' INTO `_entrytag`(id_tag, id_entry) VALUES(?, ?)';
  248. } else {
  249. $sql = 'DELETE FROM `_entrytag` WHERE id_tag=? AND id_entry=?';
  250. }
  251. $stm = $this->pdo->prepare($sql);
  252. $values = [$id_tag, $id_entry];
  253. if ($stm !== false && $stm->execute($values)) {
  254. return true;
  255. }
  256. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  257. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  258. return false;
  259. }
  260. /**
  261. * @param iterable<array{id_tag:int,id_entry:numeric-string|int}> $addLabels Labels to insert as batch
  262. * @return int|false Number of new entries or false in case of error
  263. */
  264. public function tagEntries(iterable $addLabels): int|false {
  265. $hasValues = false;
  266. $sql = 'INSERT ' . $this->sqlIgnore() . ' INTO `_entrytag`(id_tag, id_entry) VALUES ';
  267. foreach ($addLabels as $addLabel) {
  268. $id_tag = (int)($addLabel['id_tag'] ?? 0);
  269. $id_entry = $addLabel['id_entry'] ?? '';
  270. if ($id_tag > 0 && (is_int($id_entry) || ctype_digit($id_entry))) {
  271. $sql .= "({$id_tag},{$id_entry}),";
  272. $hasValues = true;
  273. }
  274. }
  275. $sql = rtrim($sql, ',');
  276. if (!$hasValues) {
  277. return false;
  278. }
  279. $affected = $this->pdo->exec($sql);
  280. if ($affected !== false) {
  281. return $affected;
  282. }
  283. $info = $this->pdo->errorInfo();
  284. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  285. return false;
  286. }
  287. /**
  288. * @return list<array{id:int,name:string,checked:bool}>
  289. */
  290. public function getTagsForEntry(string $id_entry): array {
  291. $sql = <<<'SQL'
  292. SELECT t.id, t.name, et.id_entry IS NOT NULL as checked
  293. FROM `_tag` t
  294. LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id AND et.id_entry=?
  295. ORDER BY t.name
  296. SQL;
  297. $stm = $this->pdo->prepare($sql);
  298. $values = [$id_entry];
  299. if ($stm !== false && $stm->execute($values) && ($lines = $stm->fetchAll(PDO::FETCH_ASSOC)) !== false) {
  300. $result = [];
  301. foreach ($lines as $line) {
  302. $result[] = [
  303. 'id' => (int)($line['id']),
  304. 'name' => $line['name'],
  305. 'checked' => !empty($line['checked']),
  306. ];
  307. }
  308. return $result;
  309. }
  310. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  311. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  312. return [];
  313. }
  314. /**
  315. * @param list<FreshRSS_Entry|numeric-string> $entries
  316. * @return list<array{id_entry:int|numeric-string,id_tag:int,name:string}>|null
  317. */
  318. public function getTagsForEntries(array $entries): array|null {
  319. $sql = <<<'SQL'
  320. SELECT et.id_entry, et.id_tag, t.name
  321. FROM `_tag` t
  322. INNER JOIN `_entrytag` et ON et.id_tag = t.id
  323. SQL;
  324. $values = [];
  325. if (count($entries) > 0) {
  326. if (count($entries) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  327. // Split a query with too many variables parameters
  328. $idsChunks = array_chunk($entries, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  329. foreach ($idsChunks as $idsChunk) {
  330. $valuesChunk = $this->getTagsForEntries($idsChunk);
  331. if (!is_array($valuesChunk)) {
  332. return null;
  333. }
  334. $values = array_merge($values, $valuesChunk);
  335. }
  336. return $values;
  337. }
  338. $sql .= ' AND et.id_entry IN (' . str_repeat('?,', count($entries) - 1) . '?)';
  339. foreach ($entries as $entry) {
  340. $values[] = is_object($entry) ? $entry->id() : $entry;
  341. }
  342. }
  343. $stm = $this->pdo->prepare($sql);
  344. if ($stm !== false && $stm->execute($values)) {
  345. $result = $stm->fetchAll(PDO::FETCH_ASSOC);
  346. /** @var list<array{id_entry:int|numeric-string,id_tag:int,name:string}> $result; */
  347. return $result;
  348. }
  349. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  350. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  351. return null;
  352. }
  353. /**
  354. * Produces an array: for each entry ID (prefixed by `e_`), associate a list of labels.
  355. * 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).
  356. * @param list<FreshRSS_Entry|numeric-string> $entries the list of entries for which to retrieve the labels.
  357. * @return array<string,array<string>> An array of the shape `[e_id_entry => ["label 1", "label 2"]]`
  358. */
  359. public function getEntryIdsTagNames(array $entries): array {
  360. $result = [];
  361. foreach ($this->getTagsForEntries($entries) ?? [] as $line) {
  362. $entryId = 'e_' . $line['id_entry'];
  363. $tagName = $line['name'];
  364. if (empty($result[$entryId])) {
  365. $result[$entryId] = [];
  366. }
  367. $result[$entryId][] = $tagName;
  368. }
  369. return $result;
  370. }
  371. /**
  372. * @param iterable<array{id:int,name:string,attributes?:string,unreads?:int}> $listDAO
  373. * @return array<int,FreshRSS_Tag> where the key is the label ID
  374. */
  375. private static function daoToTags(iterable $listDAO): array {
  376. $list = [];
  377. foreach ($listDAO as $dao) {
  378. if (empty($dao['id']) || empty($dao['name'])) {
  379. continue;
  380. }
  381. $tag = new FreshRSS_Tag($dao['name']);
  382. $tag->_id($dao['id']);
  383. if (!empty($dao['attributes'])) {
  384. $tag->_attributes($dao['attributes']);
  385. }
  386. if (isset($dao['unreads'])) {
  387. $tag->_nbUnread($dao['unreads']);
  388. }
  389. $list[$tag->id()] = $tag;
  390. }
  391. return $list;
  392. }
  393. }