Entry.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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(Minz_HookType::EntryAutoRead, $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(Minz_HookType::EntryAutoRead, $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. 'frss:id' => $this->id(),
  1054. 'id' => 'tag:google.com,2005:reader/item/' . self::dec2hex($this->id()),
  1055. 'crawlTimeMsec' => substr($this->dateAdded(true, true), 0, -3),
  1056. 'timestampUsec' => '' . $this->dateAdded(true, true), //EasyRSS & Reeder
  1057. 'published' => $this->date(true),
  1058. // 'updated' => $this->date(true),
  1059. 'title' => $this->title(),
  1060. 'canonical' => [
  1061. ['href' => htmlspecialchars_decode($this->link(), ENT_QUOTES)],
  1062. ],
  1063. 'alternate' => [
  1064. [
  1065. 'href' => htmlspecialchars_decode($this->link(), ENT_QUOTES),
  1066. 'type' => 'text/html',
  1067. ],
  1068. ],
  1069. 'categories' => [
  1070. 'user/-/state/com.google/reading-list',
  1071. ],
  1072. 'origin' => [
  1073. 'streamId' => 'feed/' . $this->feedId,
  1074. ],
  1075. ];
  1076. if ($mode === 'compat') {
  1077. $item['title'] = escapeToUnicodeAlternative($this->title(), false);
  1078. unset($item['alternate'][0]['type']);
  1079. $item['summary'] = [
  1080. 'content' => mb_strcut($this->content(true), 0, self::API_MAX_COMPAT_CONTENT_LENGTH, 'UTF-8'),
  1081. ];
  1082. } else {
  1083. $item['content'] = [
  1084. 'content' => $this->content(false),
  1085. ];
  1086. }
  1087. if ($mode === 'freshrss') {
  1088. $item['guid'] = $this->guid();
  1089. }
  1090. if ($category != null && $mode !== 'freshrss') {
  1091. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($category->name(), ENT_QUOTES);
  1092. }
  1093. if ($feed !== null) {
  1094. $item['origin']['htmlUrl'] = htmlspecialchars_decode($feed->website());
  1095. $item['origin']['title'] = $feed->name(); //EasyRSS
  1096. if ($mode === 'compat') {
  1097. $item['origin']['title'] = escapeToUnicodeAlternative($feed->name(), true);
  1098. } elseif ($mode === 'freshrss') {
  1099. $item['origin']['feedUrl'] = htmlspecialchars_decode($feed->url());
  1100. }
  1101. }
  1102. foreach ($this->enclosures() as $enclosure) {
  1103. if (!empty($enclosure['url'])) {
  1104. $media = [
  1105. 'href' => $enclosure['url'],
  1106. 'type' => $enclosure['type'] ?? $enclosure['medium'] ??
  1107. (self::enclosureIsImage($enclosure) ? 'image' : ''),
  1108. ];
  1109. if (!empty($enclosure['length'])) {
  1110. $media['length'] = (int)$enclosure['length'];
  1111. }
  1112. $item['enclosure'][] = $media;
  1113. }
  1114. }
  1115. $author = $this->authors(true);
  1116. $author = trim($author, '; ');
  1117. if ($author != '') {
  1118. if ($mode === 'compat') {
  1119. $item['author'] = escapeToUnicodeAlternative($author, false);
  1120. } else {
  1121. $item['author'] = $author;
  1122. }
  1123. }
  1124. if ($this->isRead()) {
  1125. $item['categories'][] = 'user/-/state/com.google/read';
  1126. } elseif ($mode === 'freshrss') {
  1127. $item['categories'][] = 'user/-/state/com.google/unread';
  1128. }
  1129. if ($this->isFavorite()) {
  1130. $item['categories'][] = 'user/-/state/com.google/starred';
  1131. }
  1132. foreach ($labels as $labelName) {
  1133. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($labelName, ENT_QUOTES);
  1134. }
  1135. foreach ($this->tags() as $tagName) {
  1136. $item['categories'][] = htmlspecialchars_decode($tagName, ENT_QUOTES);
  1137. }
  1138. return $item;
  1139. }
  1140. }