CategoryDAO.php 17 KB

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