TagDAO.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. protected function autoUpdateDb(array $errorInfo) {
  28. if (isset($errorInfo[0])) {
  29. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_TABLE_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_TABLE) {
  30. if (stripos($errorInfo[2], 'tag') !== false) {
  31. return $this->createTagTable(); //v1.12.0
  32. }
  33. }
  34. }
  35. return false;
  36. }
  37. public function addTag($valuesTmp) {
  38. // TRIM() gives a text type hint to PostgreSQL
  39. // No category of the same name
  40. $sql = <<<'SQL'
  41. INSERT INTO `_tag`(name, attributes)
  42. SELECT * FROM (SELECT TRIM(?) as name, TRIM(?) as attributes) t2
  43. WHERE NOT EXISTS (SELECT 1 FROM `_category` WHERE name = TRIM(?))
  44. SQL;
  45. $stm = $this->pdo->prepare($sql);
  46. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, 63, 'UTF-8');
  47. if (!isset($valuesTmp['attributes'])) {
  48. $valuesTmp['attributes'] = [];
  49. }
  50. $values = array(
  51. $valuesTmp['name'],
  52. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  53. $valuesTmp['name'],
  54. );
  55. if ($stm && $stm->execute($values) && $stm->rowCount() > 0) {
  56. return $this->pdo->lastInsertId('`_tag_id_seq`');
  57. } else {
  58. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  59. Minz_Log::error('SQL error addTag: ' . $info[2]);
  60. return false;
  61. }
  62. }
  63. /**
  64. * @param FreshRSS_Tag $tag
  65. */
  66. public function addTagObject($tag) {
  67. $tag0 = $this->searchByName($tag->name());
  68. if (!$tag0) {
  69. $values = array(
  70. 'name' => $tag->name(),
  71. 'attributes' => $tag->attributes(),
  72. );
  73. return $this->addTag($values);
  74. }
  75. return $tag->id();
  76. }
  77. /**
  78. * @return integer|false
  79. */
  80. public function updateTag($id, $valuesTmp) {
  81. // No category of the same name
  82. $sql = <<<'SQL'
  83. UPDATE `_tag` SET name=?, attributes=? WHERE id=?
  84. AND NOT EXISTS (SELECT 1 FROM `_category` WHERE name = ?)
  85. SQL;
  86. $stm = $this->pdo->prepare($sql);
  87. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, 63, 'UTF-8');
  88. if (!isset($valuesTmp['attributes'])) {
  89. $valuesTmp['attributes'] = [];
  90. }
  91. $values = array(
  92. $valuesTmp['name'],
  93. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  94. $id,
  95. $valuesTmp['name'],
  96. );
  97. if ($stm && $stm->execute($values)) {
  98. return $stm->rowCount();
  99. } else {
  100. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  101. Minz_Log::error('SQL error updateTag: ' . $info[2]);
  102. return false;
  103. }
  104. }
  105. /**
  106. * @return integer|false
  107. */
  108. public function updateTagAttribute($tag, $key, $value) {
  109. if ($tag instanceof FreshRSS_Tag) {
  110. $tag->_attributes($key, $value);
  111. return $this->updateTag(
  112. $tag->id(),
  113. [ 'attributes' => $tag->attributes() ]
  114. );
  115. }
  116. return false;
  117. }
  118. /**
  119. * @return integer|false
  120. */
  121. public function deleteTag($id) {
  122. if ($id <= 0) {
  123. return false;
  124. }
  125. $sql = 'DELETE FROM `_tag` WHERE id=?';
  126. $stm = $this->pdo->prepare($sql);
  127. $values = array($id);
  128. if ($stm && $stm->execute($values)) {
  129. return $stm->rowCount();
  130. } else {
  131. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  132. Minz_Log::error('SQL error deleteTag: ' . $info[2]);
  133. return false;
  134. }
  135. }
  136. public function selectAll() {
  137. $sql = 'SELECT id, name, attributes FROM `_tag`';
  138. $stm = $this->pdo->query($sql);
  139. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  140. yield $row;
  141. }
  142. }
  143. public function selectEntryTag() {
  144. $sql = 'SELECT id_tag, id_entry FROM `_entrytag`';
  145. $stm = $this->pdo->query($sql);
  146. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  147. yield $row;
  148. }
  149. }
  150. /**
  151. * @return integer|false
  152. */
  153. public function updateEntryTag($oldTagId, $newTagId) {
  154. $sql = <<<'SQL'
  155. DELETE FROM `_entrytag` WHERE EXISTS (
  156. SELECT 1 FROM `_entrytag` AS e
  157. WHERE e.id_entry = `_entrytag`.id_entry AND e.id_tag = ? AND `_entrytag`.id_tag = ?)
  158. SQL;
  159. $stm = $this->pdo->prepare($sql);
  160. if (!($stm && $stm->execute([$newTagId, $oldTagId]))) {
  161. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  162. Minz_Log::error('SQL error moveTag: ' . $info[2]);
  163. return false;
  164. }
  165. $sql = 'UPDATE `_entrytag` SET id_tag = ? WHERE id_tag = ?';
  166. $stm = $this->pdo->prepare($sql);
  167. if ($stm && $stm->execute([$newTagId, $oldTagId])) {
  168. return $stm->rowCount();
  169. } else {
  170. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  171. Minz_Log::error('SQL error moveTag: ' . $info[2]);
  172. return false;
  173. }
  174. }
  175. public function searchById(int $id): ?FreshRSS_Tag {
  176. $sql = 'SELECT * FROM `_tag` WHERE id=?';
  177. $stm = $this->pdo->prepare($sql);
  178. $values = array($id);
  179. $stm->execute($values);
  180. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  181. $tag = self::daoToTag($res);
  182. return isset($tag[0]) ? $tag[0] : null;
  183. }
  184. /**
  185. * @return FreshRSS_Tag|null
  186. */
  187. public function searchByName($name) {
  188. $sql = 'SELECT * FROM `_tag` WHERE name=?';
  189. $stm = $this->pdo->prepare($sql);
  190. $values = array($name);
  191. $stm->execute($values);
  192. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  193. $tag = self::daoToTag($res);
  194. return isset($tag[0]) ? $tag[0] : null;
  195. }
  196. public function listTags($precounts = false) {
  197. if ($precounts) {
  198. $sql = 'SELECT t.id, t.name, count(e.id) AS unreads '
  199. . 'FROM `_tag` t '
  200. . 'LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id '
  201. . 'LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id AND e.is_read = 0 '
  202. . 'GROUP BY t.id '
  203. . 'ORDER BY t.name';
  204. } else {
  205. $sql = 'SELECT * FROM `_tag` ORDER BY name';
  206. }
  207. $stm = $this->pdo->query($sql);
  208. if ($stm !== false) {
  209. return self::daoToTag($stm->fetchAll(PDO::FETCH_ASSOC));
  210. } else {
  211. $info = $this->pdo->errorInfo();
  212. if ($this->autoUpdateDb($info)) {
  213. return $this->listTags($precounts);
  214. }
  215. Minz_Log::error('SQL error listTags: ' . $info[2]);
  216. return false;
  217. }
  218. }
  219. public function listTagsNewestItemUsec($id_tag = null) {
  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($id_tag, $id_entry, $checked = true) {
  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. public function getTagsForEntry($id_entry) {
  308. $sql = 'SELECT t.id, t.name, et.id_entry IS NOT NULL as checked '
  309. . 'FROM `_tag` t '
  310. . 'LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id AND et.id_entry=? '
  311. . 'ORDER BY t.name';
  312. $stm = $this->pdo->prepare($sql);
  313. $values = array($id_entry);
  314. if ($stm && $stm->execute($values)) {
  315. $lines = $stm->fetchAll(PDO::FETCH_ASSOC);
  316. for ($i = count($lines) - 1; $i >= 0; $i--) {
  317. $lines[$i]['id'] = intval($lines[$i]['id']);
  318. $lines[$i]['checked'] = !empty($lines[$i]['checked']);
  319. }
  320. return $lines;
  321. } else {
  322. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  323. if ($this->autoUpdateDb($info)) {
  324. return $this->getTagsForEntry($id_entry);
  325. }
  326. Minz_Log::error('SQL error getTagsForEntry: ' . $info[2]);
  327. return false;
  328. }
  329. }
  330. public function getTagsForEntries($entries) {
  331. $sql = 'SELECT et.id_entry, et.id_tag, t.name '
  332. . 'FROM `_tag` t '
  333. . 'INNER JOIN `_entrytag` et ON et.id_tag = t.id';
  334. $values = array();
  335. if (is_array($entries) && count($entries) > 0) {
  336. if (count($entries) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  337. // Split a query with too many variables parameters
  338. $idsChunks = array_chunk($entries, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  339. foreach ($idsChunks as $idsChunk) {
  340. $values += $this->getTagsForEntries($idsChunk);
  341. }
  342. return $values;
  343. }
  344. $sql .= ' AND et.id_entry IN (' . str_repeat('?,', count($entries) - 1). '?)';
  345. if (is_array($entries[0])) {
  346. foreach ($entries as $entry) {
  347. $values[] = $entry['id'];
  348. }
  349. } elseif (is_object($entries[0])) {
  350. foreach ($entries as $entry) {
  351. $values[] = $entry->id();
  352. }
  353. } else {
  354. foreach ($entries as $entry) {
  355. $values[] = $entry;
  356. }
  357. }
  358. }
  359. $stm = $this->pdo->prepare($sql);
  360. if ($stm && $stm->execute($values)) {
  361. return $stm->fetchAll(PDO::FETCH_ASSOC);
  362. } else {
  363. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  364. if ($this->autoUpdateDb($info)) {
  365. return $this->getTagsForEntries($entries);
  366. }
  367. Minz_Log::error('SQL error getTagsForEntries: ' . $info[2]);
  368. return false;
  369. }
  370. }
  371. //For API
  372. public function getEntryIdsTagNames($entries) {
  373. $result = array();
  374. foreach ($this->getTagsForEntries($entries) as $line) {
  375. $entryId = 'e_' . $line['id_entry'];
  376. $tagName = $line['name'];
  377. if (empty($result[$entryId])) {
  378. $result[$entryId] = array();
  379. }
  380. $result[$entryId][] = $tagName;
  381. }
  382. return $result;
  383. }
  384. public static function daoToTag($listDAO) {
  385. $list = array();
  386. if (!is_array($listDAO)) {
  387. $listDAO = array($listDAO);
  388. }
  389. foreach ($listDAO as $key => $dao) {
  390. $tag = new FreshRSS_Tag(
  391. $dao['name']
  392. );
  393. $tag->_id($dao['id']);
  394. if (!empty($dao['attributes'])) {
  395. $tag->_attributes('', $dao['attributes']);
  396. }
  397. if (isset($dao['unreads'])) {
  398. $tag->_nbUnread($dao['unreads']);
  399. }
  400. $list[$key] = $tag;
  401. }
  402. return $list;
  403. }
  404. }