EntryDAO.php 77 KB

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