EntryDAO.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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. . ', is_read=COALESCE(: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. if ($this->updateEntryPrepared) {
  179. $valuesTmp['guid'] = substr($valuesTmp['guid'], 0, 760);
  180. $valuesTmp['guid'] = safe_ascii($valuesTmp['guid']);
  181. $this->updateEntryPrepared->bindParam(':guid', $valuesTmp['guid']);
  182. $valuesTmp['title'] = mb_strcut($valuesTmp['title'], 0, 255, 'UTF-8');
  183. $valuesTmp['title'] = safe_utf8($valuesTmp['title']);
  184. $this->updateEntryPrepared->bindParam(':title', $valuesTmp['title']);
  185. $valuesTmp['author'] = mb_strcut($valuesTmp['author'], 0, 255, 'UTF-8');
  186. $valuesTmp['author'] = safe_utf8($valuesTmp['author']);
  187. $this->updateEntryPrepared->bindParam(':author', $valuesTmp['author']);
  188. $valuesTmp['content'] = safe_utf8($valuesTmp['content']);
  189. $this->updateEntryPrepared->bindParam(':content', $valuesTmp['content']);
  190. $valuesTmp['link'] = substr($valuesTmp['link'], 0, 1023);
  191. $valuesTmp['link'] = safe_ascii($valuesTmp['link']);
  192. $this->updateEntryPrepared->bindParam(':link', $valuesTmp['link']);
  193. $valuesTmp['date'] = min($valuesTmp['date'], 2147483647);
  194. $this->updateEntryPrepared->bindParam(':date', $valuesTmp['date'], PDO::PARAM_INT);
  195. $valuesTmp['lastSeen'] = time();
  196. $this->updateEntryPrepared->bindParam(':last_seen', $valuesTmp['lastSeen'], PDO::PARAM_INT);
  197. if ($valuesTmp['is_read'] === null) {
  198. $this->updateEntryPrepared->bindValue(':is_read', null, PDO::PARAM_NULL);
  199. } else {
  200. $this->updateEntryPrepared->bindValue(':is_read', $valuesTmp['is_read'] ? 1 : 0, PDO::PARAM_INT);
  201. }
  202. $this->updateEntryPrepared->bindParam(':id_feed', $valuesTmp['id_feed'], PDO::PARAM_INT);
  203. $valuesTmp['tags'] = mb_strcut($valuesTmp['tags'], 0, 1023, 'UTF-8');
  204. $valuesTmp['tags'] = safe_utf8($valuesTmp['tags']);
  205. $this->updateEntryPrepared->bindParam(':tags', $valuesTmp['tags']);
  206. if ($this->hasNativeHex()) {
  207. $this->updateEntryPrepared->bindParam(':hash', $valuesTmp['hash']);
  208. } else {
  209. $valuesTmp['hashBin'] = hex2bin($valuesTmp['hash']);
  210. $this->updateEntryPrepared->bindParam(':hash', $valuesTmp['hashBin']);
  211. }
  212. }
  213. if ($this->updateEntryPrepared && $this->updateEntryPrepared->execute()) {
  214. return true;
  215. } else {
  216. $info = $this->updateEntryPrepared == null ? $this->pdo->errorInfo() : $this->updateEntryPrepared->errorInfo();
  217. if ($this->autoUpdateDb($info)) {
  218. return $this->updateEntry($valuesTmp);
  219. }
  220. Minz_Log::error('SQL error updateEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  221. . ' while updating entry with GUID ' . $valuesTmp['guid'] . ' in feed ' . $valuesTmp['id_feed']);
  222. return false;
  223. }
  224. }
  225. /**
  226. * Toggle favorite marker on one or more article
  227. *
  228. * @todo simplify the query by removing the str_repeat. I am pretty sure
  229. * there is an other way to do that.
  230. *
  231. * @param integer|array $ids
  232. * @param boolean $is_favorite
  233. * @return false|integer
  234. */
  235. public function markFavorite($ids, $is_favorite = true) {
  236. if (!is_array($ids)) {
  237. $ids = array($ids);
  238. }
  239. if (count($ids) < 1) {
  240. return 0;
  241. }
  242. FreshRSS_UserDAO::touch();
  243. if (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  244. // Split a query with too many variables parameters
  245. $affected = 0;
  246. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  247. foreach ($idsChunks as $idsChunk) {
  248. $affected += $this->markFavorite($idsChunk, $is_favorite);
  249. }
  250. return $affected;
  251. }
  252. $sql = 'UPDATE `_entry` '
  253. . 'SET is_favorite=? '
  254. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)';
  255. $values = array($is_favorite ? 1 : 0);
  256. $values = array_merge($values, $ids);
  257. $stm = $this->pdo->prepare($sql);
  258. if ($stm && $stm->execute($values)) {
  259. return $stm->rowCount();
  260. } else {
  261. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  262. Minz_Log::error('SQL error markFavorite: ' . $info[2]);
  263. return false;
  264. }
  265. }
  266. /**
  267. * Update the unread article cache held on every feed details.
  268. * Depending on the parameters, it updates the cache on one feed, on all
  269. * feeds from one category or on all feeds.
  270. *
  271. * @todo It can use the query builder refactoring to build that query
  272. *
  273. * @param false|integer $catId category ID
  274. * @param false|integer $feedId feed ID
  275. * @return boolean
  276. */
  277. protected function updateCacheUnreads($catId = false, $feedId = false) {
  278. $sql = 'UPDATE `_feed` f '
  279. . 'LEFT OUTER JOIN ('
  280. . 'SELECT e.id_feed, '
  281. . 'COUNT(*) AS nbUnreads '
  282. . 'FROM `_entry` e '
  283. . 'WHERE e.is_read=0 '
  284. . 'GROUP BY e.id_feed'
  285. . ') x ON x.id_feed=f.id '
  286. . 'SET f.`cache_nbUnreads`=COALESCE(x.nbUnreads, 0)';
  287. $hasWhere = false;
  288. $values = array();
  289. if ($feedId !== false) {
  290. $sql .= $hasWhere ? ' AND' : ' WHERE';
  291. $hasWhere = true;
  292. $sql .= ' f.id=?';
  293. $values[] = $feedId;
  294. }
  295. if ($catId !== false) {
  296. $sql .= $hasWhere ? ' AND' : ' WHERE';
  297. $hasWhere = true;
  298. $sql .= ' f.category=?';
  299. $values[] = $catId;
  300. }
  301. $stm = $this->pdo->prepare($sql);
  302. if ($stm && $stm->execute($values)) {
  303. return true;
  304. } else {
  305. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  306. Minz_Log::error('SQL error updateCacheUnreads: ' . $info[2]);
  307. return false;
  308. }
  309. }
  310. /**
  311. * Toggle the read marker on one or more article.
  312. * Then the cache is updated.
  313. *
  314. * @todo change the way the query is build because it seems there is
  315. * unnecessary code in here. For instance, the part with the str_repeat.
  316. * @todo remove code duplication. It seems the code is basically the
  317. * same if it is an array or not.
  318. *
  319. * @param integer|array $ids
  320. * @param boolean $is_read
  321. * @return integer affected rows
  322. */
  323. public function markRead($ids, $is_read = true) {
  324. FreshRSS_UserDAO::touch();
  325. if (is_array($ids)) { //Many IDs at once
  326. if (count($ids) < 6) { //Speed heuristics
  327. $affected = 0;
  328. foreach ($ids as $id) {
  329. $affected += $this->markRead($id, $is_read);
  330. }
  331. return $affected;
  332. } elseif (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  333. // Split a query with too many variables parameters
  334. $affected = 0;
  335. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  336. foreach ($idsChunks as $idsChunk) {
  337. $affected += $this->markRead($idsChunk, $is_read);
  338. }
  339. return $affected;
  340. }
  341. $sql = 'UPDATE `_entry` '
  342. . 'SET is_read=? '
  343. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)';
  344. $values = array($is_read ? 1 : 0);
  345. $values = array_merge($values, $ids);
  346. $stm = $this->pdo->prepare($sql);
  347. if (!($stm && $stm->execute($values))) {
  348. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  349. Minz_Log::error('SQL error markRead: ' . $info[2]);
  350. return false;
  351. }
  352. $affected = $stm->rowCount();
  353. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  354. return false;
  355. }
  356. return $affected;
  357. } else {
  358. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  359. . 'SET e.is_read=?,'
  360. . 'f.`cache_nbUnreads`=f.`cache_nbUnreads`' . ($is_read ? '-' : '+') . '1 '
  361. . 'WHERE e.id=? AND e.is_read=?';
  362. $values = array($is_read ? 1 : 0, $ids, $is_read ? 0 : 1);
  363. $stm = $this->pdo->prepare($sql);
  364. if ($stm && $stm->execute($values)) {
  365. return $stm->rowCount();
  366. } else {
  367. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  368. Minz_Log::error('SQL error markRead: ' . $info[2]);
  369. return false;
  370. }
  371. }
  372. }
  373. /**
  374. * Mark all entries as read depending on parameters.
  375. * If $onlyFavorites is true, it is used when the user mark as read in
  376. * the favorite pseudo-category.
  377. * If $priorityMin is greater than 0, it is used when the user mark as
  378. * read in the main feed pseudo-category.
  379. * Then the cache is updated.
  380. *
  381. * If $idMax equals 0, a deprecated debug message is logged
  382. *
  383. * @todo refactor this method along with markReadCat and markReadFeed
  384. * since they are all doing the same thing. I think we need to build a
  385. * tool to generate the query instead of having queries all over the
  386. * place. It will be reused also for the filtering making every thing
  387. * separated.
  388. *
  389. * @param integer $idMax fail safe article ID
  390. * @param boolean $onlyFavorites
  391. * @param integer $priorityMin
  392. * @return integer affected rows
  393. */
  394. public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0, $filters = null, $state = 0, $is_read = true) {
  395. FreshRSS_UserDAO::touch();
  396. if ($idMax == 0) {
  397. $idMax = time() . '000000';
  398. Minz_Log::debug('Calling markReadEntries(0) is deprecated!');
  399. }
  400. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  401. . 'SET e.is_read=? '
  402. . 'WHERE e.is_read <> ? AND e.id <= ?';
  403. if ($onlyFavorites) {
  404. $sql .= ' AND e.is_favorite=1';
  405. } elseif ($priorityMin >= 0) {
  406. $sql .= ' AND f.priority > ' . intval($priorityMin);
  407. }
  408. $values = array($is_read ? 1 : 0, $is_read ? 1 : 0, $idMax);
  409. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state);
  410. $stm = $this->pdo->prepare($sql . $search);
  411. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  412. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  413. Minz_Log::error('SQL error markReadEntries: ' . $info[2]);
  414. return false;
  415. }
  416. $affected = $stm->rowCount();
  417. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  418. return false;
  419. }
  420. return $affected;
  421. }
  422. /**
  423. * Mark all the articles in a category as read.
  424. * There is a fail safe to prevent to mark as read articles that are
  425. * loaded during the mark as read action. Then the cache is updated.
  426. *
  427. * If $idMax equals 0, a deprecated debug message is logged
  428. *
  429. * @param integer $id category ID
  430. * @param integer $idMax fail safe article ID
  431. * @return integer affected rows
  432. */
  433. public function markReadCat($id, $idMax = 0, $filters = null, $state = 0, $is_read = true) {
  434. FreshRSS_UserDAO::touch();
  435. if ($idMax == 0) {
  436. $idMax = time() . '000000';
  437. Minz_Log::debug('Calling markReadCat(0) is deprecated!');
  438. }
  439. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  440. . 'SET e.is_read=? '
  441. . 'WHERE f.category=? AND e.is_read <> ? AND e.id <= ?';
  442. $values = array($is_read ? 1 : 0, $id, $is_read ? 1 : 0, $idMax);
  443. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state);
  444. $stm = $this->pdo->prepare($sql . $search);
  445. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  446. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  447. Minz_Log::error('SQL error markReadCat: ' . $info[2]);
  448. return false;
  449. }
  450. $affected = $stm->rowCount();
  451. if (($affected > 0) && (!$this->updateCacheUnreads($id, false))) {
  452. return false;
  453. }
  454. return $affected;
  455. }
  456. /**
  457. * Mark all the articles in a feed as read.
  458. * There is a fail safe to prevent to mark as read articles that are
  459. * loaded during the mark as read action. Then the cache is updated.
  460. *
  461. * If $idMax equals 0, a deprecated debug message is logged
  462. *
  463. * @param integer $id_feed feed ID
  464. * @param integer $idMax fail safe article ID
  465. * @return integer affected rows
  466. */
  467. public function markReadFeed($id_feed, $idMax = 0, $filters = null, $state = 0, $is_read = true) {
  468. FreshRSS_UserDAO::touch();
  469. if ($idMax == 0) {
  470. $idMax = time() . '000000';
  471. Minz_Log::debug('Calling markReadFeed(0) is deprecated!');
  472. }
  473. $this->pdo->beginTransaction();
  474. $sql = 'UPDATE `_entry` '
  475. . 'SET is_read=? '
  476. . 'WHERE id_feed=? AND is_read <> ? AND id <= ?';
  477. $values = array($is_read ? 1 : 0, $id_feed, $is_read ? 1 : 0, $idMax);
  478. list($searchValues, $search) = $this->sqlListEntriesWhere('', $filters, $state);
  479. $stm = $this->pdo->prepare($sql . $search);
  480. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  481. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  482. Minz_Log::error('SQL error markReadFeed: ' . $info[2] . ' with SQL: ' . $sql . $search);
  483. $this->pdo->rollBack();
  484. return false;
  485. }
  486. $affected = $stm->rowCount();
  487. if ($affected > 0) {
  488. $sql = 'UPDATE `_feed` '
  489. . 'SET `cache_nbUnreads`=`cache_nbUnreads`-' . $affected
  490. . ' WHERE id=:id';
  491. $stm = $this->pdo->prepare($sql);
  492. $stm->bindParam(':id', $id_feed, PDO::PARAM_INT);
  493. if (!($stm && $stm->execute())) {
  494. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  495. Minz_Log::error('SQL error markReadFeed cache: ' . $info[2]);
  496. $this->pdo->rollBack();
  497. return false;
  498. }
  499. }
  500. $this->pdo->commit();
  501. return $affected;
  502. }
  503. /**
  504. * Mark all the articles in a tag as read.
  505. * @param integer $id tag ID, or empty for targetting any tag
  506. * @param integer $idMax max article ID
  507. * @return integer affected rows
  508. */
  509. public function markReadTag($id = '', $idMax = 0, $filters = null, $state = 0, $is_read = true) {
  510. FreshRSS_UserDAO::touch();
  511. if ($idMax == 0) {
  512. $idMax = time() . '000000';
  513. Minz_Log::debug('Calling markReadTag(0) is deprecated!');
  514. }
  515. $sql = 'UPDATE `_entry` e INNER JOIN `_entrytag` et ON et.id_entry = e.id '
  516. . 'SET e.is_read = ? '
  517. . 'WHERE '
  518. . ($id == '' ? '' : 'et.id_tag = ? AND ')
  519. . 'e.is_read <> ? AND e.id <= ?';
  520. $values = array($is_read ? 1 : 0);
  521. if ($id != '') {
  522. $values[] = $id;
  523. }
  524. $values[] = $is_read ? 1 : 0;
  525. $values[] = $idMax;
  526. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state);
  527. $stm = $this->pdo->prepare($sql . $search);
  528. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  529. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  530. Minz_Log::error('SQL error markReadTag: ' . $info[2]);
  531. return false;
  532. }
  533. $affected = $stm->rowCount();
  534. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  535. return false;
  536. }
  537. return $affected;
  538. }
  539. public function cleanOldEntries($id_feed, $options = []) { //Remember to call updateCachedValue($id_feed) or updateCachedValues() just after
  540. $sql = 'DELETE FROM `_entry` WHERE id_feed = :id_feed1'; //No alias for MySQL / MariaDB
  541. $params = [];
  542. $params[':id_feed1'] = $id_feed;
  543. //==Exclusions==
  544. if (!empty($options['keep_favourites'])) {
  545. $sql .= ' AND is_favorite = 0';
  546. }
  547. if (!empty($options['keep_unreads'])) {
  548. $sql .= ' AND is_read = 1';
  549. }
  550. if (!empty($options['keep_labels'])) {
  551. $sql .= ' AND NOT EXISTS (SELECT 1 FROM `_entrytag` WHERE id_entry = id)';
  552. }
  553. if (!empty($options['keep_min']) && $options['keep_min'] > 0) {
  554. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  555. $sql .= ' AND `lastSeen` < (SELECT `lastSeen`'
  556. . ' FROM (SELECT e2.`lastSeen` FROM `_entry` e2 WHERE e2.id_feed = :id_feed2'
  557. . ' ORDER BY e2.`lastSeen` DESC LIMIT 1 OFFSET :keep_min) last_seen2)';
  558. $params[':id_feed2'] = $id_feed;
  559. $params[':keep_min'] = (int)$options['keep_min'];
  560. }
  561. //Keep at least the articles seen at the last refresh
  562. $sql .= ' AND `lastSeen` < (SELECT maxlastseen'
  563. . ' FROM (SELECT MAX(e3.`lastSeen`) AS maxlastseen FROM `_entry` e3 WHERE e3.id_feed = :id_feed3) last_seen3)';
  564. $params[':id_feed3'] = $id_feed;
  565. //==Inclusions==
  566. $sql .= ' AND (1=0';
  567. if (!empty($options['keep_period'])) {
  568. $sql .= ' OR `lastSeen` < :max_last_seen';
  569. $now = new DateTime('now');
  570. $now->sub(new DateInterval($options['keep_period']));
  571. $params[':max_last_seen'] = $now->format('U');
  572. }
  573. if (!empty($options['keep_max']) && $options['keep_max'] > 0) {
  574. $sql .= ' OR `lastSeen` <= (SELECT `lastSeen`'
  575. . ' FROM (SELECT e4.`lastSeen` FROM `_entry` e4 WHERE e4.id_feed = :id_feed4'
  576. . ' ORDER BY e4.`lastSeen` DESC LIMIT 1 OFFSET :keep_max) last_seen4)';
  577. $params[':id_feed4'] = $id_feed;
  578. $params[':keep_max'] = (int)$options['keep_max'];
  579. }
  580. $sql .= ')';
  581. $stm = $this->pdo->prepare($sql);
  582. if ($stm && $stm->execute($params)) {
  583. return $stm->rowCount();
  584. } else {
  585. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  586. if ($this->autoUpdateDb($info)) {
  587. return $this->cleanOldEntries($id_feed, $options);
  588. }
  589. Minz_Log::error(__method__ . ' error:' . json_encode($info));
  590. return false;
  591. }
  592. }
  593. public function selectAll() {
  594. $sql = 'SELECT id, guid, title, author, '
  595. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  596. . ', link, date, `lastSeen`, ' . $this->sqlHexEncode('hash') . ' AS hash, is_read, is_favorite, id_feed, tags '
  597. . 'FROM `_entry`';
  598. $stm = $this->pdo->query($sql);
  599. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  600. yield $row;
  601. }
  602. }
  603. public function searchByGuid($id_feed, $guid) {
  604. // un guid est unique pour un flux donné
  605. $sql = 'SELECT id, guid, title, author, '
  606. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  607. . ', link, date, is_read, is_favorite, id_feed, tags '
  608. . 'FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  609. $stm = $this->pdo->prepare($sql);
  610. $stm->bindParam(':id_feed', $id_feed, PDO::PARAM_INT);
  611. $stm->bindParam(':guid', $guid);
  612. $stm->execute();
  613. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  614. return isset($res[0]) ? self::daoToEntry($res[0]) : null;
  615. }
  616. public function searchById($id) {
  617. $sql = 'SELECT id, guid, title, author, '
  618. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  619. . ', link, date, is_read, is_favorite, id_feed, tags '
  620. . 'FROM `_entry` WHERE id=:id';
  621. $stm = $this->pdo->prepare($sql);
  622. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  623. $stm->execute();
  624. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  625. return isset($res[0]) ? self::daoToEntry($res[0]) : null;
  626. }
  627. public function searchIdByGuid($id_feed, $guid) {
  628. $sql = 'SELECT id FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  629. $stm = $this->pdo->prepare($sql);
  630. $stm->bindParam(':id_feed', $id_feed, PDO::PARAM_INT);
  631. $stm->bindParam(':guid', $guid);
  632. $stm->execute();
  633. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  634. return isset($res[0]) ? $res[0] : null;
  635. }
  636. protected function sqlConcat($s1, $s2) {
  637. return 'CONCAT(' . $s1 . ',' . $s2 . ')'; //MySQL
  638. }
  639. protected function sqlListEntriesWhere($alias = '', $filters = null, $state = FreshRSS_Entry::STATE_ALL,
  640. $order = 'DESC', $firstId = '', $date_min = 0) {
  641. $search = ' ';
  642. $values = array();
  643. if ($state & FreshRSS_Entry::STATE_NOT_READ) {
  644. if (!($state & FreshRSS_Entry::STATE_READ)) {
  645. $search .= 'AND ' . $alias . 'is_read=0 ';
  646. }
  647. } elseif ($state & FreshRSS_Entry::STATE_READ) {
  648. $search .= 'AND ' . $alias . 'is_read=1 ';
  649. }
  650. if ($state & FreshRSS_Entry::STATE_FAVORITE) {
  651. if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) {
  652. $search .= 'AND ' . $alias . 'is_favorite=1 ';
  653. }
  654. } elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
  655. $search .= 'AND ' . $alias . 'is_favorite=0 ';
  656. }
  657. switch ($order) {
  658. case 'DESC':
  659. case 'ASC':
  660. break;
  661. default:
  662. throw new FreshRSS_EntriesGetter_Exception('Bad order in Entry->listByType: [' . $order . ']!');
  663. }
  664. if ($firstId !== '') {
  665. $search .= 'AND ' . $alias . 'id ' . ($order === 'DESC' ? '<=' : '>=') . ' ? ';
  666. $values[] = $firstId;
  667. }
  668. if ($date_min > 0) {
  669. $search .= 'AND ' . $alias . 'id >= ? ';
  670. $values[] = $date_min . '000000';
  671. }
  672. if ($filters && count($filters->searches()) > 0) {
  673. $isOpen = false;
  674. foreach ($filters->searches() as $filter) {
  675. if ($filter == null) {
  676. continue;
  677. }
  678. $sub_search = '';
  679. if ($filter->getMinDate()) {
  680. $sub_search .= 'AND ' . $alias . 'id >= ? ';
  681. $values[] = "{$filter->getMinDate()}000000";
  682. }
  683. if ($filter->getMaxDate()) {
  684. $sub_search .= 'AND ' . $alias . 'id <= ? ';
  685. $values[] = "{$filter->getMaxDate()}000000";
  686. }
  687. if ($filter->getMinPubdate()) {
  688. $sub_search .= 'AND ' . $alias . 'date >= ? ';
  689. $values[] = $filter->getMinPubdate();
  690. }
  691. if ($filter->getMaxPubdate()) {
  692. $sub_search .= 'AND ' . $alias . 'date <= ? ';
  693. $values[] = $filter->getMaxPubdate();
  694. }
  695. //Negation of date intervals must be combined by OR
  696. if ($filter->getNotMinDate() || $filter->getNotMaxDate()) {
  697. $sub_search .= 'AND (';
  698. if ($filter->getNotMinDate()) {
  699. $sub_search .= $alias . 'id < ?';
  700. $values[] = "{$filter->getNotMinDate()}000000";
  701. if ($filter->getNotMaxDate()) {
  702. $sub_search .= ' OR ';
  703. }
  704. }
  705. if ($filter->getNotMaxDate()) {
  706. $sub_search .= $alias . 'id > ?';
  707. $values[] = "{$filter->getNotMaxDate()}000000";
  708. }
  709. $sub_search .= ') ';
  710. }
  711. if ($filter->getNotMinPubdate() || $filter->getNotMaxPubdate()) {
  712. $sub_search .= 'AND (';
  713. if ($filter->getNotMinPubdate()) {
  714. $sub_search .= $alias . 'date < ?';
  715. $values[] = $filter->getNotMinPubdate();
  716. if ($filter->getNotMaxPubdate()) {
  717. $sub_search .= ' OR ';
  718. }
  719. }
  720. if ($filter->getNotMaxPubdate()) {
  721. $sub_search .= $alias . 'date > ?';
  722. $values[] = $filter->getNotMaxPubdate();
  723. }
  724. $sub_search .= ') ';
  725. }
  726. if ($filter->getFeedIds()) {
  727. foreach ($filter->getFeedIds() as $feed_ids) {
  728. $sub_search .= 'AND ' . $alias . 'id_feed IN (';
  729. foreach ($feed_ids as $feed_id) {
  730. $sub_search .= '?,';
  731. $values[] = $feed_id;
  732. }
  733. $sub_search = rtrim($sub_search, ',');
  734. $sub_search .= ') ';
  735. }
  736. }
  737. if ($filter->getNotFeedIds()) {
  738. foreach ($filter->getNotFeedIds() as $feed_ids) {
  739. $sub_search .= 'AND ' . $alias . 'id_feed NOT IN (';
  740. foreach ($feed_ids as $feed_id) {
  741. $sub_search .= '?,';
  742. $values[] = $feed_id;
  743. }
  744. $sub_search = rtrim($sub_search, ',');
  745. $sub_search .= ') ';
  746. }
  747. }
  748. if ($filter->getLabelIds()) {
  749. foreach ($filter->getLabelIds() as $label_ids) {
  750. if ($label_ids === '*') {
  751. $sub_search .= 'AND EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  752. } else {
  753. $sub_search .= 'AND ' . $alias . 'id IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  754. foreach ($label_ids as $label_id) {
  755. $sub_search .= '?,';
  756. $values[] = $label_id;
  757. }
  758. $sub_search = rtrim($sub_search, ',');
  759. $sub_search .= ')) ';
  760. }
  761. }
  762. }
  763. if ($filter->getNotLabelIds()) {
  764. foreach ($filter->getNotLabelIds() as $label_ids) {
  765. if ($label_ids === '*') {
  766. $sub_search .= 'AND NOT EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  767. } else {
  768. $sub_search .= 'AND ' . $alias . 'id NOT IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  769. foreach ($label_ids as $label_id) {
  770. $sub_search .= '?,';
  771. $values[] = $label_id;
  772. }
  773. $sub_search = rtrim($sub_search, ',');
  774. $sub_search .= ')) ';
  775. }
  776. }
  777. }
  778. if ($filter->getLabelNames()) {
  779. foreach ($filter->getLabelNames() as $label_names) {
  780. $sub_search .= 'AND ' . $alias . 'id IN (SELECT et.id_entry FROM `_entrytag` et, `_tag` t WHERE et.id_tag = t.id AND t.name IN (';
  781. foreach ($label_names as $label_name) {
  782. $sub_search .= '?,';
  783. $values[] = $label_name;
  784. }
  785. $sub_search = rtrim($sub_search, ',');
  786. $sub_search .= ')) ';
  787. }
  788. }
  789. if ($filter->getNotLabelNames()) {
  790. foreach ($filter->getNotLabelNames() as $label_names) {
  791. $sub_search .= 'AND ' . $alias . 'id NOT IN (SELECT et.id_entry FROM `_entrytag` et, `_tag` t WHERE et.id_tag = t.id AND t.name IN (';
  792. foreach ($label_names as $label_name) {
  793. $sub_search .= '?,';
  794. $values[] = $label_name;
  795. }
  796. $sub_search = rtrim($sub_search, ',');
  797. $sub_search .= ')) ';
  798. }
  799. }
  800. if ($filter->getAuthor()) {
  801. foreach ($filter->getAuthor() as $author) {
  802. $sub_search .= 'AND ' . $alias . 'author LIKE ? ';
  803. $values[] = "%{$author}%";
  804. }
  805. }
  806. if ($filter->getIntitle()) {
  807. foreach ($filter->getIntitle() as $title) {
  808. $sub_search .= 'AND ' . $alias . 'title LIKE ? ';
  809. $values[] = "%{$title}%";
  810. }
  811. }
  812. if ($filter->getTags()) {
  813. foreach ($filter->getTags() as $tag) {
  814. $sub_search .= 'AND ' . $alias . 'tags LIKE ? ';
  815. $values[] = "%{$tag}%";
  816. }
  817. }
  818. if ($filter->getInurl()) {
  819. foreach ($filter->getInurl() as $url) {
  820. $sub_search .= 'AND ' . $this->sqlConcat($alias . 'link', $alias . 'guid') . ' LIKE ? ';
  821. $values[] = "%{$url}%";
  822. }
  823. }
  824. if ($filter->getNotAuthor()) {
  825. foreach ($filter->getNotAuthor() as $author) {
  826. $sub_search .= 'AND (NOT ' . $alias . 'author LIKE ?) ';
  827. $values[] = "%{$author}%";
  828. }
  829. }
  830. if ($filter->getNotIntitle()) {
  831. foreach ($filter->getNotIntitle() as $title) {
  832. $sub_search .= 'AND (NOT ' . $alias . 'title LIKE ?) ';
  833. $values[] = "%{$title}%";
  834. }
  835. }
  836. if ($filter->getNotTags()) {
  837. foreach ($filter->getNotTags() as $tag) {
  838. $sub_search .= 'AND (NOT ' . $alias . 'tags LIKE ?) ';
  839. $values[] = "%{$tag}%";
  840. }
  841. }
  842. if ($filter->getNotInurl()) {
  843. foreach ($filter->getNotInurl() as $url) {
  844. $sub_search .= 'AND (NOT ' . $this->sqlConcat($alias . 'link', $alias . 'guid') . ' LIKE ?) ';
  845. $values[] = "%{$url}%";
  846. }
  847. }
  848. if ($filter->getSearch()) {
  849. foreach ($filter->getSearch() as $search_value) {
  850. $sub_search .= 'AND ' . $this->sqlConcat($alias . 'title',
  851. $this->isCompressed() ? 'UNCOMPRESS(' . $alias . 'content_bin)' : '' . $alias . 'content') . ' LIKE ? ';
  852. $values[] = "%{$search_value}%";
  853. }
  854. }
  855. if ($filter->getNotSearch()) {
  856. foreach ($filter->getNotSearch() as $search_value) {
  857. $sub_search .= 'AND (NOT ' . $this->sqlConcat($alias . 'title',
  858. $this->isCompressed() ? 'UNCOMPRESS(' . $alias . 'content_bin)' : '' . $alias . 'content') . ' LIKE ?) ';
  859. $values[] = "%{$search_value}%";
  860. }
  861. }
  862. if ($sub_search != '') {
  863. if ($isOpen) {
  864. $search .= 'OR ';
  865. } else {
  866. $search .= 'AND (';
  867. $isOpen = true;
  868. }
  869. $search .= '(' . substr($sub_search, 4) . ') ';
  870. }
  871. }
  872. if ($isOpen) {
  873. $search .= ') ';
  874. }
  875. }
  876. return array($values, $search);
  877. }
  878. private function sqlListWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL,
  879. $order = 'DESC', $limit = 1, $firstId = '', $filters = null, $date_min = 0) {
  880. if (!$state) {
  881. $state = FreshRSS_Entry::STATE_ALL;
  882. }
  883. $where = '';
  884. $joinFeed = false;
  885. $values = array();
  886. switch ($type) {
  887. case 'a': //All PRIORITY_MAIN_STREAM
  888. $where .= 'f.priority > ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  889. break;
  890. case 'A': //All except PRIORITY_ARCHIVED
  891. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  892. break;
  893. case 's': //Starred. Deprecated: use $state instead
  894. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  895. $where .= 'AND e.is_favorite=1 ';
  896. break;
  897. case 'S': //Starred
  898. $where .= 'e.is_favorite=1 ';
  899. break;
  900. case 'c': //Category
  901. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  902. $where .= 'AND f.category=? ';
  903. $values[] = intval($id);
  904. break;
  905. case 'f': //Feed
  906. $where .= 'e.id_feed=? ';
  907. $values[] = intval($id);
  908. break;
  909. case 't': //Tag (label)
  910. $where .= 'et.id_tag=? ';
  911. $values[] = intval($id);
  912. break;
  913. case 'T': //Any tag (label)
  914. $where .= '1=1 ';
  915. break;
  916. case 'ST': //Starred or tagged (label)
  917. $where .= 'e.is_favorite=1 OR EXISTS (SELECT et2.id_tag FROM `_entrytag` et2 WHERE et2.id_entry = e.id) ';
  918. break;
  919. default:
  920. throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
  921. }
  922. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state, $order, $firstId, $date_min);
  923. return array(array_merge($values, $searchValues),
  924. 'SELECT '
  925. . ($type === 'T' ? 'DISTINCT ' : '')
  926. . 'e.id FROM `_entry` e '
  927. . 'INNER JOIN `_feed` f ON e.id_feed = f.id '
  928. . ($type === 't' || $type === 'T' ? 'INNER JOIN `_entrytag` et ON et.id_entry = e.id ' : '')
  929. . 'WHERE ' . $where
  930. . $search
  931. . 'ORDER BY e.id ' . $order
  932. . ($limit > 0 ? ' LIMIT ' . intval($limit) : '')); //TODO: See http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
  933. }
  934. public function listWhereRaw($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL,
  935. $order = 'DESC', $limit = 1, $firstId = '', $filters = null, $date_min = 0) {
  936. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filters, $date_min);
  937. $sql = 'SELECT e0.id, e0.guid, e0.title, e0.author, '
  938. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  939. . ', e0.link, e0.date, e0.is_read, e0.is_favorite, e0.id_feed, e0.tags '
  940. . 'FROM `_entry` e0 '
  941. . 'INNER JOIN ('
  942. . $sql
  943. . ') e2 ON e2.id=e0.id '
  944. . 'ORDER BY e0.id ' . $order;
  945. $stm = $this->pdo->prepare($sql);
  946. if ($stm && $stm->execute($values)) {
  947. return $stm;
  948. } else {
  949. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  950. Minz_Log::error('SQL error listWhereRaw: ' . $info[2]);
  951. return false;
  952. }
  953. }
  954. public function listWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL,
  955. $order = 'DESC', $limit = 1, $firstId = '', $filters = null, $date_min = 0) {
  956. $stm = $this->listWhereRaw($type, $id, $state, $order, $limit, $firstId, $filters, $date_min);
  957. if ($stm) {
  958. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  959. yield self::daoToEntry($row);
  960. }
  961. } else {
  962. yield false;
  963. }
  964. }
  965. public function listByIds($ids, $order = 'DESC') {
  966. if (count($ids) < 1) {
  967. yield false;
  968. } elseif (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  969. // Split a query with too many variables parameters
  970. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  971. foreach ($idsChunks as $idsChunk) {
  972. foreach ($this->listByIds($idsChunk, $order) as $entry) {
  973. yield $entry;
  974. }
  975. }
  976. return;
  977. }
  978. $sql = 'SELECT id, guid, title, author, '
  979. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  980. . ', link, date, is_read, is_favorite, id_feed, tags '
  981. . 'FROM `_entry` '
  982. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?) '
  983. . 'ORDER BY id ' . $order;
  984. $stm = $this->pdo->prepare($sql);
  985. $stm->execute($ids);
  986. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  987. yield self::daoToEntry($row);
  988. }
  989. }
  990. public function listIdsWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL,
  991. $order = 'DESC', $limit = 1, $firstId = '', $filters = null) { //For API
  992. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filters);
  993. $stm = $this->pdo->prepare($sql);
  994. $stm->execute($values);
  995. return $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  996. }
  997. public function listHashForFeedGuids($id_feed, $guids) {
  998. $result = [];
  999. if (count($guids) < 1) {
  1000. return $result;
  1001. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1002. // Split a query with too many variables parameters
  1003. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1004. foreach ($guidsChunks as $guidsChunk) {
  1005. $result += $this->listHashForFeedGuids($id_feed, $guidsChunk);
  1006. }
  1007. return $result;
  1008. }
  1009. $guids = array_unique($guids);
  1010. $sql = 'SELECT guid, ' . $this->sqlHexEncode('hash') .
  1011. ' AS hex_hash FROM `_entry` WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  1012. $stm = $this->pdo->prepare($sql);
  1013. $values = array($id_feed);
  1014. $values = array_merge($values, $guids);
  1015. if ($stm && $stm->execute($values)) {
  1016. $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
  1017. foreach ($rows as $row) {
  1018. $result[$row['guid']] = $row['hex_hash'];
  1019. }
  1020. return $result;
  1021. } else {
  1022. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1023. if ($this->autoUpdateDb($info)) {
  1024. return $this->listHashForFeedGuids($id_feed, $guids);
  1025. }
  1026. Minz_Log::error('SQL error listHashForFeedGuids: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  1027. . ' while querying feed ' . $id_feed);
  1028. return false;
  1029. }
  1030. }
  1031. public function updateLastSeen($id_feed, $guids, $mtime = 0) {
  1032. if (count($guids) < 1) {
  1033. return 0;
  1034. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1035. // Split a query with too many variables parameters
  1036. $affected = 0;
  1037. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1038. foreach ($guidsChunks as $guidsChunk) {
  1039. $affected += $this->updateLastSeen($id_feed, $guidsChunk, $mtime);
  1040. }
  1041. return $affected;
  1042. }
  1043. $sql = 'UPDATE `_entry` SET `lastSeen`=? WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  1044. $stm = $this->pdo->prepare($sql);
  1045. if ($mtime <= 0) {
  1046. $mtime = time();
  1047. }
  1048. $values = array($mtime, $id_feed);
  1049. $values = array_merge($values, $guids);
  1050. if ($stm && $stm->execute($values)) {
  1051. return $stm->rowCount();
  1052. } else {
  1053. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1054. if ($this->autoUpdateDb($info)) {
  1055. return $this->updateLastSeen($id_feed, $guids);
  1056. }
  1057. Minz_Log::error('SQL error updateLastSeen: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  1058. . ' while updating feed ' . $id_feed);
  1059. return false;
  1060. }
  1061. }
  1062. public function countUnreadRead() {
  1063. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id WHERE f.priority > 0'
  1064. . ' 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';
  1065. $stm = $this->pdo->query($sql);
  1066. if ($stm === false) {
  1067. return false;
  1068. }
  1069. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1070. rsort($res);
  1071. $all = empty($res[0]) ? 0 : intval($res[0]);
  1072. $unread = empty($res[1]) ? 0 : intval($res[1]);
  1073. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  1074. }
  1075. public function count($minPriority = null) {
  1076. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1077. if ($minPriority !== null) {
  1078. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1079. $sql .= ' WHERE f.priority > ' . intval($minPriority);
  1080. }
  1081. $stm = $this->pdo->query($sql);
  1082. if ($stm == false) {
  1083. return false;
  1084. }
  1085. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1086. return isset($res[0]) ? intval($res[0]) : 0;
  1087. }
  1088. public function countNotRead($minPriority = null) {
  1089. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1090. if ($minPriority !== null) {
  1091. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1092. }
  1093. $sql .= ' WHERE e.is_read=0';
  1094. if ($minPriority !== null) {
  1095. $sql .= ' AND f.priority > ' . intval($minPriority);
  1096. }
  1097. $stm = $this->pdo->query($sql);
  1098. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1099. return isset($res[0]) ? intval($res[0]) : 0;
  1100. }
  1101. public function countUnreadReadFavorites() {
  1102. $sql = <<<'SQL'
  1103. SELECT c FROM (
  1104. SELECT COUNT(e1.id) AS c, 1 AS o
  1105. FROM `_entry` AS e1
  1106. JOIN `_feed` AS f1 ON e1.id_feed = f1.id
  1107. WHERE e1.is_favorite = 1
  1108. AND f1.priority >= :priority_normal1
  1109. UNION
  1110. SELECT COUNT(e2.id) AS c, 2 AS o
  1111. FROM `_entry` AS e2
  1112. JOIN `_feed` AS f2 ON e2.id_feed = f2.id
  1113. WHERE e2.is_favorite = 1
  1114. AND e2.is_read = 0
  1115. AND f2.priority >= :priority_normal2
  1116. ) u
  1117. ORDER BY o
  1118. SQL;
  1119. $stm = $this->pdo->prepare($sql);
  1120. if (!$stm) {
  1121. Minz_Log::error('SQL error in ' . __method__ . ' ' . json_encode($this->pdo->errorInfo()));
  1122. return false;
  1123. }
  1124. //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
  1125. $stm->bindValue(':priority_normal1', FreshRSS_Feed::PRIORITY_NORMAL, PDO::PARAM_INT);
  1126. $stm->bindValue(':priority_normal2', FreshRSS_Feed::PRIORITY_NORMAL, PDO::PARAM_INT);
  1127. $stm->execute();
  1128. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1129. rsort($res);
  1130. $all = empty($res[0]) ? 0 : intval($res[0]);
  1131. $unread = empty($res[1]) ? 0 : intval($res[1]);
  1132. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  1133. }
  1134. public static function daoToEntry($dao) {
  1135. $entry = new FreshRSS_Entry(
  1136. $dao['id_feed'],
  1137. $dao['guid'],
  1138. $dao['title'],
  1139. $dao['author'],
  1140. $dao['content'],
  1141. $dao['link'],
  1142. $dao['date'],
  1143. $dao['is_read'],
  1144. $dao['is_favorite'],
  1145. isset($dao['tags']) ? $dao['tags'] : ''
  1146. );
  1147. if (isset($dao['id'])) {
  1148. $entry->_id($dao['id']);
  1149. }
  1150. return $entry;
  1151. }
  1152. }