CategoryDAO.php 13 KB

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