4
0

Entry.php 39 KB

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