EntryDAO.php 38 KB

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