4
0

Entry.php 45 KB

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