Entry.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. $attributes = empty($this->attributeArray('enclosures')) ? '' : json_encode($this->attributes(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  447. //Do not include $this->date because it may be automatically generated when lacking
  448. $this->hash = md5($this->link . $this->title . $this->authors(true) . $this->originalContent() . $this->tags(true) . $attributes);
  449. }
  450. return $this->hash;
  451. }
  452. public function _hash(string $value): string {
  453. $value = trim($value);
  454. if (ctype_xdigit($value)) {
  455. $this->hash = substr($value, 0, 32);
  456. }
  457. return $this->hash;
  458. }
  459. /** @param int|numeric-string $value String is for compatibility with 32-bit platforms */
  460. public function _id(int|string $value): void {
  461. if (is_int($value)) {
  462. $value = (string)$value;
  463. }
  464. $this->id = $value;
  465. if ($this->date_added == 0) {
  466. $this->date_added = $value;
  467. }
  468. }
  469. public function _guid(string $value): void {
  470. $this->guid = trim($value);
  471. }
  472. public function _title(string $value): void {
  473. $this->hash = '';
  474. $this->title = trim($value);
  475. }
  476. /** @deprecated */
  477. public function _author(string $value): void {
  478. $this->_authors($value);
  479. }
  480. /** @param array<string>|string $value */
  481. public function _authors(array|string $value): void {
  482. $this->hash = '';
  483. if (!is_array($value)) {
  484. if (str_contains($value, ';')) {
  485. $value = htmlspecialchars_decode($value, ENT_QUOTES);
  486. $value = preg_split('/\s*[;]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  487. $value = Minz_Helper::htmlspecialchars_utf8($value);
  488. } else {
  489. $value = preg_split('/\s*[,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  490. }
  491. }
  492. $this->authors = $value;
  493. }
  494. public function _content(string $value): void {
  495. $this->hash = '';
  496. $this->content = $value;
  497. }
  498. public function _link(string $value): void {
  499. $this->hash = '';
  500. $this->link = trim($value);
  501. }
  502. /** @param int|numeric-string $value */
  503. public function _date(int|string $value): void {
  504. $value = (int)$value;
  505. $this->date = $value > 1 ? $value : time();
  506. }
  507. /**
  508. * @param int|numeric-string $value
  509. * 32-bit systems provide a string and will fail in year 2038
  510. */
  511. public function _lastSeen(int|string $value): void {
  512. $value = (int)$value;
  513. $this->lastSeen = $value > 0 ? $value : 0;
  514. }
  515. /** @param int|numeric-string $value */
  516. public function _dateAdded(int|string $value, bool $microsecond = false): void {
  517. if ($microsecond) {
  518. $this->date_added = (string)($value);
  519. } else {
  520. $this->date_added = $value . '000000';
  521. }
  522. }
  523. public function _isRead(bool|int|null $value): void {
  524. $this->is_read = $value === null ? null : (bool)$value;
  525. }
  526. public function _isFavorite(bool|int|null $value): void {
  527. $this->is_favorite = $value === null ? null : (bool)$value;
  528. }
  529. public function _feed(?FreshRSS_Feed $feed): void {
  530. $this->feed = $feed;
  531. $this->feedId = $this->feed == null ? 0 : $this->feed->id();
  532. }
  533. private function _feedId(int $id): void {
  534. $this->feed = null;
  535. $this->feedId = $id;
  536. }
  537. /** @param array<string>|string $value */
  538. public function _tags(array|string $value): void {
  539. $this->hash = '';
  540. if (!is_array($value)) {
  541. $value = preg_split('/\s*[#,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  542. }
  543. $this->tags = $value;
  544. }
  545. public function matches(FreshRSS_BooleanSearch $booleanSearch): bool {
  546. $ok = true;
  547. foreach ($booleanSearch->searches() as $filter) {
  548. if ($filter instanceof FreshRSS_BooleanSearch) {
  549. // BooleanSearches are combined by AND (default) or OR or AND NOT (special cases) operators and are recursive
  550. match ($filter->operator()) {
  551. 'AND' => $ok &= $this->matches($filter),
  552. 'OR' => $ok |= $this->matches($filter),
  553. 'AND NOT' => $ok &= !$this->matches($filter),
  554. 'OR NOT' => $ok |= !$this->matches($filter),
  555. default => $ok &= $this->matches($filter),
  556. };
  557. } elseif ($filter instanceof FreshRSS_Search) {
  558. // Searches are combined by OR and are not recursive
  559. $ok = true;
  560. if ($filter->getEntryIds() !== null) {
  561. $ok &= in_array($this->id, $filter->getEntryIds(), true);
  562. }
  563. if ($ok && $filter->getNotEntryIds() !== null) {
  564. $ok &= !in_array($this->id, $filter->getNotEntryIds(), true);
  565. }
  566. if ($ok && $filter->getMinDate() !== null) {
  567. $ok &= strnatcmp($this->id, $filter->getMinDate() . '000000') >= 0;
  568. }
  569. if ($ok && $filter->getNotMinDate() !== null) {
  570. $ok &= strnatcmp($this->id, $filter->getNotMinDate() . '000000') < 0;
  571. }
  572. if ($ok && $filter->getMaxDate() !== null) {
  573. $ok &= strnatcmp($this->id, $filter->getMaxDate() . '000000') <= 0;
  574. }
  575. if ($ok && $filter->getNotMaxDate() !== null) {
  576. $ok &= strnatcmp($this->id, $filter->getNotMaxDate() . '000000') > 0;
  577. }
  578. if ($ok && $filter->getMinPubdate() !== null) {
  579. $ok &= $this->date >= $filter->getMinPubdate();
  580. }
  581. if ($ok && $filter->getNotMinPubdate() !== null) {
  582. $ok &= $this->date < $filter->getNotMinPubdate();
  583. }
  584. if ($ok && $filter->getMaxPubdate() !== null) {
  585. $ok &= $this->date <= $filter->getMaxPubdate();
  586. }
  587. if ($ok && $filter->getNotMaxPubdate() !== null) {
  588. $ok &= $this->date > $filter->getNotMaxPubdate();
  589. }
  590. if ($ok && $filter->getFeedIds() !== null) {
  591. $ok &= in_array($this->feedId, $filter->getFeedIds(), true);
  592. }
  593. if ($ok && $filter->getNotFeedIds() !== null) {
  594. $ok &= !in_array($this->feedId, $filter->getNotFeedIds(), true);
  595. }
  596. if ($ok && $filter->getCategoryIds() !== null) {
  597. $ok &= in_array($this->feed()?->categoryId(), $filter->getCategoryIds(), true);
  598. }
  599. if ($ok && $filter->getNotCategoryIds() !== null) {
  600. $ok &= !in_array($this->feed()?->categoryId(), $filter->getNotCategoryIds(), true);
  601. }
  602. if ($ok && $filter->getAuthor() !== null) {
  603. foreach ($filter->getAuthor() as $author) {
  604. $ok &= stripos(implode(';', $this->authors), $author) !== false;
  605. }
  606. }
  607. if ($ok && $filter->getAuthorRegex() !== null) {
  608. foreach ($filter->getAuthorRegex() as $author) {
  609. $ok &= preg_match($author, implode("\n", $this->authors)) === 1;
  610. }
  611. }
  612. if ($ok && $filter->getNotAuthor() !== null) {
  613. foreach ($filter->getNotAuthor() as $author) {
  614. $ok &= stripos(implode(';', $this->authors), $author) === false;
  615. }
  616. }
  617. if ($ok && $filter->getNotAuthorRegex() !== null) {
  618. foreach ($filter->getNotAuthorRegex() as $author) {
  619. $ok &= preg_match($author, implode("\n", $this->authors)) === 0;
  620. }
  621. }
  622. if ($ok && $filter->getIntitle() !== null) {
  623. foreach ($filter->getIntitle() as $title) {
  624. $ok &= stripos($this->title, $title) !== false;
  625. }
  626. }
  627. if ($ok && $filter->getIntitleRegex() !== null) {
  628. foreach ($filter->getIntitleRegex() as $title) {
  629. $ok &= preg_match($title, $this->title) === 1;
  630. }
  631. }
  632. if ($ok && $filter->getNotIntitle() !== null) {
  633. foreach ($filter->getNotIntitle() as $title) {
  634. $ok &= stripos($this->title, $title) === false;
  635. }
  636. }
  637. if ($ok && $filter->getNotIntitleRegex() !== null) {
  638. foreach ($filter->getNotIntitleRegex() as $title) {
  639. $ok &= preg_match($title, $this->title) === 0;
  640. }
  641. }
  642. if ($ok && $filter->getIntext() !== null) {
  643. foreach ($filter->getIntext() as $content) {
  644. $ok &= stripos($this->content, $content) !== false;
  645. }
  646. }
  647. if ($ok && $filter->getIntextRegex() !== null) {
  648. foreach ($filter->getIntextRegex() as $content) {
  649. $ok &= preg_match($content, $this->content) === 1;
  650. }
  651. }
  652. if ($ok && $filter->getNotIntext() !== null) {
  653. foreach ($filter->getNotIntext() as $content) {
  654. $ok &= stripos($this->content, $content) === false;
  655. }
  656. }
  657. if ($ok && $filter->getNotIntextRegex() !== null) {
  658. foreach ($filter->getNotIntextRegex() as $content) {
  659. $ok &= preg_match($content, $this->content) === 0;
  660. }
  661. }
  662. if ($ok && $filter->getTags() !== null) {
  663. foreach ($filter->getTags() as $tag2) {
  664. $found = false;
  665. foreach ($this->tags as $tag1) {
  666. $tag1 = ltrim($tag1, '#');
  667. if (strcasecmp($tag1, $tag2) === 0) {
  668. $found = true;
  669. break;
  670. }
  671. }
  672. $ok &= $found;
  673. }
  674. }
  675. if ($ok && $filter->getTagsRegex() !== null) {
  676. foreach ($filter->getTagsRegex() as $tag2) {
  677. $found = false;
  678. foreach ($this->tags as $tag1) {
  679. $tag1 = ltrim($tag1, '#');
  680. if (preg_match($tag2, $tag1) === 1) {
  681. $found = true;
  682. break;
  683. }
  684. }
  685. $ok &= $found;
  686. }
  687. }
  688. if ($ok && $filter->getNotTags() !== null) {
  689. foreach ($filter->getNotTags() as $tag2) {
  690. $found = false;
  691. foreach ($this->tags as $tag1) {
  692. $tag1 = ltrim($tag1, '#');
  693. if (strcasecmp($tag1, $tag2) === 0) {
  694. $found = true;
  695. break;
  696. }
  697. }
  698. $ok &= !$found;
  699. }
  700. }
  701. if ($ok && $filter->getNotTagsRegex() !== null) {
  702. foreach ($filter->getNotTagsRegex() as $tag2) {
  703. $found = false;
  704. foreach ($this->tags as $tag1) {
  705. $tag1 = ltrim($tag1, '#');
  706. if (preg_match($tag2, $tag1) === 1) {
  707. $found = true;
  708. break;
  709. }
  710. }
  711. $ok &= !$found;
  712. }
  713. }
  714. if ($ok && $filter->getInurl() !== null) {
  715. foreach ($filter->getInurl() as $url) {
  716. $ok &= stripos($this->link, $url) !== false;
  717. }
  718. }
  719. if ($ok && $filter->getInurlRegex() !== null) {
  720. foreach ($filter->getInurlRegex() as $url) {
  721. $ok &= preg_match($url, $this->link) === 1;
  722. }
  723. }
  724. if ($ok && $filter->getNotInurl() !== null) {
  725. foreach ($filter->getNotInurl() as $url) {
  726. $ok &= stripos($this->link, $url) === false;
  727. }
  728. }
  729. if ($ok && $filter->getNotInurlRegex() !== null) {
  730. foreach ($filter->getNotInurlRegex() as $url) {
  731. $ok &= preg_match($url, $this->link) === 0;
  732. }
  733. }
  734. if ($ok && $filter->getSearch() !== null) {
  735. foreach ($filter->getSearch() as $needle) {
  736. $ok &= (stripos($this->title, $needle) !== false || stripos($this->content, $needle) !== false);
  737. }
  738. }
  739. if ($ok && $filter->getNotSearch() !== null) {
  740. foreach ($filter->getNotSearch() as $needle) {
  741. $ok &= (stripos($this->title, $needle) === false && stripos($this->content, $needle) === false);
  742. }
  743. }
  744. if ($ok && $filter->getSearchRegex() !== null) {
  745. foreach ($filter->getSearchRegex() as $needle) {
  746. $ok &= (preg_match($needle, $this->title) === 1 || preg_match($needle, $this->content) === 1);
  747. }
  748. }
  749. if ($ok && $filter->getNotSearchRegex() !== null) {
  750. foreach ($filter->getNotSearchRegex() as $needle) {
  751. $ok &= (preg_match($needle, $this->title) === 0 && preg_match($needle, $this->content) === 0);
  752. }
  753. }
  754. if ($ok) {
  755. return true;
  756. }
  757. }
  758. }
  759. return (bool)$ok;
  760. }
  761. /** @param array<string,bool|int> $titlesAsRead */
  762. public function applyFilterActions(array $titlesAsRead = []): void {
  763. $feed = $this->feed;
  764. if ($feed === null) {
  765. return;
  766. }
  767. if (!$this->isRead()) {
  768. if ($feed->attributeBoolean('read_upon_reception') ?? FreshRSS_Context::userConf()->mark_when['reception']) {
  769. $this->_isRead(true);
  770. Minz_ExtensionManager::callHook('entry_auto_read', $this, 'upon_reception');
  771. }
  772. if (!empty($titlesAsRead[$this->title()])) {
  773. Minz_Log::debug('Mark title as read: ' . $this->title());
  774. $this->_isRead(true);
  775. Minz_ExtensionManager::callHook('entry_auto_read', $this, 'same_title_in_feed');
  776. }
  777. }
  778. FreshRSS_Context::userConf()->applyFilterActions($this);
  779. $feed->category()?->applyFilterActions($this);
  780. $feed->applyFilterActions($this);
  781. }
  782. public function isDay(int $day, int $today): bool {
  783. $date = $this->dateAdded(true);
  784. switch ($day) {
  785. case FreshRSS_Days::TODAY:
  786. $tomorrow = $today + 86400;
  787. return $date >= $today && $date < $tomorrow;
  788. case FreshRSS_Days::YESTERDAY:
  789. $yesterday = $today - 86400;
  790. return $date >= $yesterday && $date < $today;
  791. case FreshRSS_Days::BEFORE_YESTERDAY:
  792. $yesterday = $today - 86400;
  793. return $date < $yesterday;
  794. default:
  795. return false;
  796. }
  797. }
  798. /**
  799. * @param string $url Overridden URL. Will default to the entry URL.
  800. * @throws Minz_Exception
  801. */
  802. public function getContentByParsing(string $url = '', int $maxRedirs = 4): string {
  803. $url = $url ?: htmlspecialchars_decode($this->link(), ENT_QUOTES);
  804. $feed = $this->feed();
  805. if ($url === '' || $feed === null || $feed->pathEntries() === '') {
  806. return '';
  807. }
  808. $conditions = $feed->attributeArray('path_entries_conditions') ?? [];
  809. $conditions = array_filter($conditions, fn($v): bool => (is_string($v) ? trim($v) : '') !== '');
  810. if (count($conditions) > 0) {
  811. $found = false;
  812. foreach ($conditions as $condition) {
  813. if (!is_string($condition) || trim($condition) === '') {
  814. continue;
  815. }
  816. $booleanSearch = new FreshRSS_BooleanSearch($condition);
  817. if ($this->matches($booleanSearch)) {
  818. $found = true;
  819. break;
  820. }
  821. }
  822. if (!$found) {
  823. return '';
  824. }
  825. }
  826. $cachePath = $feed->cacheFilename($url . '#' . $feed->pathEntries());
  827. $response = httpGet($url, $cachePath, 'html', $feed->attributes(), $feed->curlOptions());
  828. $html = $response['body'];
  829. if ($html !== '') {
  830. $doc = new DOMDocument();
  831. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  832. $xpath = new DOMXPath($doc);
  833. // Account for HTTP redirections
  834. $url = $response['effective_url'] ?: $url;
  835. $maxRedirs -= $response['redirect_count'];
  836. if ($maxRedirs > 0) {
  837. //Follow any HTML redirection
  838. $metas = $xpath->query('//meta[@content]') ?: [];
  839. foreach ($metas as $meta) {
  840. if ($meta instanceof DOMElement && strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') {
  841. $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content')));
  842. $refresh = is_string($refresh) ? \SimplePie\Misc::absolutize_url($refresh, $url) : false;
  843. if ($refresh != false && $refresh !== $url) {
  844. return $this->getContentByParsing($refresh, $maxRedirs - 1);
  845. }
  846. }
  847. }
  848. }
  849. $base = $xpath->evaluate('normalize-space(//base/@href)');
  850. if ($base == false || !is_string($base)) {
  851. $base = $url;
  852. } elseif (str_starts_with($base, '//')) {
  853. //Protocol-relative URLs "//www.example.net"
  854. $base = (parse_url($url, PHP_URL_SCHEME) ?? 'https') . ':' . $base;
  855. }
  856. $html = '';
  857. $cssSelector = htmlspecialchars_decode($feed->pathEntries(), ENT_QUOTES);
  858. $cssSelector = trim($cssSelector, ', ');
  859. $path_entries_filter = trim($feed->attributeString('path_entries_filter') ?? '', ', ');
  860. $nodes = $xpath->query((new Gt\CssXPath\Translator($cssSelector, '//'))->asXPath());
  861. if ($nodes != false) {
  862. $filter_xpath = $path_entries_filter === '' ? '' : (new Gt\CssXPath\Translator($path_entries_filter, 'descendant-or-self::'))->asXPath();
  863. foreach ($nodes as $node) {
  864. if ($filter_xpath !== '' && ($filterednodes = $xpath->query($filter_xpath, $node)) !== false) {
  865. // Remove unwanted elements once before sanitizing, for CSS selectors to also match original content
  866. foreach ($filterednodes as $filterednode) {
  867. if ($filterednode === $node) {
  868. continue 2;
  869. }
  870. if (!($filterednode instanceof DOMElement) || $filterednode->parentNode === null) {
  871. continue;
  872. }
  873. $filterednode->parentNode->removeChild($filterednode);
  874. }
  875. }
  876. $html .= $doc->saveHTML($node) . "\n";
  877. }
  878. }
  879. unset($xpath, $doc);
  880. $html = sanitizeHTML($html, $base);
  881. if ($path_entries_filter !== '') {
  882. // Remove unwanted elements again after sanitizing, for CSS selectors to also match sanitized content
  883. $modified = false;
  884. $doc = new DOMDocument();
  885. $utf8BOM = "\xEF\xBB\xBF";
  886. $doc->loadHTML($utf8BOM . $html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  887. $xpath = new DOMXPath($doc);
  888. $filterednodes = $xpath->query((new Gt\CssXPath\Translator($path_entries_filter, '//'))->asXPath()) ?: [];
  889. foreach ($filterednodes as $filterednode) {
  890. if (!($filterednode instanceof DOMElement) || $filterednode->parentNode === null) {
  891. continue;
  892. }
  893. $filterednode->parentNode->removeChild($filterednode);
  894. $modified = true;
  895. }
  896. if ($modified) {
  897. $html = $doc->saveHTML($doc->getElementsByTagName('body')->item(0) ?? $doc->firstElementChild) ?: $html;
  898. }
  899. }
  900. return trim($html);
  901. } else {
  902. throw new Minz_Exception();
  903. }
  904. }
  905. /**
  906. * @return bool True if the content was modified, false otherwise
  907. */
  908. public function loadCompleteContent(bool $force = false): bool {
  909. // Gestion du contenu
  910. // Trying to fetch full article content even when feeds do not propose it
  911. $feed = $this->feed();
  912. if ($feed === null) {
  913. return false;
  914. }
  915. if (trim($feed->pathEntries()) != '') {
  916. $entryDAO = FreshRSS_Factory::createEntryDao();
  917. $entry = $force ? null : $entryDAO->searchByGuid($this->feedId, $this->guid);
  918. if ($entry !== null) {
  919. // l’article existe déjà en BDD, en se contente de recharger ce contenu
  920. $this->content = $entry->content(false);
  921. } else {
  922. try {
  923. // The article is not yet in the database, so let’s fetch it
  924. $fullContent = $this->getContentByParsing();
  925. if ('' !== $fullContent) {
  926. $fullContent = "<!-- FULLCONTENT start //-->{$fullContent}<!-- FULLCONTENT end //-->";
  927. $originalContent = $this->originalContent();
  928. switch ($feed->attributeString('content_action')) {
  929. case 'prepend':
  930. $this->_attribute('original_content');
  931. $this->content = $fullContent . $originalContent;
  932. break;
  933. case 'append':
  934. $this->_attribute('original_content');
  935. $this->content = $originalContent . $fullContent;
  936. break;
  937. case 'replace':
  938. default:
  939. $this->_attribute('original_content', $originalContent);
  940. $this->content = $fullContent;
  941. break;
  942. }
  943. return true;
  944. }
  945. } catch (Exception $e) {
  946. // rien à faire, on garde l’ancien contenu(requête a échoué)
  947. Minz_Log::warning($e->getMessage());
  948. }
  949. }
  950. } elseif (trim($feed->attributeString('path_entries_filter') ?? '') !== '') {
  951. $originalContent = $this->attributeString('original_content') ?? $this->content;
  952. $doc = new DOMDocument();
  953. $utf8BOM = "\xEF\xBB\xBF";
  954. if (!$doc->loadHTML($utf8BOM . $originalContent, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) {
  955. return false;
  956. }
  957. $xpath = new DOMXPath($doc);
  958. $filterednodes = $xpath->query((new Gt\CssXPath\Translator($feed->attributeString('path_entries_filter') ?? '', '//'))->asXPath()) ?: [];
  959. foreach ($filterednodes as $filterednode) {
  960. if (!($filterednode instanceof DOMElement) || $filterednode->parentNode === null) {
  961. continue;
  962. }
  963. $filterednode->parentNode->removeChild($filterednode);
  964. }
  965. $html = $doc->saveHTML($doc->getElementsByTagName('body')->item(0) ?? $doc->firstElementChild);
  966. if (!is_string($html)) {
  967. return false;
  968. }
  969. $html = preg_replace('%^\s*<body>\s*|\s*</body>\s*$%i', '', $html);
  970. $this->_attribute('original_content');
  971. if (is_string($html) && $this->content !== $html) {
  972. $this->_attribute('original_content', $originalContent);
  973. $this->content = $html;
  974. return true;
  975. }
  976. } else {
  977. $originalContent = $this->originalContent();
  978. if ($originalContent !== $this->content) {
  979. $this->content = $originalContent;
  980. return true;
  981. }
  982. }
  983. return false;
  984. }
  985. /**
  986. * @return array{'id':string,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,'lastSeen':int,
  987. * 'hash':string,'is_read':?bool,'is_favorite':?bool,'id_feed':int,'tags':string,'attributes':array<string,mixed>}
  988. */
  989. public function toArray(): array {
  990. return [
  991. 'id' => $this->id(),
  992. 'guid' => $this->guid(),
  993. 'title' => $this->title(),
  994. 'author' => $this->authors(true),
  995. 'content' => $this->content(false),
  996. 'link' => $this->link(raw: true),
  997. 'date' => $this->date(true),
  998. 'lastSeen' => $this->lastSeen(),
  999. 'hash' => $this->hash(),
  1000. 'is_read' => $this->isRead(),
  1001. 'is_favorite' => $this->isFavorite(),
  1002. 'id_feed' => $this->feedId(),
  1003. 'tags' => $this->tags(true),
  1004. 'attributes' => $this->attributes(),
  1005. ];
  1006. }
  1007. /**
  1008. * @return array{array<string>,array<string>} Array of first tags to show, then array of remaining tags
  1009. */
  1010. public function tagsFormattingHelper(): array {
  1011. $firstTags = [];
  1012. $remainingTags = [];
  1013. if (FreshRSS_Context::hasUserConf() && in_array(FreshRSS_Context::userConf()->show_tags, ['b', 'f', 'h'], true)) {
  1014. $maxTagsDisplayed = (int)FreshRSS_Context::userConf()->show_tags_max;
  1015. $tags = $this->tags();
  1016. if (!empty($tags)) {
  1017. if ($maxTagsDisplayed > 0) {
  1018. $firstTags = array_slice($tags, 0, $maxTagsDisplayed);
  1019. $remainingTags = array_slice($tags, $maxTagsDisplayed);
  1020. } else {
  1021. $firstTags = $tags;
  1022. }
  1023. }
  1024. }
  1025. return [$firstTags,$remainingTags];
  1026. }
  1027. /**
  1028. * Integer format conversion for Google Reader API format
  1029. * @param numeric-string|int $dec Decimal number
  1030. * @return string 64-bit hexa http://code.google.com/p/google-reader-api/wiki/ItemId
  1031. */
  1032. private static function dec2hex(string|int $dec): string {
  1033. return PHP_INT_SIZE < 8 ? // 32-bit ?
  1034. str_pad(gmp_strval(gmp_init($dec, 10), 16), 16, '0', STR_PAD_LEFT) :
  1035. str_pad(dechex((int)($dec)), 16, '0', STR_PAD_LEFT);
  1036. }
  1037. /**
  1038. * Some clients (tested with News+) would fail if sending too long item content
  1039. * @var int
  1040. */
  1041. public const API_MAX_COMPAT_CONTENT_LENGTH = 500000;
  1042. /**
  1043. * N.B.: To avoid expensive lookups, ensure to set `$entry->_feed($feed)` before calling this function.
  1044. * @param string $mode Set to `'compat'` to use an alternative Unicode representation for problematic HTML special characters not decoded by some clients;
  1045. * set to `'freshrss'` for using FreshRSS additions for internal use (e.g. export/import).
  1046. * @param array<string> $labels List of labels associated to this entry.
  1047. * @return array<string,mixed> A representation of this entry in a format compatible with Google Reader API
  1048. */
  1049. public function toGReader(string $mode = '', array $labels = []): array {
  1050. $feed = $this->feed();
  1051. $category = $feed == null ? null : $feed->category();
  1052. $item = [
  1053. 'id' => 'tag:google.com,2005:reader/item/' . self::dec2hex($this->id()),
  1054. 'crawlTimeMsec' => substr($this->dateAdded(true, true), 0, -3),
  1055. 'timestampUsec' => '' . $this->dateAdded(true, true), //EasyRSS & Reeder
  1056. 'published' => $this->date(true),
  1057. // 'updated' => $this->date(true),
  1058. 'title' => $this->title(),
  1059. 'canonical' => [
  1060. ['href' => htmlspecialchars_decode($this->link(), ENT_QUOTES)],
  1061. ],
  1062. 'alternate' => [
  1063. [
  1064. 'href' => htmlspecialchars_decode($this->link(), ENT_QUOTES),
  1065. 'type' => 'text/html',
  1066. ],
  1067. ],
  1068. 'categories' => [
  1069. 'user/-/state/com.google/reading-list',
  1070. ],
  1071. 'origin' => [
  1072. 'streamId' => 'feed/' . $this->feedId,
  1073. ],
  1074. ];
  1075. if ($mode === 'compat') {
  1076. $item['title'] = escapeToUnicodeAlternative($this->title(), false);
  1077. unset($item['alternate'][0]['type']);
  1078. $item['summary'] = [
  1079. 'content' => mb_strcut($this->content(true), 0, self::API_MAX_COMPAT_CONTENT_LENGTH, 'UTF-8'),
  1080. ];
  1081. } else {
  1082. $item['content'] = [
  1083. 'content' => $this->content(false),
  1084. ];
  1085. }
  1086. if ($mode === 'freshrss') {
  1087. $item['guid'] = $this->guid();
  1088. }
  1089. if ($category != null && $mode !== 'freshrss') {
  1090. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($category->name(), ENT_QUOTES);
  1091. }
  1092. if ($feed !== null) {
  1093. $item['origin']['htmlUrl'] = htmlspecialchars_decode($feed->website());
  1094. $item['origin']['title'] = $feed->name(); //EasyRSS
  1095. if ($mode === 'compat') {
  1096. $item['origin']['title'] = escapeToUnicodeAlternative($feed->name(), true);
  1097. } elseif ($mode === 'freshrss') {
  1098. $item['origin']['feedUrl'] = htmlspecialchars_decode($feed->url());
  1099. }
  1100. }
  1101. foreach ($this->enclosures() as $enclosure) {
  1102. if (!empty($enclosure['url'])) {
  1103. $media = [
  1104. 'href' => $enclosure['url'],
  1105. 'type' => $enclosure['type'] ?? $enclosure['medium'] ??
  1106. (self::enclosureIsImage($enclosure) ? 'image' : ''),
  1107. ];
  1108. if (!empty($enclosure['length'])) {
  1109. $media['length'] = (int)$enclosure['length'];
  1110. }
  1111. $item['enclosure'][] = $media;
  1112. }
  1113. }
  1114. $author = $this->authors(true);
  1115. $author = trim($author, '; ');
  1116. if ($author != '') {
  1117. if ($mode === 'compat') {
  1118. $item['author'] = escapeToUnicodeAlternative($author, false);
  1119. } else {
  1120. $item['author'] = $author;
  1121. }
  1122. }
  1123. if ($this->isRead()) {
  1124. $item['categories'][] = 'user/-/state/com.google/read';
  1125. } elseif ($mode === 'freshrss') {
  1126. $item['categories'][] = 'user/-/state/com.google/unread';
  1127. }
  1128. if ($this->isFavorite()) {
  1129. $item['categories'][] = 'user/-/state/com.google/starred';
  1130. }
  1131. foreach ($labels as $labelName) {
  1132. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($labelName, ENT_QUOTES);
  1133. }
  1134. foreach ($this->tags() as $tagName) {
  1135. $item['categories'][] = htmlspecialchars_decode($tagName, ENT_QUOTES);
  1136. }
  1137. return $item;
  1138. }
  1139. }