TagDAO.php 12 KB

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