Entry.php 26 KB

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