TagDAO.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. <?php
  2. class FreshRSS_TagDAO extends Minz_ModelPdo {
  3. public function sqlIgnore(): string {
  4. return 'IGNORE';
  5. }
  6. public function createTagTable() {
  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. public function addTag($valuesTmp) {
  39. // TRIM() gives a text type hint to PostgreSQL
  40. // No category of the same name
  41. $sql = <<<'SQL'
  42. INSERT INTO `_tag`(name, attributes)
  43. SELECT * FROM (SELECT TRIM(?) as name, TRIM(?) as attributes) t2
  44. WHERE NOT EXISTS (SELECT 1 FROM `_category` WHERE name = TRIM(?))
  45. SQL;
  46. $stm = $this->pdo->prepare($sql);
  47. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, 63, 'UTF-8');
  48. if (!isset($valuesTmp['attributes'])) {
  49. $valuesTmp['attributes'] = [];
  50. }
  51. $values = array(
  52. $valuesTmp['name'],
  53. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  54. $valuesTmp['name'],
  55. );
  56. if ($stm && $stm->execute($values) && $stm->rowCount() > 0) {
  57. return $this->pdo->lastInsertId('`_tag_id_seq`');
  58. } else {
  59. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  60. Minz_Log::error('SQL error addTag: ' . $info[2]);
  61. return false;
  62. }
  63. }
  64. /**
  65. * @param FreshRSS_Tag $tag
  66. */
  67. public function addTagObject($tag) {
  68. $tag0 = $this->searchByName($tag->name());
  69. if (!$tag0) {
  70. $values = array(
  71. 'name' => $tag->name(),
  72. 'attributes' => $tag->attributes(),
  73. );
  74. return $this->addTag($values);
  75. }
  76. return $tag->id();
  77. }
  78. /**
  79. * @return integer|false
  80. */
  81. public function updateTag($id, $valuesTmp) {
  82. // No category of the same name
  83. $sql = <<<'SQL'
  84. UPDATE `_tag` SET name=?, attributes=? WHERE id=?
  85. AND NOT EXISTS (SELECT 1 FROM `_category` WHERE name = ?)
  86. SQL;
  87. $stm = $this->pdo->prepare($sql);
  88. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, 63, 'UTF-8');
  89. if (!isset($valuesTmp['attributes'])) {
  90. $valuesTmp['attributes'] = [];
  91. }
  92. $values = array(
  93. $valuesTmp['name'],
  94. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  95. $id,
  96. $valuesTmp['name'],
  97. );
  98. if ($stm && $stm->execute($values)) {
  99. return $stm->rowCount();
  100. } else {
  101. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  102. Minz_Log::error('SQL error updateTag: ' . $info[2]);
  103. return false;
  104. }
  105. }
  106. /**
  107. * @return integer|false
  108. */
  109. public function updateTagAttribute($tag, $key, $value) {
  110. if ($tag instanceof FreshRSS_Tag) {
  111. $tag->_attributes($key, $value);
  112. return $this->updateTag(
  113. $tag->id(),
  114. [ 'attributes' => $tag->attributes() ]
  115. );
  116. }
  117. return false;
  118. }
  119. /**
  120. * @return integer|false
  121. */
  122. public function deleteTag($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. public function selectAll() {
  138. $sql = 'SELECT id, name, attributes FROM `_tag`';
  139. $stm = $this->pdo->query($sql);
  140. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  141. yield $row;
  142. }
  143. }
  144. public function selectEntryTag() {
  145. $sql = 'SELECT id_tag, id_entry FROM `_entrytag`';
  146. $stm = $this->pdo->query($sql);
  147. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  148. yield $row;
  149. }
  150. }
  151. /**
  152. * @return integer|false
  153. */
  154. public function updateEntryTag($oldTagId, $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. public function listTags($precounts = false) {
  195. if ($precounts) {
  196. $sql = 'SELECT t.id, t.name, count(e.id) AS unreads '
  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 AND e.is_read = 0 '
  200. . 'GROUP BY t.id '
  201. . 'ORDER BY t.name';
  202. } else {
  203. $sql = 'SELECT * FROM `_tag` ORDER BY name';
  204. }
  205. $stm = $this->pdo->query($sql);
  206. if ($stm !== false) {
  207. return self::daoToTag($stm->fetchAll(PDO::FETCH_ASSOC));
  208. } else {
  209. $info = $this->pdo->errorInfo();
  210. if ($this->autoUpdateDb($info)) {
  211. return $this->listTags($precounts);
  212. }
  213. Minz_Log::error('SQL error listTags: ' . $info[2]);
  214. return false;
  215. }
  216. }
  217. public function listTagsNewestItemUsec($id_tag = null) {
  218. $sql = 'SELECT t.id AS id_tag, MAX(e.id) AS newest_item_us '
  219. . 'FROM `_tag` t '
  220. . 'LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id '
  221. . 'LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id ';
  222. if ($id_tag === null) {
  223. $sql .= 'GROUP BY t.id';
  224. } else {
  225. $sql .= 'WHERE t.id=' . intval($id_tag);
  226. }
  227. $stm = $this->pdo->query($sql);
  228. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  229. $newestItemUsec = [];
  230. foreach ($res as $line) {
  231. $newestItemUsec['t_' . $line['id_tag']] = $line['newest_item_us'];
  232. }
  233. return $newestItemUsec;
  234. }
  235. /** @return int|false */
  236. public function count() {
  237. $sql = 'SELECT COUNT(*) AS count FROM `_tag`';
  238. $stm = $this->pdo->query($sql);
  239. if ($stm !== false) {
  240. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  241. return (int)$res[0]['count'];
  242. } else {
  243. $info = $this->pdo->errorInfo();
  244. if ($this->autoUpdateDb($info)) {
  245. return $this->count();
  246. }
  247. Minz_Log::error('SQL error TagDAO::count: ' . $info[2]);
  248. return false;
  249. }
  250. }
  251. /**
  252. * @return int|false
  253. */
  254. public function countEntries(int $id) {
  255. $sql = 'SELECT COUNT(*) AS count FROM `_entrytag` WHERE id_tag=?';
  256. $values = array($id);
  257. if (($stm = $this->pdo->prepare($sql)) !== false &&
  258. $stm->execute($values) &&
  259. ($res = $stm->fetchAll(PDO::FETCH_ASSOC)) !== false) {
  260. return (int)$res[0]['count'];
  261. } else {
  262. $info = is_object($stm) ? $stm->errorInfo() : $this->pdo->errorInfo();
  263. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  264. return false;
  265. }
  266. }
  267. /**
  268. * @return int|false
  269. */
  270. public function countNotRead(?int $id = null) {
  271. $sql = 'SELECT COUNT(*) AS count FROM `_entrytag` et '
  272. . 'INNER JOIN `_entry` e ON et.id_entry=e.id '
  273. . 'WHERE e.is_read=0';
  274. $values = null;
  275. if (null !== $id) {
  276. $sql .= ' AND et.id_tag=?';
  277. $values = [$id];
  278. }
  279. if (($stm = $this->pdo->prepare($sql)) !== false &&
  280. $stm->execute($values) &&
  281. ($res = $stm->fetchAll(PDO::FETCH_ASSOC)) !== false) {
  282. return (int)$res[0]['count'];
  283. } else {
  284. $info = is_object($stm) ? $stm->errorInfo() : $this->pdo->errorInfo();
  285. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  286. return false;
  287. }
  288. }
  289. public function tagEntry(int $id_tag, string $id_entry, bool $checked = true) {
  290. if ($checked) {
  291. $sql = 'INSERT ' . $this->sqlIgnore() . ' INTO `_entrytag`(id_tag, id_entry) VALUES(?, ?)';
  292. } else {
  293. $sql = 'DELETE FROM `_entrytag` WHERE id_tag=? AND id_entry=?';
  294. }
  295. $stm = $this->pdo->prepare($sql);
  296. $values = array($id_tag, $id_entry);
  297. if ($stm && $stm->execute($values)) {
  298. return true;
  299. } else {
  300. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  301. Minz_Log::error('SQL error tagEntry: ' . $info[2]);
  302. return false;
  303. }
  304. }
  305. /**
  306. * @return array<int,array{'id':int,'name':string,'id_entry':string,'checked':bool}>|false
  307. */
  308. public function getTagsForEntry(string $id_entry) {
  309. $sql = 'SELECT t.id, t.name, et.id_entry IS NOT NULL as checked '
  310. . 'FROM `_tag` t '
  311. . 'LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id AND et.id_entry=? '
  312. . 'ORDER BY t.name';
  313. $stm = $this->pdo->prepare($sql);
  314. $values = array($id_entry);
  315. if ($stm && $stm->execute($values)) {
  316. $lines = $stm->fetchAll(PDO::FETCH_ASSOC);
  317. for ($i = count($lines) - 1; $i >= 0; $i--) {
  318. $lines[$i]['id'] = intval($lines[$i]['id']);
  319. $lines[$i]['checked'] = !empty($lines[$i]['checked']);
  320. }
  321. return $lines;
  322. } else {
  323. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  324. if ($this->autoUpdateDb($info)) {
  325. return $this->getTagsForEntry($id_entry);
  326. }
  327. Minz_Log::error('SQL error getTagsForEntry: ' . $info[2]);
  328. return false;
  329. }
  330. }
  331. /**
  332. * @param array<FreshRSS_Entry|numeric-string|array<string,string>> $entries
  333. * @return array<array{'id_entry':string,'id_tag':int,'name':string}>|false
  334. */
  335. public function getTagsForEntries(array $entries) {
  336. $sql = 'SELECT et.id_entry, et.id_tag, t.name '
  337. . 'FROM `_tag` t '
  338. . 'INNER JOIN `_entrytag` et ON et.id_tag = t.id';
  339. $values = array();
  340. if (is_array($entries) && count($entries) > 0) {
  341. if (count($entries) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  342. // Split a query with too many variables parameters
  343. $idsChunks = array_chunk($entries, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  344. foreach ($idsChunks as $idsChunk) {
  345. $values += $this->getTagsForEntries($idsChunk);
  346. }
  347. return $values;
  348. }
  349. $sql .= ' AND et.id_entry IN (' . str_repeat('?,', count($entries) - 1). '?)';
  350. if (is_array($entries[0])) {
  351. foreach ($entries as $entry) {
  352. $values[] = $entry['id'];
  353. }
  354. } elseif (is_object($entries[0])) {
  355. foreach ($entries as $entry) {
  356. $values[] = $entry->id();
  357. }
  358. } else {
  359. foreach ($entries as $entry) {
  360. $values[] = $entry;
  361. }
  362. }
  363. }
  364. $stm = $this->pdo->prepare($sql);
  365. if ($stm && $stm->execute($values)) {
  366. return $stm->fetchAll(PDO::FETCH_ASSOC);
  367. } else {
  368. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  369. if ($this->autoUpdateDb($info)) {
  370. return $this->getTagsForEntries($entries);
  371. }
  372. Minz_Log::error('SQL error getTagsForEntries: ' . $info[2]);
  373. return false;
  374. }
  375. }
  376. /**
  377. * For API
  378. * @param array<FreshRSS_Entry|numeric-string> $entries
  379. * @return array<string,array<string>>
  380. */
  381. public function getEntryIdsTagNames(array $entries): array {
  382. $result = array();
  383. foreach ($this->getTagsForEntries($entries) as $line) {
  384. $entryId = 'e_' . $line['id_entry'];
  385. $tagName = $line['name'];
  386. if (empty($result[$entryId])) {
  387. $result[$entryId] = array();
  388. }
  389. $result[$entryId][] = $tagName;
  390. }
  391. return $result;
  392. }
  393. /** @return array<FreshRSS_Tag> */
  394. private static function daoToTag($listDAO) {
  395. $list = array();
  396. if (!is_array($listDAO)) {
  397. $listDAO = array($listDAO);
  398. }
  399. foreach ($listDAO as $key => $dao) {
  400. $tag = new FreshRSS_Tag(
  401. $dao['name']
  402. );
  403. $tag->_id($dao['id']);
  404. if (!empty($dao['attributes'])) {
  405. $tag->_attributes('', $dao['attributes']);
  406. }
  407. if (isset($dao['unreads'])) {
  408. $tag->_nbUnread($dao['unreads']);
  409. }
  410. $list[$key] = $tag;
  411. }
  412. return $list;
  413. }
  414. }