CategoryDAO.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. <?php
  2. class FreshRSS_CategoryDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
  3. const DEFAULTCATEGORYID = 1;
  4. protected function addColumn($name) {
  5. Minz_Log::warning(__method__ . ': ' . $name);
  6. try {
  7. if ('attributes' === $name) { //v1.15.0
  8. $ok = $this->pdo->exec('ALTER TABLE `_category` ADD COLUMN attributes TEXT') !== false;
  9. $stm = $this->pdo->query('SELECT * FROM `_feed`');
  10. $feeds = $stm->fetchAll(PDO::FETCH_ASSOC);
  11. $stm = $this->pdo->prepare('UPDATE `_feed` SET attributes = :attributes WHERE id = :id');
  12. foreach ($feeds as $feed) {
  13. if (empty($feed['keep_history']) || empty($feed['id'])) {
  14. continue;
  15. }
  16. $keepHistory = $feed['keep_history'];
  17. $attributes = empty($feed['attributes']) ? [] : json_decode($feed['attributes'], true);
  18. if (is_string($attributes)) { //Legacy risk of double-encoding
  19. $attributes = json_decode($attributes, true);
  20. }
  21. if (!is_array($attributes)) {
  22. $attributes = [];
  23. }
  24. if ($keepHistory > 0) {
  25. $attributes['archiving']['keep_min'] = intval($keepHistory);
  26. } elseif ($keepHistory == -1) { //Infinite
  27. $attributes['archiving']['keep_period'] = false;
  28. $attributes['archiving']['keep_max'] = false;
  29. $attributes['archiving']['keep_min'] = false;
  30. } else {
  31. continue;
  32. }
  33. $stm->bindValue(':id', $feed['id'], PDO::PARAM_INT);
  34. $stm->bindValue(':attributes', json_encode($attributes, JSON_UNESCAPED_SLASHES));
  35. $stm->execute();
  36. }
  37. if ($this->pdo->dbType() !== 'sqlite') { //SQLite does not support DROP COLUMN
  38. $this->pdo->exec('ALTER TABLE `_feed` DROP COLUMN keep_history');
  39. } else {
  40. $this->pdo->exec('DROP INDEX IF EXISTS feed_keep_history_index'); //SQLite at least drop index
  41. }
  42. $stm = $this->pdo->prepare('UPDATE `_category` SET name = :name WHERE id = :id');
  43. $stm->bindValue(':id', self::DEFAULTCATEGORYID, PDO::PARAM_INT);
  44. $stm->bindValue(':name', 'Uncategorized');
  45. $stm->execute();
  46. return $ok;
  47. }
  48. } catch (Exception $e) {
  49. Minz_Log::error(__method__ . ': ' . $e->getMessage());
  50. }
  51. return false;
  52. }
  53. protected function autoUpdateDb($errorInfo) {
  54. if (isset($errorInfo[0])) {
  55. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_FIELD_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_COLUMN) {
  56. foreach (['attributes'] as $column) {
  57. if (stripos($errorInfo[2], $column) !== false) {
  58. return $this->addColumn($column);
  59. }
  60. }
  61. }
  62. }
  63. return false;
  64. }
  65. public function addCategory($valuesTmp) {
  66. $sql = 'INSERT INTO `_category`(name, attributes) '
  67. . 'SELECT * FROM (SELECT TRIM(?), ?) c2 ' //TRIM() to provide a type hint as text for PostgreSQL
  68. . 'WHERE NOT EXISTS (SELECT 1 FROM `_tag` WHERE name = TRIM(?))'; //No tag of the same name
  69. $stm = $this->pdo->prepare($sql);
  70. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  71. if (!isset($valuesTmp['attributes'])) {
  72. $valuesTmp['attributes'] = [];
  73. }
  74. $values = array(
  75. $valuesTmp['name'],
  76. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  77. $valuesTmp['name'],
  78. );
  79. if ($stm && $stm->execute($values)) {
  80. return $this->pdo->lastInsertId('`_category_id_seq`');
  81. } else {
  82. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  83. if ($this->autoUpdateDb($info)) {
  84. return $this->addCategory($valuesTmp);
  85. }
  86. Minz_Log::error('SQL error addCategory: ' . json_encode($info));
  87. return false;
  88. }
  89. }
  90. public function addCategoryObject($category) {
  91. $cat = $this->searchByName($category->name());
  92. if (!$cat) {
  93. // Category does not exist yet in DB so we add it before continue
  94. $values = array(
  95. 'name' => $category->name(),
  96. );
  97. return $this->addCategory($values);
  98. }
  99. return $cat->id();
  100. }
  101. public function updateCategory($id, $valuesTmp) {
  102. $sql = 'UPDATE `_category` SET name=?, attributes=? WHERE id=? '
  103. . 'AND NOT EXISTS (SELECT 1 FROM `_tag` WHERE name = ?)'; //No tag of the same name
  104. $stm = $this->pdo->prepare($sql);
  105. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  106. if (!isset($valuesTmp['attributes'])) {
  107. $valuesTmp['attributes'] = [];
  108. }
  109. $values = array(
  110. $valuesTmp['name'],
  111. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  112. $id,
  113. $valuesTmp['name'],
  114. );
  115. if ($stm && $stm->execute($values)) {
  116. return $stm->rowCount();
  117. } else {
  118. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  119. if ($this->autoUpdateDb($info)) {
  120. return $this->updateCategory($valuesTmp);
  121. }
  122. Minz_Log::error('SQL error updateCategory: ' . json_encode($info));
  123. return false;
  124. }
  125. }
  126. public function deleteCategory($id) {
  127. if ($id <= self::DEFAULTCATEGORYID) {
  128. return false;
  129. }
  130. $sql = 'DELETE FROM `_category` WHERE id=:id';
  131. $stm = $this->pdo->prepare($sql);
  132. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  133. if ($stm && $stm->execute()) {
  134. return $stm->rowCount();
  135. } else {
  136. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  137. Minz_Log::error('SQL error deleteCategory: ' . json_encode($info));
  138. return false;
  139. }
  140. }
  141. public function selectAll() {
  142. $sql = 'SELECT id, name, attributes FROM `_category`';
  143. $stm = $this->pdo->query($sql);
  144. if ($stm != false) {
  145. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  146. yield $row;
  147. }
  148. } else {
  149. $info = $this->pdo->errorInfo();
  150. if ($this->autoUpdateDb($info)) {
  151. foreach ($this->selectAll() as $category) { // `yield from` requires PHP 7+
  152. yield $category;
  153. }
  154. }
  155. Minz_Log::error(__method__ . ' error: ' . json_encode($info));
  156. yield false;
  157. }
  158. }
  159. public function searchById($id) {
  160. $sql = 'SELECT * FROM `_category` WHERE id=:id';
  161. $stm = $this->pdo->prepare($sql);
  162. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  163. $stm->execute();
  164. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  165. $cat = self::daoToCategory($res);
  166. if (isset($cat[0])) {
  167. return $cat[0];
  168. } else {
  169. return null;
  170. }
  171. }
  172. public function searchByName($name) {
  173. $sql = 'SELECT * FROM `_category` WHERE name=:name';
  174. $stm = $this->pdo->prepare($sql);
  175. if ($stm == false) {
  176. return false;
  177. }
  178. $stm->bindParam(':name', $name);
  179. $stm->execute();
  180. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  181. $cat = self::daoToCategory($res);
  182. if (isset($cat[0])) {
  183. return $cat[0];
  184. } else {
  185. return null;
  186. }
  187. }
  188. public function listSortedCategories($prePopulateFeeds = true, $details = false) {
  189. $categories = $this->listCategories($prePopulateFeeds, $details);
  190. if (!is_array($categories)) {
  191. return $categories;
  192. }
  193. uasort($categories, function ($a, $b) {
  194. $aPosition = $a->attributes('position');
  195. $bPosition = $b->attributes('position');
  196. if ($aPosition === $bPosition) {
  197. return ($a->name() < $b->name()) ? -1 : 1;
  198. } elseif (null === $aPosition) {
  199. return 1;
  200. } elseif (null === $bPosition) {
  201. return -1;
  202. }
  203. return ($aPosition < $bPosition) ? -1 : 1;
  204. });
  205. return $categories;
  206. }
  207. public function listCategories($prePopulateFeeds = true, $details = false) {
  208. if ($prePopulateFeeds) {
  209. $sql = 'SELECT c.id AS c_id, c.name AS c_name, c.attributes AS c_attributes, '
  210. . ($details ? 'f.* ' : 'f.id, f.name, f.url, f.website, f.priority, f.error, f.`cache_nbEntries`, f.`cache_nbUnreads`, f.ttl ')
  211. . 'FROM `_category` c '
  212. . 'LEFT OUTER JOIN `_feed` f ON f.category=c.id '
  213. . 'WHERE f.priority >= :priority_normal '
  214. . 'GROUP BY f.id, c_id '
  215. . 'ORDER BY c.name, f.name';
  216. $stm = $this->pdo->prepare($sql);
  217. $values = [ ':priority_normal' => FreshRSS_Feed::PRIORITY_NORMAL ];
  218. if ($stm && $stm->execute($values)) {
  219. return self::daoToCategoryPrepopulated($stm->fetchAll(PDO::FETCH_ASSOC));
  220. } else {
  221. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  222. if ($this->autoUpdateDb($info)) {
  223. return $this->listCategories($prePopulateFeeds, $details);
  224. }
  225. Minz_Log::error('SQL error listCategories: ' . json_encode($info));
  226. return false;
  227. }
  228. } else {
  229. $sql = 'SELECT * FROM `_category` ORDER BY name';
  230. $stm = $this->pdo->query($sql);
  231. return self::daoToCategory($stm->fetchAll(PDO::FETCH_ASSOC));
  232. }
  233. }
  234. public function getDefault() {
  235. $sql = 'SELECT * FROM `_category` WHERE id=:id';
  236. $stm = $this->pdo->prepare($sql);
  237. $stm->bindValue(':id', self::DEFAULTCATEGORYID, PDO::PARAM_INT);
  238. $stm->execute();
  239. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  240. $cat = self::daoToCategory($res);
  241. if (isset($cat[0])) {
  242. return $cat[0];
  243. } else {
  244. if (FreshRSS_Context::$isCli) {
  245. fwrite(STDERR, 'FreshRSS database error: Default category not found!' . "\n");
  246. }
  247. Minz_Log::error('FreshRSS database error: Default category not found!');
  248. return null;
  249. }
  250. }
  251. public function checkDefault() {
  252. $def_cat = $this->searchById(self::DEFAULTCATEGORYID);
  253. if ($def_cat == null) {
  254. $cat = new FreshRSS_Category(_t('gen.short.default_category'));
  255. $cat->_id(self::DEFAULTCATEGORYID);
  256. $sql = 'INSERT INTO `_category`(id, name) VALUES(?, ?)';
  257. if ($this->pdo->dbType() === 'pgsql') {
  258. //Force call to nextval()
  259. $sql .= " RETURNING nextval('`_category_id_seq`');";
  260. }
  261. $stm = $this->pdo->prepare($sql);
  262. $values = array(
  263. $cat->id(),
  264. $cat->name(),
  265. );
  266. if ($stm && $stm->execute($values)) {
  267. return $this->pdo->lastInsertId('`_category_id_seq`');
  268. } else {
  269. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  270. Minz_Log::error('SQL error check default category: ' . json_encode($info));
  271. return false;
  272. }
  273. }
  274. return true;
  275. }
  276. public function count() {
  277. $sql = 'SELECT COUNT(*) AS count FROM `_category`';
  278. $stm = $this->pdo->query($sql);
  279. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  280. return $res[0]['count'];
  281. }
  282. public function countFeed($id) {
  283. $sql = 'SELECT COUNT(*) AS count FROM `_feed` WHERE category=:id';
  284. $stm = $this->pdo->prepare($sql);
  285. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  286. $stm->execute();
  287. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  288. return $res[0]['count'];
  289. }
  290. public function countNotRead($id) {
  291. $sql = 'SELECT COUNT(*) AS count FROM `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id WHERE category=:id AND e.is_read=0';
  292. $stm = $this->pdo->prepare($sql);
  293. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  294. $stm->execute();
  295. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  296. return $res[0]['count'];
  297. }
  298. public static function findFeed($categories, $feed_id) {
  299. foreach ($categories as $category) {
  300. foreach ($category->feeds() as $feed) {
  301. if ($feed->id() === $feed_id) {
  302. return $feed;
  303. }
  304. }
  305. }
  306. return null;
  307. }
  308. public static function CountUnreads($categories, $minPriority = 0) {
  309. $n = 0;
  310. foreach ($categories as $category) {
  311. foreach ($category->feeds() as $feed) {
  312. if ($feed->priority() >= $minPriority) {
  313. $n += $feed->nbNotRead();
  314. }
  315. }
  316. }
  317. return $n;
  318. }
  319. public static function daoToCategoryPrepopulated($listDAO) {
  320. $list = array();
  321. if (!is_array($listDAO)) {
  322. $listDAO = array($listDAO);
  323. }
  324. $previousLine = null;
  325. $feedsDao = array();
  326. $feedDao = FreshRSS_Factory::createFeedDAO();
  327. foreach ($listDAO as $line) {
  328. if ($previousLine['c_id'] != null && $line['c_id'] !== $previousLine['c_id']) {
  329. // End of the current category, we add it to the $list
  330. $cat = new FreshRSS_Category(
  331. $previousLine['c_name'],
  332. $feedDao->daoToFeed($feedsDao, $previousLine['c_id'])
  333. );
  334. $cat->_id($previousLine['c_id']);
  335. $cat->_attributes('', $previousLine['c_attributes']);
  336. $list[$previousLine['c_id']] = $cat;
  337. $feedsDao = array(); //Prepare for next category
  338. }
  339. $previousLine = $line;
  340. $feedsDao[] = $line;
  341. }
  342. // add the last category
  343. if ($previousLine != null) {
  344. $cat = new FreshRSS_Category(
  345. $previousLine['c_name'],
  346. $feedDao->daoToFeed($feedsDao, $previousLine['c_id'])
  347. );
  348. $cat->_id($previousLine['c_id']);
  349. $cat->_attributes('', $previousLine['c_attributes']);
  350. $list[$previousLine['c_id']] = $cat;
  351. }
  352. return $list;
  353. }
  354. public static function daoToCategory($listDAO) {
  355. $list = array();
  356. if (!is_array($listDAO)) {
  357. $listDAO = array($listDAO);
  358. }
  359. foreach ($listDAO as $key => $dao) {
  360. $cat = new FreshRSS_Category(
  361. $dao['name']
  362. );
  363. $cat->_id($dao['id']);
  364. $cat->_attributes('', isset($dao['attributes']) ? $dao['attributes'] : '');
  365. $cat->_isDefault(static::DEFAULTCATEGORYID === intval($dao['id']));
  366. $list[$key] = $cat;
  367. }
  368. return $list;
  369. }
  370. }