EntryDAO.php 39 KB

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