Entry.php 26 KB

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