Entry.php 46 KB

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