Entry.php 40 KB

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