TagDAO.php 13 KB

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