EntryDAO.php 39 KB

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