Entry.php 43 KB

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