EntryDAO.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. <?php
  2. class FreshRSS_EntryDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
  3. public function isCompressed(): bool {
  4. return true;
  5. }
  6. public function hasNativeHex(): bool {
  7. return true;
  8. }
  9. public function sqlHexDecode(string $x): string {
  10. return 'unhex(' . $x . ')';
  11. }
  12. public function sqlHexEncode(string $x): string {
  13. return 'hex(' . $x . ')';
  14. }
  15. public function sqlIgnoreConflict(string $sql): string {
  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($GLOBALS['SQL_CREATE_TABLE_ENTRYTMP'] . $GLOBALS['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(array $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(array $valuesTmp, bool $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. * @return false|integer
  233. */
  234. public function markFavorite($ids, bool $is_favorite = true) {
  235. if (!is_array($ids)) {
  236. $ids = array($ids);
  237. }
  238. if (count($ids) < 1) {
  239. return 0;
  240. }
  241. FreshRSS_UserDAO::touch();
  242. if (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  243. // Split a query with too many variables parameters
  244. $affected = 0;
  245. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  246. foreach ($idsChunks as $idsChunk) {
  247. $affected += $this->markFavorite($idsChunk, $is_favorite);
  248. }
  249. return $affected;
  250. }
  251. $sql = 'UPDATE `_entry` '
  252. . 'SET is_favorite=? '
  253. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)';
  254. $values = array($is_favorite ? 1 : 0);
  255. $values = array_merge($values, $ids);
  256. $stm = $this->pdo->prepare($sql);
  257. if ($stm && $stm->execute($values)) {
  258. return $stm->rowCount();
  259. } else {
  260. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  261. Minz_Log::error('SQL error markFavorite: ' . $info[2]);
  262. return false;
  263. }
  264. }
  265. /**
  266. * Update the unread article cache held on every feed details.
  267. * Depending on the parameters, it updates the cache on one feed, on all
  268. * feeds from one category or on all feeds.
  269. *
  270. * @todo It can use the query builder refactoring to build that query
  271. *
  272. * @param false|integer $catId category ID
  273. * @param false|integer $feedId feed ID
  274. * @return boolean
  275. */
  276. protected function updateCacheUnreads($catId = false, $feedId = false) {
  277. $sql = 'UPDATE `_feed` f '
  278. . 'LEFT OUTER JOIN ('
  279. . 'SELECT e.id_feed, '
  280. . 'COUNT(*) AS nbUnreads '
  281. . 'FROM `_entry` e '
  282. . 'WHERE e.is_read=0 '
  283. . 'GROUP BY e.id_feed'
  284. . ') x ON x.id_feed=f.id '
  285. . 'SET f.`cache_nbUnreads`=COALESCE(x.nbUnreads, 0)';
  286. $hasWhere = false;
  287. $values = array();
  288. if ($feedId !== false) {
  289. $sql .= ' WHERE';
  290. $hasWhere = true;
  291. $sql .= ' f.id=?';
  292. $values[] = $feedId;
  293. }
  294. if ($catId !== false) {
  295. $sql .= $hasWhere ? ' AND' : ' WHERE';
  296. $hasWhere = true;
  297. $sql .= ' f.category=?';
  298. $values[] = $catId;
  299. }
  300. $stm = $this->pdo->prepare($sql);
  301. if ($stm && $stm->execute($values)) {
  302. return true;
  303. } else {
  304. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  305. Minz_Log::error('SQL error updateCacheUnreads: ' . $info[2]);
  306. return false;
  307. }
  308. }
  309. /**
  310. * Toggle the read marker on one or more article.
  311. * Then the cache is updated.
  312. *
  313. * @todo change the way the query is build because it seems there is
  314. * unnecessary code in here. For instance, the part with the str_repeat.
  315. * @todo remove code duplication. It seems the code is basically the
  316. * same if it is an array or not.
  317. *
  318. * @param integer|array $ids
  319. * @param boolean $is_read
  320. * @return integer|false affected rows
  321. */
  322. public function markRead($ids, $is_read = true) {
  323. FreshRSS_UserDAO::touch();
  324. if (is_array($ids)) { //Many IDs at once
  325. if (count($ids) < 6) { //Speed heuristics
  326. $affected = 0;
  327. foreach ($ids as $id) {
  328. $affected += $this->markRead($id, $is_read);
  329. }
  330. return $affected;
  331. } elseif (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  332. // Split a query with too many variables parameters
  333. $affected = 0;
  334. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  335. foreach ($idsChunks as $idsChunk) {
  336. $affected += $this->markRead($idsChunk, $is_read);
  337. }
  338. return $affected;
  339. }
  340. $sql = 'UPDATE `_entry` '
  341. . 'SET is_read=? '
  342. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)';
  343. $values = array($is_read ? 1 : 0);
  344. $values = array_merge($values, $ids);
  345. $stm = $this->pdo->prepare($sql);
  346. if (!($stm && $stm->execute($values))) {
  347. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  348. Minz_Log::error('SQL error markRead: ' . $info[2]);
  349. return false;
  350. }
  351. $affected = $stm->rowCount();
  352. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  353. return false;
  354. }
  355. return $affected;
  356. } else {
  357. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  358. . 'SET e.is_read=?,'
  359. . 'f.`cache_nbUnreads`=f.`cache_nbUnreads`' . ($is_read ? '-' : '+') . '1 '
  360. . 'WHERE e.id=? AND e.is_read=?';
  361. $values = array($is_read ? 1 : 0, $ids, $is_read ? 0 : 1);
  362. $stm = $this->pdo->prepare($sql);
  363. if ($stm && $stm->execute($values)) {
  364. return $stm->rowCount();
  365. } else {
  366. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  367. Minz_Log::error('SQL error markRead: ' . $info[2]);
  368. return false;
  369. }
  370. }
  371. }
  372. /**
  373. * Mark all entries as read depending on parameters.
  374. * If $onlyFavorites is true, it is used when the user mark as read in
  375. * the favorite pseudo-category.
  376. * If $priorityMin is greater than 0, it is used when the user mark as
  377. * read in the main feed pseudo-category.
  378. * Then the cache is updated.
  379. *
  380. * If $idMax equals 0, a deprecated debug message is logged
  381. *
  382. * @todo refactor this method along with markReadCat and markReadFeed
  383. * since they are all doing the same thing. I think we need to build a
  384. * tool to generate the query instead of having queries all over the
  385. * place. It will be reused also for the filtering making every thing
  386. * separated.
  387. *
  388. * @param integer $idMax fail safe article ID
  389. * @param boolean $onlyFavorites
  390. * @param integer $priorityMin
  391. * @return integer|false affected rows
  392. */
  393. public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0, $filters = null, $state = 0, $is_read = true) {
  394. FreshRSS_UserDAO::touch();
  395. if ($idMax == 0) {
  396. $idMax = time() . '000000';
  397. Minz_Log::debug('Calling markReadEntries(0) is deprecated!');
  398. }
  399. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  400. . 'SET e.is_read=? '
  401. . 'WHERE e.is_read <> ? AND e.id <= ?';
  402. if ($onlyFavorites) {
  403. $sql .= ' AND e.is_favorite=1';
  404. } elseif ($priorityMin >= 0) {
  405. $sql .= ' AND f.priority > ' . intval($priorityMin);
  406. }
  407. $values = array($is_read ? 1 : 0, $is_read ? 1 : 0, $idMax);
  408. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state);
  409. $stm = $this->pdo->prepare($sql . $search);
  410. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  411. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  412. Minz_Log::error('SQL error markReadEntries: ' . $info[2]);
  413. return false;
  414. }
  415. $affected = $stm->rowCount();
  416. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  417. return false;
  418. }
  419. return $affected;
  420. }
  421. /**
  422. * Mark all the articles in a category as read.
  423. * There is a fail safe to prevent to mark as read articles that are
  424. * loaded during the mark as read action. Then the cache is updated.
  425. *
  426. * If $idMax equals 0, a deprecated debug message is logged
  427. *
  428. * @param integer $id category ID
  429. * @param integer $idMax fail safe article ID
  430. * @return integer|false affected rows
  431. */
  432. public function markReadCat($id, $idMax = 0, $filters = null, $state = 0, $is_read = true) {
  433. FreshRSS_UserDAO::touch();
  434. if ($idMax == 0) {
  435. $idMax = time() . '000000';
  436. Minz_Log::debug('Calling markReadCat(0) is deprecated!');
  437. }
  438. $sql = 'UPDATE `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id '
  439. . 'SET e.is_read=? '
  440. . 'WHERE f.category=? AND e.is_read <> ? AND e.id <= ?';
  441. $values = array($is_read ? 1 : 0, $id, $is_read ? 1 : 0, $idMax);
  442. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state);
  443. $stm = $this->pdo->prepare($sql . $search);
  444. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  445. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  446. Minz_Log::error('SQL error markReadCat: ' . $info[2]);
  447. return false;
  448. }
  449. $affected = $stm->rowCount();
  450. if (($affected > 0) && (!$this->updateCacheUnreads($id, false))) {
  451. return false;
  452. }
  453. return $affected;
  454. }
  455. /**
  456. * Mark all the articles in a feed as read.
  457. * There is a fail safe to prevent to mark as read articles that are
  458. * loaded during the mark as read action. Then the cache is updated.
  459. *
  460. * If $idMax equals 0, a deprecated debug message is logged
  461. *
  462. * @param integer $id_feed feed ID
  463. * @param string $idMax fail safe article ID
  464. * @return integer|false affected rows
  465. */
  466. public function markReadFeed($id_feed, $idMax = '0', $filters = null, $state = 0, $is_read = true) {
  467. FreshRSS_UserDAO::touch();
  468. if ($idMax == '0') {
  469. $idMax = time() . '000000';
  470. Minz_Log::debug('Calling markReadFeed(0) is deprecated!');
  471. }
  472. $this->pdo->beginTransaction();
  473. $sql = 'UPDATE `_entry` '
  474. . 'SET is_read=? '
  475. . 'WHERE id_feed=? AND is_read <> ? AND id <= ?';
  476. $values = array($is_read ? 1 : 0, $id_feed, $is_read ? 1 : 0, $idMax);
  477. list($searchValues, $search) = $this->sqlListEntriesWhere('', $filters, $state);
  478. $stm = $this->pdo->prepare($sql . $search);
  479. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  480. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  481. Minz_Log::error('SQL error markReadFeed: ' . $info[2] . ' with SQL: ' . $sql . $search);
  482. $this->pdo->rollBack();
  483. return false;
  484. }
  485. $affected = $stm->rowCount();
  486. if ($affected > 0) {
  487. $sql = 'UPDATE `_feed` '
  488. . 'SET `cache_nbUnreads`=`cache_nbUnreads`-' . $affected
  489. . ' WHERE id=:id';
  490. $stm = $this->pdo->prepare($sql);
  491. $stm->bindParam(':id', $id_feed, PDO::PARAM_INT);
  492. if (!($stm && $stm->execute())) {
  493. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  494. Minz_Log::error('SQL error markReadFeed cache: ' . $info[2]);
  495. $this->pdo->rollBack();
  496. return false;
  497. }
  498. }
  499. $this->pdo->commit();
  500. return $affected;
  501. }
  502. /**
  503. * Mark all the articles in a tag as read.
  504. * @param integer $id tag ID, or empty for targeting any tag
  505. * @param string $idMax max article ID
  506. * @return integer|false affected rows
  507. */
  508. public function markReadTag($id = 0, string $idMax = '0', $filters = null, int $state = 0, bool $is_read = true) {
  509. FreshRSS_UserDAO::touch();
  510. if ($idMax == '0') {
  511. $idMax = time() . '000000';
  512. Minz_Log::debug('Calling markReadTag(0) is deprecated!');
  513. }
  514. $sql = 'UPDATE `_entry` e INNER JOIN `_entrytag` et ON et.id_entry = e.id '
  515. . 'SET e.is_read = ? '
  516. . 'WHERE '
  517. . ($id == 0 ? '' : 'et.id_tag = ? AND ')
  518. . 'e.is_read <> ? AND e.id <= ?';
  519. $values = array($is_read ? 1 : 0);
  520. if ($id != 0) {
  521. $values[] = $id;
  522. }
  523. $values[] = $is_read ? 1 : 0;
  524. $values[] = $idMax;
  525. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state);
  526. $stm = $this->pdo->prepare($sql . $search);
  527. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  528. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  529. Minz_Log::error('SQL error markReadTag: ' . $info[2]);
  530. return false;
  531. }
  532. $affected = $stm->rowCount();
  533. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  534. return false;
  535. }
  536. return $affected;
  537. }
  538. /**
  539. * Remember to call updateCachedValue($id_feed) or updateCachedValues() just after.
  540. */
  541. public function cleanOldEntries($id_feed, $options = []) {
  542. $sql = 'DELETE FROM `_entry` WHERE id_feed = :id_feed1'; //No alias for MySQL / MariaDB
  543. $params = [];
  544. $params[':id_feed1'] = $id_feed;
  545. //==Exclusions==
  546. if (!empty($options['keep_favourites'])) {
  547. $sql .= ' AND is_favorite = 0';
  548. }
  549. if (!empty($options['keep_unreads'])) {
  550. $sql .= ' AND is_read = 1';
  551. }
  552. if (!empty($options['keep_labels'])) {
  553. $sql .= ' AND NOT EXISTS (SELECT 1 FROM `_entrytag` WHERE id_entry = id)';
  554. }
  555. if (!empty($options['keep_min']) && $options['keep_min'] > 0) {
  556. //Double SELECT for MySQL workaround ERROR 1093 (HY000)
  557. $sql .= ' AND `lastSeen` < (SELECT `lastSeen`'
  558. . ' FROM (SELECT e2.`lastSeen` FROM `_entry` e2 WHERE e2.id_feed = :id_feed2'
  559. . ' ORDER BY e2.`lastSeen` DESC LIMIT 1 OFFSET :keep_min) last_seen2)';
  560. $params[':id_feed2'] = $id_feed;
  561. $params[':keep_min'] = (int)$options['keep_min'];
  562. }
  563. //Keep at least the articles seen at the last refresh
  564. $sql .= ' AND `lastSeen` < (SELECT maxlastseen'
  565. . ' FROM (SELECT MAX(e3.`lastSeen`) AS maxlastseen FROM `_entry` e3 WHERE e3.id_feed = :id_feed3) last_seen3)';
  566. $params[':id_feed3'] = $id_feed;
  567. //==Inclusions==
  568. $sql .= ' AND (1=0';
  569. if (!empty($options['keep_period'])) {
  570. $sql .= ' OR `lastSeen` < :max_last_seen';
  571. $now = new DateTime('now');
  572. $now->sub(new DateInterval($options['keep_period']));
  573. $params[':max_last_seen'] = $now->format('U');
  574. }
  575. if (!empty($options['keep_max']) && $options['keep_max'] > 0) {
  576. $sql .= ' OR `lastSeen` <= (SELECT `lastSeen`'
  577. . ' FROM (SELECT e4.`lastSeen` FROM `_entry` e4 WHERE e4.id_feed = :id_feed4'
  578. . ' ORDER BY e4.`lastSeen` DESC LIMIT 1 OFFSET :keep_max) last_seen4)';
  579. $params[':id_feed4'] = $id_feed;
  580. $params[':keep_max'] = (int)$options['keep_max'];
  581. }
  582. $sql .= ')';
  583. $stm = $this->pdo->prepare($sql);
  584. if ($stm && $stm->execute($params)) {
  585. return $stm->rowCount();
  586. } else {
  587. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  588. if ($this->autoUpdateDb($info)) {
  589. return $this->cleanOldEntries($id_feed, $options);
  590. }
  591. Minz_Log::error(__method__ . ' error:' . json_encode($info));
  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 `_entry`';
  600. $stm = $this->pdo->query($sql);
  601. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  602. yield $row;
  603. }
  604. }
  605. public function searchByGuid($id_feed, $guid) {
  606. // un guid est unique pour un flux donné
  607. $sql = 'SELECT id, guid, title, author, '
  608. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  609. . ', link, date, is_read, is_favorite, id_feed, tags '
  610. . 'FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  611. $stm = $this->pdo->prepare($sql);
  612. $stm->bindParam(':id_feed', $id_feed, PDO::PARAM_INT);
  613. $stm->bindParam(':guid', $guid);
  614. $stm->execute();
  615. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  616. return isset($res[0]) ? self::daoToEntry($res[0]) : null;
  617. }
  618. public function searchById($id) {
  619. $sql = 'SELECT id, guid, title, author, '
  620. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  621. . ', link, date, is_read, is_favorite, id_feed, tags '
  622. . 'FROM `_entry` WHERE id=:id';
  623. $stm = $this->pdo->prepare($sql);
  624. $stm->bindParam(':id', $id, PDO::PARAM_INT);
  625. $stm->execute();
  626. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  627. return isset($res[0]) ? self::daoToEntry($res[0]) : null;
  628. }
  629. public function searchIdByGuid($id_feed, $guid) {
  630. $sql = 'SELECT id FROM `_entry` WHERE id_feed=:id_feed AND guid=:guid';
  631. $stm = $this->pdo->prepare($sql);
  632. $stm->bindParam(':id_feed', $id_feed, PDO::PARAM_INT);
  633. $stm->bindParam(':guid', $guid);
  634. $stm->execute();
  635. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  636. return isset($res[0]) ? $res[0] : null;
  637. }
  638. protected function sqlConcat($s1, $s2) {
  639. return 'CONCAT(' . $s1 . ',' . $s2 . ')'; //MySQL
  640. }
  641. protected function sqlListEntriesWhere($alias = '', $filters = null, $state = FreshRSS_Entry::STATE_ALL,
  642. $order = 'DESC', $firstId = '', $date_min = 0) {
  643. $search = ' ';
  644. $values = array();
  645. if ($state & FreshRSS_Entry::STATE_NOT_READ) {
  646. if (!($state & FreshRSS_Entry::STATE_READ)) {
  647. $search .= 'AND ' . $alias . 'is_read=0 ';
  648. }
  649. } elseif ($state & FreshRSS_Entry::STATE_READ) {
  650. $search .= 'AND ' . $alias . 'is_read=1 ';
  651. }
  652. if ($state & FreshRSS_Entry::STATE_FAVORITE) {
  653. if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) {
  654. $search .= 'AND ' . $alias . 'is_favorite=1 ';
  655. }
  656. } elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
  657. $search .= 'AND ' . $alias . 'is_favorite=0 ';
  658. }
  659. switch ($order) {
  660. case 'DESC':
  661. case 'ASC':
  662. break;
  663. default:
  664. throw new FreshRSS_EntriesGetter_Exception('Bad order in Entry->listByType: [' . $order . ']!');
  665. }
  666. if ($firstId !== '') {
  667. $search .= 'AND ' . $alias . 'id ' . ($order === 'DESC' ? '<=' : '>=') . ' ? ';
  668. $values[] = $firstId;
  669. }
  670. if ($date_min > 0) {
  671. $search .= 'AND ' . $alias . 'id >= ? ';
  672. $values[] = $date_min . '000000';
  673. }
  674. if ($filters && count($filters->searches()) > 0) {
  675. $isOpen = false;
  676. foreach ($filters->searches() as $filter) {
  677. if ($filter == null) {
  678. continue;
  679. }
  680. $sub_search = '';
  681. if ($filter->getEntryIds()) {
  682. foreach ($filter->getEntryIds() as $entry_ids) {
  683. $sub_search .= 'AND ' . $alias . 'id IN (';
  684. foreach ($entry_ids as $entry_id) {
  685. $sub_search .= '?,';
  686. $values[] = $entry_id;
  687. }
  688. $sub_search = rtrim($sub_search, ',');
  689. $sub_search .= ') ';
  690. }
  691. }
  692. if ($filter->getNotEntryIds()) {
  693. foreach ($filter->getNotEntryIds() as $entry_ids) {
  694. $sub_search .= 'AND ' . $alias . 'id NOT IN (';
  695. foreach ($entry_ids as $entry_id) {
  696. $sub_search .= '?,';
  697. $values[] = $entry_id;
  698. }
  699. $sub_search = rtrim($sub_search, ',');
  700. $sub_search .= ') ';
  701. }
  702. }
  703. if ($filter->getMinDate()) {
  704. $sub_search .= 'AND ' . $alias . 'id >= ? ';
  705. $values[] = "{$filter->getMinDate()}000000";
  706. }
  707. if ($filter->getMaxDate()) {
  708. $sub_search .= 'AND ' . $alias . 'id <= ? ';
  709. $values[] = "{$filter->getMaxDate()}000000";
  710. }
  711. if ($filter->getMinPubdate()) {
  712. $sub_search .= 'AND ' . $alias . 'date >= ? ';
  713. $values[] = $filter->getMinPubdate();
  714. }
  715. if ($filter->getMaxPubdate()) {
  716. $sub_search .= 'AND ' . $alias . 'date <= ? ';
  717. $values[] = $filter->getMaxPubdate();
  718. }
  719. //Negation of date intervals must be combined by OR
  720. if ($filter->getNotMinDate() || $filter->getNotMaxDate()) {
  721. $sub_search .= 'AND (';
  722. if ($filter->getNotMinDate()) {
  723. $sub_search .= $alias . 'id < ?';
  724. $values[] = "{$filter->getNotMinDate()}000000";
  725. if ($filter->getNotMaxDate()) {
  726. $sub_search .= ' OR ';
  727. }
  728. }
  729. if ($filter->getNotMaxDate()) {
  730. $sub_search .= $alias . 'id > ?';
  731. $values[] = "{$filter->getNotMaxDate()}000000";
  732. }
  733. $sub_search .= ') ';
  734. }
  735. if ($filter->getNotMinPubdate() || $filter->getNotMaxPubdate()) {
  736. $sub_search .= 'AND (';
  737. if ($filter->getNotMinPubdate()) {
  738. $sub_search .= $alias . 'date < ?';
  739. $values[] = $filter->getNotMinPubdate();
  740. if ($filter->getNotMaxPubdate()) {
  741. $sub_search .= ' OR ';
  742. }
  743. }
  744. if ($filter->getNotMaxPubdate()) {
  745. $sub_search .= $alias . 'date > ?';
  746. $values[] = $filter->getNotMaxPubdate();
  747. }
  748. $sub_search .= ') ';
  749. }
  750. if ($filter->getFeedIds()) {
  751. foreach ($filter->getFeedIds() as $feed_ids) {
  752. $sub_search .= 'AND ' . $alias . 'id_feed IN (';
  753. foreach ($feed_ids as $feed_id) {
  754. $sub_search .= '?,';
  755. $values[] = $feed_id;
  756. }
  757. $sub_search = rtrim($sub_search, ',');
  758. $sub_search .= ') ';
  759. }
  760. }
  761. if ($filter->getNotFeedIds()) {
  762. foreach ($filter->getNotFeedIds() as $feed_ids) {
  763. $sub_search .= 'AND ' . $alias . 'id_feed NOT IN (';
  764. foreach ($feed_ids as $feed_id) {
  765. $sub_search .= '?,';
  766. $values[] = $feed_id;
  767. }
  768. $sub_search = rtrim($sub_search, ',');
  769. $sub_search .= ') ';
  770. }
  771. }
  772. if ($filter->getLabelIds()) {
  773. foreach ($filter->getLabelIds() as $label_ids) {
  774. if ($label_ids === '*') {
  775. $sub_search .= 'AND EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  776. } else {
  777. $sub_search .= 'AND ' . $alias . 'id IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  778. foreach ($label_ids as $label_id) {
  779. $sub_search .= '?,';
  780. $values[] = $label_id;
  781. }
  782. $sub_search = rtrim($sub_search, ',');
  783. $sub_search .= ')) ';
  784. }
  785. }
  786. }
  787. if ($filter->getNotLabelIds()) {
  788. foreach ($filter->getNotLabelIds() as $label_ids) {
  789. if ($label_ids === '*') {
  790. $sub_search .= 'AND NOT EXISTS (SELECT et.id_tag FROM `_entrytag` et WHERE et.id_entry = ' . $alias . 'id) ';
  791. } else {
  792. $sub_search .= 'AND ' . $alias . 'id NOT IN (SELECT et.id_entry FROM `_entrytag` et WHERE et.id_tag IN (';
  793. foreach ($label_ids as $label_id) {
  794. $sub_search .= '?,';
  795. $values[] = $label_id;
  796. }
  797. $sub_search = rtrim($sub_search, ',');
  798. $sub_search .= ')) ';
  799. }
  800. }
  801. }
  802. if ($filter->getLabelNames()) {
  803. foreach ($filter->getLabelNames() as $label_names) {
  804. $sub_search .= 'AND ' . $alias . 'id IN (SELECT et.id_entry FROM `_entrytag` et, `_tag` t WHERE et.id_tag = t.id AND t.name IN (';
  805. foreach ($label_names as $label_name) {
  806. $sub_search .= '?,';
  807. $values[] = $label_name;
  808. }
  809. $sub_search = rtrim($sub_search, ',');
  810. $sub_search .= ')) ';
  811. }
  812. }
  813. if ($filter->getNotLabelNames()) {
  814. foreach ($filter->getNotLabelNames() as $label_names) {
  815. $sub_search .= 'AND ' . $alias . 'id NOT IN (SELECT et.id_entry FROM `_entrytag` et, `_tag` t WHERE et.id_tag = t.id AND t.name IN (';
  816. foreach ($label_names as $label_name) {
  817. $sub_search .= '?,';
  818. $values[] = $label_name;
  819. }
  820. $sub_search = rtrim($sub_search, ',');
  821. $sub_search .= ')) ';
  822. }
  823. }
  824. if ($filter->getAuthor()) {
  825. foreach ($filter->getAuthor() as $author) {
  826. $sub_search .= 'AND ' . $alias . 'author LIKE ? ';
  827. $values[] = "%{$author}%";
  828. }
  829. }
  830. if ($filter->getIntitle()) {
  831. foreach ($filter->getIntitle() as $title) {
  832. $sub_search .= 'AND ' . $alias . 'title LIKE ? ';
  833. $values[] = "%{$title}%";
  834. }
  835. }
  836. if ($filter->getTags()) {
  837. foreach ($filter->getTags() as $tag) {
  838. $sub_search .= 'AND ' . $alias . 'tags LIKE ? ';
  839. $values[] = "%{$tag}%";
  840. }
  841. }
  842. if ($filter->getInurl()) {
  843. foreach ($filter->getInurl() as $url) {
  844. $sub_search .= 'AND ' . $this->sqlConcat($alias . 'link', $alias . 'guid') . ' LIKE ? ';
  845. $values[] = "%{$url}%";
  846. }
  847. }
  848. if ($filter->getNotAuthor()) {
  849. foreach ($filter->getNotAuthor() as $author) {
  850. $sub_search .= 'AND (NOT ' . $alias . 'author LIKE ?) ';
  851. $values[] = "%{$author}%";
  852. }
  853. }
  854. if ($filter->getNotIntitle()) {
  855. foreach ($filter->getNotIntitle() as $title) {
  856. $sub_search .= 'AND (NOT ' . $alias . 'title LIKE ?) ';
  857. $values[] = "%{$title}%";
  858. }
  859. }
  860. if ($filter->getNotTags()) {
  861. foreach ($filter->getNotTags() as $tag) {
  862. $sub_search .= 'AND (NOT ' . $alias . 'tags LIKE ?) ';
  863. $values[] = "%{$tag}%";
  864. }
  865. }
  866. if ($filter->getNotInurl()) {
  867. foreach ($filter->getNotInurl() as $url) {
  868. $sub_search .= 'AND (NOT ' . $this->sqlConcat($alias . 'link', $alias . 'guid') . ' LIKE ?) ';
  869. $values[] = "%{$url}%";
  870. }
  871. }
  872. if ($filter->getSearch()) {
  873. foreach ($filter->getSearch() as $search_value) {
  874. $sub_search .= 'AND ' . $this->sqlConcat($alias . 'title',
  875. $this->isCompressed() ? 'UNCOMPRESS(' . $alias . 'content_bin)' : '' . $alias . 'content') . ' LIKE ? ';
  876. $values[] = "%{$search_value}%";
  877. }
  878. }
  879. if ($filter->getNotSearch()) {
  880. foreach ($filter->getNotSearch() as $search_value) {
  881. $sub_search .= 'AND (NOT ' . $this->sqlConcat($alias . 'title',
  882. $this->isCompressed() ? 'UNCOMPRESS(' . $alias . 'content_bin)' : '' . $alias . 'content') . ' LIKE ?) ';
  883. $values[] = "%{$search_value}%";
  884. }
  885. }
  886. if ($sub_search != '') {
  887. if ($isOpen) {
  888. $search .= 'OR ';
  889. } else {
  890. $search .= 'AND (';
  891. $isOpen = true;
  892. }
  893. $search .= '(' . substr($sub_search, 4) . ') ';
  894. }
  895. }
  896. if ($isOpen) {
  897. $search .= ') ';
  898. }
  899. }
  900. return array($values, $search);
  901. }
  902. private function sqlListWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL,
  903. $order = 'DESC', $limit = 1, $firstId = '', $filters = null, $date_min = 0) {
  904. if (!$state) {
  905. $state = FreshRSS_Entry::STATE_ALL;
  906. }
  907. $where = '';
  908. $joinFeed = false;
  909. $values = array();
  910. switch ($type) {
  911. case 'a': //All PRIORITY_MAIN_STREAM
  912. $where .= 'f.priority > ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  913. break;
  914. case 'A': //All except PRIORITY_ARCHIVED
  915. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  916. break;
  917. case 's': //Starred. Deprecated: use $state instead
  918. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  919. $where .= 'AND e.is_favorite=1 ';
  920. break;
  921. case 'S': //Starred
  922. $where .= 'e.is_favorite=1 ';
  923. break;
  924. case 'c': //Category
  925. $where .= 'f.priority >= ' . FreshRSS_Feed::PRIORITY_NORMAL . ' ';
  926. $where .= 'AND f.category=? ';
  927. $values[] = intval($id);
  928. break;
  929. case 'f': //Feed
  930. $where .= 'e.id_feed=? ';
  931. $values[] = intval($id);
  932. break;
  933. case 't': //Tag (label)
  934. $where .= 'et.id_tag=? ';
  935. $values[] = intval($id);
  936. break;
  937. case 'T': //Any tag (label)
  938. $where .= '1=1 ';
  939. break;
  940. case 'ST': //Starred or tagged (label)
  941. $where .= 'e.is_favorite=1 OR EXISTS (SELECT et2.id_tag FROM `_entrytag` et2 WHERE et2.id_entry = e.id) ';
  942. break;
  943. default:
  944. throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
  945. }
  946. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filters, $state, $order, $firstId, $date_min);
  947. return array(array_merge($values, $searchValues),
  948. 'SELECT '
  949. . ($type === 'T' ? 'DISTINCT ' : '')
  950. . 'e.id FROM `_entry` e '
  951. . 'INNER JOIN `_feed` f ON e.id_feed = f.id '
  952. . ($type === 't' || $type === 'T' ? 'INNER JOIN `_entrytag` et ON et.id_entry = e.id ' : '')
  953. . 'WHERE ' . $where
  954. . $search
  955. . 'ORDER BY e.id ' . $order
  956. . ($limit > 0 ? ' LIMIT ' . intval($limit) : '')); //TODO: See http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
  957. }
  958. public function listWhereRaw($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL,
  959. $order = 'DESC', $limit = 1, $firstId = '', $filters = null, $date_min = 0) {
  960. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filters, $date_min);
  961. $sql = 'SELECT e0.id, e0.guid, e0.title, e0.author, '
  962. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  963. . ', e0.link, e0.date, e0.is_read, e0.is_favorite, e0.id_feed, e0.tags '
  964. . 'FROM `_entry` e0 '
  965. . 'INNER JOIN ('
  966. . $sql
  967. . ') e2 ON e2.id=e0.id '
  968. . 'ORDER BY e0.id ' . $order;
  969. $stm = $this->pdo->prepare($sql);
  970. if ($stm && $stm->execute($values)) {
  971. return $stm;
  972. } else {
  973. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  974. Minz_Log::error('SQL error listWhereRaw: ' . $info[2]);
  975. return false;
  976. }
  977. }
  978. public function listWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL,
  979. $order = 'DESC', $limit = 1, $firstId = '', $filters = null, $date_min = 0) {
  980. $stm = $this->listWhereRaw($type, $id, $state, $order, $limit, $firstId, $filters, $date_min);
  981. if ($stm) {
  982. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  983. yield self::daoToEntry($row);
  984. }
  985. } else {
  986. yield false;
  987. }
  988. }
  989. public function listByIds($ids, $order = 'DESC') {
  990. if (count($ids) < 1) {
  991. yield false;
  992. } elseif (count($ids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  993. // Split a query with too many variables parameters
  994. $idsChunks = array_chunk($ids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  995. foreach ($idsChunks as $idsChunk) {
  996. foreach ($this->listByIds($idsChunk, $order) as $entry) {
  997. yield $entry;
  998. }
  999. }
  1000. return;
  1001. }
  1002. $sql = 'SELECT id, guid, title, author, '
  1003. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  1004. . ', link, date, is_read, is_favorite, id_feed, tags '
  1005. . 'FROM `_entry` '
  1006. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?) '
  1007. . 'ORDER BY id ' . $order;
  1008. $stm = $this->pdo->prepare($sql);
  1009. $stm->execute($ids);
  1010. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  1011. yield self::daoToEntry($row);
  1012. }
  1013. }
  1014. /**
  1015. * For API
  1016. */
  1017. public function listIdsWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL,
  1018. $order = 'DESC', $limit = 1, $firstId = '', $filters = null) {
  1019. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filters);
  1020. $stm = $this->pdo->prepare($sql);
  1021. $stm->execute($values);
  1022. return $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1023. }
  1024. public function listHashForFeedGuids($id_feed, $guids) {
  1025. $result = [];
  1026. if (count($guids) < 1) {
  1027. return $result;
  1028. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1029. // Split a query with too many variables parameters
  1030. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1031. foreach ($guidsChunks as $guidsChunk) {
  1032. $result += $this->listHashForFeedGuids($id_feed, $guidsChunk);
  1033. }
  1034. return $result;
  1035. }
  1036. $guids = array_unique($guids);
  1037. $sql = 'SELECT guid, ' . $this->sqlHexEncode('hash') .
  1038. ' AS hex_hash FROM `_entry` WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  1039. $stm = $this->pdo->prepare($sql);
  1040. $values = array($id_feed);
  1041. $values = array_merge($values, $guids);
  1042. if ($stm && $stm->execute($values)) {
  1043. $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
  1044. foreach ($rows as $row) {
  1045. $result[$row['guid']] = $row['hex_hash'];
  1046. }
  1047. return $result;
  1048. } else {
  1049. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1050. if ($this->autoUpdateDb($info)) {
  1051. return $this->listHashForFeedGuids($id_feed, $guids);
  1052. }
  1053. Minz_Log::error('SQL error listHashForFeedGuids: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  1054. . ' while querying feed ' . $id_feed);
  1055. return false;
  1056. }
  1057. }
  1058. public function updateLastSeen($id_feed, $guids, $mtime = 0) {
  1059. if (count($guids) < 1) {
  1060. return 0;
  1061. } elseif (count($guids) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  1062. // Split a query with too many variables parameters
  1063. $affected = 0;
  1064. $guidsChunks = array_chunk($guids, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  1065. foreach ($guidsChunks as $guidsChunk) {
  1066. $affected += $this->updateLastSeen($id_feed, $guidsChunk, $mtime);
  1067. }
  1068. return $affected;
  1069. }
  1070. $sql = 'UPDATE `_entry` SET `lastSeen`=? WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  1071. $stm = $this->pdo->prepare($sql);
  1072. if ($mtime <= 0) {
  1073. $mtime = time();
  1074. }
  1075. $values = array($mtime, $id_feed);
  1076. $values = array_merge($values, $guids);
  1077. if ($stm && $stm->execute($values)) {
  1078. return $stm->rowCount();
  1079. } else {
  1080. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  1081. if ($this->autoUpdateDb($info)) {
  1082. return $this->updateLastSeen($id_feed, $guids);
  1083. }
  1084. Minz_Log::error('SQL error updateLastSeen: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  1085. . ' while updating feed ' . $id_feed);
  1086. return false;
  1087. }
  1088. }
  1089. public function countUnreadRead() {
  1090. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e INNER JOIN `_feed` f ON e.id_feed=f.id WHERE f.priority > 0'
  1091. . ' 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';
  1092. $stm = $this->pdo->query($sql);
  1093. if ($stm === false) {
  1094. return false;
  1095. }
  1096. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1097. rsort($res);
  1098. $all = empty($res[0]) ? 0 : intval($res[0]);
  1099. $unread = empty($res[1]) ? 0 : intval($res[1]);
  1100. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  1101. }
  1102. public function count($minPriority = null) {
  1103. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1104. if ($minPriority !== null) {
  1105. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1106. $sql .= ' WHERE f.priority > ' . intval($minPriority);
  1107. }
  1108. $stm = $this->pdo->query($sql);
  1109. if ($stm == false) {
  1110. return false;
  1111. }
  1112. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1113. return isset($res[0]) ? intval($res[0]) : 0;
  1114. }
  1115. public function countNotRead($minPriority = null) {
  1116. $sql = 'SELECT COUNT(e.id) AS count FROM `_entry` e';
  1117. if ($minPriority !== null) {
  1118. $sql .= ' INNER JOIN `_feed` f ON e.id_feed=f.id';
  1119. }
  1120. $sql .= ' WHERE e.is_read=0';
  1121. if ($minPriority !== null) {
  1122. $sql .= ' AND f.priority > ' . intval($minPriority);
  1123. }
  1124. $stm = $this->pdo->query($sql);
  1125. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1126. return isset($res[0]) ? intval($res[0]) : 0;
  1127. }
  1128. public function countUnreadReadFavorites() {
  1129. $sql = <<<'SQL'
  1130. SELECT c FROM (
  1131. SELECT COUNT(e1.id) AS c, 1 AS o
  1132. FROM `_entry` AS e1
  1133. JOIN `_feed` AS f1 ON e1.id_feed = f1.id
  1134. WHERE e1.is_favorite = 1
  1135. AND f1.priority >= :priority_normal1
  1136. UNION
  1137. SELECT COUNT(e2.id) AS c, 2 AS o
  1138. FROM `_entry` AS e2
  1139. JOIN `_feed` AS f2 ON e2.id_feed = f2.id
  1140. WHERE e2.is_favorite = 1
  1141. AND e2.is_read = 0
  1142. AND f2.priority >= :priority_normal2
  1143. ) u
  1144. ORDER BY o
  1145. SQL;
  1146. $stm = $this->pdo->prepare($sql);
  1147. if (!$stm) {
  1148. Minz_Log::error('SQL error in ' . __method__ . ' ' . json_encode($this->pdo->errorInfo()));
  1149. return false;
  1150. }
  1151. //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
  1152. $stm->bindValue(':priority_normal1', FreshRSS_Feed::PRIORITY_NORMAL, PDO::PARAM_INT);
  1153. $stm->bindValue(':priority_normal2', FreshRSS_Feed::PRIORITY_NORMAL, PDO::PARAM_INT);
  1154. $stm->execute();
  1155. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  1156. rsort($res);
  1157. $all = empty($res[0]) ? 0 : intval($res[0]);
  1158. $unread = empty($res[1]) ? 0 : intval($res[1]);
  1159. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  1160. }
  1161. public static function daoToEntry($dao) {
  1162. $entry = new FreshRSS_Entry(
  1163. $dao['id_feed'],
  1164. $dao['guid'],
  1165. $dao['title'],
  1166. $dao['author'],
  1167. $dao['content'],
  1168. $dao['link'],
  1169. $dao['date'],
  1170. $dao['is_read'],
  1171. $dao['is_favorite'],
  1172. isset($dao['tags']) ? $dao['tags'] : ''
  1173. );
  1174. if (isset($dao['id'])) {
  1175. $entry->_id($dao['id']);
  1176. }
  1177. return $entry;
  1178. }
  1179. }