TagDAO.php 13 KB

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