TagDAO.php 12 KB

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