EntryDAO.php 47 KB

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