EntryDAO.php 36 KB

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