Entry.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  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->getMinUserdate() !== null) {
  606. $ok &= $this->lastUserModified >= $filter->getMinUserdate();
  607. }
  608. if ($ok && $filter->getNotMinUserdate() !== null) {
  609. $ok &= $this->lastUserModified < $filter->getNotMinUserdate();
  610. }
  611. if ($ok && $filter->getMaxUserdate() !== null) {
  612. $ok &= $this->lastUserModified <= $filter->getMaxUserdate();
  613. }
  614. if ($ok && $filter->getNotMaxUserdate() !== null) {
  615. $ok &= $this->lastUserModified > $filter->getNotMaxUserdate();
  616. }
  617. if ($ok && $filter->getFeedIds() !== null) {
  618. $ok &= in_array($this->feedId, $filter->getFeedIds(), true);
  619. }
  620. if ($ok && $filter->getNotFeedIds() !== null) {
  621. $ok &= !in_array($this->feedId, $filter->getNotFeedIds(), true);
  622. }
  623. if ($ok && $filter->getCategoryIds() !== null) {
  624. $ok &= in_array($this->feed()?->categoryId(), $filter->getCategoryIds(), true);
  625. }
  626. if ($ok && $filter->getNotCategoryIds() !== null) {
  627. $ok &= !in_array($this->feed()?->categoryId(), $filter->getNotCategoryIds(), true);
  628. }
  629. if ($ok && $filter->getAuthor() !== null) {
  630. foreach ($filter->getAuthor() as $author) {
  631. $ok &= stripos(implode(';', $this->authors), $author) !== false;
  632. }
  633. }
  634. if ($ok && $filter->getAuthorRegex() !== null) {
  635. foreach ($filter->getAuthorRegex() as $author) {
  636. $ok &= preg_match($author, implode("\n", $this->authors)) === 1;
  637. }
  638. }
  639. if ($ok && $filter->getNotAuthor() !== null) {
  640. foreach ($filter->getNotAuthor() as $author) {
  641. $ok &= stripos(implode(';', $this->authors), $author) === false;
  642. }
  643. }
  644. if ($ok && $filter->getNotAuthorRegex() !== null) {
  645. foreach ($filter->getNotAuthorRegex() as $author) {
  646. $ok &= preg_match($author, implode("\n", $this->authors)) === 0;
  647. }
  648. }
  649. if ($ok && $filter->getIntitle() !== null) {
  650. foreach ($filter->getIntitle() as $title) {
  651. $ok &= stripos($this->title, $title) !== false;
  652. }
  653. }
  654. if ($ok && $filter->getIntitleRegex() !== null) {
  655. foreach ($filter->getIntitleRegex() as $title) {
  656. $ok &= preg_match($title, $this->title) === 1;
  657. }
  658. }
  659. if ($ok && $filter->getNotIntitle() !== null) {
  660. foreach ($filter->getNotIntitle() as $title) {
  661. $ok &= stripos($this->title, $title) === false;
  662. }
  663. }
  664. if ($ok && $filter->getNotIntitleRegex() !== null) {
  665. foreach ($filter->getNotIntitleRegex() as $title) {
  666. $ok &= preg_match($title, $this->title) === 0;
  667. }
  668. }
  669. if ($ok && $filter->getIntext() !== null) {
  670. foreach ($filter->getIntext() as $content) {
  671. $ok &= stripos($this->content, $content) !== false;
  672. }
  673. }
  674. if ($ok && $filter->getIntextRegex() !== null) {
  675. foreach ($filter->getIntextRegex() as $content) {
  676. $ok &= preg_match($content, $this->content) === 1;
  677. }
  678. }
  679. if ($ok && $filter->getNotIntext() !== null) {
  680. foreach ($filter->getNotIntext() as $content) {
  681. $ok &= stripos($this->content, $content) === false;
  682. }
  683. }
  684. if ($ok && $filter->getNotIntextRegex() !== null) {
  685. foreach ($filter->getNotIntextRegex() as $content) {
  686. $ok &= preg_match($content, $this->content) === 0;
  687. }
  688. }
  689. if ($ok && $filter->getTags() !== null) {
  690. foreach ($filter->getTags() as $tag2) {
  691. $found = false;
  692. foreach ($this->tags as $tag1) {
  693. $tag1 = ltrim($tag1, '#');
  694. if (strcasecmp($tag1, $tag2) === 0) {
  695. $found = true;
  696. break;
  697. }
  698. }
  699. $ok &= $found;
  700. }
  701. }
  702. if ($ok && $filter->getTagsRegex() !== null) {
  703. foreach ($filter->getTagsRegex() as $tag2) {
  704. $found = false;
  705. foreach ($this->tags as $tag1) {
  706. $tag1 = ltrim($tag1, '#');
  707. if (preg_match($tag2, $tag1) === 1) {
  708. $found = true;
  709. break;
  710. }
  711. }
  712. $ok &= $found;
  713. }
  714. }
  715. if ($ok && $filter->getNotTags() !== null) {
  716. foreach ($filter->getNotTags() as $tag2) {
  717. $found = false;
  718. foreach ($this->tags as $tag1) {
  719. $tag1 = ltrim($tag1, '#');
  720. if (strcasecmp($tag1, $tag2) === 0) {
  721. $found = true;
  722. break;
  723. }
  724. }
  725. $ok &= !$found;
  726. }
  727. }
  728. if ($ok && $filter->getNotTagsRegex() !== null) {
  729. foreach ($filter->getNotTagsRegex() as $tag2) {
  730. $found = false;
  731. foreach ($this->tags as $tag1) {
  732. $tag1 = ltrim($tag1, '#');
  733. if (preg_match($tag2, $tag1) === 1) {
  734. $found = true;
  735. break;
  736. }
  737. }
  738. $ok &= !$found;
  739. }
  740. }
  741. if ($ok && $filter->getInurl() !== null) {
  742. foreach ($filter->getInurl() as $url) {
  743. $ok &= stripos($this->link, $url) !== false;
  744. }
  745. }
  746. if ($ok && $filter->getInurlRegex() !== null) {
  747. foreach ($filter->getInurlRegex() as $url) {
  748. $ok &= preg_match($url, $this->link) === 1;
  749. }
  750. }
  751. if ($ok && $filter->getNotInurl() !== null) {
  752. foreach ($filter->getNotInurl() as $url) {
  753. $ok &= stripos($this->link, $url) === false;
  754. }
  755. }
  756. if ($ok && $filter->getNotInurlRegex() !== null) {
  757. foreach ($filter->getNotInurlRegex() as $url) {
  758. $ok &= preg_match($url, $this->link) === 0;
  759. }
  760. }
  761. if ($ok && $filter->getSearch() !== null) {
  762. foreach ($filter->getSearch() as $needle) {
  763. $ok &= (stripos($this->title, $needle) !== false || stripos($this->content, $needle) !== false);
  764. }
  765. }
  766. if ($ok && $filter->getNotSearch() !== null) {
  767. foreach ($filter->getNotSearch() as $needle) {
  768. $ok &= (stripos($this->title, $needle) === false && stripos($this->content, $needle) === false);
  769. }
  770. }
  771. if ($ok && $filter->getSearchRegex() !== null) {
  772. foreach ($filter->getSearchRegex() as $needle) {
  773. $ok &= (preg_match($needle, $this->title) === 1 || preg_match($needle, $this->content) === 1);
  774. }
  775. }
  776. if ($ok && $filter->getNotSearchRegex() !== null) {
  777. foreach ($filter->getNotSearchRegex() as $needle) {
  778. $ok &= (preg_match($needle, $this->title) === 0 && preg_match($needle, $this->content) === 0);
  779. }
  780. }
  781. if ($ok) {
  782. return true;
  783. }
  784. }
  785. }
  786. return (bool)$ok;
  787. }
  788. /** @param array<string,bool|int> $titlesAsRead */
  789. public function applyFilterActions(array $titlesAsRead = []): void {
  790. $feed = $this->feed;
  791. if ($feed === null) {
  792. return;
  793. }
  794. if (!$this->isRead()) {
  795. if ($feed->attributeBoolean('read_upon_reception') ?? FreshRSS_Context::userConf()->mark_when['reception']) {
  796. $this->_isRead(true);
  797. Minz_ExtensionManager::callHook(Minz_HookType::EntryAutoRead, $this, 'upon_reception');
  798. }
  799. if (!empty($titlesAsRead[$this->title()])) {
  800. Minz_Log::debug('Mark title as read: ' . $this->title());
  801. $this->_isRead(true);
  802. Minz_ExtensionManager::callHook(Minz_HookType::EntryAutoRead, $this, 'same_title_in_feed');
  803. }
  804. }
  805. FreshRSS_Context::userConf()->applyFilterActions($this);
  806. $feed->category()?->applyFilterActions($this);
  807. $feed->applyFilterActions($this);
  808. }
  809. public function isDay(int $day, int $today): bool {
  810. $date = $this->dateAdded(true);
  811. switch ($day) {
  812. case FreshRSS_Days::TODAY:
  813. $tomorrow = $today + 86400;
  814. return $date >= $today && $date < $tomorrow;
  815. case FreshRSS_Days::YESTERDAY:
  816. $yesterday = $today - 86400;
  817. return $date >= $yesterday && $date < $today;
  818. case FreshRSS_Days::BEFORE_YESTERDAY:
  819. $yesterday = $today - 86400;
  820. return $date < $yesterday;
  821. default:
  822. return false;
  823. }
  824. }
  825. /**
  826. * @param string $url Overridden URL. Will default to the entry URL.
  827. * @throws Minz_Exception
  828. */
  829. public function getContentByParsing(string $url = '', int $maxRedirs = 4): string {
  830. $url = $url ?: htmlspecialchars_decode($this->link(), ENT_QUOTES);
  831. $feed = $this->feed();
  832. if ($url === '' || $feed === null || $feed->pathEntries() === '') {
  833. return '';
  834. }
  835. $conditions = $feed->attributeArray('path_entries_conditions') ?? [];
  836. $conditions = array_filter($conditions, fn($v): bool => (is_string($v) ? trim($v) : '') !== '');
  837. if (count($conditions) > 0) {
  838. $found = false;
  839. foreach ($conditions as $condition) {
  840. if (!is_string($condition) || trim($condition) === '') {
  841. continue;
  842. }
  843. $booleanSearch = new FreshRSS_BooleanSearch($condition);
  844. if ($this->matches($booleanSearch)) {
  845. $found = true;
  846. break;
  847. }
  848. }
  849. if (!$found) {
  850. return '';
  851. }
  852. }
  853. $cachePath = $feed->cacheFilename($url . '#' . $feed->pathEntries());
  854. $response = httpGet($url, $cachePath, 'html', $feed->attributes(), $feed->curlOptions());
  855. $html = $response['body'];
  856. if ($html !== '') {
  857. $doc = new DOMDocument();
  858. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  859. $xpath = new DOMXPath($doc);
  860. // Account for HTTP redirections
  861. $url = $response['effective_url'] ?: $url;
  862. $maxRedirs -= $response['redirect_count'];
  863. if ($maxRedirs > 0) {
  864. //Follow any HTML redirection
  865. $metas = $xpath->query('//meta[@content]') ?: [];
  866. foreach ($metas as $meta) {
  867. if ($meta instanceof DOMElement && strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') {
  868. $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content')));
  869. $refresh = is_string($refresh) ? \SimplePie\Misc::absolutize_url($refresh, $url) : false;
  870. if ($refresh != false && $refresh !== $url) {
  871. return $this->getContentByParsing($refresh, $maxRedirs - 1);
  872. }
  873. }
  874. }
  875. }
  876. $base = $xpath->evaluate('normalize-space(//base/@href)');
  877. if ($base == false || !is_string($base)) {
  878. $base = $url;
  879. } elseif (str_starts_with($base, '//')) {
  880. //Protocol-relative URLs "//www.example.net"
  881. $base = (parse_url($url, PHP_URL_SCHEME) ?? 'https') . ':' . $base;
  882. }
  883. $html = '';
  884. $cssSelector = htmlspecialchars_decode($feed->pathEntries(), ENT_QUOTES);
  885. $cssSelector = trim($cssSelector, ', ');
  886. $path_entries_filter = trim($feed->attributeString('path_entries_filter') ?? '', ', ');
  887. $nodes = $xpath->query((new Gt\CssXPath\Translator($cssSelector, '//'))->asXPath());
  888. if ($nodes != false) {
  889. $filter_xpath = $path_entries_filter === '' ? '' : (new Gt\CssXPath\Translator($path_entries_filter, 'descendant-or-self::'))->asXPath();
  890. foreach ($nodes as $node) {
  891. if ($filter_xpath !== '' && ($filterednodes = $xpath->query($filter_xpath, $node)) !== false) {
  892. // Remove unwanted elements once before sanitizing, for CSS selectors to also match original content
  893. foreach ($filterednodes as $filterednode) {
  894. if ($filterednode === $node) {
  895. continue 2;
  896. }
  897. if (!($filterednode instanceof DOMElement) || $filterednode->parentNode === null) {
  898. continue;
  899. }
  900. $filterednode->parentNode->removeChild($filterednode);
  901. }
  902. }
  903. $html .= $doc->saveHTML($node) . "\n";
  904. }
  905. }
  906. unset($xpath, $doc);
  907. $html = sanitizeHTML($html, $base);
  908. if ($path_entries_filter !== '') {
  909. // Remove unwanted elements again after sanitizing, for CSS selectors to also match sanitized content
  910. $modified = false;
  911. $doc = new DOMDocument();
  912. $utf8BOM = "\xEF\xBB\xBF";
  913. $doc->loadHTML($utf8BOM . $html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  914. $xpath = new DOMXPath($doc);
  915. $filterednodes = $xpath->query((new Gt\CssXPath\Translator($path_entries_filter, '//'))->asXPath()) ?: [];
  916. foreach ($filterednodes as $filterednode) {
  917. if (!($filterednode instanceof DOMElement) || $filterednode->parentNode === null) {
  918. continue;
  919. }
  920. $filterednode->parentNode->removeChild($filterednode);
  921. $modified = true;
  922. }
  923. if ($modified) {
  924. $html = $doc->saveHTML($doc->getElementsByTagName('body')->item(0) ?? $doc->firstElementChild) ?: $html;
  925. }
  926. }
  927. return trim($html);
  928. } else {
  929. throw new Minz_Exception();
  930. }
  931. }
  932. /**
  933. * @return bool True if the content was modified, false otherwise
  934. */
  935. public function loadCompleteContent(bool $force = false): bool {
  936. // Gestion du contenu
  937. // Trying to fetch full article content even when feeds do not propose it
  938. $feed = $this->feed();
  939. if ($feed === null) {
  940. return false;
  941. }
  942. if (trim($feed->pathEntries()) != '') {
  943. $entryDAO = FreshRSS_Factory::createEntryDao();
  944. $entry = $force ? null : $entryDAO->searchByGuid($this->feedId, $this->guid);
  945. if ($entry !== null) {
  946. // l’article existe déjà en BDD, en se contente de recharger ce contenu
  947. $this->content = $entry->content(false);
  948. } else {
  949. try {
  950. // The article is not yet in the database, so let’s fetch it
  951. $fullContent = $this->getContentByParsing();
  952. if ('' !== $fullContent) {
  953. $fullContent = "<!-- FULLCONTENT start //-->{$fullContent}<!-- FULLCONTENT end //-->";
  954. $originalContent = $this->originalContent();
  955. switch ($feed->attributeString('content_action')) {
  956. case 'prepend':
  957. $this->_attribute('original_content');
  958. $this->content = $fullContent . $originalContent;
  959. break;
  960. case 'append':
  961. $this->_attribute('original_content');
  962. $this->content = $originalContent . $fullContent;
  963. break;
  964. case 'replace':
  965. default:
  966. $this->_attribute('original_content', $originalContent);
  967. $this->content = $fullContent;
  968. break;
  969. }
  970. return true;
  971. }
  972. } catch (Exception $e) {
  973. // rien à faire, on garde l’ancien contenu(requête a échoué)
  974. Minz_Log::warning($e->getMessage());
  975. }
  976. }
  977. } elseif (trim($feed->attributeString('path_entries_filter') ?? '') !== '') {
  978. $originalContent = $this->attributeString('original_content') ?? $this->content;
  979. $doc = new DOMDocument();
  980. $utf8BOM = "\xEF\xBB\xBF";
  981. if (!$doc->loadHTML($utf8BOM . $originalContent, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) {
  982. return false;
  983. }
  984. $xpath = new DOMXPath($doc);
  985. $filterednodes = $xpath->query((new Gt\CssXPath\Translator($feed->attributeString('path_entries_filter'), '//'))->asXPath()) ?: [];
  986. foreach ($filterednodes as $filterednode) {
  987. if (!($filterednode instanceof DOMElement) || $filterednode->parentNode === null) {
  988. continue;
  989. }
  990. $filterednode->parentNode->removeChild($filterednode);
  991. }
  992. $html = $doc->saveHTML($doc->getElementsByTagName('body')->item(0) ?? $doc->firstElementChild);
  993. if (!is_string($html)) {
  994. return false;
  995. }
  996. $html = preg_replace('%^\s*<body>\s*|\s*</body>\s*$%i', '', $html);
  997. $this->_attribute('original_content');
  998. if (is_string($html) && $this->content !== $html) {
  999. $this->_attribute('original_content', $originalContent);
  1000. $this->content = $html;
  1001. return true;
  1002. }
  1003. } else {
  1004. $originalContent = $this->originalContent();
  1005. if ($originalContent !== $this->content) {
  1006. $this->content = $originalContent;
  1007. return true;
  1008. }
  1009. }
  1010. return false;
  1011. }
  1012. /**
  1013. * @return array{id:string,guid:string,title:string,author:string,content:string,link:string,date:int,
  1014. * lastSeen:int,lastUserModified:int,
  1015. * hash:string,is_read:?bool,is_favorite:?bool,id_feed:int,tags:string,attributes:array<string,mixed>}
  1016. */
  1017. public function toArray(): array {
  1018. return [
  1019. 'id' => $this->id(),
  1020. 'guid' => $this->guid(),
  1021. 'title' => $this->title(),
  1022. 'author' => $this->authors(true),
  1023. 'content' => $this->content(false),
  1024. 'link' => $this->link(raw: true),
  1025. 'date' => $this->date(true),
  1026. 'lastSeen' => $this->lastSeen(),
  1027. 'lastUserModified' => $this->lastUserModified(),
  1028. 'hash' => $this->hash(),
  1029. 'is_read' => $this->isRead(),
  1030. 'is_favorite' => $this->isFavorite(),
  1031. 'id_feed' => $this->feedId(),
  1032. 'tags' => $this->tags(true),
  1033. 'attributes' => $this->attributes(),
  1034. ];
  1035. }
  1036. /**
  1037. * @return array{array<string>,array<string>} Array of first tags to show, then array of remaining tags
  1038. */
  1039. public function tagsFormattingHelper(): array {
  1040. $firstTags = [];
  1041. $remainingTags = [];
  1042. if (FreshRSS_Context::hasUserConf() && in_array(FreshRSS_Context::userConf()->show_tags, ['b', 'f', 'h'], true)) {
  1043. $maxTagsDisplayed = (int)FreshRSS_Context::userConf()->show_tags_max;
  1044. $tags = $this->tags();
  1045. if (!empty($tags)) {
  1046. if ($maxTagsDisplayed > 0) {
  1047. $firstTags = array_slice($tags, 0, $maxTagsDisplayed);
  1048. $remainingTags = array_slice($tags, $maxTagsDisplayed);
  1049. } else {
  1050. $firstTags = $tags;
  1051. }
  1052. }
  1053. }
  1054. return [$firstTags,$remainingTags];
  1055. }
  1056. /**
  1057. * Integer format conversion for Google Reader API format
  1058. * @param numeric-string|int $dec Decimal number
  1059. * @return string 64-bit hexa http://code.google.com/p/google-reader-api/wiki/ItemId
  1060. */
  1061. private static function dec2hex(string|int $dec): string {
  1062. return PHP_INT_SIZE < 8 ? // 32-bit ?
  1063. str_pad(gmp_strval(gmp_init($dec, 10), 16), 16, '0', STR_PAD_LEFT) :
  1064. str_pad(dechex((int)($dec)), 16, '0', STR_PAD_LEFT);
  1065. }
  1066. /**
  1067. * Some clients (tested with News+) would fail if sending too long item content
  1068. * @var int
  1069. */
  1070. public const API_MAX_COMPAT_CONTENT_LENGTH = 500000;
  1071. /**
  1072. * N.B.: To avoid expensive lookups, ensure to set `$entry->_feed($feed)` before calling this function.
  1073. * @param string $mode Set to `'compat'` to use an alternative Unicode representation for problematic HTML special characters not decoded by some clients;
  1074. * set to `'freshrss'` for using FreshRSS additions for internal use (e.g. export/import).
  1075. * @param array<string> $labels List of labels associated to this entry.
  1076. * @return array<string,mixed> A representation of this entry in a format compatible with Google Reader API
  1077. */
  1078. public function toGReader(string $mode = '', array $labels = []): array {
  1079. $feed = $this->feed();
  1080. $category = $feed == null ? null : $feed->category();
  1081. $item = [
  1082. 'frss:id' => $this->id(),
  1083. 'id' => 'tag:google.com,2005:reader/item/' . self::dec2hex($this->id()),
  1084. 'crawlTimeMsec' => substr($this->dateAdded(true, true), 0, -3),
  1085. 'timestampUsec' => '' . $this->dateAdded(true, true), //EasyRSS & Reeder
  1086. 'published' => $this->date(true),
  1087. // 'updated' => $this->date(true),
  1088. 'title' => $this->title(),
  1089. 'canonical' => [
  1090. ['href' => htmlspecialchars_decode($this->link(), ENT_QUOTES)],
  1091. ],
  1092. 'alternate' => [
  1093. [
  1094. 'href' => htmlspecialchars_decode($this->link(), ENT_QUOTES),
  1095. 'type' => 'text/html',
  1096. ],
  1097. ],
  1098. 'categories' => [
  1099. 'user/-/state/com.google/reading-list',
  1100. ],
  1101. 'origin' => [
  1102. 'streamId' => 'feed/' . $this->feedId,
  1103. ],
  1104. ];
  1105. if ($mode === 'compat') {
  1106. $item['title'] = escapeToUnicodeAlternative($this->title(), false);
  1107. unset($item['alternate'][0]['type']);
  1108. $item['summary'] = [
  1109. 'content' => mb_strcut($this->content(true), 0, self::API_MAX_COMPAT_CONTENT_LENGTH, 'UTF-8'),
  1110. ];
  1111. } else {
  1112. $item['content'] = [
  1113. 'content' => $this->content(false),
  1114. ];
  1115. }
  1116. if ($mode === 'freshrss') {
  1117. $item['guid'] = $this->guid();
  1118. }
  1119. if ($category != null && $mode !== 'freshrss') {
  1120. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($category->name(), ENT_QUOTES);
  1121. }
  1122. if ($feed !== null) {
  1123. $item['origin']['htmlUrl'] = htmlspecialchars_decode($feed->website());
  1124. $item['origin']['title'] = $feed->name(); //EasyRSS
  1125. if ($mode === 'compat') {
  1126. $item['origin']['title'] = escapeToUnicodeAlternative($feed->name(), true);
  1127. } elseif ($mode === 'freshrss') {
  1128. $item['origin']['feedUrl'] = htmlspecialchars_decode($feed->url());
  1129. }
  1130. }
  1131. foreach ($this->enclosures() as $enclosure) {
  1132. if (!empty($enclosure['url'])) {
  1133. $media = [
  1134. 'href' => $enclosure['url'],
  1135. 'type' => $enclosure['type'] ?? $enclosure['medium'] ??
  1136. (self::enclosureIsImage($enclosure) ? 'image' : ''),
  1137. ];
  1138. if (!empty($enclosure['length'])) {
  1139. $media['length'] = (int)$enclosure['length'];
  1140. }
  1141. $item['enclosure'][] = $media;
  1142. }
  1143. }
  1144. $author = $this->authors(true);
  1145. $author = trim($author, '; ');
  1146. if ($author != '') {
  1147. if ($mode === 'compat') {
  1148. $item['author'] = escapeToUnicodeAlternative($author, false);
  1149. } else {
  1150. $item['author'] = $author;
  1151. }
  1152. }
  1153. if ($this->isRead()) {
  1154. $item['categories'][] = 'user/-/state/com.google/read';
  1155. } elseif ($mode === 'freshrss') {
  1156. $item['categories'][] = 'user/-/state/com.google/unread';
  1157. }
  1158. if ($this->isFavorite()) {
  1159. $item['categories'][] = 'user/-/state/com.google/starred';
  1160. }
  1161. foreach ($labels as $labelName) {
  1162. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($labelName, ENT_QUOTES);
  1163. }
  1164. foreach ($this->tags() as $tagName) {
  1165. $item['categories'][] = htmlspecialchars_decode($tagName, ENT_QUOTES);
  1166. }
  1167. return $item;
  1168. }
  1169. }