Entry.php 43 KB

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