EntryDAO.php 47 KB

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