4
0

Entry.php 45 KB

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