EntryDAO.php 47 KB

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