TagDAO.php 13 KB

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