EntryDAO.php 44 KB

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