EntryDAO.php 68 KB

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