Entry.php 40 KB

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