TagDAO.php 10 KB

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