TagDAO.php 13 KB

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