EntryDAO.php 46 KB

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