EntryDAO.php 39 KB

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