EntryDAO.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  1. <?php
  2. class FreshRSS_EntryDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
  3. public function isCompressed() {
  4. return true;
  5. }
  6. public function hasNativeHex() {
  7. return true;
  8. }
  9. public function sqlHexDecode($x) {
  10. return 'unhex(' . $x . ')';
  11. }
  12. public function sqlHexEncode($x) {
  13. return 'hex(' . $x . ')';
  14. }
  15. //TODO: Move the database auto-updates to DatabaseDAO
  16. protected function createEntryTempTable() {
  17. $ok = false;
  18. $hadTransaction = $this->pdo->inTransaction();
  19. if ($hadTransaction) {
  20. $this->pdo->commit();
  21. }
  22. try {
  23. require(APP_PATH . '/SQL/install.sql.' . $this->pdo->dbType() . '.php');
  24. Minz_Log::warning('SQL CREATE TABLE entrytmp...');
  25. $ok = $this->pdo->exec($SQL_CREATE_TABLE_ENTRYTMP . $SQL_CREATE_INDEX_ENTRY_1) !== false;
  26. } catch (Exception $ex) {
  27. Minz_Log::error(__method__ . ' error: ' . $ex->getMessage());
  28. }
  29. if ($hadTransaction) {
  30. $this->pdo->beginTransaction();
  31. }
  32. return $ok;
  33. }
  34. private function updateToMediumBlob() {
  35. if ($this->pdo->dbType() !== 'mysql') {
  36. return false;
  37. }
  38. Minz_Log::warning('Update MySQL table to use MEDIUMBLOB...');
  39. $sql = <<<'SQL'
  40. ALTER TABLE `_entry` MODIFY `content_bin` MEDIUMBLOB;
  41. ALTER TABLE `_entrytmp` MODIFY `content_bin` MEDIUMBLOB;
  42. SQL;
  43. try {
  44. $ok = $this->pdo->exec($sql) !== false;
  45. } catch (Exception $e) {
  46. $ok = false;
  47. Minz_Log::error(__method__ . ' error: ' . $e->getMessage());
  48. }
  49. return $ok;
  50. }
  51. //TODO: Move the database auto-updates to DatabaseDAO
  52. protected function autoUpdateDb($errorInfo) {
  53. if (isset($errorInfo[0])) {
  54. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_TABLE_ERROR) {
  55. if (stripos($errorInfo[2], 'tag') !== false) {
  56. $tagDAO = FreshRSS_Factory::createTagDao();
  57. return $tagDAO->createTagTable(); //v1.12.0
  58. } elseif (stripos($errorInfo[2], 'entrytmp') !== false) {
  59. return $this->createEntryTempTable(); //v1.7.0
  60. }
  61. }
  62. }
  63. if (isset($errorInfo[1])) {
  64. if ($errorInfo[1] == FreshRSS_DatabaseDAO::ER_DATA_TOO_LONG) {
  65. if (stripos($errorInfo[2], 'content_bin') !== false) {
  66. return $this->updateToMediumBlob(); //v1.15.0
  67. }
  68. }
  69. }
  70. return false;
  71. }
  72. private $addEntryPrepared = null;
  73. public function addEntry($valuesTmp, $useTmpTable = true) {
  74. if ($this->addEntryPrepared == null) {
  75. $sql = 'INSERT INTO `_' . ($useTmpTable ? 'entrytmp' : 'entry') . '` (id, guid, title, author, '
  76. . ($this->isCompressed() ? 'content_bin' : 'content')
  77. . ', link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags) '
  78. . 'VALUES(:id, :guid, :title, :author, '
  79. . ($this->isCompressed() ? 'COMPRESS(:content)' : ':content')
  80. . ', :link, :date, :last_seen, '
  81. . $this->sqlHexDecode(':hash')
  82. . ', :is_read, :is_favorite, :id_feed, :tags)';
  83. $this->addEntryPrepared = $this->pdo->prepare($sql);
  84. }
  85. if ($this->addEntryPrepared) {
  86. $this->addEntryPrepared->bindParam(':id', $valuesTmp['id']);
  87. $valuesTmp['guid'] = substr($valuesTmp['guid'], 0, 760);
  88. $valuesTmp['guid'] = safe_ascii($valuesTmp['guid']);
  89. $this->addEntryPrepared->bindParam(':guid', $valuesTmp['guid']);
  90. $valuesTmp['title'] = mb_strcut($valuesTmp['title'], 0, 255, 'UTF-8');
  91. $valuesTmp['title'] = safe_utf8($valuesTmp['title']);
  92. $this->addEntryPrepared->bindParam(':title', $valuesTmp['title']);
  93. $valuesTmp['author'] = mb_strcut($valuesTmp['author'], 0, 255, 'UTF-8');
  94. $valuesTmp['author'] = safe_utf8($valuesTmp['author']);
  95. $this->addEntryPrepared->bindParam(':author', $valuesTmp['author']);
  96. $valuesTmp['content'] = safe_utf8($valuesTmp['content']);
  97. $this->addEntryPrepared->bindParam(':content', $valuesTmp['content']);
  98. $valuesTmp['link'] = substr($valuesTmp['link'], 0, 1023);
  99. $valuesTmp['link'] = safe_ascii($valuesTmp['link']);
  100. $this->addEntryPrepared->bindParam(':link', $valuesTmp['link']);
  101. $this->addEntryPrepared->bindParam(':date', $valuesTmp['date'], PDO::PARAM_INT);
  102. if (empty($valuesTmp['lastSeen'])) {
  103. $valuesTmp['lastSeen'] = time();
  104. }
  105. $this->addEntryPrepared->bindParam(':last_seen', $valuesTmp['lastSeen'], PDO::PARAM_INT);
  106. $valuesTmp['is_read'] = $valuesTmp['is_read'] ? 1 : 0;
  107. $this->addEntryPrepared->bindParam(':is_read', $valuesTmp['is_read'], PDO::PARAM_INT);
  108. $valuesTmp['is_favorite'] = $valuesTmp['is_favorite'] ? 1 : 0;
  109. $this->addEntryPrepared->bindParam(':is_favorite', $valuesTmp['is_favorite'], PDO::PARAM_INT);
  110. $this->addEntryPrepared->bindParam(':id_feed', $valuesTmp['id_feed'], PDO::PARAM_INT);
  111. $valuesTmp['tags'] = mb_strcut($valuesTmp['tags'], 0, 1023, 'UTF-8');
  112. $valuesTmp['tags'] = safe_utf8($valuesTmp['tags']);
  113. $this->addEntryPrepared->bindParam(':tags', $valuesTmp['tags']);
  114. if ($this->hasNativeHex()) {
  115. $this->addEntryPrepared->bindParam(':hash', $valuesTmp['hash']);
  116. } else {
  117. $valuesTmp['hashBin'] = hex2bin($valuesTmp['hash']);
  118. $this->addEntryPrepared->bindParam(':hash', $valuesTmp['hashBin']);
  119. }
  120. }
  121. if ($this->addEntryPrepared && $this->addEntryPrepared->execute()) {
  122. return true;
  123. } else {
  124. $info = $this->addEntryPrepared == null ? $this->pdo->errorInfo() : $this->addEntryPrepared->errorInfo();
  125. if ($this->autoUpdateDb($info)) {
  126. $this->addEntryPrepared = null;
  127. return $this->addEntry($valuesTmp);
  128. } elseif ((int)((int)$info[0] / 1000) !== 23) { //Filter out "SQLSTATE Class code 23: Constraint Violation" because of expected duplicate entries
  129. Minz_Log::error('SQL error addEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  130. . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title']);
  131. }
  132. return false;
  133. }
  134. }
  135. public function commitNewEntries() {
  136. $sql = <<<'SQL'
  137. SET @rank=(SELECT MAX(id) - COUNT(*) FROM `_entrytmp`);
  138. INSERT IGNORE INTO `_entry` (
  139. id, guid, title, author, content_bin, link, date, `lastSeen`,
  140. hash, is_read, is_favorite, id_feed, tags
  141. )
  142. SELECT @rank:=@rank+1 AS id, guid, title, author, content_bin, link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags
  143. FROM `_entrytmp`
  144. ORDER BY date;
  145. DELETE FROM `_entrytmp` WHERE id <= @rank;';
  146. SQL;
  147. $hadTransaction = $this->pdo->inTransaction();
  148. if (!$hadTransaction) {
  149. $this->pdo->beginTransaction();
  150. }
  151. $result = $this->pdo->exec($sql) !== false;
  152. if (!$hadTransaction) {
  153. $this->pdo->commit();
  154. }
  155. return $result;
  156. }
  157. private $updateEntryPrepared = null;
  158. public function updateEntry($valuesTmp) {
  159. if (!isset($valuesTmp['is_read'])) {
  160. $valuesTmp['is_read'] = null;
  161. }
  162. if ($this->updateEntryPrepared === null) {
  163. $sql = 'UPDATE `_entry` '
  164. . 'SET title=:title, author=:author, '
  165. . ($this->isCompressed() ? 'content_bin=COMPRESS(:content)' : 'content=:content')
  166. . ', link=:link, date=:date, `lastSeen`=:last_seen, '
  167. . 'hash=' . $this->sqlHexDecode(':hash')
  168. . ', ' . ($valuesTmp['is_read'] === null ? '' : 'is_read=:is_read, ')
  169. . 'tags=:tags '
  170. . 'WHERE id_feed=:id_feed AND guid=:guid';
  171. $this->updateEntryPrepared = $this->pdo->prepare($sql);
  172. }
  173. $valuesTmp['guid'] = substr($valuesTmp['guid'], 0, 760);
  174. $valuesTmp['guid'] = safe_ascii($valuesTmp['guid']);
  175. $this->updateEntryPrepared->bindParam(':guid', $valuesTmp['guid']);
  176. $valuesTmp['title'] = mb_strcut($valuesTmp['title'], 0, 255, 'UTF-8');
  177. $valuesTmp['title'] = safe_utf8($valuesTmp['title']);
  178. $this->updateEntryPrepared->bindParam(':title', $valuesTmp['title']);
  179. $valuesTmp['author'] = mb_strcut($valuesTmp['author'], 0, 255, 'UTF-8');
  180. $valuesTmp['author'] = safe_utf8($valuesTmp['author']);
  181. $this->updateEntryPrepared->bindParam(':author', $valuesTmp['author']);
  182. $valuesTmp['content'] = safe_utf8($valuesTmp['content']);
  183. $this->updateEntryPrepared->bindParam(':content', $valuesTmp['content']);
  184. $valuesTmp['link'] = substr($valuesTmp['link'], 0, 1023);
  185. $valuesTmp['link'] = safe_ascii($valuesTmp['link']);
  186. $this->updateEntryPrepared->bindParam(':link', $valuesTmp['link']);
  187. $this->updateEntryPrepared->bindParam(':date', $valuesTmp['date'], PDO::PARAM_INT);
  188. $valuesTmp['lastSeen'] = time();
  189. $this->updateEntryPrepared->bindParam(':last_seen', $valuesTmp['lastSeen'], PDO::PARAM_INT);
  190. if ($valuesTmp['is_read'] !== null) {
  191. $this->updateEntryPrepared->bindValue(':is_read', $valuesTmp['is_read'] ? 1 : 0, PDO::PARAM_INT);
  192. }
  193. $this->updateEntryPrepared->bindParam(':id_feed', $valuesTmp['id_feed'], PDO::PARAM_INT);
  194. $valuesTmp['tags'] = mb_strcut($valuesTmp['tags'], 0, 1023, 'UTF-8');
  195. $valuesTmp['tags'] = safe_utf8($valuesTmp['tags']);
  196. $this->updateEntryPrepared->bindParam(':tags', $valuesTmp['tags']);
  197. if ($this->hasNativeHex()) {
  198. $this->updateEntryPrepared->bindParam(':hash', $valuesTmp['hash']);
  199. } else {
  200. $valuesTmp['hashBin'] = hex2bin($valuesTmp['hash']);
  201. $this->updateEntryPrepared->bindParam(':hash', $valuesTmp['hashBin']);
  202. }
  203. if ($this->updateEntryPrepared && $this->updateEntryPrepared->execute()) {
  204. return true;
  205. } else {
  206. $info = $this->updateEntryPrepared == null ? $this->pdo->errorInfo() : $this->updateEntryPrepared->errorInfo();
  207. if ($this->autoUpdateDb($info)) {
  208. return $this->updateEntry($valuesTmp);
  209. }
  210. Minz_Log::error('SQL error updateEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  211. . ' while updating entry with GUID ' . $valuesTmp['guid'] . ' in feed ' . $valuesTmp['id_feed']);
  212. return false;
  213. }
  214. }
  215. /**
  216. * Toggle favorite marker on one or more article
  217. *
  218. * @todo simplify the query by removing the str_repeat. I am pretty sure
  219. * there is an other way to do that.
  220. *
  221. * @param integer|array $ids
  222. * @param boolean $is_favorite
  223. * @return false|integer
  224. */
  225. public function markFavorite($ids, $is_favorite = true) {
  226. if (!is_array($ids)) {
  227. $ids = array($ids);
  228. }
  229. if (count($ids) < 1) {
  230. return 0;
  231. }
  232. FreshRSS_UserDAO::touch();
  233. $sql = 'UPDATE `_entry` '
  234. . 'SET is_favorite=? '
  235. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)';
  236. $values = array($is_favorite ? 1 : 0);
  237. $values = array_merge($values, $ids);
  238. $stm = $this->pdo->prepare($sql);
  239. if ($stm && $stm->execute($values)) {
  240. return $stm->rowCount();
  241. } else {
  242. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  243. Minz_Log::error('SQL error markFavorite: ' . $info[2]);
  244. return false;
  245. }
  246. }
  247. /**
  248. * Update the unread article cache held on every feed details.
  249. * Depending on the parameters, it updates the cache on one feed, on all
  250. * feeds from one category or on all feeds.
  251. *
  252. * @todo It can use the query builder refactoring to build that query
  253. *
  254. * @param false|integer $catId category ID
  255. * @param false|integer $feedId feed ID
  256. * @return boolean
  257. */
  258. protected function updateCacheUnreads($catId = false, $feedId = false) {
  259. $sql = 'UPDATE `_feed` f '
  260. . 'LEFT OUTER JOIN ('
  261. . 'SELECT e.id_feed, '
  262. . 'COUNT(*) AS nbUnreads '
  263. . 'FROM `_entry` e '
  264. . 'WHERE e.is_read=0 '
  265. . 'GROUP BY e.id_feed'
  266. . ') x ON x.id_feed=f.id '
  267. . 'SET f.`cache_nbUnreads`=COALESCE(x.nbUnreads, 0)';
  268. $hasWhere = false;
  269. $values = array();
  270. if ($feedId !== false) {
  271. $sql .= $hasWhere ? ' AND' : ' WHERE';
  272. $hasWhere = true;
  273. $sql .= ' f.id=?';
  274. $values[] = $feedId;
  275. }
  276. if ($catId !== false) {
  277. $sql .= $hasWhere ? ' AND' : ' WHERE';
  278. $hasWhere = true;
  279. $sql .= ' f.category=?';
  280. $values[] = $catId;
  281. }
  282. $stm = $this->pdo->prepare($sql);
  283. if ($stm && $stm->execute($values)) {
  284. return true;
  285. } else {
  286. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  287. Minz_Log::error('SQL error updateCacheUnreads: ' . $info[2]);
  288. return false;
  289. }
  290. }
  291. /**
  292. * Toggle the read marker on one or more article.
  293. * Then the cache is updated.
  294. *
  295. * @todo change the way the query is build because it seems there is
  296. * unnecessary code in here. For instance, the part with the str_repeat.
  297. * @todo remove code duplication. It seems the code is basically the
  298. * same if it is an array or not.
  299. *
  300. * @param integer|array $ids
  301. * @param boolean $is_read
  302. * @return integer affected rows
  303. */
  304. public function markRead($ids, $is_read = true) {
  305. FreshRSS_UserDAO::touch();
  306. if (is_array($ids)) { //Many IDs at once
  307. if (count($ids) < 6) { //Speed heuristics
  308. $affected = 0;
  309. foreach ($ids as $id) {
  310. $affected += $this->markRead($id, $is_read);
  311. }
  312. return $affected;
  313. }
  314. $sql = 'UPDATE `_entry` '
  315. . 'SET is_read=? '
  316. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)';
  317. $values = array($is_read ? 1 : 0);
  318. $values = array_merge($values, $ids);
  319. $stm = $this->pdo->prepare($sql);
  320. if (!($stm && $stm->execute($values))) {
  321. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  322. Minz_Log::error('SQL error markRead: ' . $info[2]);
  323. return false;
  324. }
  325. $affected = $stm->rowCount();
  326. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  327. return false;
  328. }
  329. return $affected;
  330. } else {
  331. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  332. . 'SET e.is_read=?,'
  333. . 'f.`cache_nbUnreads`=f.`cache_nbUnreads`' . ($is_read ? '-' : '+') . '1 '
  334. . 'WHERE e.id=? AND e.is_read=?';
  335. $values = array($is_read ? 1 : 0, $ids, $is_read ? 0 : 1);
  336. $stm = $this->pdo->prepare($sql);
  337. if ($stm && $stm->execute($values)) {
  338. return $stm->rowCount();
  339. } else {
  340. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  341. Minz_Log::error('SQL error markRead: ' . $info[2]);
  342. return false;
  343. }
  344. }
  345. }
  346. /**
  347. * Mark all entries as read depending on parameters.
  348. * If $onlyFavorites is true, it is used when the user mark as read in
  349. * the favorite pseudo-category.
  350. * If $priorityMin is greater than 0, it is used when the user mark as
  351. * read in the main feed pseudo-category.
  352. * Then the cache is updated.
  353. *
  354. * If $idMax equals 0, a deprecated debug message is logged
  355. *
  356. * @todo refactor this method along with markReadCat and markReadFeed
  357. * since they are all doing the same thing. I think we need to build a
  358. * tool to generate the query instead of having queries all over the
  359. * place. It will be reused also for the filtering making every thing
  360. * separated.
  361. *
  362. * @param integer $idMax fail safe article ID
  363. * @param boolean $onlyFavorites
  364. * @param integer $priorityMin
  365. * @return integer affected rows
  366. */
  367. public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0, $filters = null, $state = 0, $is_read = true) {
  368. FreshRSS_UserDAO::touch();
  369. if ($idMax == 0) {
  370. $idMax = time() . '000000';
  371. Minz_Log::debug('Calling markReadEntries(0) is deprecated!');
  372. }
  373. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  374. . 'SET e.is_read=? '
  375. . 'WHERE e.is_read <> ? AND e.id <= ?';
  376. if ($onlyFavorites) {
  377. $sql .= ' AND e.is_favorite=1';
  378. } elseif ($priorityMin >= 0) {
  379. $sql .= ' AND f.priority > ' . intval($priorityMin);
  380. }
  381. $values = array($is_read ? 1 : 0, $is_read ? 1 : 0, $idMax);
  382. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state);
  383. $stm = $this->pdo->prepare($sql . $search);
  384. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  385. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  386. Minz_Log::error('SQL error markReadEntries: ' . $info[2]);
  387. return false;
  388. }
  389. $affected = $stm->rowCount();
  390. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  391. return false;
  392. }
  393. return $affected;
  394. }
  395. /**
  396. * Mark all the articles in a category as read.
  397. * There is a fail safe to prevent to mark as read articles that are
  398. * loaded during the mark as read action. Then the cache is updated.
  399. *
  400. * If $idMax equals 0, a deprecated debug message is logged
  401. *
  402. * @param integer $id category ID
  403. * @param integer $idMax fail safe article ID
  404. * @return integer affected rows
  405. */
  406. public function markReadCat($id, $idMax = 0, $filters = null, $state = 0, $is_read = true) {
  407. FreshRSS_UserDAO::touch();
  408. if ($idMax == 0) {
  409. $idMax = time() . '000000';
  410. Minz_Log::debug('Calling markReadCat(0) is deprecated!');
  411. }
  412. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  413. . 'SET e.is_read=? '
  414. . 'WHERE f.category=? AND e.is_read <> ? AND e.id <= ?';
  415. $values = array($is_read ? 1 : 0, $id, $is_read ? 1 : 0, $idMax);
  416. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state);
  417. $stm = $this->pdo->prepare($sql . $search);
  418. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  419. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  420. Minz_Log::error('SQL error markReadCat: ' . $info[2]);
  421. return false;
  422. }
  423. $affected = $stm->rowCount();
  424. if (($affected > 0) && (!$this->updateCacheUnreads($id, false))) {
  425. return false;
  426. }
  427. return $affected;
  428. }
  429. /**
  430. * Mark all the articles in a feed as read.
  431. * There is a fail safe to prevent to mark as read articles that are
  432. * loaded during the mark as read action. Then the cache is updated.
  433. *
  434. * If $idMax equals 0, a deprecated debug message is logged
  435. *
  436. * @param integer $id_feed feed ID
  437. * @param integer $idMax fail safe article ID
  438. * @return integer affected rows
  439. */
  440. public function markReadFeed($id_feed, $idMax = 0, $filters = null, $state = 0, $is_read = true) {
  441. FreshRSS_UserDAO::touch();
  442. if ($idMax == 0) {
  443. $idMax = time() . '000000';
  444. Minz_Log::debug('Calling markReadFeed(0) is deprecated!');
  445. }
  446. $this->pdo->beginTransaction();
  447. $sql = 'UPDATE `_entry` '
  448. . 'SET is_read=? '
  449. . 'WHERE id_feed=? AND is_read <> ? AND id <= ?';
  450. $values = array($is_read ? 1 : 0, $id_feed, $is_read ? 1 : 0, $idMax);
  451. list($searchValues, $search) = $this->sqlListEntriesWhere('', $filters, $state);
  452. $stm = $this->pdo->prepare($sql . $search);
  453. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  454. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  455. Minz_Log::error('SQL error markReadFeed: ' . $info[2] . ' with SQL: ' . $sql . $search);
  456. $this->pdo->rollBack();
  457. return false;
  458. }
  459. $affected = $stm->rowCount();
  460. if ($affected > 0) {
  461. $sql = 'UPDATE `_feed` '
  462. . 'SET `cache_nbUnreads`=`cache_nbUnreads`-' . $affected
  463. . ' WHERE id=:id';
  464. $stm = $this->pdo->prepare($sql);
  465. $stm->bindParam(':id', $id_feed, PDO::PARAM_INT);
  466. if (!($stm && $stm->execute())) {
  467. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  468. Minz_Log::error('SQL error markReadFeed cache: ' . $info[2]);
  469. $this->pdo->rollBack();
  470. return false;
  471. }
  472. }
  473. $this->pdo->commit();
  474. return $affected;
  475. }
  476. /**
  477. * Mark all the articles in a tag as read.
  478. * @param integer $id tag ID, or empty for targetting any tag
  479. * @param integer $idMax max article ID
  480. * @return integer affected rows
  481. */
  482. public function markReadTag($id = '', $idMax = 0, $filters = null, $state = 0, $is_read = true) {
  483. FreshRSS_UserDAO::touch();
  484. if ($idMax == 0) {
  485. $idMax = time() . '000000';
  486. Minz_Log::debug('Calling markReadTag(0) is deprecated!');
  487. }
  488. $sql = 'UPDATE `_entry` e INNER JOIN `_entrytag` et ON et.id_entry = e.id '
  489. . 'SET e.is_read = ? '
  490. . 'WHERE '
  491. . ($id == '' ? '' : 'et.id_tag = ? AND ')
  492. . 'e.is_read <> ? AND e.id <= ?';
  493. $values = array($is_read ? 1 : 0);
  494. if ($id != '') {
  495. $values[] = $id;
  496. }
  497. $values[] = $is_read ? 1 : 0;
  498. $values[] = $idMax;
  499. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state);
  500. $stm = $this->pdo->prepare($sql . $search);
  501. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  502. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  503. Minz_Log::error('SQL error markReadTag: ' . $info[2]);
  504. return false;
  505. }
  506. $affected = $stm->rowCount();
  507. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  508. return false;
  509. }
  510. return $affected;
  511. }
  512. public function cleanOldEntries($id_feed, $options = []) { //Remember to call updateCachedValue($id_feed) or updateCachedValues() just after
  513. $sql = 'DELETE FROM `_entry` WHERE id_feed = :id_feed1'; //No alias for MySQL / MariaDB
  514. $params = [];
  515. $params[':id_feed1'] = $id_feed;
  516. //==Exclusions==
  517. if (!empty($options['keep_favourites'])) {
  518. $sql .= ' AND is_favorite = 0';
  519. }
  520. if (!empty($options['keep_unreads'])) {
  521. $sql .= ' AND is_read = 1';
  522. }
  523. if (!empty($options['keep_labels'])) {
  524. $sql .= ' AND NOT EXISTS (SELECT 1 FROM `_entrytag` WHERE id_entry = id)';
  525. }
  526. if (!empty($options['keep_min']) && $options['keep_min'] > 0) {
  527. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  528. $sql .= ' AND `lastSeen` < (SELECT `lastSeen`'
  529. . ' FROM (SELECT e2.`lastSeen` FROM `_entry` e2 WHERE e2.id_feed = :id_feed2'
  530. . ' ORDER BY e2.`lastSeen` DESC LIMIT 1 OFFSET :keep_min) last_seen2)';
  531. $params[':id_feed2'] = $id_feed;
  532. $params[':keep_min'] = (int)$options['keep_min'];
  533. }
  534. //Keep at least the articles seen at the last refresh
  535. $sql .= ' AND `lastSeen` < (SELECT maxlastseen'
  536. . ' FROM (SELECT MAX(e3.`lastSeen`) AS maxlastseen FROM `_entry` e3 WHERE e3.id_feed = :id_feed3) last_seen3)';
  537. $params[':id_feed3'] = $id_feed;
  538. //==Inclusions==
  539. $sql .= ' AND (1=0';
  540. if (!empty($options['keep_period'])) {
  541. $sql .= ' OR `lastSeen` < :max_last_seen';
  542. $now = new DateTime('now');
  543. $now->sub(new DateInterval($options['keep_period']));
  544. $params[':max_last_seen'] = $now->format('U');
  545. }
  546. if (!empty($options['keep_max']) && $options['keep_max'] > 0) {
  547. $sql .= ' OR `lastSeen` <= (SELECT `lastSeen`'
  548. . ' FROM (SELECT e4.`lastSeen` FROM `_entry` e4 WHERE e4.id_feed = :id_feed4'
  549. . ' ORDER BY e4.`lastSeen` DESC LIMIT 1 OFFSET :keep_max) last_seen4)';
  550. $params[':id_feed4'] = $id_feed;
  551. $params[':keep_max'] = (int)$options['keep_max'];
  552. }
  553. $sql .= ')';
  554. $stm = $this->pdo->prepare($sql);
  555. if ($stm && $stm->execute($params)) {
  556. return $stm->rowCount();
  557. } else {
  558. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  559. if ($this->autoUpdateDb($info)) {
  560. return $this->cleanOldEntries($id_feed, $options);
  561. }
  562. Minz_Log::error(__method__ . ' error:' . json_encode($info));
  563. return false;
  564. }
  565. }
  566. public function selectAll() {
  567. $sql = 'SELECT id, guid, title, author, '
  568. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  569. . ', link, date, `lastSeen`, ' . $this->sqlHexEncode('hash') . ' AS hash, is_read, is_favorite, id_feed, tags '
  570. . 'FROM `_entry`';
  571. $stm = $this->pdo->query($sql);
  572. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  573. yield $row;
  574. }
  575. }
  576. public function searchByGuid($id_feed, $guid) {
  577. // un guid est unique pour un flux donné
  578. $sql = 'SELECT id, guid, title, author, '
  579. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  580. . ', link, date, is_read, is_favorite, id_feed, tags '
  581. . 'FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  582. $stm = $this->pdo->prepare($sql);
  583. $stm->bindParam(':id_feed', $id_feed, PDO::PARAM_INT);
  584. $stm->bindParam(':guid', $guid);
  585. $stm->execute();
  586. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  587. $entries = self::daoToEntries($res);
  588. return isset($entries[0]) ? $entries[0] : null;
  589. }
  590. public function searchById($id) {
  591. $sql = 'SELECT id, guid, title, author, '
  592. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  593. . ', link, date, is_read, is_favorite, id_feed, tags '
  594. . 'FROM `_entry` WHERE id=:id';
  595. $stm = $this->pdo->prepare($sql);
  596. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  597. $stm->execute();
  598. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  599. $entries = self::daoToEntries($res);
  600. return isset($entries[0]) ? $entries[0] : null;
  601. }
  602. public function searchIdByGuid($id_feed, $guid) {
  603. $sql = 'SELECT id FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  604. $stm = $this->pdo->prepare($sql);
  605. $stm->bindParam(':id_feed', $id_feed, PDO::PARAM_INT);
  606. $stm->bindParam(':guid', $guid);
  607. $stm->execute();
  608. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  609. return isset($res[0]) ? $res[0] : null;
  610. }
  611. protected function sqlConcat($s1, $s2) {
  612. return 'CONCAT(' . $s1 . ',' . $s2 . ')'; //MySQL
  613. }
  614. protected function sqlListEntriesWhere($alias = '', $filters = null, $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $firstId = '', $date_min = 0) {
  615. $search = ' ';
  616. $values = array();
  617. if ($state & FreshRSS_Entry::STATE_NOT_READ) {
  618. if (!($state & FreshRSS_Entry::STATE_READ)) {
  619. $search .= 'AND ' . $alias . 'is_read=0 ';
  620. }
  621. } elseif ($state & FreshRSS_Entry::STATE_READ) {
  622. $search .= 'AND ' . $alias . 'is_read=1 ';
  623. }
  624. if ($state & FreshRSS_Entry::STATE_FAVORITE) {
  625. if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) {
  626. $search .= 'AND ' . $alias . 'is_favorite=1 ';
  627. }
  628. } elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
  629. $search .= 'AND ' . $alias . 'is_favorite=0 ';
  630. }
  631. switch ($order) {
  632. case 'DESC':
  633. case 'ASC':
  634. break;
  635. default:
  636. throw new FreshRSS_EntriesGetter_Exception('Bad order in Entry->listByType: [' . $order . ']!');
  637. }
  638. if ($firstId !== '') {
  639. $search .= 'AND ' . $alias . 'id ' . ($order === 'DESC' ? '<=' : '>=') . ' ? ';
  640. $values[] = $firstId;
  641. }
  642. if ($date_min > 0) {
  643. $search .= 'AND ' . $alias . 'id >= ? ';
  644. $values[] = $date_min . '000000';
  645. }
  646. if ($filters && count($filters->searches()) > 0) {
  647. $isOpen = false;
  648. foreach ($filters->searches() as $filter) {
  649. if ($filter == null) {
  650. continue;
  651. }
  652. $sub_search = '';
  653. if ($filter->getMinDate()) {
  654. $sub_search .= 'AND ' . $alias . 'id >= ? ';
  655. $values[] = "{$filter->getMinDate()}000000";
  656. }
  657. if ($filter->getMaxDate()) {
  658. $sub_search .= 'AND ' . $alias . 'id <= ? ';
  659. $values[] = "{$filter->getMaxDate()}000000";
  660. }
  661. if ($filter->getMinPubdate()) {
  662. $sub_search .= 'AND ' . $alias . 'date >= ? ';
  663. $values[] = $filter->getMinPubdate();
  664. }
  665. if ($filter->getMaxPubdate()) {
  666. $sub_search .= 'AND ' . $alias . 'date <= ? ';
  667. $values[] = $filter->getMaxPubdate();
  668. }
  669. if ($filter->getAuthor()) {
  670. foreach ($filter->getAuthor() as $author) {
  671. $sub_search .= 'AND ' . $alias . 'author LIKE ? ';
  672. $values[] = "%{$author}%";
  673. }
  674. }
  675. if ($filter->getIntitle()) {
  676. foreach ($filter->getIntitle() as $title) {
  677. $sub_search .= 'AND ' . $alias . 'title LIKE ? ';
  678. $values[] = "%{$title}%";
  679. }
  680. }
  681. if ($filter->getTags()) {
  682. foreach ($filter->getTags() as $tag) {
  683. $sub_search .= 'AND ' . $alias . 'tags LIKE ? ';
  684. $values[] = "%{$tag}%";
  685. }
  686. }
  687. if ($filter->getInurl()) {
  688. foreach ($filter->getInurl() as $url) {
  689. $sub_search .= 'AND ' . $this->sqlConcat($alias . 'link', $alias . 'guid') . ' LIKE ? ';
  690. $values[] = "%{$url}%";
  691. }
  692. }
  693. if ($filter->getNotAuthor()) {
  694. foreach ($filter->getNotAuthor() as $author) {
  695. $sub_search .= 'AND (NOT ' . $alias . 'author LIKE ?) ';
  696. $values[] = "%{$author}%";
  697. }
  698. }
  699. if ($filter->getNotIntitle()) {
  700. foreach ($filter->getNotIntitle() as $title) {
  701. $sub_search .= 'AND (NOT ' . $alias . 'title LIKE ?) ';
  702. $values[] = "%{$title}%";
  703. }
  704. }
  705. if ($filter->getNotTags()) {
  706. foreach ($filter->getNotTags() as $tag) {
  707. $sub_search .= 'AND (NOT ' . $alias . 'tags LIKE ?) ';
  708. $values[] = "%{$tag}%";
  709. }
  710. }
  711. if ($filter->getNotInurl()) {
  712. foreach ($filter->getNotInurl() as $url) {
  713. $sub_search .= 'AND (NOT ' . $this->sqlConcat($alias . 'link', $alias . 'guid') . ' LIKE ?) ';
  714. $values[] = "%{$url}%";
  715. }
  716. }
  717. if ($filter->getSearch()) {
  718. foreach ($filter->getSearch() as $search_value) {
  719. $sub_search .= 'AND ' . $this->sqlConcat($alias . 'title', $this->isCompressed() ? 'UNCOMPRESS(' . $alias . 'content_bin)' : '' . $alias . 'content') . ' LIKE ? ';
  720. $values[] = "%{$search_value}%";
  721. }
  722. }
  723. if ($filter->getNotSearch()) {
  724. foreach ($filter->getNotSearch() as $search_value) {
  725. $sub_search .= 'AND (NOT ' . $this->sqlConcat($alias . 'title', $this->isCompressed() ? 'UNCOMPRESS(' . $alias . 'content_bin)' : '' . $alias . 'content') . ' LIKE ?) ';
  726. $values[] = "%{$search_value}%";
  727. }
  728. }
  729. if ($sub_search != '') {
  730. if ($isOpen) {
  731. $search .= 'OR ';
  732. } else {
  733. $search .= 'AND (';
  734. $isOpen = true;
  735. }
  736. $search .= '(' . substr($sub_search, 4) . ') ';
  737. }
  738. }
  739. if ($isOpen) {
  740. $search .= ') ';
  741. }
  742. }
  743. return array($values, $search);
  744. }
  745. private function sqlListWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filters = null, $date_min = 0) {
  746. if (!$state) {
  747. $state = FreshRSS_Entry::STATE_ALL;
  748. }
  749. $where = '';
  750. $joinFeed = false;
  751. $values = array();
  752. switch ($type) {
  753. case 'a': //All PRIORITY_MAIN_STREAM
  754. $where .= 'f.priority > ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  755. break;
  756. case 'A': //All except PRIORITY_ARCHIVED
  757. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  758. break;
  759. case 's': //Starred. Deprecated: use $state instead
  760. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  761. $where .= 'AND e.is_favorite=1 ';
  762. break;
  763. case 'S': //Starred
  764. $where .= 'e.is_favorite=1 ';
  765. break;
  766. case 'c': //Category
  767. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  768. $where .= 'AND f.category=? ';
  769. $values[] = intval($id);
  770. break;
  771. case 'f': //Feed
  772. $where .= 'e.id_feed=? ';
  773. $values[] = intval($id);
  774. break;
  775. case 't': //Tag
  776. $where .= 'et.id_tag=? ';
  777. $values[] = intval($id);
  778. break;
  779. case 'T': //Any tag
  780. $where .= '1=1 ';
  781. break;
  782. case 'ST': //Starred or tagged
  783. $where .= 'e.is_favorite=1 OR EXISTS (SELECT et2.id_tag FROM `_entrytag` et2 WHERE et2.id_entry = e.id) ';
  784. break;
  785. default:
  786. throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
  787. }
  788. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state, $order, $firstId, $date_min);
  789. return array(array_merge($values, $searchValues),
  790. 'SELECT '
  791. . ($type === 'T' ? 'DISTINCT ' : '')
  792. . 'e.id FROM `_entry` e '
  793. . 'INNER JOIN `_feed` f ON e.id_feed = f.id '
  794. . ($type === 't' || $type === 'T' ? 'INNER JOIN `_entrytag` et ON et.id_entry = e.id ' : '')
  795. . 'WHERE ' . $where
  796. . $search
  797. . 'ORDER BY e.id ' . $order
  798. . ($limit > 0 ? ' LIMIT ' . intval($limit) : '')); //TODO: See http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
  799. }
  800. public function listWhereRaw($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filters = null, $date_min = 0) {
  801. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filters, $date_min);
  802. $sql = 'SELECT e0.id, e0.guid, e0.title, e0.author, '
  803. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  804. . ', e0.link, e0.date, e0.is_read, e0.is_favorite, e0.id_feed, e0.tags '
  805. . 'FROM `_entry` e0 '
  806. . 'INNER JOIN ('
  807. . $sql
  808. . ') e2 ON e2.id=e0.id '
  809. . 'ORDER BY e0.id ' . $order;
  810. $stm = $this->pdo->prepare($sql);
  811. if ($stm && $stm->execute($values)) {
  812. return $stm;
  813. } else {
  814. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  815. Minz_Log::error('SQL error listWhereRaw: ' . $info[2]);
  816. return false;
  817. }
  818. }
  819. public function listWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filters = null, $date_min = 0) {
  820. $stm = $this->listWhereRaw($type, $id, $state, $order, $limit, $firstId, $filters, $date_min);
  821. if ($stm) {
  822. return self::daoToEntries($stm->fetchAll(PDO::FETCH_ASSOC));
  823. } else {
  824. return false;
  825. }
  826. }
  827. public function listByIds($ids, $order = 'DESC') {
  828. if (count($ids) < 1) {
  829. return array();
  830. }
  831. $sql = 'SELECT id, guid, title, author, '
  832. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  833. . ', link, date, is_read, is_favorite, id_feed, tags '
  834. . 'FROM `_entry` '
  835. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?) '
  836. . 'ORDER BY id ' . $order;
  837. $stm = $this->pdo->prepare($sql);
  838. $stm->execute($ids);
  839. return self::daoToEntries($stm->fetchAll(PDO::FETCH_ASSOC));
  840. }
  841. public function listIdsWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filters = null) { //For API
  842. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filters);
  843. $stm = $this->pdo->prepare($sql);
  844. $stm->execute($values);
  845. return $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  846. }
  847. public function listHashForFeedGuids($id_feed, $guids) {
  848. if (count($guids) < 1) {
  849. return array();
  850. }
  851. $guids = array_unique($guids);
  852. $sql = 'SELECT guid, ' . $this->sqlHexEncode('hash') . ' AS hex_hash FROM `_entry` WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  853. $stm = $this->pdo->prepare($sql);
  854. $values = array($id_feed);
  855. $values = array_merge($values, $guids);
  856. if ($stm && $stm->execute($values)) {
  857. $result = array();
  858. $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
  859. foreach ($rows as $row) {
  860. $result[$row['guid']] = $row['hex_hash'];
  861. }
  862. return $result;
  863. } else {
  864. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  865. if ($this->autoUpdateDb($info)) {
  866. return $this->listHashForFeedGuids($id_feed, $guids);
  867. }
  868. Minz_Log::error('SQL error listHashForFeedGuids: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  869. . ' while querying feed ' . $id_feed);
  870. return false;
  871. }
  872. }
  873. public function updateLastSeen($id_feed, $guids, $mtime = 0) {
  874. if (count($guids) < 1) {
  875. return 0;
  876. }
  877. $sql = 'UPDATE `_entry` SET `lastSeen`=? WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  878. $stm = $this->pdo->prepare($sql);
  879. if ($mtime <= 0) {
  880. $mtime = time();
  881. }
  882. $values = array($mtime, $id_feed);
  883. $values = array_merge($values, $guids);
  884. if ($stm && $stm->execute($values)) {
  885. return $stm->rowCount();
  886. } else {
  887. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  888. if ($this->autoUpdateDb($info)) {
  889. return $this->updateLastSeen($id_feed, $guids);
  890. }
  891. Minz_Log::error('SQL error updateLastSeen: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  892. . ' while updating feed ' . $id_feed);
  893. return false;
  894. }
  895. }
  896. public function countUnreadRead() {
  897. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id WHERE f.priority > 0'
  898. . ' UNION SELECT COUNT(e.id) AS count FROM `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id WHERE f.priority > 0 AND e.is_read=0';
  899. $stm = $this->pdo->query($sql);
  900. if ($stm === false) {
  901. return false;
  902. }
  903. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  904. rsort($res);
  905. $all = empty($res[0]) ? 0 : $res[0];
  906. $unread = empty($res[1]) ? 0 : $res[1];
  907. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  908. }
  909. public function count($minPriority = null) {
  910. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  911. if ($minPriority !== null) {
  912. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  913. $sql .= ' WHERE f.priority > ' . intval($minPriority);
  914. }
  915. $stm = $this->pdo->query($sql);
  916. if ($stm == false) {
  917. return false;
  918. }
  919. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  920. return isset($res[0]) ? $res[0] : 0;
  921. }
  922. public function countNotRead($minPriority = null) {
  923. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  924. if ($minPriority !== null) {
  925. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  926. }
  927. $sql .= ' WHERE e.is_read=0';
  928. if ($minPriority !== null) {
  929. $sql .= ' AND f.priority > ' . intval($minPriority);
  930. }
  931. $stm = $this->pdo->query($sql);
  932. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  933. return $res[0];
  934. }
  935. public function countUnreadReadFavorites() {
  936. $sql = <<<'SQL'
  937. SELECT c FROM (
  938. SELECT COUNT(e1.id) AS c, 1 AS o
  939. FROM `_entry` AS e1
  940. JOIN `_feed` AS f1 ON e1.id_feed = f1.id
  941. WHERE e1.is_favorite = 1
  942. AND f1.priority >= :priority_normal1
  943. UNION
  944. SELECT COUNT(e2.id) AS c, 2 AS o
  945. FROM `_entry` AS e2
  946. JOIN `_feed` AS f2 ON e2.id_feed = f2.id
  947. WHERE e2.is_favorite = 1
  948. AND e2.is_read = 0
  949. AND f2.priority >= :priority_normal2
  950. ) u
  951. ORDER BY o
  952. SQL;
  953. $stm = $this->pdo->prepare($sql);
  954. //Binding a value more than once is not standard and does not work with native prepared statements (e.g. MySQL) https://bugs.php.net/bug.php?id=40417
  955. $stm->bindValue(':priority_normal1', FreshRSS_Feed::PRIORITY_NORMAL, PDO::PARAM_INT);
  956. $stm->bindValue(':priority_normal2', FreshRSS_Feed::PRIORITY_NORMAL, PDO::PARAM_INT);
  957. $stm->execute();
  958. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  959. rsort($res);
  960. $all = empty($res[0]) ? 0 : $res[0];
  961. $unread = empty($res[1]) ? 0 : $res[1];
  962. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  963. }
  964. public static function daoToEntry($dao) {
  965. $entry = new FreshRSS_Entry(
  966. $dao['id_feed'],
  967. $dao['guid'],
  968. $dao['title'],
  969. $dao['author'],
  970. $dao['content'],
  971. $dao['link'],
  972. $dao['date'],
  973. $dao['is_read'],
  974. $dao['is_favorite'],
  975. isset($dao['tags']) ? $dao['tags'] : ''
  976. );
  977. if (isset($dao['id'])) {
  978. $entry->_id($dao['id']);
  979. }
  980. return $entry;
  981. }
  982. private static function daoToEntries($listDAO) {
  983. $list = array();
  984. if (!is_array($listDAO)) {
  985. $listDAO = array($listDAO);
  986. }
  987. foreach ($listDAO as $key => $dao) {
  988. $list[] = self::daoToEntry($dao);
  989. }
  990. unset($listDAO);
  991. return $list;
  992. }
  993. }