Entry.php 39 KB

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