CategoryDAO.php 13 KB

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