EntryDAO.php 56 KB

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