CategoryDAO.php 15 KB

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