EntryDAO.php 38 KB

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