TagDAO.php 14 KB

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