Entry.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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. /** @param array<string,bool|int> $titlesAsRead */
  832. public function applyFilterActions(array $titlesAsRead = []): void {
  833. $feed = $this->feed;
  834. if ($feed === null) {
  835. return;
  836. }
  837. if (!$this->isRead()) {
  838. if ($feed->attributeBoolean('read_upon_reception') ?? FreshRSS_Context::userConf()->mark_when['reception']) {
  839. $this->_isRead(true);
  840. Minz_ExtensionManager::callHook(Minz_HookType::EntryAutoRead, $this, 'upon_reception');
  841. }
  842. if (!empty($titlesAsRead[$this->title()])) {
  843. Minz_Log::debug('Mark title as read: ' . $this->title());
  844. $this->_isRead(true);
  845. Minz_ExtensionManager::callHook(Minz_HookType::EntryAutoRead, $this, 'same_title_in_feed');
  846. }
  847. }
  848. FreshRSS_Context::userConf()->applyFilterActions($this);
  849. $feed->category()?->applyFilterActions($this);
  850. $feed->applyFilterActions($this);
  851. }
  852. /**
  853. * @param string $url Overridden URL. Will default to the entry URL.
  854. * @throws Minz_Exception
  855. */
  856. public function getContentByParsing(string $url = '', int $maxRedirs = 4): string {
  857. $url = $url ?: htmlspecialchars_decode($this->link(), ENT_QUOTES);
  858. $feed = $this->feed();
  859. if ($url === '' || $feed === null || $feed->pathEntries() === '') {
  860. return '';
  861. }
  862. $conditions = $feed->attributeArray('path_entries_conditions') ?? [];
  863. $conditions = array_filter($conditions, fn($v): bool => (is_string($v) ? trim($v) : '') !== '');
  864. if (count($conditions) > 0) {
  865. $found = false;
  866. foreach ($conditions as $condition) {
  867. if (!is_string($condition) || trim($condition) === '') {
  868. continue;
  869. }
  870. $booleanSearch = new FreshRSS_BooleanSearch($condition);
  871. if ($this->matches($booleanSearch)) {
  872. $found = true;
  873. break;
  874. }
  875. }
  876. if (!$found) {
  877. return '';
  878. }
  879. }
  880. $cachePath = $feed->cacheFilename($url . '#' . $feed->pathEntries());
  881. $response = FreshRSS_http_Util::httpGet($url, $cachePath, 'html', $feed->attributes(), $feed->curlOptions());
  882. $html = $response['body'];
  883. if ($html !== '') {
  884. $doc = new DOMDocument();
  885. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  886. $xpath = new DOMXPath($doc);
  887. // Account for HTTP redirections
  888. $url = $response['effective_url'] ?: $url;
  889. $maxRedirs -= $response['redirect_count'];
  890. if ($maxRedirs > 0) {
  891. //Follow any HTML redirection
  892. $metas = $xpath->query('//meta[@content]') ?: [];
  893. foreach ($metas as $meta) {
  894. if ($meta instanceof DOMElement && strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') {
  895. $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content')));
  896. $refresh = is_string($refresh) ? \SimplePie\Misc::absolutize_url($refresh, $url) : false;
  897. if ($refresh != false && $refresh !== $url) {
  898. return $this->getContentByParsing($refresh, $maxRedirs - 1);
  899. }
  900. }
  901. }
  902. }
  903. $base = $xpath->evaluate('normalize-space(//base/@href)');
  904. if ($base == false || !is_string($base)) {
  905. $base = $url;
  906. } elseif (str_starts_with($base, '//')) {
  907. //Protocol-relative URLs "//www.example.net"
  908. $base = (parse_url($url, PHP_URL_SCHEME) ?? 'https') . ':' . $base;
  909. }
  910. $html = '';
  911. $cssSelector = htmlspecialchars_decode($feed->pathEntries(), ENT_QUOTES);
  912. $cssSelector = trim($cssSelector, ', ');
  913. $path_entries_filter = trim($feed->attributeString('path_entries_filter') ?? '', ', ');
  914. $nodes = $xpath->query((new Gt\CssXPath\Translator($cssSelector, '//'))->asXPath());
  915. if ($nodes != false) {
  916. $filter_xpath = $path_entries_filter === '' ? '' : (new Gt\CssXPath\Translator($path_entries_filter, 'descendant-or-self::'))->asXPath();
  917. foreach ($nodes as $node) {
  918. try {
  919. if (!($node instanceof DOMElement)) {
  920. continue;
  921. }
  922. if ($filter_xpath !== '' && ($filterednodes = $xpath->query($filter_xpath, $node)) !== false) {
  923. // Remove unwanted elements once before sanitizing, for CSS selectors to also match original content
  924. foreach ($filterednodes as $filterednode) {
  925. try {
  926. if ($filterednode === $node) {
  927. continue 2;
  928. }
  929. if (!($filterednode instanceof DOMElement) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) {
  930. continue;
  931. }
  932. $filterednode->remove();
  933. } catch (Error $e) { // @phpstan-ignore catch.neverThrown
  934. if (!str_contains($e->getMessage(), 'Node no longer exists')) {
  935. throw $e;
  936. }
  937. }
  938. }
  939. }
  940. if ($node->ownerDocument !== $doc || $node->parentNode === null) {
  941. continue;
  942. }
  943. $html .= $doc->saveHTML($node) . "\n";
  944. } catch (Error $e) {
  945. if (!str_contains($e->getMessage(), 'Node no longer exists')) {
  946. throw $e;
  947. }
  948. }
  949. }
  950. }
  951. unset($xpath, $doc);
  952. $html = FreshRSS_SimplePieCustom::sanitizeHTML($html, $base);
  953. if ($path_entries_filter !== '') {
  954. // Remove unwanted elements again after sanitizing, for CSS selectors to also match sanitized content
  955. $modified = false;
  956. $doc = new DOMDocument();
  957. $utf8BOM = "\xEF\xBB\xBF";
  958. $doc->loadHTML($utf8BOM . $html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  959. $xpath = new DOMXPath($doc);
  960. $filterednodes = $xpath->query((new Gt\CssXPath\Translator($path_entries_filter, '//'))->asXPath()) ?: [];
  961. foreach ($filterednodes as $filterednode) {
  962. try {
  963. if (!($filterednode instanceof DOMElement) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) {
  964. continue;
  965. }
  966. $filterednode->remove();
  967. $modified = true;
  968. } catch (Error $e) { // @phpstan-ignore catch.neverThrown
  969. if (!str_contains($e->getMessage(), 'Node no longer exists')) {
  970. throw $e;
  971. }
  972. }
  973. }
  974. if ($modified) {
  975. $html = $doc->saveHTML($doc->getElementsByTagName('body')->item(0) ?? $doc->firstElementChild) ?: $html;
  976. }
  977. }
  978. return trim($html);
  979. } else {
  980. throw new Minz_Exception();
  981. }
  982. }
  983. /**
  984. * @return bool True if the content was modified, false otherwise
  985. */
  986. public function loadCompleteContent(bool $force = false): bool {
  987. // Gestion du contenu
  988. // Trying to fetch full article content even when feeds do not propose it
  989. $feed = $this->feed();
  990. if ($feed === null) {
  991. return false;
  992. }
  993. if (trim($feed->pathEntries()) != '') {
  994. $entryDAO = FreshRSS_Factory::createEntryDao();
  995. $entry = $force ? null : $entryDAO->searchByGuid($this->feedId, $this->guid);
  996. if ($entry !== null) {
  997. // l’article existe déjà en BDD, en se contente de recharger ce contenu
  998. $this->content = $entry->content(false);
  999. } else {
  1000. try {
  1001. // The article is not yet in the database, so let’s fetch it
  1002. $fullContent = $this->getContentByParsing();
  1003. if ('' !== $fullContent) {
  1004. $fullContent = "<!-- FULLCONTENT start //-->{$fullContent}<!-- FULLCONTENT end //-->";
  1005. $originalContent = $this->originalContent();
  1006. switch ($feed->attributeString('content_action')) {
  1007. case 'prepend':
  1008. $this->_attribute('original_content');
  1009. $this->content = $fullContent . $originalContent;
  1010. break;
  1011. case 'append':
  1012. $this->_attribute('original_content');
  1013. $this->content = $originalContent . $fullContent;
  1014. break;
  1015. case 'replace':
  1016. default:
  1017. $this->_attribute('original_content', $originalContent);
  1018. $this->content = $fullContent;
  1019. break;
  1020. }
  1021. return true;
  1022. }
  1023. } catch (Exception $e) {
  1024. // rien à faire, on garde l’ancien contenu(requête a échoué)
  1025. Minz_Log::warning($e->getMessage());
  1026. }
  1027. }
  1028. } elseif (trim($feed->attributeString('path_entries_filter') ?? '') !== '') {
  1029. $originalContent = $this->attributeString('original_content') ?? $this->content;
  1030. $doc = new DOMDocument();
  1031. $utf8BOM = "\xEF\xBB\xBF";
  1032. if (!$doc->loadHTML($utf8BOM . $originalContent, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) {
  1033. return false;
  1034. }
  1035. $xpath = new DOMXPath($doc);
  1036. $filterednodes = $xpath->query((new Gt\CssXPath\Translator($feed->attributeString('path_entries_filter'), '//'))->asXPath()) ?: [];
  1037. foreach ($filterednodes as $filterednode) {
  1038. try {
  1039. if (!($filterednode instanceof DOMElement) || $filterednode->ownerDocument !== $doc || $filterednode->parentNode === null) {
  1040. continue;
  1041. }
  1042. $filterednode->remove();
  1043. } catch (Error $e) { // @phpstan-ignore catch.neverThrown
  1044. if (!str_contains($e->getMessage(), 'Node no longer exists')) {
  1045. throw $e;
  1046. }
  1047. }
  1048. }
  1049. $html = $doc->saveHTML($doc->getElementsByTagName('body')->item(0) ?? $doc->firstElementChild);
  1050. if (!is_string($html)) {
  1051. return false;
  1052. }
  1053. $html = preg_replace('%^\s*<body>\s*|\s*</body>\s*$%i', '', $html);
  1054. $this->_attribute('original_content');
  1055. if (is_string($html) && $this->content !== $html) {
  1056. $this->_attribute('original_content', $originalContent);
  1057. $this->content = $html;
  1058. return true;
  1059. }
  1060. } else {
  1061. $originalContent = $this->originalContent();
  1062. if ($originalContent !== $this->content) {
  1063. $this->content = $originalContent;
  1064. return true;
  1065. }
  1066. }
  1067. return false;
  1068. }
  1069. /**
  1070. * @return array{id:string,guid:string,title:string,author:string,content:string,link:string,date:int,
  1071. * lastSeen:int,lastModified:?int,lastUserModified:?int,
  1072. * hash:string,is_read:?bool,is_favorite:?bool,id_feed:int,tags:string,attributes:array<string,mixed>}
  1073. */
  1074. public function toArray(): array {
  1075. return [
  1076. 'id' => $this->id(),
  1077. 'guid' => $this->guid(),
  1078. 'title' => $this->title(),
  1079. 'author' => $this->authors(true),
  1080. 'content' => $this->content(false),
  1081. 'link' => $this->link(raw: true),
  1082. 'date' => $this->date(true),
  1083. 'lastSeen' => $this->lastSeen(),
  1084. 'lastModified' => $this->lastModified(),
  1085. 'lastUserModified' => $this->lastUserModified(),
  1086. 'hash' => $this->hash(),
  1087. 'is_read' => $this->isRead(),
  1088. 'is_favorite' => $this->isFavorite(),
  1089. 'id_feed' => $this->feedId(),
  1090. 'tags' => $this->tags(true),
  1091. 'attributes' => $this->attributes(),
  1092. ];
  1093. }
  1094. /**
  1095. * @return array{array<string>,array<string>} Array of first tags to show, then array of remaining tags
  1096. */
  1097. public function tagsFormattingHelper(): array {
  1098. $firstTags = [];
  1099. $remainingTags = [];
  1100. if (FreshRSS_Context::hasUserConf() && in_array(FreshRSS_Context::userConf()->show_tags, ['b', 'f', 'h'], true)) {
  1101. $maxTagsDisplayed = (int)FreshRSS_Context::userConf()->show_tags_max;
  1102. $tags = $this->tags();
  1103. if (!empty($tags)) {
  1104. if ($maxTagsDisplayed > 0) {
  1105. $firstTags = array_slice($tags, 0, $maxTagsDisplayed);
  1106. $remainingTags = array_slice($tags, $maxTagsDisplayed);
  1107. } else {
  1108. $firstTags = $tags;
  1109. }
  1110. }
  1111. }
  1112. return [$firstTags,$remainingTags];
  1113. }
  1114. /**
  1115. * Integer format conversion for Google Reader API format
  1116. * @param numeric-string|int $dec Decimal number
  1117. * @return string 64-bit hexa http://code.google.com/p/google-reader-api/wiki/ItemId
  1118. */
  1119. private static function dec2hex(string|int $dec): string {
  1120. return PHP_INT_SIZE < 8 ? // 32-bit ?
  1121. str_pad(gmp_strval(gmp_init($dec, 10), 16), 16, '0', STR_PAD_LEFT) :
  1122. str_pad(dechex((int)($dec)), 16, '0', STR_PAD_LEFT);
  1123. }
  1124. /**
  1125. * Some clients (tested with News+) would fail if sending too long item content
  1126. * @var int
  1127. */
  1128. public const API_MAX_COMPAT_CONTENT_LENGTH = 500000;
  1129. /**
  1130. * N.B.: To avoid expensive lookups, ensure to set `$entry->_feed($feed)` before calling this function.
  1131. * @param string $mode Set to `'compat'` to use an alternative Unicode representation for problematic HTML special characters not decoded by some clients;
  1132. * set to `'freshrss'` for using FreshRSS additions for internal use (e.g. export/import).
  1133. * @param array<string> $labels List of labels associated to this entry.
  1134. * @return array<string,mixed> A representation of this entry in a format compatible with Google Reader API
  1135. */
  1136. public function toGReader(string $mode = '', array $labels = []): array {
  1137. $feed = $this->feed();
  1138. $category = $feed == null ? null : $feed->category();
  1139. $item = [
  1140. 'frss:id' => $this->id(),
  1141. 'id' => 'tag:google.com,2005:reader/item/' . self::dec2hex($this->id()),
  1142. 'crawlTimeMsec' => substr($this->dateAdded(true, true), 0, -3),
  1143. 'timestampUsec' => '' . $this->dateAdded(true, true), //EasyRSS & Reeder
  1144. 'published' => $this->date(true),
  1145. // 'updated' => $this->date(true),
  1146. 'title' => $this->title(),
  1147. 'canonical' => [
  1148. ['href' => htmlspecialchars_decode($this->link(), ENT_QUOTES)],
  1149. ],
  1150. 'alternate' => [
  1151. [
  1152. 'href' => htmlspecialchars_decode($this->link(), ENT_QUOTES),
  1153. 'type' => 'text/html',
  1154. ],
  1155. ],
  1156. 'categories' => [
  1157. 'user/-/state/com.google/reading-list',
  1158. ],
  1159. 'origin' => [
  1160. 'streamId' => 'feed/' . $this->feedId,
  1161. ],
  1162. ];
  1163. if ($mode === 'compat') {
  1164. $item['title'] = escapeToUnicodeAlternative($this->title(), false);
  1165. unset($item['alternate'][0]['type']);
  1166. $item['summary'] = [
  1167. 'content' => mb_strcut($this->content(true), 0, self::API_MAX_COMPAT_CONTENT_LENGTH, 'UTF-8'),
  1168. ];
  1169. } else {
  1170. $item['content'] = [
  1171. 'content' => $this->content(false),
  1172. ];
  1173. }
  1174. if ($mode === 'freshrss') {
  1175. $item['guid'] = $this->guid();
  1176. }
  1177. if ($category != null && $mode !== 'freshrss') {
  1178. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($category->name(), ENT_QUOTES);
  1179. }
  1180. if ($feed !== null) {
  1181. $item['origin']['htmlUrl'] = htmlspecialchars_decode($feed->website());
  1182. $item['origin']['title'] = $feed->name(); //EasyRSS
  1183. if ($mode === 'compat') {
  1184. $item['origin']['title'] = escapeToUnicodeAlternative($feed->name(), true);
  1185. } elseif ($mode === 'freshrss') {
  1186. $item['origin']['feedUrl'] = htmlspecialchars_decode($feed->url());
  1187. }
  1188. if ($feed->priority() >= FreshRSS_Feed::PRIORITY_MAIN_STREAM) {
  1189. $item['categories'][] = 'user/-/state/org.freshrss/main';
  1190. if ($feed->priority() >= FreshRSS_Feed::PRIORITY_IMPORTANT) {
  1191. $item['categories'][] = 'user/-/state/org.freshrss/important';
  1192. }
  1193. } elseif ($feed->priority() <= FreshRSS_Feed::PRIORITY_HIDDEN) {
  1194. $item['categories'][] = 'user/-/state/org.freshrss/hidden';
  1195. }
  1196. }
  1197. foreach ($this->enclosures() as $enclosure) {
  1198. if (!empty($enclosure['url'])) {
  1199. $media = [
  1200. 'href' => $enclosure['url'],
  1201. 'type' => $enclosure['type'] ?? $enclosure['medium'] ??
  1202. (self::enclosureIsImage($enclosure) ? 'image' : ''),
  1203. ];
  1204. if (!empty($enclosure['length'])) {
  1205. $media['length'] = (int)$enclosure['length'];
  1206. }
  1207. $item['enclosure'][] = $media;
  1208. }
  1209. }
  1210. $author = $this->authors(true);
  1211. $author = trim($author, '; ');
  1212. if ($author != '') {
  1213. if ($mode === 'compat') {
  1214. $item['author'] = escapeToUnicodeAlternative($author, false);
  1215. } else {
  1216. $item['author'] = $author;
  1217. }
  1218. }
  1219. if ($this->isRead()) {
  1220. $item['categories'][] = 'user/-/state/com.google/read';
  1221. } elseif ($mode === 'freshrss') {
  1222. $item['categories'][] = 'user/-/state/com.google/unread';
  1223. }
  1224. if ($this->isFavorite()) {
  1225. $item['categories'][] = 'user/-/state/com.google/starred';
  1226. }
  1227. foreach ($labels as $labelName) {
  1228. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($labelName, ENT_QUOTES);
  1229. }
  1230. foreach ($this->tags() as $tagName) {
  1231. $item['categories'][] = htmlspecialchars_decode($tagName, ENT_QUOTES);
  1232. }
  1233. return $item;
  1234. }
  1235. }