TagDAO.php 13 KB

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