4
0

Entry.php 39 KB

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