CategoryDAO.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 BIGINT 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, int $mtime = 0): int|false {
  196. $sql = <<<'SQL'
  197. UPDATE `_category` SET `lastUpdate`=:last_update, error=0 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(':id', $id, PDO::PARAM_INT) &&
  203. $stm->execute()) {
  204. return $stm->rowCount();
  205. } else {
  206. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  207. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  208. return false;
  209. }
  210. }
  211. public function updateLastError(int $id, ?int $mtime = null): int|false {
  212. $sql = <<<'SQL'
  213. UPDATE `_category` SET error=:last_update WHERE id=:id
  214. SQL;
  215. $stm = $this->pdo->prepare($sql);
  216. if ($stm !== false &&
  217. $stm->bindValue(':last_update', $mtime === null || $mtime < 0 ? time() : $mtime, PDO::PARAM_INT) &&
  218. $stm->bindValue(':id', $id, PDO::PARAM_INT) &&
  219. $stm->execute()) {
  220. return $stm->rowCount();
  221. } else {
  222. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  223. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  224. return false;
  225. }
  226. }
  227. public function deleteCategory(int $id): int|false {
  228. $sql = <<<'SQL'
  229. DELETE FROM `_category` WHERE id=:id
  230. SQL;
  231. $stm = $this->pdo->prepare($sql);
  232. if ($stm !== false && $stm->bindValue(':id', $id, PDO::PARAM_INT) && $stm->execute()) {
  233. return $stm->rowCount();
  234. } else {
  235. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  236. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  237. return false;
  238. }
  239. }
  240. /** @return Traversable<array{id:int,name:string,kind:int,lastUpdate:int,error:int,attributes?:array<string,mixed>}> */
  241. public function selectAll(): Traversable {
  242. $sql = <<<'SQL'
  243. SELECT id, name, kind, `lastUpdate`, error, attributes FROM `_category`
  244. SQL;
  245. $stm = $this->pdo->query($sql);
  246. if ($stm !== false) {
  247. while (is_array($row = $stm->fetch(PDO::FETCH_ASSOC))) {
  248. /** @var array{id:int,name:string,kind:int,lastUpdate:int,error:int,attributes?:array<string,mixed>} $row */
  249. yield $row;
  250. }
  251. } else {
  252. $info = $this->pdo->errorInfo();
  253. /** @var array{0:string,1:int,2:string} $info */
  254. if ($this->autoUpdateDb($info)) {
  255. yield from $this->selectAll();
  256. } else {
  257. Minz_Log::error(__METHOD__ . ' error: ' . json_encode($info));
  258. }
  259. }
  260. }
  261. public function searchById(int $id): ?FreshRSS_Category {
  262. $sql = <<<'SQL'
  263. SELECT * FROM `_category` WHERE id=:id
  264. SQL;
  265. $res = $this->fetchAssoc($sql, ['id' => $id]) ?? [];
  266. /** @var list<array{name:string,id:int,kind:int,lastUpdate?:int,error:int,attributes?:string}> $res */
  267. $categories = self::daoToCategories($res);
  268. return reset($categories) ?: null;
  269. }
  270. public function searchByName(string $name): ?FreshRSS_Category {
  271. $sql = <<<'SQL'
  272. SELECT * FROM `_category` WHERE name=:name
  273. SQL;
  274. $res = $this->fetchAssoc($sql, ['name' => $name]) ?? [];
  275. /** @var list<array{name:string,id:int,kind:int,lastUpdate:int,error:int,attributes:string}> $res */
  276. $categories = self::daoToCategories($res);
  277. return reset($categories) ?: null;
  278. }
  279. /** @return array<int,FreshRSS_Category> where the key is the category ID */
  280. public function listSortedCategories(bool $prePopulateFeeds = true, bool $details = false): array {
  281. $categories = $this->listCategories($prePopulateFeeds, $details);
  282. uasort($categories, static function (FreshRSS_Category $a, FreshRSS_Category $b) {
  283. $aPosition = $a->attributeInt('position');
  284. $bPosition = $b->attributeInt('position');
  285. if ($aPosition === $bPosition) {
  286. return strnatcasecmp($a->name(), $b->name());
  287. } elseif (null === $aPosition) {
  288. return 1;
  289. } elseif (null === $bPosition) {
  290. return -1;
  291. }
  292. return ($aPosition < $bPosition) ? -1 : 1;
  293. });
  294. return $categories;
  295. }
  296. /** @return array<int,FreshRSS_Category> where the key is the category ID */
  297. public function listCategories(bool $prePopulateFeeds = true, bool $details = false): array {
  298. if ($prePopulateFeeds) {
  299. $feedFields = $details ?
  300. 'f.*' :
  301. 'f.id, f.name, f.url, f.kind, f.website, f.priority, f.error, f.attributes, f.`cache_nbEntries`, f.`cache_nbUnreads`, f.ttl';
  302. $sql = <<<SQL
  303. 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,
  304. {$feedFields}
  305. FROM `_category` c
  306. LEFT OUTER JOIN `_feed` f ON f.category=c.id
  307. GROUP BY f.id, c_id
  308. ORDER BY c.name, f.name
  309. SQL;
  310. $stm = $this->pdo->prepare($sql);
  311. if ($stm !== false && $stm->execute() && ($res = $stm->fetchAll(PDO::FETCH_ASSOC)) !== false) {
  312. /** @var list<array{c_name:string,c_id:int,c_kind:int,c_last_update:int,c_error:int,c_attributes?:string,
  313. * 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 */
  314. return self::daoToCategoriesPrepopulated($res);
  315. } else {
  316. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  317. /** @var array{0:string,1:int,2:string} $info */
  318. if ($this->autoUpdateDb($info)) {
  319. return $this->listCategories($prePopulateFeeds, $details);
  320. }
  321. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  322. return [];
  323. }
  324. } else {
  325. $res = $this->fetchAssoc('SELECT * FROM `_category` ORDER BY name') ?? [];
  326. /** @var list<array{name:string,id:int,kind:int,lastUpdate?:int,error?:int,attributes?:string}> $res */
  327. return empty($res) ? [] : self::daoToCategories($res);
  328. }
  329. }
  330. /** @return array<int,FreshRSS_Category> where the key is the category ID */
  331. public function listCategoriesOrderUpdate(int $defaultCacheDuration = 86400, int $limit = 0): array {
  332. $limitSql = $limit < 1 ? '' : 'LIMIT ' . $limit;
  333. $sql = <<<SQL
  334. SELECT * FROM `_category` WHERE kind = :kind AND `lastUpdate` < :lu ORDER BY `lastUpdate` {$limitSql}
  335. SQL;
  336. $stm = $this->pdo->prepare($sql);
  337. if ($stm !== false &&
  338. $stm->bindValue(':kind', FreshRSS_Category::KIND_DYNAMIC_OPML, PDO::PARAM_INT) &&
  339. $stm->bindValue(':lu', time() - $defaultCacheDuration, PDO::PARAM_INT) &&
  340. $stm->execute()) {
  341. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  342. /** @var list<array{name:string,id:int,kind:int,lastUpdate:int,error?:int,attributes?:string}> $res */
  343. return self::daoToCategories($res);
  344. } else {
  345. $info = $stm !== false ? $stm->errorInfo() : $this->pdo->errorInfo();
  346. /** @var array{0:string,1:int,2:string} $info */
  347. if ($this->autoUpdateDb($info)) {
  348. return $this->listCategoriesOrderUpdate($defaultCacheDuration, $limit);
  349. }
  350. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  351. return [];
  352. }
  353. }
  354. public function getDefault(): ?FreshRSS_Category {
  355. $sql = <<<'SQL'
  356. SELECT * FROM `_category` WHERE id=:id
  357. SQL;
  358. $res = $this->fetchAssoc($sql, [':id' => self::DEFAULTCATEGORYID]) ?? [];
  359. /** @var list<array{name:string,id:int,kind:int,lastUpdate?:int,error?:int,attributes?:string}> $res */
  360. $categories = self::daoToCategories($res);
  361. if (isset($categories[self::DEFAULTCATEGORYID])) {
  362. return $categories[self::DEFAULTCATEGORYID];
  363. } else {
  364. if (FreshRSS_Context::$isCli) {
  365. fwrite(STDERR, 'FreshRSS database error: Default category not found!' . "\n");
  366. }
  367. Minz_Log::error('FreshRSS database error: Default category not found!');
  368. return null;
  369. }
  370. }
  371. public function checkDefault(): int|bool {
  372. $def_cat = $this->searchById(self::DEFAULTCATEGORYID);
  373. if ($def_cat == null) {
  374. $cat = new FreshRSS_Category(_t('gen.short.default_category'), self::DEFAULTCATEGORYID);
  375. $sql = <<<'SQL'
  376. INSERT INTO `_category`(id, name) VALUES(:id, :name)
  377. SQL;
  378. $stm = $this->pdo->prepare($sql);
  379. if ($stm !== false &&
  380. $stm->bindValue(':id', $cat->id(), PDO::PARAM_INT) &&
  381. $stm->bindValue(':name', $cat->name(), PDO::PARAM_STR) &&
  382. $stm->execute()) {
  383. $catId = $this->pdo->lastInsertId('`_category_id_seq`');
  384. $this->sqlResetSequence();
  385. return $catId === false ? false : (int)$catId;
  386. } else {
  387. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  388. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  389. return false;
  390. }
  391. }
  392. return true;
  393. }
  394. public function count(): int {
  395. $sql = <<<'SQL'
  396. SELECT COUNT(*) AS count FROM `_category`
  397. SQL;
  398. return $this->fetchInt($sql) ?? -1;
  399. }
  400. public function countFeed(int $id): int {
  401. $sql = <<<'SQL'
  402. SELECT COUNT(*) AS count FROM `_feed` WHERE category=:id
  403. SQL;
  404. return $this->fetchInt($sql, [':id' => $id]) ?? -1;
  405. }
  406. public function countNotRead(int $id, int $minPriority = FreshRSS_Feed::PRIORITY_CATEGORY): int {
  407. $sql = <<<'SQL'
  408. SELECT COUNT(*) AS count FROM `_entry` e
  409. INNER JOIN `_feed` f ON e.id_feed=f.id
  410. WHERE f.category=:id AND e.is_read=0
  411. AND f.priority>=:minPriority
  412. SQL;
  413. return $this->fetchInt($sql, [':id' => $id, ':minPriority' => $minPriority]) ?? -1;
  414. }
  415. /** @return list<string> */
  416. public function listTitles(int $id, int $limit = 0): array {
  417. $sql = <<<'SQL'
  418. SELECT e.title FROM `_entry` e
  419. INNER JOIN `_feed` f ON e.id_feed=f.id
  420. WHERE f.category=:id_category
  421. ORDER BY e.id DESC
  422. SQL;
  423. $sql .= ($limit < 1 ? '' : ' LIMIT ' . intval($limit));
  424. $res = $this->fetchColumn($sql, 0, [':id_category' => $id]) ?? [];
  425. /** @var list<string> $res */
  426. return $res;
  427. }
  428. /**
  429. * @param array<array{c_name:string,c_id:int,c_kind:int,c_last_update:int,c_error:int|bool,c_attributes?:string,
  430. * id?:int,name?:string,url?:string,kind?:int,website?:string,priority?:int,
  431. * error?:int|bool,attributes?:string,cache_nbEntries?:int,cache_nbUnreads?:int,ttl?:int}> $listDAO
  432. * @return array<int,FreshRSS_Category> where the key is the category ID
  433. */
  434. private static function daoToCategoriesPrepopulated(array $listDAO): array {
  435. $list = [];
  436. $previousLine = [];
  437. $feedsDao = [];
  438. $feedDao = FreshRSS_Factory::createFeedDao();
  439. foreach ($listDAO as $line) {
  440. if (!empty($previousLine['c_id']) && $line['c_id'] !== $previousLine['c_id']) {
  441. // End of the current category, we add it to the $list
  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->_attributes($previousLine['c_attributes'] ?? '[]');
  449. $list[$cat->id()] = $cat;
  450. $feedsDao = []; //Prepare for next category
  451. }
  452. $previousLine = $line;
  453. $feedsDao[] = $line;
  454. }
  455. // add the last category
  456. if ($previousLine != null) {
  457. $cat = new FreshRSS_Category(
  458. $previousLine['c_name'],
  459. $previousLine['c_id'],
  460. $feedDao::daoToFeeds($feedsDao, $previousLine['c_id'])
  461. );
  462. $cat->_kind($previousLine['c_kind']);
  463. $cat->_lastUpdate($previousLine['c_last_update'] ?? 0);
  464. $cat->_error($previousLine['c_error'] ?? 0);
  465. $cat->_attributes($previousLine['c_attributes'] ?? []);
  466. $list[$cat->id()] = $cat;
  467. }
  468. return $list;
  469. }
  470. /**
  471. * @param array<array{name:string,id:int,kind:int,lastUpdate?:int,error?:int|bool,attributes?:string}> $listDAO
  472. * @return array<int,FreshRSS_Category> where the key is the category ID
  473. */
  474. private static function daoToCategories(array $listDAO): array {
  475. $list = [];
  476. foreach ($listDAO as $dao) {
  477. $cat = new FreshRSS_Category(
  478. $dao['name'],
  479. $dao['id']
  480. );
  481. $cat->_kind($dao['kind']);
  482. $cat->_lastUpdate($dao['lastUpdate'] ?? 0);
  483. $cat->_error($dao['error'] ?? 0);
  484. $cat->_attributes($dao['attributes'] ?? '');
  485. $list[$cat->id()] = $cat;
  486. }
  487. return $list;
  488. }
  489. }