CategoryDAO.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. <?php
  2. class FreshRSS_CategoryDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
  3. const DEFAULTCATEGORYID = 1;
  4. protected function addColumn($name) {
  5. Minz_Log::warning(__method__ . ': ' . $name);
  6. try {
  7. if ('attributes' === $name) { //v1.15.0
  8. $ok = $this->pdo->exec('ALTER TABLE `_category` ADD COLUMN attributes TEXT') !== false;
  9. $stm = $this->pdo->query('SELECT * FROM `_feed`');
  10. $feeds = $stm->fetchAll(PDO::FETCH_ASSOC);
  11. $stm = $this->pdo->prepare('UPDATE `_feed` SET attributes = :attributes WHERE id = :id');
  12. foreach ($feeds as $feed) {
  13. if (empty($feed['keep_history']) || empty($feed['id'])) {
  14. continue;
  15. }
  16. $keepHistory = $feed['keep_history'];
  17. $attributes = empty($feed['attributes']) ? [] : json_decode($feed['attributes'], true);
  18. if (is_string($attributes)) { //Legacy risk of double-encoding
  19. $attributes = json_decode($attributes, true);
  20. }
  21. if (!is_array($attributes)) {
  22. $attributes = [];
  23. }
  24. if ($keepHistory > 0) {
  25. $attributes['archiving']['keep_min'] = intval($keepHistory);
  26. } elseif ($keepHistory == -1) { //Infinite
  27. $attributes['archiving']['keep_period'] = false;
  28. $attributes['archiving']['keep_max'] = false;
  29. $attributes['archiving']['keep_min'] = false;
  30. } else {
  31. continue;
  32. }
  33. $stm->bindValue(':id', $feed['id'], PDO::PARAM_INT);
  34. $stm->bindValue(':attributes', json_encode($attributes, JSON_UNESCAPED_SLASHES));
  35. $stm->execute();
  36. }
  37. if ($this->pdo->dbType() !== 'sqlite') { //SQLite does not support DROP COLUMN
  38. $this->pdo->exec('ALTER TABLE `_feed` DROP COLUMN keep_history');
  39. } else {
  40. $this->pdo->exec('DROP INDEX IF EXISTS feed_keep_history_index'); //SQLite at least drop index
  41. }
  42. return $ok;
  43. }
  44. } catch (Exception $e) {
  45. Minz_Log::error(__method__ . ': ' . $e->getMessage());
  46. }
  47. return false;
  48. }
  49. protected function autoUpdateDb($errorInfo) {
  50. if (isset($errorInfo[0])) {
  51. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_FIELD_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_COLUMN) {
  52. foreach (['attributes'] as $column) {
  53. if (stripos($errorInfo[2], $column) !== false) {
  54. return $this->addColumn($column);
  55. }
  56. }
  57. }
  58. }
  59. return false;
  60. }
  61. public function addCategory($valuesTmp) {
  62. $sql = 'INSERT INTO `_category`(name, attributes) '
  63. . 'SELECT * FROM (SELECT TRIM(?), ?) c2 ' //TRIM() to provide a type hint as text for PostgreSQL
  64. . 'WHERE NOT EXISTS (SELECT 1 FROM `_tag` WHERE name = TRIM(?))'; //No tag of the same name
  65. $stm = $this->pdo->prepare($sql);
  66. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  67. if (!isset($valuesTmp['attributes'])) {
  68. $valuesTmp['attributes'] = [];
  69. }
  70. $values = array(
  71. $valuesTmp['name'],
  72. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  73. $valuesTmp['name'],
  74. );
  75. if ($stm && $stm->execute($values)) {
  76. return $this->pdo->lastInsertId('`_category_id_seq`');
  77. } else {
  78. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  79. if ($this->autoUpdateDb($info)) {
  80. return $this->addCategory($valuesTmp);
  81. }
  82. Minz_Log::error('SQL error addCategory: ' . json_encode($info));
  83. return false;
  84. }
  85. }
  86. public function addCategoryObject($category) {
  87. $cat = $this->searchByName($category->name());
  88. if (!$cat) {
  89. // Category does not exist yet in DB so we add it before continue
  90. $values = array(
  91. 'name' => $category->name(),
  92. );
  93. return $this->addCategory($values);
  94. }
  95. return $cat->id();
  96. }
  97. public function updateCategory($id, $valuesTmp) {
  98. $sql = 'UPDATE `_category` SET name=?, attributes=? WHERE id=? '
  99. . 'AND NOT EXISTS (SELECT 1 FROM `_tag` WHERE name = ?)'; //No tag of the same name
  100. $stm = $this->pdo->prepare($sql);
  101. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  102. if (!isset($valuesTmp['attributes'])) {
  103. $valuesTmp['attributes'] = [];
  104. }
  105. $values = array(
  106. $valuesTmp['name'],
  107. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES),
  108. $id,
  109. $valuesTmp['name'],
  110. );
  111. if ($stm && $stm->execute($values)) {
  112. return $stm->rowCount();
  113. } else {
  114. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  115. if ($this->autoUpdateDb($info)) {
  116. return $this->updateCategory($valuesTmp);
  117. }
  118. Minz_Log::error('SQL error updateCategory: ' . json_encode($info));
  119. return false;
  120. }
  121. }
  122. public function deleteCategory($id) {
  123. if ($id <= self::DEFAULTCATEGORYID) {
  124. return false;
  125. }
  126. $sql = 'DELETE FROM `_category` WHERE id=:id';
  127. $stm = $this->pdo->prepare($sql);
  128. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  129. if ($stm && $stm->execute()) {
  130. return $stm->rowCount();
  131. } else {
  132. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  133. Minz_Log::error('SQL error deleteCategory: ' . json_encode($info));
  134. return false;
  135. }
  136. }
  137. public function selectAll() {
  138. $sql = 'SELECT id, name, attributes FROM `_category`';
  139. $stm = $this->pdo->query($sql);
  140. if ($stm != false) {
  141. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  142. yield $row;
  143. }
  144. } else {
  145. $info = $this->pdo->errorInfo();
  146. if ($this->autoUpdateDb($info)) {
  147. foreach ($this->selectAll() as $category) { // `yield from` requires PHP 7+
  148. yield $category;
  149. }
  150. }
  151. Minz_Log::error(__method__ . ' error: ' . json_encode($info));
  152. yield false;
  153. }
  154. }
  155. public function searchById($id) {
  156. $sql = 'SELECT * FROM `_category` WHERE id=:id';
  157. $stm = $this->pdo->prepare($sql);
  158. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  159. $stm->execute();
  160. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  161. $cat = self::daoToCategory($res);
  162. if (isset($cat[0])) {
  163. return $cat[0];
  164. } else {
  165. return null;
  166. }
  167. }
  168. public function searchByName($name) {
  169. $sql = 'SELECT * FROM `_category` WHERE name=:name';
  170. $stm = $this->pdo->prepare($sql);
  171. if ($stm == false) {
  172. return false;
  173. }
  174. $stm->bindParam(':name', $name);
  175. $stm->execute();
  176. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  177. $cat = self::daoToCategory($res);
  178. if (isset($cat[0])) {
  179. return $cat[0];
  180. } else {
  181. return null;
  182. }
  183. }
  184. public function listSortedCategories($prePopulateFeeds = true, $details = false) {
  185. $categories = $this->listCategories($prePopulateFeeds, $details);
  186. if (!is_array($categories)) {
  187. return $categories;
  188. }
  189. usort($categories, function ($a, $b) {
  190. $aPosition = $a->attributes('position');
  191. $bPosition = $b->attributes('position');
  192. if ($aPosition === $bPosition) {
  193. return ($a->name() < $b->name()) ? -1 : 1;
  194. } elseif (null === $aPosition) {
  195. return 1;
  196. } elseif (null === $bPosition) {
  197. return -1;
  198. }
  199. return ($aPosition < $bPosition) ? -1 : 1;
  200. });
  201. return $categories;
  202. }
  203. public function listCategories($prePopulateFeeds = true, $details = false) {
  204. if ($prePopulateFeeds) {
  205. $sql = 'SELECT c.id AS c_id, c.name AS c_name, c.attributes AS c_attributes, '
  206. . ($details ? 'f.* ' : 'f.id, f.name, f.url, f.website, f.priority, f.error, f.`cache_nbEntries`, f.`cache_nbUnreads`, f.ttl ')
  207. . 'FROM `_category` c '
  208. . 'LEFT OUTER JOIN `_feed` f ON f.category=c.id '
  209. . 'WHERE f.priority >= :priority_normal '
  210. . 'GROUP BY f.id, c_id '
  211. . 'ORDER BY c.name, f.name';
  212. $stm = $this->pdo->prepare($sql);
  213. $values = [ ':priority_normal' => FreshRSS_Feed::PRIORITY_NORMAL ];
  214. if ($stm && $stm->execute($values)) {
  215. return self::daoToCategoryPrepopulated($stm->fetchAll(PDO::FETCH_ASSOC));
  216. } else {
  217. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  218. if ($this->autoUpdateDb($info)) {
  219. return $this->listCategories($prePopulateFeeds, $details);
  220. }
  221. Minz_Log::error('SQL error listCategories: ' . json_encode($info));
  222. return false;
  223. }
  224. } else {
  225. $sql = 'SELECT * FROM `_category` ORDER BY name';
  226. $stm = $this->pdo->query($sql);
  227. return self::daoToCategory($stm->fetchAll(PDO::FETCH_ASSOC));
  228. }
  229. }
  230. public function getDefault() {
  231. $sql = 'SELECT * FROM `_category` WHERE id=:id';
  232. $stm = $this->pdo->prepare($sql);
  233. $stm->bindValue(':id', self::DEFAULTCATEGORYID, PDO::PARAM_INT);
  234. $stm->execute();
  235. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  236. $cat = self::daoToCategory($res);
  237. if (isset($cat[0])) {
  238. return $cat[0];
  239. } else {
  240. if (FreshRSS_Context::$isCli) {
  241. fwrite(STDERR, 'FreshRSS database error: Default category not found!' . "\n");
  242. }
  243. Minz_Log::error('FreshRSS database error: Default category not found!');
  244. return null;
  245. }
  246. }
  247. public function checkDefault() {
  248. $def_cat = $this->searchById(self::DEFAULTCATEGORYID);
  249. if ($def_cat == null) {
  250. $cat = new FreshRSS_Category(_t('gen.short.default_category'));
  251. $cat->_id(self::DEFAULTCATEGORYID);
  252. $sql = 'INSERT INTO `_category`(id, name) VALUES(?, ?)';
  253. if ($this->pdo->dbType() === 'pgsql') {
  254. //Force call to nextval()
  255. $sql .= " RETURNING nextval('`_category_id_seq`');";
  256. }
  257. $stm = $this->pdo->prepare($sql);
  258. $values = array(
  259. $cat->id(),
  260. $cat->name(),
  261. );
  262. if ($stm && $stm->execute($values)) {
  263. return $this->pdo->lastInsertId('`_category_id_seq`');
  264. } else {
  265. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  266. Minz_Log::error('SQL error check default category: ' . json_encode($info));
  267. return false;
  268. }
  269. }
  270. return true;
  271. }
  272. public function count() {
  273. $sql = 'SELECT COUNT(*) AS count FROM `_category`';
  274. $stm = $this->pdo->query($sql);
  275. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  276. return $res[0]['count'];
  277. }
  278. public function countFeed($id) {
  279. $sql = 'SELECT COUNT(*) AS count FROM `_feed` WHERE category=:id';
  280. $stm = $this->pdo->prepare($sql);
  281. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  282. $stm->execute();
  283. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  284. return $res[0]['count'];
  285. }
  286. public function countNotRead($id) {
  287. $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';
  288. $stm = $this->pdo->prepare($sql);
  289. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  290. $stm->execute();
  291. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  292. return $res[0]['count'];
  293. }
  294. public static function findFeed($categories, $feed_id) {
  295. foreach ($categories as $category) {
  296. foreach ($category->feeds() as $feed) {
  297. if ($feed->id() === $feed_id) {
  298. return $feed;
  299. }
  300. }
  301. }
  302. return null;
  303. }
  304. public static function CountUnreads($categories, $minPriority = 0) {
  305. $n = 0;
  306. foreach ($categories as $category) {
  307. foreach ($category->feeds() as $feed) {
  308. if ($feed->priority() >= $minPriority) {
  309. $n += $feed->nbNotRead();
  310. }
  311. }
  312. }
  313. return $n;
  314. }
  315. public static function daoToCategoryPrepopulated($listDAO) {
  316. $list = array();
  317. if (!is_array($listDAO)) {
  318. $listDAO = array($listDAO);
  319. }
  320. $previousLine = null;
  321. $feedsDao = array();
  322. $feedDao = FreshRSS_Factory::createFeedDAO();
  323. foreach ($listDAO as $line) {
  324. if ($previousLine['c_id'] != null && $line['c_id'] !== $previousLine['c_id']) {
  325. // End of the current category, we add it to the $list
  326. $cat = new FreshRSS_Category(
  327. $previousLine['c_name'],
  328. $feedDao->daoToFeed($feedsDao, $previousLine['c_id'])
  329. );
  330. $cat->_id($previousLine['c_id']);
  331. $cat->_attributes('', $previousLine['c_attributes']);
  332. $list[$previousLine['c_id']] = $cat;
  333. $feedsDao = array(); //Prepare for next category
  334. }
  335. $previousLine = $line;
  336. $feedsDao[] = $line;
  337. }
  338. // add the last category
  339. if ($previousLine != null) {
  340. $cat = new FreshRSS_Category(
  341. $previousLine['c_name'],
  342. $feedDao->daoToFeed($feedsDao, $previousLine['c_id'])
  343. );
  344. $cat->_id($previousLine['c_id']);
  345. $cat->_attributes('', $previousLine['c_attributes']);
  346. $list[$previousLine['c_id']] = $cat;
  347. }
  348. return $list;
  349. }
  350. public static function daoToCategory($listDAO) {
  351. $list = array();
  352. if (!is_array($listDAO)) {
  353. $listDAO = array($listDAO);
  354. }
  355. foreach ($listDAO as $key => $dao) {
  356. $cat = new FreshRSS_Category(
  357. $dao['name']
  358. );
  359. $cat->_id($dao['id']);
  360. $cat->_attributes('', isset($dao['attributes']) ? $dao['attributes'] : '');
  361. $cat->_isDefault(static::DEFAULTCATEGORYID === intval($dao['id']));
  362. $list[$key] = $cat;
  363. }
  364. return $list;
  365. }
  366. }