4
0

TagDAO.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. /**
  186. * @return FreshRSS_Tag|null
  187. */
  188. public function searchByName($name) {
  189. $sql = 'SELECT * FROM `_tag` WHERE name=?';
  190. $stm = $this->pdo->prepare($sql);
  191. $values = array($name);
  192. $stm->execute($values);
  193. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  194. $tag = self::daoToTag($res);
  195. return isset($tag[0]) ? $tag[0] : null;
  196. }
  197. public function listTags($precounts = false) {
  198. if ($precounts) {
  199. $sql = 'SELECT t.id, t.name, count(e.id) AS unreads '
  200. . 'FROM `_tag` t '
  201. . 'LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id '
  202. . 'LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id AND e.is_read = 0 '
  203. . 'GROUP BY t.id '
  204. . 'ORDER BY t.name';
  205. } else {
  206. $sql = 'SELECT * FROM `_tag` ORDER BY name';
  207. }
  208. $stm = $this->pdo->query($sql);
  209. if ($stm !== false) {
  210. return self::daoToTag($stm->fetchAll(PDO::FETCH_ASSOC));
  211. } else {
  212. $info = $this->pdo->errorInfo();
  213. if ($this->autoUpdateDb($info)) {
  214. return $this->listTags($precounts);
  215. }
  216. Minz_Log::error('SQL error listTags: ' . $info[2]);
  217. return false;
  218. }
  219. }
  220. public function listTagsNewestItemUsec($id_tag = null) {
  221. $sql = 'SELECT t.id AS id_tag, MAX(e.id) AS newest_item_us '
  222. . 'FROM `_tag` t '
  223. . 'LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id '
  224. . 'LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id ';
  225. if ($id_tag === null) {
  226. $sql .= 'GROUP BY t.id';
  227. } else {
  228. $sql .= 'WHERE t.id=' . intval($id_tag);
  229. }
  230. $stm = $this->pdo->query($sql);
  231. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  232. $newestItemUsec = [];
  233. foreach ($res as $line) {
  234. $newestItemUsec['t_' . $line['id_tag']] = $line['newest_item_us'];
  235. }
  236. return $newestItemUsec;
  237. }
  238. /** @return int|false */
  239. public function count() {
  240. $sql = 'SELECT COUNT(*) AS count FROM `_tag`';
  241. $stm = $this->pdo->query($sql);
  242. if ($stm !== false) {
  243. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  244. return (int)$res[0]['count'];
  245. } else {
  246. $info = $this->pdo->errorInfo();
  247. if ($this->autoUpdateDb($info)) {
  248. return $this->count();
  249. }
  250. Minz_Log::error('SQL error TagDAO::count: ' . $info[2]);
  251. return false;
  252. }
  253. }
  254. /**
  255. * @return int|false
  256. */
  257. public function countEntries(int $id) {
  258. $sql = 'SELECT COUNT(*) AS count FROM `_entrytag` WHERE id_tag=?';
  259. $values = array($id);
  260. if (($stm = $this->pdo->prepare($sql)) !== false &&
  261. $stm->execute($values) &&
  262. ($res = $stm->fetchAll(PDO::FETCH_ASSOC)) !== false) {
  263. return (int)$res[0]['count'];
  264. } else {
  265. $info = is_object($stm) ? $stm->errorInfo() : $this->pdo->errorInfo();
  266. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  267. return false;
  268. }
  269. }
  270. /**
  271. * @return int|false
  272. */
  273. public function countNotRead(?int $id = null) {
  274. $sql = 'SELECT COUNT(*) AS count FROM `_entrytag` et '
  275. . 'INNER JOIN `_entry` e ON et.id_entry=e.id '
  276. . 'WHERE e.is_read=0';
  277. $values = null;
  278. if (null !== $id) {
  279. $sql .= ' AND et.id_tag=?';
  280. $values = [$id];
  281. }
  282. if (($stm = $this->pdo->prepare($sql)) !== false &&
  283. $stm->execute($values) &&
  284. ($res = $stm->fetchAll(PDO::FETCH_ASSOC)) !== false) {
  285. return (int)$res[0]['count'];
  286. } else {
  287. $info = is_object($stm) ? $stm->errorInfo() : $this->pdo->errorInfo();
  288. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  289. return false;
  290. }
  291. }
  292. public function tagEntry($id_tag, $id_entry, $checked = true) {
  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 && $stm->execute($values)) {
  301. return true;
  302. } else {
  303. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  304. Minz_Log::error('SQL error tagEntry: ' . $info[2]);
  305. return false;
  306. }
  307. }
  308. public function getTagsForEntry($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. public function getTagsForEntries($entries) {
  332. $sql = 'SELECT et.id_entry, et.id_tag, t.name '
  333. . 'FROM `_tag` t '
  334. . 'INNER JOIN `_entrytag` et ON et.id_tag = t.id';
  335. $values = array();
  336. if (is_array($entries) && count($entries) > 0) {
  337. if (count($entries) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  338. // Split a query with too many variables parameters
  339. $idsChunks = array_chunk($entries, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  340. foreach ($idsChunks as $idsChunk) {
  341. $values += $this->getTagsForEntries($idsChunk);
  342. }
  343. return $values;
  344. }
  345. $sql .= ' AND et.id_entry IN (' . str_repeat('?,', count($entries) - 1). '?)';
  346. if (is_array($entries[0])) {
  347. foreach ($entries as $entry) {
  348. $values[] = $entry['id'];
  349. }
  350. } elseif (is_object($entries[0])) {
  351. foreach ($entries as $entry) {
  352. $values[] = $entry->id();
  353. }
  354. } else {
  355. foreach ($entries as $entry) {
  356. $values[] = $entry;
  357. }
  358. }
  359. }
  360. $stm = $this->pdo->prepare($sql);
  361. if ($stm && $stm->execute($values)) {
  362. return $stm->fetchAll(PDO::FETCH_ASSOC);
  363. } else {
  364. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  365. if ($this->autoUpdateDb($info)) {
  366. return $this->getTagsForEntries($entries);
  367. }
  368. Minz_Log::error('SQL error getTagsForEntries: ' . $info[2]);
  369. return false;
  370. }
  371. }
  372. //For API
  373. public function getEntryIdsTagNames($entries) {
  374. $result = array();
  375. foreach ($this->getTagsForEntries($entries) as $line) {
  376. $entryId = 'e_' . $line['id_entry'];
  377. $tagName = $line['name'];
  378. if (empty($result[$entryId])) {
  379. $result[$entryId] = array();
  380. }
  381. $result[$entryId][] = $tagName;
  382. }
  383. return $result;
  384. }
  385. public static function daoToTag($listDAO) {
  386. $list = array();
  387. if (!is_array($listDAO)) {
  388. $listDAO = array($listDAO);
  389. }
  390. foreach ($listDAO as $key => $dao) {
  391. $tag = new FreshRSS_Tag(
  392. $dao['name']
  393. );
  394. $tag->_id($dao['id']);
  395. if (!empty($dao['attributes'])) {
  396. $tag->_attributes('', $dao['attributes']);
  397. }
  398. if (isset($dao['unreads'])) {
  399. $tag->_nbUnread($dao['unreads']);
  400. }
  401. $list[$key] = $tag;
  402. }
  403. return $list;
  404. }
  405. }