EntryDAO.php 62 KB

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