EntryDAO.php 47 KB

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