Entry.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. <?php
  2. class FreshRSS_Entry extends Minz_Model {
  3. const STATE_READ = 1;
  4. const STATE_NOT_READ = 2;
  5. const STATE_ALL = 3;
  6. const STATE_FAVORITE = 4;
  7. const STATE_NOT_FAVORITE = 8;
  8. /**
  9. * @var string
  10. */
  11. private $id = '0';
  12. /**
  13. * @var string
  14. */
  15. private $guid;
  16. private $title;
  17. private $authors;
  18. private $content;
  19. private $link;
  20. private $date;
  21. private $date_added = 0; //In microseconds
  22. /**
  23. * @var string
  24. */
  25. private $hash = '';
  26. /**
  27. * @var bool|null
  28. */
  29. private $is_read;
  30. /** @var bool|null */
  31. private $is_favorite;
  32. /**
  33. * @var int
  34. */
  35. private $feedId;
  36. /**
  37. * @var FreshRSS_Feed|null
  38. */
  39. private $feed;
  40. private $tags;
  41. private $attributes = [];
  42. public function __construct(int $feedId = 0, string $guid = '', string $title = '', string $authors = '', string $content = '',
  43. string $link = '', $pubdate = 0, bool $is_read = false, bool $is_favorite = false, string $tags = '') {
  44. $this->_title($title);
  45. $this->_authors($authors);
  46. $this->_content($content);
  47. $this->_link($link);
  48. $this->_date($pubdate);
  49. $this->_isRead($is_read);
  50. $this->_isFavorite($is_favorite);
  51. $this->_feedId($feedId);
  52. $this->_tags($tags);
  53. $this->_guid($guid);
  54. }
  55. /** @param array<string,mixed> $dao */
  56. public static function fromArray(array $dao): FreshRSS_Entry {
  57. if (empty($dao['content'])) {
  58. $dao['content'] = '';
  59. }
  60. if (!empty($dao['thumbnail'])) {
  61. $dao['content'] .= '<p class="enclosure-content"><img src="' . $dao['thumbnail'] . '" alt="" /></p>';
  62. }
  63. $entry = new FreshRSS_Entry(
  64. $dao['id_feed'] ?? 0,
  65. $dao['guid'] ?? '',
  66. $dao['title'] ?? '',
  67. $dao['author'] ?? '',
  68. $dao['content'] ?? '',
  69. $dao['link'] ?? '',
  70. $dao['date'] ?? 0,
  71. $dao['is_read'] ?? false,
  72. $dao['is_favorite'] ?? false,
  73. $dao['tags'] ?? ''
  74. );
  75. if (!empty($dao['id'])) {
  76. $entry->_id($dao['id']);
  77. }
  78. if (!empty($dao['timestamp'])) {
  79. $entry->_date(strtotime($dao['timestamp']));
  80. }
  81. if (!empty($dao['categories'])) {
  82. $entry->_tags($dao['categories']);
  83. }
  84. if (!empty($dao['attributes'])) {
  85. $entry->_attributes('', $dao['attributes']);
  86. }
  87. return $entry;
  88. }
  89. public function id(): string {
  90. return $this->id;
  91. }
  92. public function guid(): string {
  93. return $this->guid;
  94. }
  95. public function title(): string {
  96. return $this->title == '' ? $this->guid() : $this->title;
  97. }
  98. public function author(): string {
  99. //Deprecated
  100. return $this->authors(true);
  101. }
  102. public function authors(bool $asString = false) {
  103. if ($asString) {
  104. return $this->authors == null ? '' : ';' . implode('; ', $this->authors);
  105. } else {
  106. return $this->authors;
  107. }
  108. }
  109. public function content(): string {
  110. return $this->content;
  111. }
  112. /** @return array<array<string,string>> */
  113. public function enclosures(bool $searchBodyImages = false): array {
  114. $results = [];
  115. try {
  116. $searchEnclosures = strpos($this->content, '<p class="enclosure-content') !== false;
  117. $searchBodyImages &= (stripos($this->content, '<img') !== false);
  118. $xpath = null;
  119. if ($searchEnclosures || $searchBodyImages) {
  120. $dom = new DOMDocument();
  121. $dom->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $this->content, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  122. $xpath = new DOMXpath($dom);
  123. }
  124. if ($searchEnclosures) {
  125. $enclosures = $xpath->query('//div[@class="enclosure"]/p[@class="enclosure-content"]/*[@src]');
  126. foreach ($enclosures as $enclosure) {
  127. $result = [
  128. 'url' => $enclosure->getAttribute('src'),
  129. 'type' => $enclosure->getAttribute('data-type'),
  130. 'medium' => $enclosure->getAttribute('data-medium'),
  131. 'length' => $enclosure->getAttribute('data-length'),
  132. ];
  133. if (empty($result['medium'])) {
  134. switch (strtolower($enclosure->nodeName)) {
  135. case 'img': $result['medium'] = 'image'; break;
  136. case 'video': $result['medium'] = 'video'; break;
  137. case 'audio': $result['medium'] = 'audio'; break;
  138. }
  139. }
  140. $results[] = $result;
  141. }
  142. }
  143. if ($searchBodyImages) {
  144. $images = $xpath->query('//img');
  145. foreach ($images as $img) {
  146. $src = $img->getAttribute('src');
  147. if ($src == null) {
  148. $src = $img->getAttribute('data-src');
  149. }
  150. if ($src != null) {
  151. $results[] = [
  152. 'url' => $src,
  153. 'alt' => $img->getAttribute('alt'),
  154. ];
  155. }
  156. }
  157. }
  158. return $results;
  159. } catch (Exception $ex) {
  160. return $results;
  161. }
  162. }
  163. /**
  164. * @return array<string,string>|null
  165. */
  166. public function thumbnail() {
  167. foreach ($this->enclosures(true) as $enclosure) {
  168. if (!empty($enclosure['url']) && empty($enclosure['type'])) {
  169. return $enclosure;
  170. }
  171. }
  172. return null;
  173. }
  174. /** @return string HTML-encoded link of the entry */
  175. public function link(): string {
  176. return $this->link;
  177. }
  178. public function date(bool $raw = false) {
  179. if ($raw) {
  180. return $this->date;
  181. }
  182. return timestamptodate($this->date);
  183. }
  184. public function machineReadableDate(): string {
  185. return @date (DATE_ATOM, $this->date);
  186. }
  187. public function dateAdded(bool $raw = false, bool $microsecond = false) {
  188. if ($raw) {
  189. if ($microsecond) {
  190. return $this->date_added;
  191. } else {
  192. return intval(substr($this->date_added, 0, -6));
  193. }
  194. } else {
  195. $date = intval(substr($this->date_added, 0, -6));
  196. return timestamptodate($date);
  197. }
  198. }
  199. public function isRead() {
  200. return $this->is_read;
  201. }
  202. public function isFavorite() {
  203. return $this->is_favorite;
  204. }
  205. /**
  206. * @return FreshRSS_Feed|null|false
  207. */
  208. public function feed() {
  209. if ($this->feed === null) {
  210. $feedDAO = FreshRSS_Factory::createFeedDao();
  211. $this->feed = $feedDAO->searchById($this->feedId);
  212. }
  213. return $this->feed;
  214. }
  215. public function feedId(): int {
  216. return $this->feedId;
  217. }
  218. public function tags($asString = false) {
  219. if ($asString) {
  220. return $this->tags == null ? '' : '#' . implode(' #', $this->tags);
  221. } else {
  222. return $this->tags;
  223. }
  224. }
  225. public function attributes($key = '') {
  226. if ($key == '') {
  227. return $this->attributes;
  228. } else {
  229. return isset($this->attributes[$key]) ? $this->attributes[$key] : null;
  230. }
  231. }
  232. public function _attributes(string $key, $value) {
  233. if ($key == '') {
  234. if (is_string($value)) {
  235. $value = json_decode($value, true);
  236. }
  237. if (is_array($value)) {
  238. $this->attributes = $value;
  239. }
  240. } elseif ($value === null) {
  241. unset($this->attributes[$key]);
  242. } else {
  243. $this->attributes[$key] = $value;
  244. }
  245. }
  246. public function hash(): string {
  247. if ($this->hash == '') {
  248. //Do not include $this->date because it may be automatically generated when lacking
  249. $this->hash = md5($this->link . $this->title . $this->authors(true) . $this->content . $this->tags(true));
  250. }
  251. return $this->hash;
  252. }
  253. public function _hash(string $value) {
  254. $value = trim($value);
  255. if (ctype_xdigit($value)) {
  256. $this->hash = substr($value, 0, 32);
  257. }
  258. return $this->hash;
  259. }
  260. public function _id($value) {
  261. $this->id = $value;
  262. if ($this->date_added == 0) {
  263. $this->date_added = $value;
  264. }
  265. }
  266. public function _guid(string $value) {
  267. if ($value == '') {
  268. $value = $this->link;
  269. if ($value == '') {
  270. $value = $this->hash();
  271. }
  272. }
  273. $this->guid = $value;
  274. }
  275. public function _title(string $value) {
  276. $this->hash = '';
  277. $this->title = trim($value);
  278. }
  279. public function _author(string $value) {
  280. //Deprecated
  281. $this->_authors($value);
  282. }
  283. public function _authors($value) {
  284. $this->hash = '';
  285. if (!is_array($value)) {
  286. if (strpos($value, ';') !== false) {
  287. $value = htmlspecialchars_decode($value, ENT_QUOTES);
  288. $value = preg_split('/\s*[;]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
  289. $value = Minz_Helper::htmlspecialchars_utf8($value);
  290. } else {
  291. $value = preg_split('/\s*[,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
  292. }
  293. }
  294. $this->authors = $value;
  295. }
  296. public function _content(string $value) {
  297. $this->hash = '';
  298. $this->content = $value;
  299. }
  300. public function _link(string $value) {
  301. $this->hash = '';
  302. $this->link = $value;
  303. }
  304. public function _date($value) {
  305. $this->hash = '';
  306. $value = intval($value);
  307. $this->date = $value > 1 ? $value : time();
  308. }
  309. public function _dateAdded($value, bool $microsecond = false) {
  310. if ($microsecond) {
  311. $this->date_added = $value;
  312. } else {
  313. $this->date_added = $value * 1000000;
  314. }
  315. }
  316. public function _isRead($value) {
  317. $this->is_read = $value === null ? null : (bool)$value;
  318. }
  319. public function _isFavorite($value) {
  320. $this->is_favorite = $value === null ? null : (bool)$value;
  321. }
  322. /** @param FreshRSS_Feed|null $feed */
  323. public function _feed($feed) {
  324. $this->feed = $feed;
  325. $this->feedId = $this->feed == null ? 0 : $this->feed->id();
  326. }
  327. /** @param int|string $id */
  328. private function _feedId($id) {
  329. $this->feed = null;
  330. $this->feedId = intval($id);
  331. }
  332. public function _tags($value) {
  333. $this->hash = '';
  334. if (!is_array($value)) {
  335. $value = preg_split('/\s*[#,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
  336. }
  337. $this->tags = $value;
  338. }
  339. public function matches(FreshRSS_BooleanSearch $booleanSearch): bool {
  340. $ok = true;
  341. foreach ($booleanSearch->searches() as $filter) {
  342. if ($filter instanceof FreshRSS_BooleanSearch) {
  343. // BooleanSearches are combined by AND (default) or OR or AND NOT (special cases) operators and are recursive
  344. if ($filter->operator() === 'OR') {
  345. $ok |= $this->matches($filter);
  346. } elseif ($filter->operator() === 'AND NOT') {
  347. $ok &= !$this->matches($filter);
  348. } else { // AND
  349. $ok &= $this->matches($filter);
  350. }
  351. } elseif ($filter instanceof FreshRSS_Search) {
  352. // Searches are combined by OR and are not recursive
  353. $ok = true;
  354. if ($filter->getMinDate()) {
  355. $ok &= strnatcmp($this->id, $filter->getMinDate() . '000000') >= 0;
  356. }
  357. if ($ok && $filter->getNotMinDate()) {
  358. $ok &= strnatcmp($this->id, $filter->getNotMinDate() . '000000') < 0;
  359. }
  360. if ($ok && $filter->getMaxDate()) {
  361. $ok &= strnatcmp($this->id, $filter->getMaxDate() . '000000') <= 0;
  362. }
  363. if ($ok && $filter->getNotMaxDate()) {
  364. $ok &= strnatcmp($this->id, $filter->getNotMaxDate() . '000000') > 0;
  365. }
  366. if ($ok && $filter->getMinPubdate()) {
  367. $ok &= $this->date >= $filter->getMinPubdate();
  368. }
  369. if ($ok && $filter->getNotMinPubdate()) {
  370. $ok &= $this->date < $filter->getNotMinPubdate();
  371. }
  372. if ($ok && $filter->getMaxPubdate()) {
  373. $ok &= $this->date <= $filter->getMaxPubdate();
  374. }
  375. if ($ok && $filter->getNotMaxPubdate()) {
  376. $ok &= $this->date > $filter->getNotMaxPubdate();
  377. }
  378. if ($ok && $filter->getFeedIds()) {
  379. $ok &= in_array($this->feedId, $filter->getFeedIds());
  380. }
  381. if ($ok && $filter->getNotFeedIds()) {
  382. $ok &= !in_array($this->feedId, $filter->getFeedIds());
  383. }
  384. if ($ok && $filter->getAuthor()) {
  385. foreach ($filter->getAuthor() as $author) {
  386. $ok &= stripos(implode(';', $this->authors), $author) !== false;
  387. }
  388. }
  389. if ($ok && $filter->getNotAuthor()) {
  390. foreach ($filter->getNotAuthor() as $author) {
  391. $ok &= stripos(implode(';', $this->authors), $author) === false;
  392. }
  393. }
  394. if ($ok && $filter->getIntitle()) {
  395. foreach ($filter->getIntitle() as $title) {
  396. $ok &= stripos($this->title, $title) !== false;
  397. }
  398. }
  399. if ($ok && $filter->getNotIntitle()) {
  400. foreach ($filter->getNotIntitle() as $title) {
  401. $ok &= stripos($this->title, $title) === false;
  402. }
  403. }
  404. if ($ok && $filter->getTags()) {
  405. foreach ($filter->getTags() as $tag2) {
  406. $found = false;
  407. foreach ($this->tags as $tag1) {
  408. if (strcasecmp($tag1, $tag2) === 0) {
  409. $found = true;
  410. }
  411. }
  412. $ok &= $found;
  413. }
  414. }
  415. if ($ok && $filter->getNotTags()) {
  416. foreach ($filter->getNotTags() as $tag2) {
  417. $found = false;
  418. foreach ($this->tags as $tag1) {
  419. if (strcasecmp($tag1, $tag2) === 0) {
  420. $found = true;
  421. }
  422. }
  423. $ok &= !$found;
  424. }
  425. }
  426. if ($ok && $filter->getInurl()) {
  427. foreach ($filter->getInurl() as $url) {
  428. $ok &= stripos($this->link, $url) !== false;
  429. }
  430. }
  431. if ($ok && $filter->getNotInurl()) {
  432. foreach ($filter->getNotInurl() as $url) {
  433. $ok &= stripos($this->link, $url) === false;
  434. }
  435. }
  436. if ($ok && $filter->getSearch()) {
  437. foreach ($filter->getSearch() as $needle) {
  438. $ok &= (stripos($this->title, $needle) !== false || stripos($this->content, $needle) !== false);
  439. }
  440. }
  441. if ($ok && $filter->getNotSearch()) {
  442. foreach ($filter->getNotSearch() as $needle) {
  443. $ok &= (stripos($this->title, $needle) === false && stripos($this->content, $needle) === false);
  444. }
  445. }
  446. if ($ok) {
  447. return true;
  448. }
  449. }
  450. }
  451. return $ok;
  452. }
  453. public function applyFilterActions(array $titlesAsRead = []) {
  454. if ($this->feed != null) {
  455. if ($this->feed->attributes('read_upon_reception') ||
  456. ($this->feed->attributes('read_upon_reception') === null && FreshRSS_Context::$user_conf->mark_when['reception'])) {
  457. $this->_isRead(true);
  458. }
  459. if (isset($titlesAsRead[$this->title()])) {
  460. Minz_Log::debug('Mark title as read: ' . $this->title());
  461. $this->_isRead(true);
  462. }
  463. foreach ($this->feed->filterActions() as $filterAction) {
  464. if ($this->matches($filterAction->booleanSearch())) {
  465. foreach ($filterAction->actions() as $action) {
  466. switch ($action) {
  467. case 'read':
  468. $this->_isRead(true);
  469. break;
  470. case 'star':
  471. $this->_isFavorite(true);
  472. break;
  473. case 'label':
  474. //TODO: Implement more actions
  475. break;
  476. }
  477. }
  478. }
  479. }
  480. }
  481. }
  482. public function isDay(int $day, int $today): bool {
  483. $date = $this->dateAdded(true);
  484. switch ($day) {
  485. case FreshRSS_Days::TODAY:
  486. $tomorrow = $today + 86400;
  487. return $date >= $today && $date < $tomorrow;
  488. case FreshRSS_Days::YESTERDAY:
  489. $yesterday = $today - 86400;
  490. return $date >= $yesterday && $date < $today;
  491. case FreshRSS_Days::BEFORE_YESTERDAY:
  492. $yesterday = $today - 86400;
  493. return $date < $yesterday;
  494. default:
  495. return false;
  496. }
  497. }
  498. /**
  499. * @param array<string,mixed> $attributes
  500. */
  501. public static function getContentByParsing(string $url, string $path, array $attributes = [], int $maxRedirs = 3): string {
  502. $cachePath = FreshRSS_Feed::cacheFilename($url, $attributes, FreshRSS_Feed::KIND_HTML_XPATH);
  503. $html = httpGet($url, $cachePath, 'html', $attributes);
  504. if (strlen($html) > 0) {
  505. $doc = new DOMDocument();
  506. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  507. $xpath = new DOMXPath($doc);
  508. if ($maxRedirs > 0) {
  509. //Follow any HTML redirection
  510. $metas = $xpath->query('//meta[@content]');
  511. /** @var array<DOMElement> $metas */
  512. foreach ($metas as $meta) {
  513. if (strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') {
  514. $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content')));
  515. $refresh = SimplePie_Misc::absolutize_url($refresh, $url);
  516. if ($refresh != false && $refresh !== $url) {
  517. return self::getContentByParsing($refresh, $path, $attributes, $maxRedirs - 1);
  518. }
  519. }
  520. }
  521. }
  522. $base = $xpath->evaluate('normalize-space(//base/@href)');
  523. if ($base == false || !is_string($base)) {
  524. $base = $url;
  525. } elseif (substr($base, 0, 2) === '//') {
  526. //Protocol-relative URLs "//www.example.net"
  527. $base = (parse_url($url, PHP_URL_SCHEME) ?? 'https') . ':' . $base;
  528. }
  529. $content = '';
  530. $nodes = $xpath->query(new Gt\CssXPath\Translator($path));
  531. if ($nodes != false) {
  532. foreach ($nodes as $node) {
  533. if (!empty($attributes['path_entries_filter'])) {
  534. $filterednodes = $xpath->query(new Gt\CssXPath\Translator($attributes['path_entries_filter']), $node);
  535. foreach ($filterednodes as $filterednode) {
  536. $filterednode->parentNode->removeChild($filterednode);
  537. }
  538. }
  539. $content .= $doc->saveHtml($node) . "\n";
  540. }
  541. }
  542. $html = trim(sanitizeHTML($content, $base));
  543. return $html;
  544. } else {
  545. throw new Exception();
  546. }
  547. }
  548. public function loadCompleteContent(bool $force = false): bool {
  549. // Gestion du contenu
  550. // Trying to fetch full article content even when feeds do not propose it
  551. $feed = $this->feed();
  552. if ($feed != null && trim($feed->pathEntries()) != '') {
  553. $entryDAO = FreshRSS_Factory::createEntryDao();
  554. $entry = $force ? null : $entryDAO->searchByGuid($this->feedId, $this->guid);
  555. if ($entry) {
  556. // l’article existe déjà en BDD, en se contente de recharger ce contenu
  557. $this->content = $entry->content();
  558. } else {
  559. try {
  560. // The article is not yet in the database, so let’s fetch it
  561. $fullContent = self::getContentByParsing(
  562. htmlspecialchars_decode($this->link(), ENT_QUOTES),
  563. htmlspecialchars_decode($feed->pathEntries(), ENT_QUOTES),
  564. $feed->attributes()
  565. );
  566. if ('' !== $fullContent) {
  567. $fullContent = "<!-- FULLCONTENT start //-->{$fullContent}<!-- FULLCONTENT end //-->";
  568. $originalContent = preg_replace('#<!-- FULLCONTENT start //-->.*<!-- FULLCONTENT end //-->#s', '', $this->content());
  569. switch ($feed->attributes('content_action')) {
  570. case 'prepend':
  571. $this->content = $fullContent . $originalContent;
  572. break;
  573. case 'append':
  574. $this->content = $originalContent . $fullContent;
  575. break;
  576. case 'replace':
  577. default:
  578. $this->content = $fullContent;
  579. break;
  580. }
  581. return true;
  582. }
  583. } catch (Exception $e) {
  584. // rien à faire, on garde l’ancien contenu(requête a échoué)
  585. Minz_Log::warning($e->getMessage());
  586. }
  587. }
  588. }
  589. return false;
  590. }
  591. public function toArray(): array {
  592. return array(
  593. 'id' => $this->id(),
  594. 'guid' => $this->guid(),
  595. 'title' => $this->title(),
  596. 'author' => $this->authors(true),
  597. 'content' => $this->content(),
  598. 'link' => $this->link(),
  599. 'date' => $this->date(true),
  600. 'hash' => $this->hash(),
  601. 'is_read' => $this->isRead(),
  602. 'is_favorite' => $this->isFavorite(),
  603. 'id_feed' => $this->feedId(),
  604. 'tags' => $this->tags(true),
  605. 'attributes' => $this->attributes(),
  606. );
  607. }
  608. /**
  609. * Integer format conversion for Google Reader API format
  610. * @param string|int $dec Decimal number
  611. * @return string 64-bit hexa http://code.google.com/p/google-reader-api/wiki/ItemId
  612. */
  613. private static function dec2hex($dec): string {
  614. return PHP_INT_SIZE < 8 ? // 32-bit ?
  615. str_pad(gmp_strval(gmp_init($dec, 10), 16), 16, '0', STR_PAD_LEFT) :
  616. str_pad(dechex($dec), 16, '0', STR_PAD_LEFT);
  617. }
  618. /**
  619. * Some clients (tested with News+) would fail if sending too long item content
  620. * @var int
  621. */
  622. const API_MAX_COMPAT_CONTENT_LENGTH = 500000;
  623. /**
  624. * N.B.: To avoid expensive lookups, ensure to set `$entry->_feed($feed)` before calling this function.
  625. * N.B.: You might have to populate `$entry->_tags()` prior to calling this function.
  626. * @param string $mode Set to `'compat'` to use an alternative Unicode representation for problematic HTML special characters not decoded by some clients;
  627. * set to `'freshrss'` for using FreshRSS additions for internal use (e.g. export/import).
  628. * @return array<string,mixed> A representation of this entry in a format compatible with Google Reader API
  629. */
  630. public function toGReader(string $mode = ''): array {
  631. $feed = $this->feed();
  632. $category = $feed == null ? null : $feed->category();
  633. $item = [
  634. 'id' => 'tag:google.com,2005:reader/item/' . self::dec2hex($this->id()),
  635. 'crawlTimeMsec' => substr($this->dateAdded(true, true), 0, -3),
  636. 'timestampUsec' => '' . $this->dateAdded(true, true), //EasyRSS & Reeder
  637. 'published' => $this->date(true),
  638. // 'updated' => $this->date(true),
  639. 'title' => $this->title(),
  640. 'summary' => ['content' => $this->content()],
  641. 'canonical' => [
  642. ['href' => htmlspecialchars_decode($this->link(), ENT_QUOTES)],
  643. ],
  644. 'alternate' => [
  645. [
  646. 'href' => htmlspecialchars_decode($this->link(), ENT_QUOTES),
  647. 'type' => 'text/html',
  648. ],
  649. ],
  650. 'categories' => [
  651. 'user/-/state/com.google/reading-list',
  652. ],
  653. 'origin' => [
  654. 'streamId' => 'feed/' . $this->feedId,
  655. ],
  656. ];
  657. if ($mode === 'compat') {
  658. $item['title'] = escapeToUnicodeAlternative($this->title(), false);
  659. unset($item['alternate'][0]['type']);
  660. if (mb_strlen($this->content(), 'UTF-8') > self::API_MAX_COMPAT_CONTENT_LENGTH) {
  661. $item['summary']['content'] = mb_strcut($this->content(), 0, self::API_MAX_COMPAT_CONTENT_LENGTH, 'UTF-8');
  662. }
  663. } elseif ($mode === 'freshrss') {
  664. $item['guid'] = $this->guid();
  665. unset($item['summary']);
  666. $item['content'] = ['content' => $this->content()];
  667. }
  668. if ($category != null && $mode !== 'freshrss') {
  669. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($category->name(), ENT_QUOTES);
  670. }
  671. if ($feed != null) {
  672. $item['origin']['htmlUrl'] = htmlspecialchars_decode($feed->website());
  673. $item['origin']['title'] = $feed->name(); //EasyRSS
  674. if ($mode === 'compat') {
  675. $item['origin']['title'] = escapeToUnicodeAlternative($feed->name(), true);
  676. } elseif ($mode === 'freshrss') {
  677. $item['origin']['feedUrl'] = htmlspecialchars_decode($feed->url());
  678. }
  679. }
  680. foreach ($this->enclosures() as $enclosure) {
  681. if (!empty($enclosure['url']) && !empty($enclosure['type'])) {
  682. $media = [
  683. 'href' => $enclosure['url'],
  684. 'type' => $enclosure['type'],
  685. ];
  686. if (!empty($enclosure['length'])) {
  687. $media['length'] = intval($enclosure['length']);
  688. }
  689. $item['enclosure'][] = $media;
  690. }
  691. }
  692. $author = $this->authors(true);
  693. $author = trim($author, '; ');
  694. if ($author != '') {
  695. if ($mode === 'compat') {
  696. $item['author'] = escapeToUnicodeAlternative($author, false);
  697. } else {
  698. $item['author'] = $author;
  699. }
  700. }
  701. if ($this->isRead()) {
  702. $item['categories'][] = 'user/-/state/com.google/read';
  703. } elseif ($mode === 'freshrss') {
  704. $item['categories'][] = 'user/-/state/com.google/unread';
  705. }
  706. if ($this->isFavorite()) {
  707. $item['categories'][] = 'user/-/state/com.google/starred';
  708. }
  709. foreach ($this->tags() as $tagName) {
  710. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($tagName, ENT_QUOTES);
  711. }
  712. return $item;
  713. }
  714. }