Entry.php 41 KB

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