Entry.php 45 KB

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