TagDAO.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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($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. public function addTagObject($tag) {
  64. $tag = $this->searchByName($tag->name());
  65. if (!$tag) {
  66. $values = array(
  67. 'name' => $tag->name(),
  68. 'attributes' => $tag->attributes(),
  69. );
  70. return $this->addTag($values);
  71. }
  72. return $tag->id();
  73. }
  74. public function updateTag($id, $valuesTmp) {
  75. // No category of the same name
  76. $sql = <<<'SQL'
  77. UPDATE `_tag` SET name=?, attributes=? WHERE id=?
  78. AND NOT EXISTS (SELECT 1 FROM `_category` WHERE name = ?)
  79. SQL;
  80. $stm = $this->pdo->prepare($sql);
  81. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, 63, 'UTF-8');
  82. if (!isset($valuesTmp['attributes'])) {
  83. $valuesTmp['attributes'] = [];
  84. }
  85. $values = array(
  86. $valuesTmp['name'],
  87. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  88. $id,
  89. $valuesTmp['name'],
  90. );
  91. if ($stm && $stm->execute($values)) {
  92. return $stm->rowCount();
  93. } else {
  94. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  95. Minz_Log::error('SQL error updateTag: ' . $info[2]);
  96. return false;
  97. }
  98. }
  99. public function updateTagAttribute($tag, $key, $value) {
  100. if ($tag instanceof FreshRSS_Tag) {
  101. $tag->_attributes($key, $value);
  102. return $this->updateTag(
  103. $tag->id(),
  104. [ 'attributes' => $tag->attributes() ]
  105. );
  106. }
  107. return false;
  108. }
  109. public function deleteTag($id) {
  110. if ($id <= 0) {
  111. return false;
  112. }
  113. $sql = 'DELETE FROM `_tag` WHERE id=?';
  114. $stm = $this->pdo->prepare($sql);
  115. $values = array($id);
  116. if ($stm && $stm->execute($values)) {
  117. return $stm->rowCount();
  118. } else {
  119. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  120. Minz_Log::error('SQL error deleteTag: ' . $info[2]);
  121. return false;
  122. }
  123. }
  124. public function selectAll() {
  125. $sql = 'SELECT id, name, attributes FROM `_tag`';
  126. $stm = $this->pdo->query($sql);
  127. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  128. yield $row;
  129. }
  130. }
  131. public function selectEntryTag() {
  132. $sql = 'SELECT id_tag, id_entry FROM `_entrytag`';
  133. $stm = $this->pdo->query($sql);
  134. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  135. yield $row;
  136. }
  137. }
  138. public function updateEntryTag($oldTagId, $newTagId) {
  139. $sql = <<<'SQL'
  140. DELETE FROM `_entrytag` WHERE EXISTS (
  141. SELECT 1 FROM `_entrytag` AS e
  142. WHERE e.id_entry = `_entrytag`.id_entry AND e.id_tag = ? AND `_entrytag`.id_tag = ?)
  143. SQL;
  144. $stm = $this->pdo->prepare($sql);
  145. if (!($stm && $stm->execute([$newTagId, $oldTagId]))) {
  146. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  147. Minz_Log::error('SQL error moveTag: ' . $info[2]);
  148. return false;
  149. }
  150. $sql = 'UPDATE `_entrytag` SET id_tag = ? WHERE id_tag = ?';
  151. $stm = $this->pdo->prepare($sql);
  152. if ($stm && $stm->execute([$newTagId, $oldTagId])) {
  153. return $stm->rowCount();
  154. } else {
  155. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  156. Minz_Log::error('SQL error moveTag: ' . $info[2]);
  157. return false;
  158. }
  159. }
  160. public function searchById($id) {
  161. $sql = 'SELECT * FROM `_tag` WHERE id=?';
  162. $stm = $this->pdo->prepare($sql);
  163. $values = array($id);
  164. $stm->execute($values);
  165. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  166. $tag = self::daoToTag($res);
  167. return isset($tag[0]) ? $tag[0] : null;
  168. }
  169. public function searchByName($name) {
  170. $sql = 'SELECT * FROM `_tag` WHERE name=?';
  171. $stm = $this->pdo->prepare($sql);
  172. $values = array($name);
  173. $stm->execute($values);
  174. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  175. $tag = self::daoToTag($res);
  176. return isset($tag[0]) ? $tag[0] : null;
  177. }
  178. public function listTags($precounts = false) {
  179. if ($precounts) {
  180. $sql = 'SELECT t.id, t.name, count(e.id) AS unreads '
  181. . 'FROM `_tag` t '
  182. . 'LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id '
  183. . 'LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id AND e.is_read = 0 '
  184. . 'GROUP BY t.id '
  185. . 'ORDER BY t.name';
  186. } else {
  187. $sql = 'SELECT * FROM `_tag` ORDER BY name';
  188. }
  189. $stm = $this->pdo->query($sql);
  190. if ($stm !== false) {
  191. return self::daoToTag($stm->fetchAll(PDO::FETCH_ASSOC));
  192. } else {
  193. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  194. if ($this->autoUpdateDb($info)) {
  195. return $this->listTags($precounts);
  196. }
  197. Minz_Log::error('SQL error listTags: ' . $info[2]);
  198. return false;
  199. }
  200. }
  201. public function listTagsNewestItemUsec($id_tag = null) {
  202. $sql = 'SELECT t.id AS id_tag, MAX(e.id) AS newest_item_us '
  203. . 'FROM `_tag` t '
  204. . 'LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id '
  205. . 'LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id ';
  206. if ($id_tag === null) {
  207. $sql .= 'GROUP BY t.id';
  208. } else {
  209. $sql .= 'WHERE t.id=' . intval($id_tag);
  210. }
  211. $stm = $this->pdo->query($sql);
  212. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  213. $newestItemUsec = [];
  214. foreach ($res as $line) {
  215. $newestItemUsec['t_' . $line['id_tag']] = $line['newest_item_us'];
  216. }
  217. return $newestItemUsec;
  218. }
  219. public function count() {
  220. $sql = 'SELECT COUNT(*) AS count FROM `_tag`';
  221. $stm = $this->pdo->query($sql);
  222. if ($stm !== false) {
  223. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  224. return $res[0]['count'];
  225. } else {
  226. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  227. if ($this->autoUpdateDb($info)) {
  228. return $this->count();
  229. }
  230. Minz_Log::error('SQL error TagDAO::count: ' . $info[2]);
  231. return false;
  232. }
  233. }
  234. public function countEntries($id) {
  235. $sql = 'SELECT COUNT(*) AS count FROM `_entrytag` WHERE id_tag=?';
  236. $stm = $this->pdo->prepare($sql);
  237. $values = array($id);
  238. $stm->execute($values);
  239. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  240. return $res[0]['count'];
  241. }
  242. public function countNotRead($id = null) {
  243. $sql = 'SELECT COUNT(*) AS count FROM `_entrytag` et '
  244. . 'INNER JOIN `_entry` e ON et.id_entry=e.id '
  245. . 'WHERE e.is_read=0';
  246. $values = null;
  247. if (null !== $id) {
  248. $sql .= ' AND et.id_tag=?';
  249. $values = [$id];
  250. }
  251. $stm = $this->pdo->prepare($sql);
  252. $stm->execute($values);
  253. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  254. return $res[0]['count'];
  255. }
  256. public function tagEntry($id_tag, $id_entry, $checked = true) {
  257. if ($checked) {
  258. $sql = 'INSERT ' . $this->sqlIgnore() . ' INTO `_entrytag`(id_tag, id_entry) VALUES(?, ?)';
  259. } else {
  260. $sql = 'DELETE FROM `_entrytag` WHERE id_tag=? AND id_entry=?';
  261. }
  262. $stm = $this->pdo->prepare($sql);
  263. $values = array($id_tag, $id_entry);
  264. if ($stm && $stm->execute($values)) {
  265. return true;
  266. } else {
  267. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  268. Minz_Log::error('SQL error tagEntry: ' . $info[2]);
  269. return false;
  270. }
  271. }
  272. public function getTagsForEntry($id_entry) {
  273. $sql = 'SELECT t.id, t.name, et.id_entry IS NOT NULL as checked '
  274. . 'FROM `_tag` t '
  275. . 'LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id AND et.id_entry=? '
  276. . 'ORDER BY t.name';
  277. $stm = $this->pdo->prepare($sql);
  278. $values = array($id_entry);
  279. if ($stm && $stm->execute($values)) {
  280. $lines = $stm->fetchAll(PDO::FETCH_ASSOC);
  281. for ($i = count($lines) - 1; $i >= 0; $i--) {
  282. $lines[$i]['id'] = intval($lines[$i]['id']);
  283. $lines[$i]['checked'] = !empty($lines[$i]['checked']);
  284. }
  285. return $lines;
  286. } else {
  287. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  288. if ($this->autoUpdateDb($info)) {
  289. return $this->getTagsForEntry($id_entry);
  290. }
  291. Minz_Log::error('SQL error getTagsForEntry: ' . $info[2]);
  292. return false;
  293. }
  294. }
  295. public function getTagsForEntries($entries) {
  296. $sql = 'SELECT et.id_entry, et.id_tag, t.name '
  297. . 'FROM `_tag` t '
  298. . 'INNER JOIN `_entrytag` et ON et.id_tag = t.id';
  299. $values = array();
  300. if (is_array($entries) && count($entries) > 0) {
  301. if (count($entries) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  302. // Split a query with too many variables parameters
  303. $idsChunks = array_chunk($entries, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  304. foreach ($idsChunks as $idsChunk) {
  305. $values += $this->getTagsForEntries($idsChunk);
  306. }
  307. return $values;
  308. }
  309. $sql .= ' AND et.id_entry IN (' . str_repeat('?,', count($entries) - 1). '?)';
  310. if (is_array($entries[0])) {
  311. foreach ($entries as $entry) {
  312. $values[] = $entry['id'];
  313. }
  314. } elseif (is_object($entries[0])) {
  315. foreach ($entries as $entry) {
  316. $values[] = $entry->id();
  317. }
  318. } else {
  319. foreach ($entries as $entry) {
  320. $values[] = $entry;
  321. }
  322. }
  323. }
  324. $stm = $this->pdo->prepare($sql);
  325. if ($stm && $stm->execute($values)) {
  326. return $stm->fetchAll(PDO::FETCH_ASSOC);
  327. } else {
  328. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  329. if ($this->autoUpdateDb($info)) {
  330. return $this->getTagsForEntries($entries);
  331. }
  332. Minz_Log::error('SQL error getTagsForEntries: ' . $info[2]);
  333. return false;
  334. }
  335. }
  336. //For API
  337. public function getEntryIdsTagNames($entries) {
  338. $result = array();
  339. foreach ($this->getTagsForEntries($entries) as $line) {
  340. $entryId = 'e_' . $line['id_entry'];
  341. $tagName = $line['name'];
  342. if (empty($result[$entryId])) {
  343. $result[$entryId] = array();
  344. }
  345. $result[$entryId][] = $tagName;
  346. }
  347. return $result;
  348. }
  349. public static function daoToTag($listDAO) {
  350. $list = array();
  351. if (!is_array($listDAO)) {
  352. $listDAO = array($listDAO);
  353. }
  354. foreach ($listDAO as $key => $dao) {
  355. $tag = new FreshRSS_Tag(
  356. $dao['name']
  357. );
  358. $tag->_id($dao['id']);
  359. if (!empty($dao['attributes'])) {
  360. $tag->_attributes('', $dao['attributes']);
  361. }
  362. if (isset($dao['unreads'])) {
  363. $tag->_nbUnread($dao['unreads']);
  364. }
  365. $list[$key] = $tag;
  366. }
  367. return $list;
  368. }
  369. }