EntryDAO.php 47 KB

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