Entry.php 26 KB

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