TagDAO.php 14 KB

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