TagDAO.php 13 KB

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