CategoryDAO.php 19 KB

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