Entry.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_Entry extends Minz_Model {
  4. use FreshRSS_AttributesTrait;
  5. public const STATE_READ = 1;
  6. public const STATE_NOT_READ = 2;
  7. public const STATE_ALL = 3;
  8. public const STATE_FAVORITE = 4;
  9. public const STATE_NOT_FAVORITE = 8;
  10. public const STATE_ANDS = self::STATE_READ | self::STATE_NOT_READ | self::STATE_FAVORITE | self::STATE_NOT_FAVORITE;
  11. public const STATE_OR_NOT_READ = 32;
  12. public const STATE_OR_FAVORITE = 64;
  13. public const STATE_ORS = self::STATE_OR_NOT_READ | self::STATE_OR_FAVORITE;
  14. /** @var numeric-string */
  15. private string $id = '0';
  16. private string $guid;
  17. private string $title;
  18. /** @var array<string> */
  19. private array $authors;
  20. private string $content;
  21. private string $link;
  22. private int $date;
  23. private int $lastSeen = 0;
  24. private ?int $lastModified = null;
  25. private ?int $lastUserModified = null;
  26. /** In microseconds */
  27. private string $date_added = '0';
  28. private string $hash = '';
  29. private ?int $sqlContentLength = null;
  30. private ?bool $is_read;
  31. private ?bool $is_favorite;
  32. private bool $is_updated = false;
  33. private int $feedId;
  34. private ?FreshRSS_Feed $feed;
  35. /** @var array<string> */
  36. private array $tags = [];
  37. /**
  38. * @param string|array<string> $tags
  39. * @param int|numeric-string $pubdate
  40. */
  41. public function __construct(int $feedId = 0, string $guid = '', string $title = '', string $authors = '', string $content = '',
  42. string $link = '', int|string $pubdate = 0, bool|int|null $is_read = false, bool|int|null $is_favorite = false, $tags = '') {
  43. $this->_title($title);
  44. $this->_authors($authors);
  45. $this->_content($content);
  46. $this->_link($link);
  47. $this->_date($pubdate);
  48. $this->_isRead($is_read);
  49. $this->_isFavorite($is_favorite);
  50. $this->_feedId($feedId);
  51. $this->_tags($tags);
  52. $this->_guid($guid);
  53. }
  54. /** @param array{id?:string,guid?:string,title?:string,author?:string,content?:string,link?:string,
  55. * date?:int|string,lastSeen?:int,lastModified?:int,lastUserModified?:int,
  56. * hash?:string,is_read?:bool|int,is_favorite?:bool|int,id_feed?:int,
  57. * tags?:string|array<string>,attributes?:?string,
  58. * thumbnail?:string,timestamp?:string,
  59. * content_length?:int} $dao */
  60. public static function fromArray(array $dao): FreshRSS_Entry {
  61. if (empty($dao['content']) || !is_string($dao['content'])) {
  62. $dao['content'] = '';
  63. }
  64. if (!is_numeric($dao['date'] ?? null)) {
  65. $dao['date'] = 0;
  66. }
  67. $dao['attributes'] = empty($dao['attributes']) ? [] : json_decode($dao['attributes'], true);
  68. if (is_array($dao['attributes'])) {
  69. $dao['attributes'] = array_filter($dao['attributes'], 'is_string', ARRAY_FILTER_USE_KEY);
  70. } else {
  71. $dao['attributes'] = [];
  72. }
  73. if (!empty($dao['thumbnail'])) {
  74. $dao['attributes']['thumbnail'] = [
  75. 'url' => $dao['thumbnail'],
  76. ];
  77. }
  78. $entry = new FreshRSS_Entry(
  79. $dao['id_feed'] ?? 0,
  80. $dao['guid'] ?? '',
  81. $dao['title'] ?? '',
  82. $dao['author'] ?? '',
  83. $dao['content'],
  84. $dao['link'] ?? '',
  85. $dao['date'] ?? 0,
  86. $dao['is_read'] ?? false,
  87. $dao['is_favorite'] ?? false,
  88. $dao['tags'] ?? ''
  89. );
  90. if (!empty($dao['id']) && is_numeric($dao['id'])) {
  91. $entry->_id($dao['id']);
  92. }
  93. if (!empty($dao['timestamp'])) {
  94. $entry->_date(strtotime($dao['timestamp']) ?: 0);
  95. }
  96. if (empty($dao['lastSeen'])) {
  97. $entry->_lastSeen($entry->id() == '0' ?
  98. 0 :
  99. (int)substr($entry->id(), 0, -6)); // Microseconds to seconds
  100. } else {
  101. $entry->_lastSeen($dao['lastSeen']);
  102. }
  103. if (!empty($dao['lastModified'])) {
  104. $entry->_lastModified($dao['lastModified']);
  105. }
  106. if (!empty($dao['lastUserModified'])) {
  107. $entry->_lastUserModified($dao['lastUserModified']);
  108. }
  109. if (!empty($dao['attributes'])) {
  110. $entry->_attributes($dao['attributes']);
  111. }
  112. if (!empty($dao['hash'])) {
  113. $entry->_hash($dao['hash']);
  114. }
  115. if (isset($dao['content_length']) && is_numeric($dao['content_length'])) {
  116. $entry->_sqlContentLength((int)$dao['content_length']);
  117. }
  118. return $entry;
  119. }
  120. /**
  121. * @param Traversable<array{id?:string,guid?:string,title?:string,author?:string,content?:string,link?:string,
  122. * date?:int|string,lastSeen?:int,lastModified?:int,lastUserModified?:int,hash?:string,is_read?:bool|int,
  123. * is_favorite?:bool|int,id_feed?:int,tags?:string|array<string>,attributes?:?string,
  124. * thumbnail?:string,timestamp?:string}> $daos
  125. * @return Traversable<FreshRSS_Entry>
  126. */
  127. public static function fromTraversable(Traversable $daos): Traversable {
  128. foreach ($daos as $dao) {
  129. yield FreshRSS_Entry::fromArray($dao);
  130. }
  131. }
  132. /** @return numeric-string */
  133. public function id(): string {
  134. return $this->id;
  135. }
  136. public function guid(): string {
  137. return $this->guid;
  138. }
  139. public function title(): string {
  140. $title = '';
  141. if ($this->title === '') {
  142. // used while fetching the article from feed and store it in the database
  143. $title = $this->guid();
  144. } else {
  145. // used while fetching from the database
  146. if ($this->title !== $this->guid) {
  147. $title = $this->title;
  148. } else {
  149. $content = trim(strip_tags($this->content(false)));
  150. $title = trim(mb_substr($content, 0, MAX_CHARS_EMPTY_FEED_TITLE, 'UTF-8'));
  151. if ($title === '') {
  152. $title = $this->guid();
  153. } elseif (strlen($content) > strlen($title)) {
  154. $title .= '…';
  155. }
  156. }
  157. }
  158. return $title;
  159. }
  160. #[Deprecated('Use authors() instead')]
  161. public function author(): string {
  162. return $this->authors(true);
  163. }
  164. /**
  165. * @phpstan-return ($asString is true ? string : array<string>)
  166. * @return string|array<string>
  167. */
  168. public function authors(bool $asString = false): string|array {
  169. if ($asString) {
  170. return $this->authors == null ? '' : ';' . implode('; ', $this->authors);
  171. } else {
  172. return $this->authors;
  173. }
  174. }
  175. /**
  176. * Basic test without ambition to catch all cases such as unquoted addresses, variants of entities, HTML comments, etc.
  177. */
  178. private static function containsLink(string $html, string $link): bool {
  179. return preg_match('/(?P<delim>[\'"])' . preg_quote($link, '/') . '(?P=delim)/', $html) == 1;
  180. }
  181. /** @param array{url?:string,length?:int,medium?:string,type?:string} $enclosure */
  182. private static function enclosureIsImage(array $enclosure): bool {
  183. $elink = $enclosure['url'] ?? '';
  184. $length = $enclosure['length'] ?? 0;
  185. $medium = $enclosure['medium'] ?? '';
  186. $mime = $enclosure['type'] ?? '';
  187. return ($elink != '' && $medium === 'image') || str_starts_with($mime, 'image') ||
  188. ($mime == '' && $length == 0 && preg_match('/[.](avif|gif|jpe?g|png|svg|webp)([?#]|$)/i', $elink));
  189. }
  190. /**
  191. * Provides the original content without additional content potentially added by loadCompleteContent().
  192. * In the style of MIME multipart boundaries, stored in the `full_content_delimiter` attribute.
  193. */
  194. public function originalContent(): string {
  195. $originalContent = $this->attributeString('original_content');
  196. if ($originalContent !== null) {
  197. return $originalContent;
  198. }
  199. $html = $this->content;
  200. if (!str_contains($html, '<!-- FULLCONTENT ')) {
  201. return $html;
  202. }
  203. $delimiter = $this->attributeString('full_content_delimiter');
  204. if ($delimiter === null || $delimiter === '') {
  205. // Legacy unsafe markers
  206. $startMarker = '<!-- FULLCONTENT start //-->';
  207. $endMarker = '<!-- FULLCONTENT end //-->';
  208. } else {
  209. $startMarker = "<!-- FULLCONTENT {$delimiter} start //-->";
  210. $endMarker = "<!-- FULLCONTENT {$delimiter} end //-->";
  211. }
  212. $startPos = strpos($html, $startMarker);
  213. if ($startPos === false) {
  214. return $html; // Could not find the start boundary, so return the HTML as-is
  215. }
  216. $endPos = strpos($html, $endMarker, $startPos + strlen($startMarker));
  217. if ($endPos === false) {
  218. return $html; // Could not find the end boundary, so return the HTML as-is
  219. }
  220. return substr($html, 0, $startPos) . substr($html, $endPos + strlen($endMarker));
  221. }
  222. /**
  223. * @param bool $withEnclosures Set to true to include the enclosures in the returned HTML, false otherwise.
  224. * @param bool $allowDuplicateEnclosures Set to false to remove obvious enclosure duplicates (based on simple string comparison), true otherwise.
  225. * @return string HTML content
  226. */
  227. public function content(bool $withEnclosures = true, bool $allowDuplicateEnclosures = false): string {
  228. if (!$withEnclosures) {
  229. return $this->content;
  230. }
  231. $content = $this->content;
  232. $thumbnailAttribute = $this->attributeArray('thumbnail') ?? [];
  233. if (!empty($thumbnailAttribute['url'])) {
  234. $elink = $thumbnailAttribute['url'];
  235. if (is_string($elink) && \SimplePie\Misc::is_remote_uri($elink) &&
  236. ($allowDuplicateEnclosures || !self::containsLink($content, $elink))) {
  237. $content .= <<<HTML
  238. <figure class="enclosure">
  239. <p class="enclosure-content">
  240. <img class="enclosure-thumbnail" src="{$elink}" alt="" />
  241. </p>
  242. </figure>
  243. HTML;
  244. }
  245. }
  246. $attributeEnclosures = $this->attributeArray('enclosures');
  247. if (empty($attributeEnclosures)) {
  248. return $content;
  249. }
  250. foreach ($attributeEnclosures as $enclosure) {
  251. if (!is_array($enclosure)) {
  252. continue;
  253. }
  254. $elink = $enclosure['url'] ?? '';
  255. if ($elink == '' || !is_string($elink) || !\SimplePie\Misc::is_remote_uri($elink)) {
  256. continue;
  257. }
  258. if (!$allowDuplicateEnclosures && self::containsLink($content, $elink)) {
  259. continue;
  260. }
  261. $credits = $enclosure['credit'] ?? '';
  262. $description = is_string($enclosure['description'] ?? null) ? nl2br($enclosure['description'], true) : '';
  263. $length = is_numeric($enclosure['length'] ?? null) ? (int)$enclosure['length'] : 0;
  264. $medium = is_string($enclosure['medium'] ?? null) ? $enclosure['medium'] : '';
  265. $mime = is_string($enclosure['type'] ?? null) ? $enclosure['type'] : '';
  266. $thumbnails = $enclosure['thumbnails'] ?? null;
  267. if (!is_array($thumbnails)) {
  268. $thumbnails = [];
  269. }
  270. $etitle = is_string($enclosure['title'] ?? null) ? $enclosure['title'] : '';
  271. $content .= "\n";
  272. $content .= '<figure class="enclosure">';
  273. foreach ($thumbnails as $thumbnail) {
  274. if (is_string($thumbnail) && \SimplePie\Misc::is_remote_uri($thumbnail)) {
  275. // No title here: it is output once with the enclosure itself below, not once more for each thumbnail
  276. $content .= '<p><img class="enclosure-thumbnail" src="' . $thumbnail . '" alt="" /></p>';
  277. }
  278. }
  279. if (self::enclosureIsImage(['url' => $elink, 'length' => $length, 'medium' => $medium, 'type' => $mime])) {
  280. $content .= '<p class="enclosure-content"><img src="' . $elink . '" alt="" title="' . $etitle . '" /></p>';
  281. } elseif ($medium === 'audio' || str_starts_with($mime, 'audio')) {
  282. $content .= '<p class="enclosure-content"><audio preload="none" src="' . $elink
  283. . ($length == null ? '' : '" data-length="' . $length)
  284. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  285. . '" controls="controls" title="' . $etitle . '"></audio> <a download="" href="' . $elink . '">💾</a></p>';
  286. } elseif ($medium === 'video' || str_starts_with($mime, 'video')) {
  287. $content .= '<p class="enclosure-content"><video preload="none" src="' . $elink
  288. . ($length == null ? '' : '" data-length="' . $length)
  289. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  290. . '" controls="controls" title="' . $etitle . '"></video> <a download="" href="' . $elink . '">💾</a></p>';
  291. } else { //e.g. application, text, unknown
  292. $content .= '<p class="enclosure-content"><a download="" href="' . $elink
  293. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  294. . ($medium == '' ? '' : '" data-medium="' . htmlspecialchars($medium, ENT_COMPAT, 'UTF-8'))
  295. . '" title="' . $etitle . '">💾</a></p>';
  296. }
  297. if ($credits != '') {
  298. if (!is_array($credits)) {
  299. $credits = [$credits];
  300. }
  301. foreach ($credits as $credit) {
  302. if (is_string($credit)) {
  303. $content .= '<p class="enclosure-credits">© ' . $credit . '</p>';
  304. }
  305. }
  306. }
  307. if ($description != '') {
  308. $content .= '<figcaption class="enclosure-description">' . $description . '</figcaption>';
  309. }
  310. $content .= "</figure>\n";
  311. }
  312. return $content;
  313. }
  314. /** @return Traversable<array{'url':string,'type'?:string,'medium'?:string,'length'?:int,'title'?:string,'description'?:string,'credit'?:string|array<string>,'height'?:int,'width'?:int,'thumbnails'?:array<string>}> */
  315. public function enclosures(bool $searchBodyImages = false): Traversable {
  316. $attributeEnclosures = $this->attributeArray('enclosures');
  317. if (is_array($attributeEnclosures)) {
  318. // FreshRSS 1.20.1+: The enclosures are saved as attributes
  319. /** @var list<array{'url':string,'type'?:string,'medium'?:string,'length'?:int,'title'?:string,'description'?:string,'credit'?:string|array<string>,'height'?:int,'width'?:int,'thumbnails'?:array<string>}> $attributeEnclosures */
  320. yield from $attributeEnclosures;
  321. }
  322. try {
  323. $searchEnclosures = !is_iterable($attributeEnclosures) && (str_contains($this->content, '<p class="enclosure-content'));
  324. $searchBodyImages &= (stripos($this->content, '<img') !== false);
  325. $doc = null;
  326. if ($searchEnclosures || $searchBodyImages) {
  327. $doc = Dom\HTMLDocument::createFromString($this->content, LIBXML_NOERROR | Dom\HTML_NO_DEFAULT_NS);
  328. }
  329. if ($searchEnclosures && $doc !== null) {
  330. // Legacy code for database entries < FreshRSS 1.20.1
  331. $enclosures = $doc->querySelectorAll('div.enclosure > p.enclosure-content > [src]');
  332. if ($enclosures->length > 0) {
  333. foreach ($enclosures as $enclosure) {
  334. if (!($enclosure instanceof Dom\Element)) {
  335. continue;
  336. }
  337. $result = [
  338. 'url' => $enclosure->getAttribute('src') ?? '',
  339. 'type' => $enclosure->getAttribute('data-type') ?? '',
  340. 'medium' => $enclosure->getAttribute('data-medium') ?? '',
  341. 'length' => (int)($enclosure->getAttribute('data-length') ?? ''),
  342. ];
  343. if (empty($result['medium'])) {
  344. switch (strtolower($enclosure->nodeName)) {
  345. case 'img': $result['medium'] = 'image'; break;
  346. case 'video': $result['medium'] = 'video'; break;
  347. case 'audio': $result['medium'] = 'audio'; break;
  348. }
  349. }
  350. yield Minz_Helper::htmlspecialchars_utf8($result);
  351. }
  352. }
  353. }
  354. if ($searchBodyImages && $doc !== null) {
  355. $images = $doc->querySelectorAll('img');
  356. if ($images->length > 0) {
  357. foreach ($images as $img) {
  358. if (!($img instanceof Dom\Element)) {
  359. continue;
  360. }
  361. $src = $img->getAttribute('src') ?? '';
  362. if ($src === '') {
  363. $src = $img->getAttribute('data-src') ?? '';
  364. }
  365. if ($src !== '') {
  366. $result = [
  367. 'url' => $src,
  368. 'medium' => 'image',
  369. ];
  370. yield Minz_Helper::htmlspecialchars_utf8($result);
  371. }
  372. }
  373. }
  374. }
  375. } catch (Exception $ex) {
  376. Minz_Log::debug(__METHOD__ . ' ' . $ex->getMessage());
  377. }
  378. }
  379. /**
  380. * @return array{'url':string,'height'?:int,'width'?:int,'time'?:string}|null
  381. */
  382. public function thumbnail(bool $searchEnclosures = true): ?array {
  383. $thumbnail = $this->attributeArray('thumbnail') ?? [];
  384. // First, use the provided thumbnail, if any
  385. if (is_string($thumbnail['url'] ?? null)) {
  386. /** @var array{'url':string,'height'?:int,'width'?:int,'time'?:string} $thumbnail */
  387. return $thumbnail;
  388. }
  389. if ($searchEnclosures) {
  390. foreach ($this->enclosures(true) as $enclosure) {
  391. // Second, search each enclosure’s thumbnails
  392. if (!empty($enclosure['thumbnails'][0])) {
  393. foreach ($enclosure['thumbnails'] as $src) {
  394. if (is_string($src)) {
  395. return [
  396. 'url' => $src,
  397. 'medium' => 'image',
  398. ];
  399. }
  400. }
  401. }
  402. // Third, check whether each enclosure itself is an appropriate image
  403. if (self::enclosureIsImage($enclosure)) {
  404. return $enclosure;
  405. }
  406. }
  407. }
  408. return null;
  409. }
  410. /**
  411. * @param bool $raw Set to true to return the raw link,
  412. * false (default) to attempt a fallback to the GUID if the link is empty.
  413. * @return string HTML-encoded link of the entry
  414. */
  415. public function link(bool $raw = false): string {
  416. if ($this->link === '' && !$raw) {
  417. // Use the GUID as a fallback if it looks like a URL
  418. if (filter_var($this->guid, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE) !== null) {
  419. return $this->guid;
  420. }
  421. }
  422. return $this->link;
  423. }
  424. /**
  425. * @phpstan-return ($raw is false ? string : int)
  426. */
  427. public function date(bool $raw = false): int|string {
  428. if ($raw) {
  429. return $this->date;
  430. }
  431. return timestamptodate($this->date);
  432. }
  433. public function machineReadableDate(): string {
  434. return @date(DATE_ATOM, $this->date);
  435. }
  436. public function lastSeen(): int {
  437. return $this->lastSeen;
  438. }
  439. public function lastModified(): ?int {
  440. return $this->lastModified;
  441. }
  442. public function lastUserModified(): ?int {
  443. return $this->lastUserModified;
  444. }
  445. /**
  446. * @phpstan-return ($raw is false ? string : ($microsecond is true ? string : int))
  447. */
  448. public function dateAdded(bool $raw = false, bool $microsecond = false): int|string {
  449. if ($raw) {
  450. if ($microsecond) {
  451. return $this->date_added;
  452. } else {
  453. return (int)substr($this->date_added, 0, -6);
  454. }
  455. } else {
  456. $date = (int)substr($this->date_added, 0, -6);
  457. return timestamptodate($date);
  458. }
  459. }
  460. public function isRead(): ?bool {
  461. return $this->is_read;
  462. }
  463. public function isFavorite(): ?bool {
  464. return $this->is_favorite;
  465. }
  466. /**
  467. * Returns whether the entry has been modified since it was inserted in database.
  468. * @returns bool `true` if the entry already existed (and has been modified), `false` if the entry is new (or unmodified).
  469. */
  470. public function isUpdated(): ?bool {
  471. return $this->is_updated;
  472. }
  473. public function _isUpdated(bool $value): void {
  474. $this->is_updated = $value;
  475. }
  476. public function feed(): ?FreshRSS_Feed {
  477. if ($this->feed === null) {
  478. $feedDAO = FreshRSS_Factory::createFeedDao();
  479. $this->feed = $feedDAO->searchById($this->feedId);
  480. }
  481. return $this->feed;
  482. }
  483. public function feedId(): int {
  484. return $this->feedId;
  485. }
  486. /**
  487. * @phpstan-return ($asString is true ? string : array<string>)
  488. * @return string|array<string>
  489. */
  490. public function tags(bool $asString = false): array|string {
  491. if ($asString) {
  492. return $this->tags == null ? '' : '#' . implode(' #', $this->tags);
  493. } else {
  494. return $this->tags;
  495. }
  496. }
  497. public function hash(): string {
  498. if ($this->hash === '') {
  499. $attributes = empty($this->attributeArray('enclosures')) ? '' : json_encode($this->attributes(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  500. //Do not include $this->date because it may be automatically generated when lacking
  501. $this->hash = md5($this->link . $this->title . $this->authors(true) . $this->originalContent() . $this->tags(true) . $attributes);
  502. }
  503. return $this->hash;
  504. }
  505. public function sqlContentLength(): ?int {
  506. return $this->sqlContentLength;
  507. }
  508. public function _hash(string $value): string {
  509. $value = trim($value);
  510. if (ctype_xdigit($value)) {
  511. $this->hash = substr($value, 0, 32);
  512. }
  513. return $this->hash;
  514. }
  515. public function _sqlContentLength(int $value): void {
  516. $this->sqlContentLength = $value > 0 ? $value : null;
  517. }
  518. /** @param int|numeric-string $value String is for compatibility with 32-bit platforms */
  519. public function _id(int|string $value): void {
  520. if (is_int($value)) {
  521. $value = (string)$value;
  522. }
  523. $this->id = $value;
  524. if ($this->date_added == 0) {
  525. $this->date_added = $value;
  526. }
  527. }
  528. public function _guid(string $value): void {
  529. $this->guid = trim($value);
  530. }
  531. public function _title(string $value): void {
  532. $this->hash = '';
  533. $this->title = trim($value);
  534. }
  535. #[Deprecated('Use _authors() instead')]
  536. public function _author(string $value): void {
  537. $this->_authors($value);
  538. }
  539. /** @param array<string>|string $value */
  540. public function _authors(array|string $value): void {
  541. $this->hash = '';
  542. if (!is_array($value)) {
  543. if (str_contains($value, ';')) {
  544. $value = htmlspecialchars_decode($value, ENT_QUOTES);
  545. $value = preg_split('/\s*[;]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  546. $value = Minz_Helper::htmlspecialchars_utf8($value);
  547. } else {
  548. $value = preg_split('/\s*[,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  549. }
  550. }
  551. $this->authors = $value;
  552. }
  553. public function _content(string $value): void {
  554. $this->hash = '';
  555. $this->content = $value;
  556. }
  557. public function _link(string $value): void {
  558. $this->hash = '';
  559. $this->link = trim($value);
  560. }
  561. /** @param int|numeric-string $value */
  562. public function _date(int|string $value): void {
  563. $value = (int)$value;
  564. $this->date = $value > 1 ? $value : time();
  565. }
  566. /**
  567. * @param int|numeric-string $value
  568. * 32-bit systems provide a string and will fail in year 2038
  569. */
  570. public function _lastSeen(int|string $value): void {
  571. $value = (int)$value;
  572. $this->lastSeen = $value > 0 ? $value : 0;
  573. }
  574. public function _lastModified(int|string $value): void {
  575. $value = (int)$value;
  576. $this->lastModified = $value > 0 ? $value : null;
  577. }
  578. public function _lastUserModified(int|string $value): void {
  579. $value = (int)$value;
  580. $this->lastUserModified = $value > 0 ? $value : null;
  581. }
  582. /** @param int|numeric-string $value */
  583. public function _dateAdded(int|string $value, bool $microsecond = false): void {
  584. if ($microsecond) {
  585. $this->date_added = (string)($value);
  586. } else {
  587. $this->date_added = $value . '000000';
  588. }
  589. }
  590. public function _isRead(bool|int|null $value): void {
  591. $this->is_read = $value === null ? null : (bool)$value;
  592. }
  593. public function _isFavorite(bool|int|null $value): void {
  594. $this->is_favorite = $value === null ? null : (bool)$value;
  595. }
  596. public function _feed(?FreshRSS_Feed $feed): void {
  597. $this->feed = $feed;
  598. $this->feedId = $this->feed == null ? 0 : $this->feed->id();
  599. }
  600. private function _feedId(int $id): void {
  601. $this->feed = null;
  602. $this->feedId = $id;
  603. }
  604. /** @param array<string>|string $value */
  605. public function _tags(array|string $value): void {
  606. $this->hash = '';
  607. if (!is_array($value)) {
  608. $value = preg_split('/\s*[#,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  609. }
  610. $this->tags = $value;
  611. }
  612. public function matches(FreshRSS_BooleanSearch $booleanSearch): bool {
  613. static $databaseDao = null;
  614. if (!($databaseDao instanceof FreshRSS_DatabaseDAO)) {
  615. $databaseDao = FreshRSS_Factory::createDatabaseDAO();
  616. }
  617. $ok = true;
  618. foreach ($booleanSearch->searches() as $filter) {
  619. if ($filter instanceof FreshRSS_BooleanSearch) {
  620. // BooleanSearches are combined by AND (default) or OR or AND NOT (special cases) operators and are recursive
  621. match ($filter->operator()) {
  622. 'AND' => $ok &= $this->matches($filter),
  623. 'OR' => $ok |= $this->matches($filter),
  624. 'AND NOT' => $ok &= !$this->matches($filter),
  625. 'OR NOT' => $ok |= !$this->matches($filter),
  626. default => $ok &= $this->matches($filter),
  627. };
  628. } elseif ($filter instanceof FreshRSS_Search) {
  629. // Searches are combined by OR and are not recursive
  630. $ok = true;
  631. if ($filter->getEntryIds() !== null) {
  632. $ok &= in_array($this->id, $filter->getEntryIds(), true);
  633. }
  634. if ($ok && $filter->getNotEntryIds() !== null) {
  635. $ok &= !in_array($this->id, $filter->getNotEntryIds(), true);
  636. }
  637. if ($ok && $filter->getMinDate() !== null) {
  638. $ok &= strnatcmp($this->id, $filter->getMinDate() . '000000') >= 0;
  639. }
  640. if ($ok && $filter->getNotMinDate() !== null) {
  641. $ok &= strnatcmp($this->id, $filter->getNotMinDate() . '000000') < 0;
  642. }
  643. if ($ok && $filter->getMaxDate() !== null) {
  644. $ok &= strnatcmp($this->id, $filter->getMaxDate() . '000000') <= 0;
  645. }
  646. if ($ok && $filter->getNotMaxDate() !== null) {
  647. $ok &= strnatcmp($this->id, $filter->getNotMaxDate() . '000000') > 0;
  648. }
  649. if ($ok && $filter->getMinPubdate() !== null) {
  650. $ok &= $this->date >= $filter->getMinPubdate();
  651. }
  652. if ($ok && $filter->getNotMinPubdate() !== null) {
  653. $ok &= $this->date < $filter->getNotMinPubdate();
  654. }
  655. if ($ok && $filter->getMaxPubdate() !== null) {
  656. $ok &= $this->date <= $filter->getMaxPubdate();
  657. }
  658. if ($ok && $filter->getNotMaxPubdate() !== null) {
  659. $ok &= $this->date > $filter->getNotMaxPubdate();
  660. }
  661. if ($ok && $filter->getMinModifiedDate() !== null) {
  662. $ok &= ($this->lastModified ?? 0) >= $filter->getMinModifiedDate();
  663. }
  664. if ($ok && $filter->getNotMinModifiedDate() !== null) {
  665. $ok &= ($this->lastModified ?? 0) < $filter->getNotMinModifiedDate();
  666. }
  667. if ($ok && $filter->getMaxModifiedDate() !== null) {
  668. $ok &= ($this->lastModified ?? 0) <= $filter->getMaxModifiedDate();
  669. }
  670. if ($ok && $filter->getNotMaxModifiedDate() !== null) {
  671. $ok &= ($this->lastModified ?? 0) > $filter->getNotMaxModifiedDate();
  672. }
  673. if ($ok && $filter->getMinUserdate() !== null) {
  674. $ok &= ($this->lastUserModified ?? 0) >= $filter->getMinUserdate();
  675. }
  676. if ($ok && $filter->getNotMinUserdate() !== null) {
  677. $ok &= ($this->lastUserModified ?? 0) < $filter->getNotMinUserdate();
  678. }
  679. if ($ok && $filter->getMaxUserdate() !== null) {
  680. $ok &= ($this->lastUserModified ?? 0) <= $filter->getMaxUserdate();
  681. }
  682. if ($ok && $filter->getNotMaxUserdate() !== null) {
  683. $ok &= ($this->lastUserModified ?? 0) > $filter->getNotMaxUserdate();
  684. }
  685. if ($ok && $filter->getFeedIds() !== null) {
  686. $ok &= in_array($this->feedId, $filter->getFeedIds(), true);
  687. }
  688. if ($ok && $filter->getNotFeedIds() !== null) {
  689. $ok &= !in_array($this->feedId, $filter->getNotFeedIds(), true);
  690. }
  691. if ($ok && $filter->getCategoryIds() !== null) {
  692. $ok &= in_array($this->feed()?->categoryId(), $filter->getCategoryIds(), true);
  693. }
  694. if ($ok && $filter->getNotCategoryIds() !== null) {
  695. $ok &= !in_array($this->feed()?->categoryId(), $filter->getNotCategoryIds(), true);
  696. }
  697. if ($ok && $filter->getAuthor() !== null) {
  698. foreach ($filter->getAuthor() as $author) {
  699. $ok &= $databaseDao::strilike(implode(';', $this->authors), $author, contains: true);
  700. }
  701. }
  702. if ($ok && $filter->getAuthorRegex() !== null) {
  703. foreach ($filter->getAuthorRegex() as $author) {
  704. $ok &= $this->regexMatch($author, implode("\n", $this->authors), $booleanSearch) === 1;
  705. }
  706. }
  707. if ($ok && $filter->getNotAuthor() !== null) {
  708. foreach ($filter->getNotAuthor() as $author) {
  709. $ok &= !$databaseDao::strilike(implode(';', $this->authors), $author, contains: true);
  710. }
  711. }
  712. if ($ok && $filter->getNotAuthorRegex() !== null) {
  713. foreach ($filter->getNotAuthorRegex() as $author) {
  714. $ok &= $this->regexMatch($author, implode("\n", $this->authors), $booleanSearch) === 0;
  715. }
  716. }
  717. if ($ok && $filter->getIntitle() !== null) {
  718. foreach ($filter->getIntitle() as $title) {
  719. $ok &= $databaseDao::strilike($this->title, $title, contains: true);
  720. }
  721. }
  722. if ($ok && $filter->getIntitleRegex() !== null) {
  723. foreach ($filter->getIntitleRegex() as $title) {
  724. $ok &= $this->regexMatch($title, $this->title, $booleanSearch) === 1;
  725. }
  726. }
  727. if ($ok && $filter->getNotIntitle() !== null) {
  728. foreach ($filter->getNotIntitle() as $title) {
  729. $ok &= !$databaseDao::strilike($this->title, $title, contains: true);
  730. }
  731. }
  732. if ($ok && $filter->getNotIntitleRegex() !== null) {
  733. foreach ($filter->getNotIntitleRegex() as $title) {
  734. $ok &= $this->regexMatch($title, $this->title, $booleanSearch) === 0;
  735. }
  736. }
  737. if ($ok && $filter->getIntext() !== null) {
  738. foreach ($filter->getIntext() as $content) {
  739. $ok &= $databaseDao::strilike($this->content, $content, contains: true);
  740. }
  741. }
  742. if ($ok && $filter->getIntextRegex() !== null) {
  743. foreach ($filter->getIntextRegex() as $content) {
  744. $ok &= $this->regexMatch($content, $this->content, $booleanSearch) === 1;
  745. }
  746. }
  747. if ($ok && $filter->getNotIntext() !== null) {
  748. foreach ($filter->getNotIntext() as $content) {
  749. $ok &= !$databaseDao::strilike($this->content, $content, contains: true);
  750. }
  751. }
  752. if ($ok && $filter->getNotIntextRegex() !== null) {
  753. foreach ($filter->getNotIntextRegex() as $content) {
  754. $ok &= $this->regexMatch($content, $this->content, $booleanSearch) === 0;
  755. }
  756. }
  757. if ($ok && $filter->getTags() !== null) {
  758. foreach ($filter->getTags() as $tag2) {
  759. $found = false;
  760. foreach ($this->tags as $tag1) {
  761. $tag1 = ltrim($tag1, '#');
  762. if ($databaseDao::strilike($tag1, $tag2, contains: false)) {
  763. $found = true;
  764. break;
  765. }
  766. }
  767. $ok &= $found;
  768. }
  769. }
  770. if ($ok && $filter->getTagsRegex() !== null) {
  771. foreach ($filter->getTagsRegex() as $tag2) {
  772. $found = false;
  773. foreach ($this->tags as $tag1) {
  774. $tag1 = ltrim($tag1, '#');
  775. if ($this->regexMatch($tag2, $tag1, $booleanSearch) === 1) {
  776. $found = true;
  777. break;
  778. }
  779. }
  780. $ok &= $found;
  781. }
  782. }
  783. if ($ok && $filter->getNotTags() !== null) {
  784. foreach ($filter->getNotTags() as $tag2) {
  785. $found = false;
  786. foreach ($this->tags as $tag1) {
  787. $tag1 = ltrim($tag1, '#');
  788. if ($databaseDao::strilike($tag1, $tag2, contains: false)) {
  789. $found = true;
  790. break;
  791. }
  792. }
  793. $ok &= !$found;
  794. }
  795. }
  796. if ($ok && $filter->getNotTagsRegex() !== null) {
  797. foreach ($filter->getNotTagsRegex() as $tag2) {
  798. $found = false;
  799. foreach ($this->tags as $tag1) {
  800. $tag1 = ltrim($tag1, '#');
  801. if ($this->regexMatch($tag2, $tag1, $booleanSearch) === 1) {
  802. $found = true;
  803. break;
  804. }
  805. }
  806. $ok &= !$found;
  807. }
  808. }
  809. if ($ok && $filter->getInurl() !== null) {
  810. foreach ($filter->getInurl() as $url) {
  811. $ok &= stripos($this->link, $url) !== false;
  812. }
  813. }
  814. if ($ok && $filter->getInurlRegex() !== null) {
  815. foreach ($filter->getInurlRegex() as $url) {
  816. $ok &= $this->regexMatch($url, $this->link, $booleanSearch) === 1;
  817. }
  818. }
  819. if ($ok && $filter->getNotInurl() !== null) {
  820. foreach ($filter->getNotInurl() as $url) {
  821. $ok &= stripos($this->link, $url) === false;
  822. }
  823. }
  824. if ($ok && $filter->getNotInurlRegex() !== null) {
  825. foreach ($filter->getNotInurlRegex() as $url) {
  826. $ok &= $this->regexMatch($url, $this->link, $booleanSearch) === 0;
  827. }
  828. }
  829. if ($ok && $filter->getSearch() !== null) {
  830. foreach ($filter->getSearch() as $needle) {
  831. $ok &= ($databaseDao::strilike($this->title, $needle, contains: true) || $databaseDao::strilike($this->content, $needle, contains: true));
  832. }
  833. }
  834. if ($ok && $filter->getNotSearch() !== null) {
  835. foreach ($filter->getNotSearch() as $needle) {
  836. $ok &= (!$databaseDao::strilike($this->title, $needle, contains: true) && !$databaseDao::strilike($this->content, $needle, contains: true));
  837. }
  838. }
  839. if ($ok && $filter->getSearchRegex() !== null) {
  840. foreach ($filter->getSearchRegex() as $needle) {
  841. $ok &= ($this->regexMatch($needle, $this->title, $booleanSearch) === 1 || $this->regexMatch($needle, $this->content, $booleanSearch) === 1);
  842. }
  843. }
  844. if ($ok && $filter->getNotSearchRegex() !== null) {
  845. foreach ($filter->getNotSearchRegex() as $needle) {
  846. $ok &= ($this->regexMatch($needle, $this->title, $booleanSearch) === 0 && $this->regexMatch($needle, $this->content, $booleanSearch) === 0);
  847. }
  848. }
  849. if ($ok) {
  850. return true;
  851. }
  852. }
  853. }
  854. return (bool)$ok;
  855. }
  856. /**
  857. * Handle `preg_match()` errors with better logging
  858. * @return int|false Same return values as preg_match()
  859. */
  860. private function regexMatch(string $pattern, string $subject, FreshRSS_BooleanSearch $booleanSearch): int|false {
  861. /** @var array<string,bool> */
  862. static $loggedRegexes = [];
  863. $result = @preg_match($pattern, $subject);
  864. if ($result === false && preg_last_error() === PREG_INTERNAL_ERROR) {
  865. if (!isset($loggedRegexes[$pattern])) {
  866. $loggedRegexes[$pattern] = true; // Log only once per run
  867. Minz_Log::warning(__METHOD__ . ' Invalid PCRE regex `' . $pattern . '`; ' .
  868. (error_get_last()['message'] ?? preg_last_error_msg()) .
  869. '; in search: `' . $booleanSearch . '`' .
  870. '; first triggered by entry ' . $this->id() . ' of feed ' . $this->feedId());
  871. }
  872. }
  873. return $result;
  874. }
  875. /**
  876. * @param array<string,bool|int> $titlesAsRead
  877. * @param array<string,bool|int> $guidsAsRead
  878. */
  879. public function applyFilterActions(array $titlesAsRead = [], array $guidsAsRead = []): void {
  880. $feed = $this->feed;
  881. if ($feed === null) {
  882. return;
  883. }
  884. if (!$this->isRead()) {
  885. if ($feed->attributeBoolean('read_upon_reception') ?? FreshRSS_Context::userConf()->mark_when['reception']) {
  886. $this->_isRead(true);
  887. Minz_ExtensionManager::callHook(Minz_HookType::EntryAutoRead, $this, 'upon_reception');
  888. }
  889. if (!empty($titlesAsRead[$this->title()])) {
  890. Minz_Log::debug('Mark title as read: ' . $this->title());
  891. $this->_isRead(true);
  892. Minz_ExtensionManager::callHook(Minz_HookType::EntryAutoRead, $this, 'same_title_in_feed');
  893. }
  894. if (!empty($guidsAsRead[$this->guid()])) {
  895. Minz_Log::debug('Mark GUID as read: ' . $this->guid());
  896. $this->_isRead(true);
  897. Minz_ExtensionManager::callHook(Minz_HookType::EntryAutoRead, $this, 'same_guid_in_category');
  898. }
  899. }
  900. FreshRSS_Context::userConf()->applyFilterActions($this);
  901. $feed->category()?->applyFilterActions($this);
  902. $feed->applyFilterActions($this);
  903. }
  904. /**
  905. * @param string $url Overridden URL. Will default to the entry URL.
  906. * @throws Minz_Exception
  907. */
  908. public function getContentByParsing(string $url = '', int $maxRedirs = 4): string {
  909. $url = $url ?: htmlspecialchars_decode($this->link(), ENT_QUOTES);
  910. $feed = $this->feed();
  911. if ($url === '' || $feed === null || $feed->pathEntries() === '') {
  912. return '';
  913. }
  914. $conditions = $feed->attributeArray('path_entries_conditions') ?? [];
  915. $conditions = array_filter($conditions, fn($v): bool => (is_string($v) ? trim($v) : '') !== '');
  916. if (count($conditions) > 0) {
  917. $found = false;
  918. foreach ($conditions as $condition) {
  919. if (!is_string($condition) || trim($condition) === '') {
  920. continue;
  921. }
  922. $booleanSearch = new FreshRSS_BooleanSearch($condition);
  923. if ($this->matches($booleanSearch)) {
  924. $found = true;
  925. break;
  926. }
  927. }
  928. if (!$found) {
  929. return '';
  930. }
  931. }
  932. $cachePath = $feed->cacheFilename($url . '#' . $feed->pathEntries());
  933. $response = FreshRSS_http_Util::httpGet($url, $cachePath, 'html', $feed->attributes(), $feed->curlOptions());
  934. $html = $response['body'];
  935. if ($html !== '') {
  936. $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);
  937. // Account for HTTP redirections
  938. $url = $response['effective_url'] ?: $url;
  939. $maxRedirs -= $response['redirect_count'];
  940. if ($maxRedirs > 0) {
  941. //Follow any HTML redirection
  942. $metas = $doc->querySelectorAll('meta[content]');
  943. foreach ($metas as $meta) {
  944. if (!$meta instanceof Dom\Element) {
  945. continue;
  946. }
  947. if (strtolower(trim($meta->getAttribute('http-equiv') ?? '')) === 'refresh') {
  948. $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content') ?? ''));
  949. $refresh = is_string($refresh) ? \SimplePie\Misc::absolutize_url($refresh, $url) : false;
  950. if ($refresh != false && $refresh !== $url) {
  951. return $this->getContentByParsing($refresh, $maxRedirs - 1);
  952. }
  953. }
  954. }
  955. }
  956. $base = '';
  957. $baseNode = $doc->querySelector('base[href]');
  958. if ($baseNode instanceof Dom\Element) {
  959. $base = trim($baseNode->getAttribute('href') ?? '');
  960. }
  961. if ($base === '') {
  962. $base = $url;
  963. } elseif (str_starts_with($base, '//')) {
  964. //Protocol-relative URLs "//www.example.net"
  965. $base = (parse_url($url, PHP_URL_SCHEME) ?? 'https') . ':' . $base;
  966. }
  967. $html = '';
  968. $cssSelector = htmlspecialchars_decode($feed->pathEntries(), ENT_QUOTES);
  969. $cssSelector = trim($cssSelector, ', ');
  970. $path_entries_filter = trim($feed->attributeString('path_entries_filter') ?? '', ', ');
  971. $nodeList = $doc->querySelectorAll($cssSelector);
  972. if ($nodeList->length === 0) {
  973. Minz_Log::warning('CSS content retrieval matched no elements for feed “' . $feed->name() . '” and article URL ' . $url . ': ' . $cssSelector);
  974. } else {
  975. foreach ($nodeList as $node) {
  976. if (!($node instanceof Dom\Element)) {
  977. continue;
  978. }
  979. if ($path_entries_filter !== '' && $node->matches($path_entries_filter)) {
  980. // Remove unwanted elements once before sanitizing, for CSS selectors to also match original content
  981. continue;
  982. }
  983. if ($path_entries_filter !== '') {
  984. $filterednodeList = $node->querySelectorAll($path_entries_filter);
  985. foreach ($filterednodeList as $filterednode) {
  986. if (!($filterednode instanceof Dom\Element) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) {
  987. continue;
  988. }
  989. $filterednode->remove();
  990. }
  991. }
  992. if ($node->ownerDocument !== $doc || $node->parentNode === null) {
  993. continue;
  994. }
  995. $html .= $doc->saveHTML($node) . "\n";
  996. }
  997. }
  998. unset($doc);
  999. $html = FreshRSS_SimplePieCustom::sanitizeHTML($html, $base);
  1000. if ($nodeList->length > 0 && trim($html) === '') {
  1001. Minz_Log::warning('CSS content retrieval returned no content for feed “' . $feed->name() . '” and article URL ' . $url . ': ' . $cssSelector);
  1002. }
  1003. if ($path_entries_filter !== '') {
  1004. // Remove unwanted elements again after sanitizing, for CSS selectors to also match sanitized content
  1005. $modified = false;
  1006. $doc = Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);
  1007. $filterednodeList = $doc->querySelectorAll($path_entries_filter);
  1008. foreach ($filterednodeList as $filterednode) {
  1009. if (!($filterednode instanceof Dom\Element) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) {
  1010. continue;
  1011. }
  1012. $filterednode->remove();
  1013. $modified = true;
  1014. }
  1015. if ($modified) {
  1016. $bodyNode = $doc->querySelector('body');
  1017. $html = $doc->saveHTML($bodyNode ?? $doc->firstElementChild) ?: $html;
  1018. }
  1019. }
  1020. return trim($html);
  1021. } else {
  1022. throw new Minz_Exception();
  1023. }
  1024. }
  1025. /**
  1026. * @return bool True if the content was modified, false otherwise
  1027. */
  1028. public function loadCompleteContent(bool $force = false): bool {
  1029. // Content handling
  1030. // Trying to fetch full article content even when feeds do not propose it
  1031. $feed = $this->feed();
  1032. if ($feed === null) {
  1033. return false;
  1034. }
  1035. if (trim($feed->pathEntries()) != '') {
  1036. $entryDAO = FreshRSS_Factory::createEntryDao();
  1037. $entry = $force ? null : $entryDAO->searchByGuid($this->feedId, $this->guid);
  1038. if ($entry !== null) {
  1039. // The article already exists in the database, so simply reload its content
  1040. $this->content = $entry->content(false);
  1041. } else {
  1042. try {
  1043. // The article is not yet in the database, so let’s fetch it
  1044. $fullContent = $this->getContentByParsing();
  1045. if ('' !== $fullContent) {
  1046. $originalContent = $this->originalContent();
  1047. // Unique delimiter, inspired by MIME multipart boundaries
  1048. $delimiter = bin2hex(random_bytes(16));
  1049. $this->_attribute('full_content_delimiter', $delimiter);
  1050. $fullContent = "<!-- FULLCONTENT {$delimiter} start //-->{$fullContent}<!-- FULLCONTENT {$delimiter} end //-->";
  1051. switch ($feed->attributeString('content_action')) {
  1052. case 'prepend':
  1053. $this->_attribute('original_content');
  1054. $this->content = $fullContent . $originalContent;
  1055. break;
  1056. case 'append':
  1057. $this->_attribute('original_content');
  1058. $this->content = $originalContent . $fullContent;
  1059. break;
  1060. case 'replace':
  1061. default:
  1062. $this->_attribute('original_content', $originalContent);
  1063. $this->content = $fullContent;
  1064. break;
  1065. }
  1066. return true;
  1067. }
  1068. } catch (Exception $e) {
  1069. // Nothing to do: the request failed, so keep the previous content
  1070. Minz_Log::warning($e->getMessage());
  1071. }
  1072. }
  1073. } elseif (trim($feed->attributeString('path_entries_filter') ?? '') !== '') {
  1074. $originalContent = $this->attributeString('original_content') ?? $this->content;
  1075. $doc = Dom\HTMLDocument::createFromString($originalContent, LIBXML_NOERROR | Dom\HTML_NO_DEFAULT_NS);
  1076. $pathEntriesFilter = $feed->attributeString('path_entries_filter');
  1077. $filterednodeList = $doc->querySelectorAll($pathEntriesFilter);
  1078. foreach ($filterednodeList as $filterednode) {
  1079. if (!($filterednode instanceof Dom\Element) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) {
  1080. continue;
  1081. }
  1082. $filterednode->remove();
  1083. }
  1084. $bodyNode = $doc->querySelector('body');
  1085. $html = $doc->saveHTML($bodyNode ?? $doc->firstElementChild) ?: '';
  1086. $html = preg_replace('%^\s*<body>\s*|\s*</body>\s*$%i', '', $html) ?? '';
  1087. $this->_attribute('original_content');
  1088. if (is_string($html) && $this->content !== $html) {
  1089. $this->_attribute('original_content', $originalContent);
  1090. $this->content = $html;
  1091. return true;
  1092. }
  1093. } else {
  1094. $originalContent = $this->originalContent();
  1095. if ($originalContent !== $this->content) {
  1096. $this->content = $originalContent;
  1097. return true;
  1098. }
  1099. }
  1100. return false;
  1101. }
  1102. /**
  1103. * @return array{id:string,guid:string,title:string,author:string,content:string,link:string,date:int,
  1104. * lastSeen:int,lastModified:?int,lastUserModified:?int,
  1105. * hash:string,is_read:?bool,is_favorite:?bool,id_feed:int,tags:string,attributes:array<string,mixed>}
  1106. */
  1107. public function toArray(): array {
  1108. return [
  1109. 'id' => $this->id(),
  1110. 'guid' => $this->guid(),
  1111. 'title' => $this->title(),
  1112. 'author' => $this->authors(true),
  1113. 'content' => $this->content(false),
  1114. 'link' => $this->link(raw: true),
  1115. 'date' => $this->date(true),
  1116. 'lastSeen' => $this->lastSeen(),
  1117. 'lastModified' => $this->lastModified(),
  1118. 'lastUserModified' => $this->lastUserModified(),
  1119. 'hash' => $this->hash(),
  1120. 'is_read' => $this->isRead(),
  1121. 'is_favorite' => $this->isFavorite(),
  1122. 'id_feed' => $this->feedId(),
  1123. 'tags' => $this->tags(true),
  1124. 'attributes' => $this->attributes(),
  1125. ];
  1126. }
  1127. /**
  1128. * @return array{array<string>,array<string>} Array of first tags to show, then array of remaining tags
  1129. */
  1130. public function tagsFormattingHelper(): array {
  1131. $firstTags = [];
  1132. $remainingTags = [];
  1133. if (FreshRSS_Context::hasUserConf() && in_array(FreshRSS_Context::userConf()->show_tags, ['b', 'f', 'h'], true)) {
  1134. $maxTagsDisplayed = (int)FreshRSS_Context::userConf()->show_tags_max;
  1135. $tags = $this->tags();
  1136. if (!empty($tags)) {
  1137. if ($maxTagsDisplayed > 0) {
  1138. $firstTags = array_slice($tags, 0, $maxTagsDisplayed);
  1139. $remainingTags = array_slice($tags, $maxTagsDisplayed);
  1140. } else {
  1141. $firstTags = $tags;
  1142. }
  1143. }
  1144. }
  1145. return [$firstTags,$remainingTags];
  1146. }
  1147. /**
  1148. * Integer format conversion for Google Reader API format
  1149. * @param numeric-string|int $dec Decimal number
  1150. * @return string 64-bit hexa https://github.com/mihaip/google-reader-api
  1151. */
  1152. private static function dec2hex(string|int $dec): string {
  1153. return PHP_INT_SIZE < 8 ? // 32-bit ?
  1154. str_pad(gmp_strval(gmp_init($dec, 10), 16), 16, '0', STR_PAD_LEFT) :
  1155. str_pad(dechex((int)($dec)), 16, '0', STR_PAD_LEFT);
  1156. }
  1157. /**
  1158. * Some clients (tested with News+) would fail if sending too long item content
  1159. * @var int
  1160. */
  1161. public const API_MAX_COMPAT_CONTENT_LENGTH = 500000;
  1162. /**
  1163. * N.B.: To avoid expensive lookups, ensure to set `$entry->_feed($feed)` before calling this function.
  1164. * @param string $mode Set to `'compat'` to use an alternative Unicode representation for problematic HTML special characters not decoded by some clients;
  1165. * set to `'freshrss'` for using FreshRSS additions for internal use (e.g. export/import).
  1166. * @param array<string> $labels List of labels associated to this entry.
  1167. * @return array<string,mixed> A representation of this entry in a format compatible with Google Reader API
  1168. */
  1169. public function toGReader(string $mode = '', array $labels = []): array {
  1170. $feed = $this->feed();
  1171. $category = $feed == null ? null : $feed->category();
  1172. $item = [
  1173. 'frss:id' => $this->id(),
  1174. 'id' => 'tag:google.com,2005:reader/item/' . self::dec2hex($this->id()),
  1175. 'crawlTimeMsec' => substr($this->dateAdded(true, true), 0, -3),
  1176. 'timestampUsec' => '' . $this->dateAdded(true, true), //EasyRSS & Reeder
  1177. 'published' => $this->date(true),
  1178. // 'updated' => $this->date(true),
  1179. 'title' => $this->title(),
  1180. 'canonical' => [
  1181. ['href' => htmlspecialchars_decode($this->link(), ENT_QUOTES)],
  1182. ],
  1183. 'alternate' => [
  1184. [
  1185. 'href' => htmlspecialchars_decode($this->link(), ENT_QUOTES),
  1186. 'type' => 'text/html',
  1187. ],
  1188. ],
  1189. 'categories' => [
  1190. 'user/-/state/com.google/reading-list',
  1191. ],
  1192. 'origin' => [
  1193. 'streamId' => 'feed/' . $this->feedId,
  1194. ],
  1195. ];
  1196. if ($mode === 'compat') {
  1197. $item['title'] = escapeToUnicodeAlternative($this->title(), false);
  1198. unset($item['alternate'][0]['type']);
  1199. $item['summary'] = [
  1200. 'content' => mb_strcut($this->content($feed?->attributeBoolean('display_enclosures') ?? true), 0, self::API_MAX_COMPAT_CONTENT_LENGTH, 'UTF-8'),
  1201. ];
  1202. } else {
  1203. $item['content'] = [
  1204. 'content' => $this->content(false),
  1205. ];
  1206. }
  1207. if ($mode === 'freshrss') {
  1208. $item['guid'] = $this->guid();
  1209. }
  1210. if ($category != null && $mode !== 'freshrss') {
  1211. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($category->name(), ENT_QUOTES);
  1212. }
  1213. if ($feed !== null) {
  1214. $item['origin']['htmlUrl'] = htmlspecialchars_decode($feed->website());
  1215. $item['origin']['title'] = $feed->name(); //EasyRSS
  1216. if ($mode === 'compat') {
  1217. $item['origin']['title'] = escapeToUnicodeAlternative($feed->name(), true);
  1218. } elseif ($mode === 'freshrss') {
  1219. $item['origin']['feedUrl'] = htmlspecialchars_decode($feed->url(includeCredentials: false));
  1220. }
  1221. if ($feed->priority() >= FreshRSS_Feed::PRIORITY_MAIN_STREAM) {
  1222. $item['categories'][] = 'user/-/state/org.freshrss/main';
  1223. if ($feed->priority() >= FreshRSS_Feed::PRIORITY_IMPORTANT) {
  1224. $item['categories'][] = 'user/-/state/org.freshrss/important';
  1225. }
  1226. } elseif ($feed->priority() <= FreshRSS_Feed::PRIORITY_HIDDEN) {
  1227. $item['categories'][] = 'user/-/state/org.freshrss/hidden';
  1228. }
  1229. }
  1230. foreach ($this->enclosures() as $enclosure) {
  1231. if (!empty($enclosure['url'])) {
  1232. $media = [
  1233. 'href' => $enclosure['url'],
  1234. 'type' => $enclosure['type'] ?? $enclosure['medium'] ??
  1235. (self::enclosureIsImage($enclosure) ? 'image' : ''),
  1236. ];
  1237. if (!empty($enclosure['length'])) {
  1238. $media['length'] = (int)$enclosure['length'];
  1239. }
  1240. $item['enclosure'][] = $media;
  1241. }
  1242. }
  1243. $author = $this->authors(true);
  1244. $author = trim($author, '; ');
  1245. if ($author != '') {
  1246. if ($mode === 'compat') {
  1247. $item['author'] = escapeToUnicodeAlternative($author, false);
  1248. } else {
  1249. $item['author'] = $author;
  1250. }
  1251. }
  1252. if ($this->isRead()) {
  1253. $item['categories'][] = 'user/-/state/com.google/read';
  1254. } elseif ($mode === 'freshrss') {
  1255. $item['categories'][] = 'user/-/state/com.google/unread';
  1256. }
  1257. if ($this->isFavorite()) {
  1258. $item['categories'][] = 'user/-/state/com.google/starred';
  1259. }
  1260. foreach ($labels as $labelName) {
  1261. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($labelName, ENT_QUOTES);
  1262. }
  1263. foreach ($this->tags() as $tagName) {
  1264. $item['categories'][] = htmlspecialchars_decode($tagName, ENT_QUOTES);
  1265. }
  1266. return $item;
  1267. }
  1268. }