EntryDAO.php 38 KB

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