EntryDAO.php 38 KB

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