Entry.php 38 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. if (empty($dao['content']) || !is_string($dao['content'])) {
  54. $dao['content'] = '';
  55. }
  56. $dao['attributes'] = empty($dao['attributes']) ? [] : json_decode($dao['attributes'], true);
  57. if (!is_array($dao['attributes'])) {
  58. $dao['attributes'] = [];
  59. }
  60. if (!empty($dao['thumbnail'])) {
  61. $dao['attributes']['thumbnail'] = [
  62. 'url' => $dao['thumbnail'],
  63. ];
  64. }
  65. $entry = new FreshRSS_Entry(
  66. $dao['id_feed'] ?? 0,
  67. $dao['guid'] ?? '',
  68. $dao['title'] ?? '',
  69. $dao['author'] ?? '',
  70. $dao['content'],
  71. $dao['link'] ?? '',
  72. $dao['date'] ?? 0,
  73. $dao['is_read'] ?? false,
  74. $dao['is_favorite'] ?? false,
  75. $dao['tags'] ?? ''
  76. );
  77. if (!empty($dao['id']) && is_numeric($dao['id'])) {
  78. $entry->_id($dao['id']);
  79. }
  80. if (!empty($dao['timestamp'])) {
  81. $entry->_date(strtotime($dao['timestamp']) ?: 0);
  82. }
  83. if (isset($dao['lastSeen'])) {
  84. $entry->_lastSeen($dao['lastSeen']);
  85. }
  86. if (!empty($dao['attributes'])) {
  87. $entry->_attributes($dao['attributes']);
  88. }
  89. if (!empty($dao['hash'])) {
  90. $entry->_hash($dao['hash']);
  91. }
  92. return $entry;
  93. }
  94. /**
  95. * @param Traversable<array{'id'?:string,'id_feed'?:int,'guid'?:string,'title'?:string,'author'?:string,'content'?:string,'link'?:string,'date'?:int|string,'lastSeen'?:int,
  96. * 'hash'?:string,'is_read'?:bool|int,'is_favorite'?:bool|int,'tags'?:string|array<string>,'attributes'?:?string,'thumbnail'?:string,'timestamp'?:string}> $daos
  97. * @return Traversable<FreshRSS_Entry>
  98. */
  99. public static function fromTraversable(Traversable $daos): Traversable {
  100. foreach ($daos as $dao) {
  101. yield FreshRSS_Entry::fromArray($dao);
  102. }
  103. }
  104. /** @return numeric-string */
  105. public function id(): string {
  106. return $this->id;
  107. }
  108. public function guid(): string {
  109. return $this->guid;
  110. }
  111. public function title(): string {
  112. $title = '';
  113. if ($this->title === '') {
  114. // used while fetching the article from feed and store it in the database
  115. $title = $this->guid();
  116. } else {
  117. // used while fetching from the database
  118. if ($this->title !== $this->guid) {
  119. $title = $this->title;
  120. } else {
  121. $content = trim(strip_tags($this->content(false)));
  122. $title = trim(mb_substr($content, 0, MAX_CHARS_EMPTY_FEED_TITLE, 'UTF-8'));
  123. if ($title === '') {
  124. $title = $this->guid();
  125. } elseif (strlen($content) > strlen($title)) {
  126. $title .= '…';
  127. }
  128. }
  129. }
  130. return $title;
  131. }
  132. /** @deprecated */
  133. public function author(): string {
  134. return $this->authors(true);
  135. }
  136. /**
  137. * @phpstan-return ($asString is true ? string : array<string>)
  138. * @return string|array<string>
  139. */
  140. public function authors(bool $asString = false): string|array {
  141. if ($asString) {
  142. return $this->authors == null ? '' : ';' . implode('; ', $this->authors);
  143. } else {
  144. return $this->authors;
  145. }
  146. }
  147. /**
  148. * Basic test without ambition to catch all cases such as unquoted addresses, variants of entities, HTML comments, etc.
  149. */
  150. private static function containsLink(string $html, string $link): bool {
  151. return preg_match('/(?P<delim>[\'"])' . preg_quote($link, '/') . '(?P=delim)/', $html) == 1;
  152. }
  153. /** @param array{'url'?:string,'length'?:int,'medium'?:string,'type'?:string} $enclosure */
  154. private static function enclosureIsImage(array $enclosure): bool {
  155. $elink = $enclosure['url'] ?? '';
  156. $length = $enclosure['length'] ?? 0;
  157. $medium = $enclosure['medium'] ?? '';
  158. $mime = $enclosure['type'] ?? '';
  159. return ($elink != '' && $medium === 'image') || str_starts_with($mime, 'image') ||
  160. ($mime == '' && $length == 0 && preg_match('/[.](avif|gif|jpe?g|png|svg|webp)([?#]|$)/i', $elink));
  161. }
  162. /**
  163. * Provides the original content without additional content potentially added by loadCompleteContent().
  164. */
  165. public function originalContent(): string {
  166. return $this->attributeString('original_content') ??
  167. preg_replace('#<!-- FULLCONTENT start //-->.*<!-- FULLCONTENT end //-->#s', '', $this->content) ?? '';
  168. }
  169. /**
  170. * @param bool $withEnclosures Set to true to include the enclosures in the returned HTML, false otherwise.
  171. * @param bool $allowDuplicateEnclosures Set to false to remove obvious enclosure duplicates (based on simple string comparison), true otherwise.
  172. * @return string HTML content
  173. */
  174. public function content(bool $withEnclosures = true, bool $allowDuplicateEnclosures = false): string {
  175. if (!$withEnclosures) {
  176. return $this->content;
  177. }
  178. $content = $this->content;
  179. $thumbnailAttribute = $this->attributeArray('thumbnail') ?? [];
  180. if (!empty($thumbnailAttribute['url'])) {
  181. $elink = $thumbnailAttribute['url'];
  182. if (is_string($elink) && ($allowDuplicateEnclosures || !self::containsLink($content, $elink))) {
  183. $content .= <<<HTML
  184. <figure class="enclosure">
  185. <p class="enclosure-content">
  186. <img class="enclosure-thumbnail" src="{$elink}" alt="" />
  187. </p>
  188. </figure>
  189. HTML;
  190. }
  191. }
  192. $attributeEnclosures = $this->attributeArray('enclosures');
  193. if (empty($attributeEnclosures)) {
  194. return $content;
  195. }
  196. foreach ($attributeEnclosures as $enclosure) {
  197. if (!is_array($enclosure)) {
  198. continue;
  199. }
  200. $elink = $enclosure['url'] ?? '';
  201. if ($elink == '' || !is_string($elink)) {
  202. continue;
  203. }
  204. if (!$allowDuplicateEnclosures && self::containsLink($content, $elink)) {
  205. continue;
  206. }
  207. $credits = $enclosure['credit'] ?? '';
  208. $description = nl2br($enclosure['description'] ?? '', true);
  209. $length = $enclosure['length'] ?? 0;
  210. $medium = $enclosure['medium'] ?? '';
  211. $mime = $enclosure['type'] ?? '';
  212. $thumbnails = $enclosure['thumbnails'] ?? null;
  213. if (!is_array($thumbnails)) {
  214. $thumbnails = [];
  215. }
  216. $etitle = $enclosure['title'] ?? '';
  217. $content .= "\n";
  218. $content .= '<figure class="enclosure">';
  219. foreach ($thumbnails as $thumbnail) {
  220. if (is_string($thumbnail)) {
  221. $content .= '<p><img class="enclosure-thumbnail" src="' . $thumbnail . '" alt="" title="' . $etitle . '" /></p>';
  222. }
  223. }
  224. if (self::enclosureIsImage($enclosure)) {
  225. $content .= '<p class="enclosure-content"><img src="' . $elink . '" alt="" title="' . $etitle . '" /></p>';
  226. } elseif ($medium === 'audio' || str_starts_with($mime, 'audio')) {
  227. $content .= '<p class="enclosure-content"><audio preload="none" src="' . $elink
  228. . ($length == null ? '' : '" data-length="' . (int)$length)
  229. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  230. . '" controls="controls" title="' . $etitle . '"></audio> <a download="" href="' . $elink . '">💾</a></p>';
  231. } elseif ($medium === 'video' || str_starts_with($mime, 'video')) {
  232. $content .= '<p class="enclosure-content"><video preload="none" src="' . $elink
  233. . ($length == null ? '' : '" data-length="' . (int)$length)
  234. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  235. . '" controls="controls" title="' . $etitle . '"></video> <a download="" href="' . $elink . '">💾</a></p>';
  236. } else { //e.g. application, text, unknown
  237. $content .= '<p class="enclosure-content"><a download="" href="' . $elink
  238. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  239. . ($medium == '' ? '' : '" data-medium="' . htmlspecialchars($medium, ENT_COMPAT, 'UTF-8'))
  240. . '" title="' . $etitle . '">💾</a></p>';
  241. }
  242. if ($credits != '') {
  243. if (!is_array($credits)) {
  244. $credits = [$credits];
  245. }
  246. foreach ($credits as $credit) {
  247. $content .= '<p class="enclosure-credits">© ' . $credit . '</p>';
  248. }
  249. }
  250. if ($description != '') {
  251. $content .= '<figcaption class="enclosure-description">' . $description . '</figcaption>';
  252. }
  253. $content .= "</figure>\n";
  254. }
  255. return $content;
  256. }
  257. /** @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>}> */
  258. public function enclosures(bool $searchBodyImages = false): Traversable {
  259. $attributeEnclosures = $this->attributeArray('enclosures');
  260. if (is_array($attributeEnclosures)) {
  261. // FreshRSS 1.20.1+: The enclosures are saved as attributes
  262. /** @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 */
  263. yield from $attributeEnclosures;
  264. }
  265. try {
  266. $searchEnclosures = !is_iterable($attributeEnclosures) && (str_contains($this->content, '<p class="enclosure-content'));
  267. $searchBodyImages &= (stripos($this->content, '<img') !== false);
  268. $xpath = null;
  269. if ($searchEnclosures || $searchBodyImages) {
  270. $dom = new DOMDocument();
  271. $dom->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $this->content, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  272. $xpath = new DOMXPath($dom);
  273. }
  274. if ($searchEnclosures && $xpath !== null) {
  275. // Legacy code for database entries < FreshRSS 1.20.1
  276. $enclosures = $xpath->query('//div[@class="enclosure"]/p[@class="enclosure-content"]/*[@src]');
  277. if (!empty($enclosures)) {
  278. foreach ($enclosures as $enclosure) {
  279. if (!($enclosure instanceof DOMElement)) {
  280. continue;
  281. }
  282. $result = [
  283. 'url' => $enclosure->getAttribute('src'),
  284. 'type' => $enclosure->getAttribute('data-type'),
  285. 'medium' => $enclosure->getAttribute('data-medium'),
  286. 'length' => (int)($enclosure->getAttribute('data-length')),
  287. ];
  288. if (empty($result['medium'])) {
  289. switch (strtolower($enclosure->nodeName)) {
  290. case 'img': $result['medium'] = 'image'; break;
  291. case 'video': $result['medium'] = 'video'; break;
  292. case 'audio': $result['medium'] = 'audio'; break;
  293. }
  294. }
  295. yield Minz_Helper::htmlspecialchars_utf8($result);
  296. }
  297. }
  298. }
  299. if ($searchBodyImages && $xpath !== null) {
  300. $images = $xpath->query('//img');
  301. if (!empty($images)) {
  302. foreach ($images as $img) {
  303. if (!($img instanceof DOMElement)) {
  304. continue;
  305. }
  306. $src = $img->getAttribute('src');
  307. if ($src == null) {
  308. $src = $img->getAttribute('data-src');
  309. }
  310. if ($src != null) {
  311. $result = [
  312. 'url' => $src,
  313. 'medium' => 'image',
  314. ];
  315. yield Minz_Helper::htmlspecialchars_utf8($result);
  316. }
  317. }
  318. }
  319. }
  320. } catch (Exception $ex) {
  321. Minz_Log::debug(__METHOD__ . ' ' . $ex->getMessage());
  322. }
  323. }
  324. /**
  325. * @return array{'url':string,'height'?:int,'width'?:int,'time'?:string}|null
  326. */
  327. public function thumbnail(bool $searchEnclosures = true): ?array {
  328. $thumbnail = $this->attributeArray('thumbnail') ?? [];
  329. // First, use the provided thumbnail, if any
  330. if (is_string($thumbnail['url'] ?? null)) {
  331. /** @var array{'url':string,'height'?:int,'width'?:int,'time'?:string} $thumbnail */
  332. return $thumbnail;
  333. }
  334. if ($searchEnclosures) {
  335. foreach ($this->enclosures(true) as $enclosure) {
  336. // Second, search each enclosure’s thumbnails
  337. if (!empty($enclosure['thumbnails'][0])) {
  338. foreach ($enclosure['thumbnails'] as $src) {
  339. if (is_string($src)) {
  340. return [
  341. 'url' => $src,
  342. 'medium' => 'image',
  343. ];
  344. }
  345. }
  346. }
  347. // Third, check whether each enclosure itself is an appropriate image
  348. if (self::enclosureIsImage($enclosure)) {
  349. return $enclosure;
  350. }
  351. }
  352. }
  353. return null;
  354. }
  355. /**
  356. * @param bool $raw Set to true to return the raw link,
  357. * false (default) to attempt a fallback to the GUID if the link is empty.
  358. * @return string HTML-encoded link of the entry
  359. */
  360. public function link(bool $raw = false): string {
  361. if ($this->link === '' && !$raw) {
  362. // Use the GUID as a fallback if it looks like a URL
  363. if (filter_var($this->guid, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE) !== null) {
  364. return $this->guid;
  365. }
  366. }
  367. return $this->link;
  368. }
  369. /**
  370. * @phpstan-return ($raw is false ? string : int)
  371. */
  372. public function date(bool $raw = false): int|string {
  373. if ($raw) {
  374. return $this->date;
  375. }
  376. return timestamptodate($this->date);
  377. }
  378. public function machineReadableDate(): string {
  379. return @date(DATE_ATOM, $this->date);
  380. }
  381. public function lastSeen(): int {
  382. return $this->lastSeen;
  383. }
  384. /**
  385. * @phpstan-return ($raw is false ? string : ($microsecond is true ? string : int))
  386. */
  387. public function dateAdded(bool $raw = false, bool $microsecond = false): int|string {
  388. if ($raw) {
  389. if ($microsecond) {
  390. return $this->date_added;
  391. } else {
  392. return (int)substr($this->date_added, 0, -6);
  393. }
  394. } else {
  395. $date = (int)substr($this->date_added, 0, -6);
  396. return timestamptodate($date);
  397. }
  398. }
  399. public function isRead(): ?bool {
  400. return $this->is_read;
  401. }
  402. public function isFavorite(): ?bool {
  403. return $this->is_favorite;
  404. }
  405. /**
  406. * Returns whether the entry has been modified since it was inserted in database.
  407. * @returns bool `true` if the entry already existed (and has been modified), `false` if the entry is new (or unmodified).
  408. */
  409. public function isUpdated(): ?bool {
  410. return $this->is_updated;
  411. }
  412. public function _isUpdated(bool $value): void {
  413. $this->is_updated = $value;
  414. }
  415. public function feed(): ?FreshRSS_Feed {
  416. if ($this->feed === null) {
  417. $feedDAO = FreshRSS_Factory::createFeedDao();
  418. $this->feed = $feedDAO->searchById($this->feedId);
  419. }
  420. return $this->feed;
  421. }
  422. public function feedId(): int {
  423. return $this->feedId;
  424. }
  425. /**
  426. * @phpstan-return ($asString is true ? string : array<string>)
  427. * @return string|array<string>
  428. */
  429. public function tags(bool $asString = false): array|string {
  430. if ($asString) {
  431. return $this->tags == null ? '' : '#' . implode(' #', $this->tags);
  432. } else {
  433. return $this->tags;
  434. }
  435. }
  436. public function hash(): string {
  437. if ($this->hash === '') {
  438. //Do not include $this->date because it may be automatically generated when lacking
  439. $this->hash = md5($this->link . $this->title . $this->authors(true) . $this->originalContent() . $this->tags(true));
  440. }
  441. return $this->hash;
  442. }
  443. public function _hash(string $value): string {
  444. $value = trim($value);
  445. if (ctype_xdigit($value)) {
  446. $this->hash = substr($value, 0, 32);
  447. }
  448. return $this->hash;
  449. }
  450. /** @param int|numeric-string $value String is for compatibility with 32-bit platforms */
  451. public function _id($value): void {
  452. if (is_int($value)) {
  453. $value = (string)$value;
  454. }
  455. $this->id = $value;
  456. if ($this->date_added == 0) {
  457. $this->date_added = $value;
  458. }
  459. }
  460. public function _guid(string $value): void {
  461. $this->guid = trim($value);
  462. }
  463. public function _title(string $value): void {
  464. $this->hash = '';
  465. $this->title = trim($value);
  466. }
  467. /** @deprecated */
  468. public function _author(string $value): void {
  469. $this->_authors($value);
  470. }
  471. /** @param array<string>|string $value */
  472. public function _authors($value): void {
  473. $this->hash = '';
  474. if (!is_array($value)) {
  475. if (str_contains($value, ';')) {
  476. $value = htmlspecialchars_decode($value, ENT_QUOTES);
  477. $value = preg_split('/\s*[;]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  478. $value = Minz_Helper::htmlspecialchars_utf8($value);
  479. } else {
  480. $value = preg_split('/\s*[,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  481. }
  482. }
  483. $this->authors = $value;
  484. }
  485. public function _content(string $value): void {
  486. $this->hash = '';
  487. $this->content = $value;
  488. }
  489. public function _link(string $value): void {
  490. $this->hash = '';
  491. $this->link = trim($value);
  492. }
  493. /** @param int|string $value */
  494. public function _date($value): void {
  495. $value = (int)$value;
  496. $this->date = $value > 1 ? $value : time();
  497. }
  498. public function _lastSeen(int $value): void {
  499. $this->lastSeen = $value > 0 ? $value : 0;
  500. }
  501. /** @param int|string $value */
  502. public function _dateAdded($value, bool $microsecond = false): void {
  503. if ($microsecond) {
  504. $this->date_added = (string)($value);
  505. } else {
  506. $this->date_added = $value . '000000';
  507. }
  508. }
  509. /** @param bool|int|null $value */
  510. public function _isRead($value): void {
  511. $this->is_read = $value === null ? null : (bool)$value;
  512. }
  513. /** @param bool|int|null $value */
  514. public function _isFavorite($value): void {
  515. $this->is_favorite = $value === null ? null : (bool)$value;
  516. }
  517. public function _feed(?FreshRSS_Feed $feed): void {
  518. $this->feed = $feed;
  519. $this->feedId = $this->feed == null ? 0 : $this->feed->id();
  520. }
  521. /** @param int|string $id */
  522. private function _feedId($id): void {
  523. $this->feed = null;
  524. $this->feedId = (int)$id;
  525. }
  526. /** @param array<string>|string $value */
  527. public function _tags($value): void {
  528. $this->hash = '';
  529. if (!is_array($value)) {
  530. $value = preg_split('/\s*[#,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  531. }
  532. $this->tags = $value;
  533. }
  534. public function matches(FreshRSS_BooleanSearch $booleanSearch): bool {
  535. $ok = true;
  536. foreach ($booleanSearch->searches() as $filter) {
  537. if ($filter instanceof FreshRSS_BooleanSearch) {
  538. // BooleanSearches are combined by AND (default) or OR or AND NOT (special cases) operators and are recursive
  539. match ($filter->operator()) {
  540. 'AND' => $ok &= $this->matches($filter),
  541. 'OR' => $ok |= $this->matches($filter),
  542. 'AND NOT' => $ok &= !$this->matches($filter),
  543. 'OR NOT' => $ok |= !$this->matches($filter),
  544. default => $ok &= $this->matches($filter),
  545. };
  546. } elseif ($filter instanceof FreshRSS_Search) {
  547. // Searches are combined by OR and are not recursive
  548. $ok = true;
  549. if ($filter->getEntryIds() !== null) {
  550. $ok &= in_array($this->id, $filter->getEntryIds(), true);
  551. }
  552. if ($ok && $filter->getNotEntryIds() !== null) {
  553. $ok &= !in_array($this->id, $filter->getNotEntryIds(), true);
  554. }
  555. if ($ok && $filter->getMinDate() !== null) {
  556. $ok &= strnatcmp($this->id, $filter->getMinDate() . '000000') >= 0;
  557. }
  558. if ($ok && $filter->getNotMinDate() !== null) {
  559. $ok &= strnatcmp($this->id, $filter->getNotMinDate() . '000000') < 0;
  560. }
  561. if ($ok && $filter->getMaxDate() !== null) {
  562. $ok &= strnatcmp($this->id, $filter->getMaxDate() . '000000') <= 0;
  563. }
  564. if ($ok && $filter->getNotMaxDate() !== null) {
  565. $ok &= strnatcmp($this->id, $filter->getNotMaxDate() . '000000') > 0;
  566. }
  567. if ($ok && $filter->getMinPubdate() !== null) {
  568. $ok &= $this->date >= $filter->getMinPubdate();
  569. }
  570. if ($ok && $filter->getNotMinPubdate() !== null) {
  571. $ok &= $this->date < $filter->getNotMinPubdate();
  572. }
  573. if ($ok && $filter->getMaxPubdate() !== null) {
  574. $ok &= $this->date <= $filter->getMaxPubdate();
  575. }
  576. if ($ok && $filter->getNotMaxPubdate() !== null) {
  577. $ok &= $this->date > $filter->getNotMaxPubdate();
  578. }
  579. if ($ok && $filter->getFeedIds() !== null) {
  580. $ok &= in_array($this->feedId, $filter->getFeedIds(), true);
  581. }
  582. if ($ok && $filter->getNotFeedIds() !== null) {
  583. $ok &= !in_array($this->feedId, $filter->getNotFeedIds(), true);
  584. }
  585. if ($ok && $filter->getAuthor() !== null) {
  586. foreach ($filter->getAuthor() as $author) {
  587. $ok &= stripos(implode(';', $this->authors), $author) !== false;
  588. }
  589. }
  590. if ($ok && $filter->getAuthorRegex() !== null) {
  591. foreach ($filter->getAuthorRegex() as $author) {
  592. $ok &= preg_match($author, implode("\n", $this->authors)) === 1;
  593. }
  594. }
  595. if ($ok && $filter->getNotAuthor() !== null) {
  596. foreach ($filter->getNotAuthor() as $author) {
  597. $ok &= stripos(implode(';', $this->authors), $author) === false;
  598. }
  599. }
  600. if ($ok && $filter->getNotAuthorRegex() !== null) {
  601. foreach ($filter->getNotAuthorRegex() as $author) {
  602. $ok &= preg_match($author, implode("\n", $this->authors)) === 0;
  603. }
  604. }
  605. if ($ok && $filter->getIntitle() !== null) {
  606. foreach ($filter->getIntitle() as $title) {
  607. $ok &= stripos($this->title, $title) !== false;
  608. }
  609. }
  610. if ($ok && $filter->getIntitleRegex() !== null) {
  611. foreach ($filter->getIntitleRegex() as $title) {
  612. $ok &= preg_match($title, $this->title) === 1;
  613. }
  614. }
  615. if ($ok && $filter->getNotIntitle() !== null) {
  616. foreach ($filter->getNotIntitle() as $title) {
  617. $ok &= stripos($this->title, $title) === false;
  618. }
  619. }
  620. if ($ok && $filter->getNotIntitleRegex() !== null) {
  621. foreach ($filter->getNotIntitleRegex() as $title) {
  622. $ok &= preg_match($title, $this->title) === 0;
  623. }
  624. }
  625. if ($ok && $filter->getTags() !== null) {
  626. foreach ($filter->getTags() as $tag2) {
  627. $found = false;
  628. foreach ($this->tags as $tag1) {
  629. $tag1 = ltrim($tag1, '#');
  630. if (strcasecmp($tag1, $tag2) === 0) {
  631. $found = true;
  632. break;
  633. }
  634. }
  635. $ok &= $found;
  636. }
  637. }
  638. if ($ok && $filter->getTagsRegex() !== null) {
  639. foreach ($filter->getTagsRegex() as $tag2) {
  640. $found = false;
  641. foreach ($this->tags as $tag1) {
  642. $tag1 = ltrim($tag1, '#');
  643. if (preg_match($tag2, $tag1) === 1) {
  644. $found = true;
  645. break;
  646. }
  647. }
  648. $ok &= $found;
  649. }
  650. }
  651. if ($ok && $filter->getNotTags() !== null) {
  652. foreach ($filter->getNotTags() as $tag2) {
  653. $found = false;
  654. foreach ($this->tags as $tag1) {
  655. $tag1 = ltrim($tag1, '#');
  656. if (strcasecmp($tag1, $tag2) === 0) {
  657. $found = true;
  658. break;
  659. }
  660. }
  661. $ok &= !$found;
  662. }
  663. }
  664. if ($ok && $filter->getNotTagsRegex() !== null) {
  665. foreach ($filter->getNotTagsRegex() as $tag2) {
  666. $found = false;
  667. foreach ($this->tags as $tag1) {
  668. $tag1 = ltrim($tag1, '#');
  669. if (preg_match($tag2, $tag1) === 1) {
  670. $found = true;
  671. break;
  672. }
  673. }
  674. $ok &= !$found;
  675. }
  676. }
  677. if ($ok && $filter->getInurl() !== null) {
  678. foreach ($filter->getInurl() as $url) {
  679. $ok &= stripos($this->link, $url) !== false;
  680. }
  681. }
  682. if ($ok && $filter->getInurlRegex() !== null) {
  683. foreach ($filter->getInurlRegex() as $url) {
  684. $ok &= preg_match($url, $this->link) === 1;
  685. }
  686. }
  687. if ($ok && $filter->getNotInurl() !== null) {
  688. foreach ($filter->getNotInurl() as $url) {
  689. $ok &= stripos($this->link, $url) === false;
  690. }
  691. }
  692. if ($ok && $filter->getNotInurlRegex() !== null) {
  693. foreach ($filter->getNotInurlRegex() as $url) {
  694. $ok &= preg_match($url, $this->link) === 0;
  695. }
  696. }
  697. if ($ok && $filter->getSearch() !== null) {
  698. foreach ($filter->getSearch() as $needle) {
  699. $ok &= (stripos($this->title, $needle) !== false || stripos($this->content, $needle) !== false);
  700. }
  701. }
  702. if ($ok && $filter->getNotSearch() !== null) {
  703. foreach ($filter->getNotSearch() as $needle) {
  704. $ok &= (stripos($this->title, $needle) === false && stripos($this->content, $needle) === false);
  705. }
  706. }
  707. if ($ok && $filter->getSearchRegex() !== null) {
  708. foreach ($filter->getSearchRegex() as $needle) {
  709. $ok &= (preg_match($needle, $this->title) === 1 || preg_match($needle, $this->content) === 1);
  710. }
  711. }
  712. if ($ok && $filter->getNotSearchRegex() !== null) {
  713. foreach ($filter->getNotSearchRegex() as $needle) {
  714. $ok &= (preg_match($needle, $this->title) === 0 && preg_match($needle, $this->content) === 0);
  715. }
  716. }
  717. if ($ok) {
  718. return true;
  719. }
  720. }
  721. }
  722. return (bool)$ok;
  723. }
  724. /** @param array<string,bool|int> $titlesAsRead */
  725. public function applyFilterActions(array $titlesAsRead = []): void {
  726. $feed = $this->feed;
  727. if ($feed === null) {
  728. return;
  729. }
  730. if (!$this->isRead()) {
  731. if ($feed->attributeBoolean('read_upon_reception') ?? FreshRSS_Context::userConf()->mark_when['reception']) {
  732. $this->_isRead(true);
  733. Minz_ExtensionManager::callHook('entry_auto_read', $this, 'upon_reception');
  734. }
  735. if (!empty($titlesAsRead[$this->title()])) {
  736. Minz_Log::debug('Mark title as read: ' . $this->title());
  737. $this->_isRead(true);
  738. Minz_ExtensionManager::callHook('entry_auto_read', $this, 'same_title_in_feed');
  739. }
  740. }
  741. FreshRSS_Context::userConf()->applyFilterActions($this);
  742. $feed->category()?->applyFilterActions($this);
  743. $feed->applyFilterActions($this);
  744. }
  745. public function isDay(int $day, int $today): bool {
  746. $date = $this->dateAdded(true);
  747. switch ($day) {
  748. case FreshRSS_Days::TODAY:
  749. $tomorrow = $today + 86400;
  750. return $date >= $today && $date < $tomorrow;
  751. case FreshRSS_Days::YESTERDAY:
  752. $yesterday = $today - 86400;
  753. return $date >= $yesterday && $date < $today;
  754. case FreshRSS_Days::BEFORE_YESTERDAY:
  755. $yesterday = $today - 86400;
  756. return $date < $yesterday;
  757. default:
  758. return false;
  759. }
  760. }
  761. /**
  762. * @param string $url Overridden URL. Will default to the entry URL.
  763. * @throws Minz_Exception
  764. */
  765. public function getContentByParsing(string $url = '', int $maxRedirs = 3): string {
  766. $url = $url ?: htmlspecialchars_decode($this->link(), ENT_QUOTES);
  767. $feed = $this->feed();
  768. if ($url === '' || $feed === null || $feed->pathEntries() === '') {
  769. return '';
  770. }
  771. $conditions = $feed->attributeArray('path_entries_conditions') ?? [];
  772. $conditions = array_filter(array_map(fn($v) => is_string($v) ? trim($v) : '', $conditions));
  773. if (count($conditions) > 0) {
  774. $found = false;
  775. foreach ($conditions as $condition) {
  776. if (!is_string($condition) || trim($condition) === '') {
  777. continue;
  778. }
  779. $booleanSearch = new FreshRSS_BooleanSearch($condition);
  780. if ($this->matches($booleanSearch)) {
  781. $found = true;
  782. break;
  783. }
  784. }
  785. if (!$found) {
  786. return '';
  787. }
  788. }
  789. $cachePath = $feed->cacheFilename($url . '#' . $feed->pathEntries());
  790. $html = httpGet($url, $cachePath, 'html', $feed->attributes(), $feed->curlOptions());
  791. if (strlen($html) > 0) {
  792. $doc = new DOMDocument();
  793. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  794. $xpath = new DOMXPath($doc);
  795. if ($maxRedirs > 0) {
  796. //Follow any HTML redirection
  797. $metas = $xpath->query('//meta[@content]') ?: [];
  798. foreach ($metas as $meta) {
  799. if ($meta instanceof DOMElement && strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') {
  800. $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content')));
  801. $refresh = is_string($refresh) ? \SimplePie\Misc::absolutize_url($refresh, $url) : false;
  802. if ($refresh != false && $refresh !== $url) {
  803. return $this->getContentByParsing($refresh, $maxRedirs - 1);
  804. }
  805. }
  806. }
  807. }
  808. $base = $xpath->evaluate('normalize-space(//base/@href)');
  809. if ($base == false || !is_string($base)) {
  810. $base = $url;
  811. } elseif (str_starts_with($base, '//')) {
  812. //Protocol-relative URLs "//www.example.net"
  813. $base = (parse_url($url, PHP_URL_SCHEME) ?? 'https') . ':' . $base;
  814. }
  815. $html = '';
  816. $cssSelector = htmlspecialchars_decode($feed->pathEntries(), ENT_QUOTES);
  817. $cssSelector = trim($cssSelector, ', ');
  818. $path_entries_filter = trim($feed->attributeString('path_entries_filter') ?? '', ', ');
  819. $nodes = $xpath->query((new Gt\CssXPath\Translator($cssSelector, '//'))->asXPath());
  820. if ($nodes != false) {
  821. $filter_xpath = $path_entries_filter === '' ? '' : (new Gt\CssXPath\Translator($path_entries_filter, 'descendant-or-self::'))->asXPath();
  822. foreach ($nodes as $node) {
  823. if ($filter_xpath !== '') {
  824. // Remove unwanted elements once before sanitizing, for CSS selectors to also match original content
  825. $filterednodes = $xpath->query($filter_xpath, $node) ?: [];
  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($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. }