TagDAO.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. class FreshRSS_TagDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
  3. public function sqlIgnore() {
  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($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)) {
  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 = $stm == null ? $this->pdo->errorInfo() : $stm->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. public function count() {
  241. $sql = 'SELECT COUNT(*) AS count FROM `_tag`';
  242. $stm = $this->pdo->query($sql);
  243. if ($stm !== false) {
  244. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  245. return $res[0]['count'];
  246. } else {
  247. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  248. if ($this->autoUpdateDb($info)) {
  249. return $this->count();
  250. }
  251. Minz_Log::error('SQL error TagDAO::count: ' . $info[2]);
  252. return false;
  253. }
  254. }
  255. public function countEntries($id) {
  256. $sql = 'SELECT COUNT(*) AS count FROM `_entrytag` WHERE id_tag=?';
  257. $stm = $this->pdo->prepare($sql);
  258. $values = array($id);
  259. $stm->execute($values);
  260. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  261. return $res[0]['count'];
  262. }
  263. public function countNotRead($id = null) {
  264. $sql = 'SELECT COUNT(*) AS count FROM `_entrytag` et '
  265. . 'INNER JOIN `_entry` e ON et.id_entry=e.id '
  266. . 'WHERE e.is_read=0';
  267. $values = null;
  268. if (null !== $id) {
  269. $sql .= ' AND et.id_tag=?';
  270. $values = [$id];
  271. }
  272. $stm = $this->pdo->prepare($sql);
  273. $stm->execute($values);
  274. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  275. return $res[0]['count'];
  276. }
  277. public function tagEntry($id_tag, $id_entry, $checked = true) {
  278. if ($checked) {
  279. $sql = 'INSERT ' . $this->sqlIgnore() . ' INTO `_entrytag`(id_tag, id_entry) VALUES(?, ?)';
  280. } else {
  281. $sql = 'DELETE FROM `_entrytag` WHERE id_tag=? AND id_entry=?';
  282. }
  283. $stm = $this->pdo->prepare($sql);
  284. $values = array($id_tag, $id_entry);
  285. if ($stm && $stm->execute($values)) {
  286. return true;
  287. } else {
  288. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  289. Minz_Log::error('SQL error tagEntry: ' . $info[2]);
  290. return false;
  291. }
  292. }
  293. public function getTagsForEntry($id_entry) {
  294. $sql = 'SELECT t.id, t.name, et.id_entry IS NOT NULL as checked '
  295. . 'FROM `_tag` t '
  296. . 'LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id AND et.id_entry=? '
  297. . 'ORDER BY t.name';
  298. $stm = $this->pdo->prepare($sql);
  299. $values = array($id_entry);
  300. if ($stm && $stm->execute($values)) {
  301. $lines = $stm->fetchAll(PDO::FETCH_ASSOC);
  302. for ($i = count($lines) - 1; $i >= 0; $i--) {
  303. $lines[$i]['id'] = intval($lines[$i]['id']);
  304. $lines[$i]['checked'] = !empty($lines[$i]['checked']);
  305. }
  306. return $lines;
  307. } else {
  308. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  309. if ($this->autoUpdateDb($info)) {
  310. return $this->getTagsForEntry($id_entry);
  311. }
  312. Minz_Log::error('SQL error getTagsForEntry: ' . $info[2]);
  313. return false;
  314. }
  315. }
  316. public function getTagsForEntries($entries) {
  317. $sql = 'SELECT et.id_entry, et.id_tag, t.name '
  318. . 'FROM `_tag` t '
  319. . 'INNER JOIN `_entrytag` et ON et.id_tag = t.id';
  320. $values = array();
  321. if (is_array($entries) && count($entries) > 0) {
  322. if (count($entries) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  323. // Split a query with too many variables parameters
  324. $idsChunks = array_chunk($entries, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  325. foreach ($idsChunks as $idsChunk) {
  326. $values += $this->getTagsForEntries($idsChunk);
  327. }
  328. return $values;
  329. }
  330. $sql .= ' AND et.id_entry IN (' . str_repeat('?,', count($entries) - 1). '?)';
  331. if (is_array($entries[0])) {
  332. foreach ($entries as $entry) {
  333. $values[] = $entry['id'];
  334. }
  335. } elseif (is_object($entries[0])) {
  336. foreach ($entries as $entry) {
  337. $values[] = $entry->id();
  338. }
  339. } else {
  340. foreach ($entries as $entry) {
  341. $values[] = $entry;
  342. }
  343. }
  344. }
  345. $stm = $this->pdo->prepare($sql);
  346. if ($stm && $stm->execute($values)) {
  347. return $stm->fetchAll(PDO::FETCH_ASSOC);
  348. } else {
  349. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  350. if ($this->autoUpdateDb($info)) {
  351. return $this->getTagsForEntries($entries);
  352. }
  353. Minz_Log::error('SQL error getTagsForEntries: ' . $info[2]);
  354. return false;
  355. }
  356. }
  357. //For API
  358. public function getEntryIdsTagNames($entries) {
  359. $result = array();
  360. foreach ($this->getTagsForEntries($entries) as $line) {
  361. $entryId = 'e_' . $line['id_entry'];
  362. $tagName = $line['name'];
  363. if (empty($result[$entryId])) {
  364. $result[$entryId] = array();
  365. }
  366. $result[$entryId][] = $tagName;
  367. }
  368. return $result;
  369. }
  370. public static function daoToTag($listDAO) {
  371. $list = array();
  372. if (!is_array($listDAO)) {
  373. $listDAO = array($listDAO);
  374. }
  375. foreach ($listDAO as $key => $dao) {
  376. $tag = new FreshRSS_Tag(
  377. $dao['name']
  378. );
  379. $tag->_id($dao['id']);
  380. if (!empty($dao['attributes'])) {
  381. $tag->_attributes('', $dao['attributes']);
  382. }
  383. if (isset($dao['unreads'])) {
  384. $tag->_nbUnread($dao['unreads']);
  385. }
  386. $list[$key] = $tag;
  387. }
  388. return $list;
  389. }
  390. }