Entry.php 26 KB

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