Entry.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. private $is_favorite;
  31. /**
  32. * @var int
  33. */
  34. private $feedId;
  35. /**
  36. * @var FreshRSS_Feed|null
  37. */
  38. private $feed;
  39. private $tags;
  40. private $attributes = [];
  41. public function __construct(int $feedId = 0, string $guid = '', string $title = '', string $authors = '', string $content = '',
  42. string $link = '', $pubdate = 0, bool $is_read = false, bool $is_favorite = false, string $tags = '') {
  43. $this->_title($title);
  44. $this->_authors($authors);
  45. $this->_content($content);
  46. $this->_link($link);
  47. $this->_date($pubdate);
  48. $this->_isRead($is_read);
  49. $this->_isFavorite($is_favorite);
  50. $this->_feedId($feedId);
  51. $this->_tags($tags);
  52. $this->_guid($guid);
  53. }
  54. /** @param array<string,mixed> $dao */
  55. public static function fromArray(array $dao): FreshRSS_Entry {
  56. if (empty($dao['content'])) {
  57. $dao['content'] = '';
  58. }
  59. if (!empty($dao['thumbnail'])) {
  60. $dao['content'] .= '<p class="enclosure-content"><img src="' . $dao['thumbnail'] . '" alt="" /></p>';
  61. }
  62. $entry = new FreshRSS_Entry(
  63. $dao['id_feed'] ?? 0,
  64. $dao['guid'] ?? '',
  65. $dao['title'] ?? '',
  66. $dao['author'] ?? '',
  67. $dao['content'] ?? '',
  68. $dao['link'] ?? '',
  69. $dao['date'] ?? 0,
  70. $dao['is_read'] ?? false,
  71. $dao['is_favorite'] ?? false,
  72. $dao['tags'] ?? ''
  73. );
  74. if (!empty($dao['id'])) {
  75. $entry->_id($dao['id']);
  76. }
  77. if (!empty($dao['timestamp'])) {
  78. $entry->_date(strtotime($dao['timestamp']));
  79. }
  80. if (!empty($dao['categories'])) {
  81. $entry->_tags($dao['categories']);
  82. }
  83. if (!empty($dao['attributes'])) {
  84. $entry->_attributes('', $dao['attributes']);
  85. }
  86. return $entry;
  87. }
  88. public function id(): string {
  89. return $this->id;
  90. }
  91. public function guid(): string {
  92. return $this->guid;
  93. }
  94. public function title(): string {
  95. return $this->title == '' ? $this->guid() : $this->title;
  96. }
  97. public function author(): string {
  98. //Deprecated
  99. return $this->authors(true);
  100. }
  101. public function authors(bool $asString = false) {
  102. if ($asString) {
  103. return $this->authors == null ? '' : ';' . implode('; ', $this->authors);
  104. } else {
  105. return $this->authors;
  106. }
  107. }
  108. public function content(): string {
  109. return $this->content;
  110. }
  111. /** @return array<array<string,string>> */
  112. public function enclosures(bool $searchBodyImages = false): array {
  113. $results = [];
  114. try {
  115. $searchEnclosures = strpos($this->content, '<p class="enclosure-content') !== false;
  116. $searchBodyImages &= (stripos($this->content, '<img') !== false);
  117. $xpath = null;
  118. if ($searchEnclosures || $searchBodyImages) {
  119. $dom = new DOMDocument();
  120. $dom->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $this->content, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  121. $xpath = new DOMXpath($dom);
  122. }
  123. if ($searchEnclosures) {
  124. $enclosures = $xpath->query('//div[@class="enclosure"]/p[@class="enclosure-content"]/*[@src]');
  125. foreach ($enclosures as $enclosure) {
  126. $result = [
  127. 'url' => $enclosure->getAttribute('src'),
  128. 'type' => $enclosure->getAttribute('data-type'),
  129. 'medium' => $enclosure->getAttribute('data-medium'),
  130. 'length' => $enclosure->getAttribute('data-length'),
  131. ];
  132. if (empty($result['medium'])) {
  133. switch (strtolower($enclosure->nodeName)) {
  134. case 'img': $result['medium'] = 'image'; break;
  135. case 'video': $result['medium'] = 'video'; break;
  136. case 'audio': $result['medium'] = 'audio'; break;
  137. }
  138. }
  139. $results[] = $result;
  140. }
  141. }
  142. if ($searchBodyImages) {
  143. $images = $xpath->query('//img');
  144. foreach ($images as $img) {
  145. $src = $img->getAttribute('src');
  146. if ($src == null) {
  147. $src = $img->getAttribute('data-src');
  148. }
  149. if ($src != null) {
  150. $results[] = [
  151. 'url' => $src,
  152. 'alt' => $img->getAttribute('alt'),
  153. ];
  154. }
  155. }
  156. }
  157. return $results;
  158. } catch (Exception $ex) {
  159. return $results;
  160. }
  161. }
  162. /**
  163. * @return array<string,string>|null
  164. */
  165. public function thumbnail() {
  166. foreach ($this->enclosures(true) as $enclosure) {
  167. if (!empty($enclosure['url']) && empty($enclosure['type'])) {
  168. return $enclosure;
  169. }
  170. }
  171. return null;
  172. }
  173. public function link(): string {
  174. return $this->link;
  175. }
  176. public function date(bool $raw = false) {
  177. if ($raw) {
  178. return $this->date;
  179. }
  180. return timestamptodate($this->date);
  181. }
  182. public function machineReadableDate(): string {
  183. return @date (DATE_ATOM, $this->date);
  184. }
  185. public function dateAdded(bool $raw = false, bool $microsecond = false) {
  186. if ($raw) {
  187. if ($microsecond) {
  188. return $this->date_added;
  189. } else {
  190. return intval(substr($this->date_added, 0, -6));
  191. }
  192. } else {
  193. $date = intval(substr($this->date_added, 0, -6));
  194. return timestamptodate($date);
  195. }
  196. }
  197. public function isRead() {
  198. return $this->is_read;
  199. }
  200. public function isFavorite() {
  201. return $this->is_favorite;
  202. }
  203. public function feed($object = false) {
  204. if ($object) {
  205. if ($this->feed == null) {
  206. $feedDAO = FreshRSS_Factory::createFeedDao();
  207. $this->feed = $feedDAO->searchById($this->feedId);
  208. }
  209. return $this->feed;
  210. } else {
  211. return $this->feedId;
  212. }
  213. }
  214. public function tags($asString = false) {
  215. if ($asString) {
  216. return $this->tags == null ? '' : '#' . implode(' #', $this->tags);
  217. } else {
  218. return $this->tags;
  219. }
  220. }
  221. public function attributes($key = '') {
  222. if ($key == '') {
  223. return $this->attributes;
  224. } else {
  225. return isset($this->attributes[$key]) ? $this->attributes[$key] : null;
  226. }
  227. }
  228. public function _attributes(string $key, $value) {
  229. if ($key == '') {
  230. if (is_string($value)) {
  231. $value = json_decode($value, true);
  232. }
  233. if (is_array($value)) {
  234. $this->attributes = $value;
  235. }
  236. } elseif ($value === null) {
  237. unset($this->attributes[$key]);
  238. } else {
  239. $this->attributes[$key] = $value;
  240. }
  241. }
  242. public function hash(): string {
  243. if ($this->hash == '') {
  244. //Do not include $this->date because it may be automatically generated when lacking
  245. $this->hash = md5($this->link . $this->title . $this->authors(true) . $this->content . $this->tags(true));
  246. }
  247. return $this->hash;
  248. }
  249. public function _hash(string $value) {
  250. $value = trim($value);
  251. if (ctype_xdigit($value)) {
  252. $this->hash = substr($value, 0, 32);
  253. }
  254. return $this->hash;
  255. }
  256. public function _id($value) {
  257. $this->id = $value;
  258. if ($this->date_added == 0) {
  259. $this->date_added = $value;
  260. }
  261. }
  262. public function _guid(string $value) {
  263. if ($value == '') {
  264. $value = $this->link;
  265. if ($value == '') {
  266. $value = $this->hash();
  267. }
  268. }
  269. $this->guid = $value;
  270. }
  271. public function _title(string $value) {
  272. $this->hash = '';
  273. $this->title = trim($value);
  274. }
  275. public function _author(string $value) {
  276. //Deprecated
  277. $this->_authors($value);
  278. }
  279. public function _authors($value) {
  280. $this->hash = '';
  281. if (!is_array($value)) {
  282. if (strpos($value, ';') !== false) {
  283. $value = htmlspecialchars_decode($value, ENT_QUOTES);
  284. $value = preg_split('/\s*[;]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
  285. $value = Minz_Helper::htmlspecialchars_utf8($value);
  286. } else {
  287. $value = preg_split('/\s*[,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
  288. }
  289. }
  290. $this->authors = $value;
  291. }
  292. public function _content(string $value) {
  293. $this->hash = '';
  294. $this->content = $value;
  295. }
  296. public function _link(string $value) {
  297. $this->hash = '';
  298. $this->link = $value;
  299. }
  300. public function _date($value) {
  301. $this->hash = '';
  302. $value = intval($value);
  303. $this->date = $value > 1 ? $value : time();
  304. }
  305. public function _dateAdded($value, bool $microsecond = false) {
  306. if ($microsecond) {
  307. $this->date_added = $value;
  308. } else {
  309. $this->date_added = $value * 1000000;
  310. }
  311. }
  312. public function _isRead($value) {
  313. $this->is_read = $value === null ? null : (bool)$value;
  314. }
  315. public function _isFavorite($value) {
  316. $this->is_favorite = $value;
  317. }
  318. public function _feed($value) {
  319. if ($value != null) {
  320. $this->feed = $value;
  321. $this->feedId = $this->feed->id();
  322. }
  323. }
  324. private function _feedId($value) {
  325. $this->feed = null;
  326. $this->feedId = intval($value);
  327. }
  328. public function _tags($value) {
  329. $this->hash = '';
  330. if (!is_array($value)) {
  331. $value = preg_split('/\s*[#,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
  332. }
  333. $this->tags = $value;
  334. }
  335. public function matches(FreshRSS_BooleanSearch $booleanSearch): bool {
  336. $ok = true;
  337. foreach ($booleanSearch->searches() as $filter) {
  338. if ($filter instanceof FreshRSS_BooleanSearch) {
  339. // BooleanSearches are combined by AND (default) or OR (special case) operator and are recursive
  340. if ($filter->operator() === 'OR') {
  341. $ok |= $this->matches($filter);
  342. } else {
  343. $ok &= $this->matches($filter);
  344. }
  345. } elseif ($filter instanceof FreshRSS_Search) {
  346. // Searches are combined by OR and are not recursive
  347. $ok = true;
  348. if ($filter->getMinDate()) {
  349. $ok &= strnatcmp($this->id, $filter->getMinDate() . '000000') >= 0;
  350. }
  351. if ($ok && $filter->getNotMinDate()) {
  352. $ok &= strnatcmp($this->id, $filter->getNotMinDate() . '000000') < 0;
  353. }
  354. if ($ok && $filter->getMaxDate()) {
  355. $ok &= strnatcmp($this->id, $filter->getMaxDate() . '000000') <= 0;
  356. }
  357. if ($ok && $filter->getNotMaxDate()) {
  358. $ok &= strnatcmp($this->id, $filter->getNotMaxDate() . '000000') > 0;
  359. }
  360. if ($ok && $filter->getMinPubdate()) {
  361. $ok &= $this->date >= $filter->getMinPubdate();
  362. }
  363. if ($ok && $filter->getNotMinPubdate()) {
  364. $ok &= $this->date < $filter->getNotMinPubdate();
  365. }
  366. if ($ok && $filter->getMaxPubdate()) {
  367. $ok &= $this->date <= $filter->getMaxPubdate();
  368. }
  369. if ($ok && $filter->getNotMaxPubdate()) {
  370. $ok &= $this->date > $filter->getNotMaxPubdate();
  371. }
  372. if ($ok && $filter->getFeedIds()) {
  373. $ok &= in_array($this->feedId, $filter->getFeedIds());
  374. }
  375. if ($ok && $filter->getNotFeedIds()) {
  376. $ok &= !in_array($this->feedId, $filter->getFeedIds());
  377. }
  378. if ($ok && $filter->getAuthor()) {
  379. foreach ($filter->getAuthor() as $author) {
  380. $ok &= stripos(implode(';', $this->authors), $author) !== false;
  381. }
  382. }
  383. if ($ok && $filter->getNotAuthor()) {
  384. foreach ($filter->getNotAuthor() as $author) {
  385. $ok &= stripos(implode(';', $this->authors), $author) === false;
  386. }
  387. }
  388. if ($ok && $filter->getIntitle()) {
  389. foreach ($filter->getIntitle() as $title) {
  390. $ok &= stripos($this->title, $title) !== false;
  391. }
  392. }
  393. if ($ok && $filter->getNotIntitle()) {
  394. foreach ($filter->getNotIntitle() as $title) {
  395. $ok &= stripos($this->title, $title) === false;
  396. }
  397. }
  398. if ($ok && $filter->getTags()) {
  399. foreach ($filter->getTags() as $tag2) {
  400. $found = false;
  401. foreach ($this->tags as $tag1) {
  402. if (strcasecmp($tag1, $tag2) === 0) {
  403. $found = true;
  404. }
  405. }
  406. $ok &= $found;
  407. }
  408. }
  409. if ($ok && $filter->getNotTags()) {
  410. foreach ($filter->getNotTags() as $tag2) {
  411. $found = false;
  412. foreach ($this->tags as $tag1) {
  413. if (strcasecmp($tag1, $tag2) === 0) {
  414. $found = true;
  415. }
  416. }
  417. $ok &= !$found;
  418. }
  419. }
  420. if ($ok && $filter->getInurl()) {
  421. foreach ($filter->getInurl() as $url) {
  422. $ok &= stripos($this->link, $url) !== false;
  423. }
  424. }
  425. if ($ok && $filter->getNotInurl()) {
  426. foreach ($filter->getNotInurl() as $url) {
  427. $ok &= stripos($this->link, $url) === false;
  428. }
  429. }
  430. if ($ok && $filter->getSearch()) {
  431. foreach ($filter->getSearch() as $needle) {
  432. $ok &= (stripos($this->title, $needle) !== false || stripos($this->content, $needle) !== false);
  433. }
  434. }
  435. if ($ok && $filter->getNotSearch()) {
  436. foreach ($filter->getNotSearch() as $needle) {
  437. $ok &= (stripos($this->title, $needle) === false && stripos($this->content, $needle) === false);
  438. }
  439. }
  440. if ($ok) {
  441. return true;
  442. }
  443. }
  444. }
  445. return $ok;
  446. }
  447. public function applyFilterActions(array $titlesAsRead = []) {
  448. if ($this->feed != null) {
  449. if ($this->feed->attributes('read_upon_reception') ||
  450. ($this->feed->attributes('read_upon_reception') === null && FreshRSS_Context::$user_conf->mark_when['reception'])) {
  451. $this->_isRead(true);
  452. }
  453. if (isset($titlesAsRead[$this->title()])) {
  454. Minz_Log::debug('Mark title as read: ' . $this->title());
  455. $this->_isRead(true);
  456. }
  457. foreach ($this->feed->filterActions() as $filterAction) {
  458. if ($this->matches($filterAction->booleanSearch())) {
  459. foreach ($filterAction->actions() as $action) {
  460. switch ($action) {
  461. case 'read':
  462. $this->_isRead(true);
  463. break;
  464. case 'star':
  465. $this->_isFavorite(true);
  466. break;
  467. case 'label':
  468. //TODO: Implement more actions
  469. break;
  470. }
  471. }
  472. }
  473. }
  474. }
  475. }
  476. public function isDay(int $day, int $today): bool {
  477. $date = $this->dateAdded(true);
  478. switch ($day) {
  479. case FreshRSS_Days::TODAY:
  480. $tomorrow = $today + 86400;
  481. return $date >= $today && $date < $tomorrow;
  482. case FreshRSS_Days::YESTERDAY:
  483. $yesterday = $today - 86400;
  484. return $date >= $yesterday && $date < $today;
  485. case FreshRSS_Days::BEFORE_YESTERDAY:
  486. $yesterday = $today - 86400;
  487. return $date < $yesterday;
  488. default:
  489. return false;
  490. }
  491. }
  492. /**
  493. * @param array<string,mixed> $attributes
  494. */
  495. public static function getContentByParsing(string $url, string $path, array $attributes = [], int $maxRedirs = 3): string {
  496. $cachePath = FreshRSS_Feed::cacheFilename($url, $attributes, FreshRSS_Feed::KIND_HTML_XPATH);
  497. $html = httpGet($url, $cachePath, 'html', $attributes);
  498. if (strlen($html) > 0) {
  499. $doc = new DOMDocument();
  500. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  501. $xpath = new DOMXPath($doc);
  502. if ($maxRedirs > 0) {
  503. //Follow any HTML redirection
  504. $metas = $xpath->query('//meta[@content]');
  505. /** @var array<DOMElement> $metas */
  506. foreach ($metas as $meta) {
  507. if (strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') {
  508. $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content')));
  509. $refresh = SimplePie_Misc::absolutize_url($refresh, $url);
  510. if ($refresh != false && $refresh !== $url) {
  511. return self::getContentByParsing($refresh, $path, $attributes, $maxRedirs - 1);
  512. }
  513. }
  514. }
  515. }
  516. $base = $xpath->evaluate('normalize-space(//base/@href)');
  517. if ($base != false && is_string($base)) {
  518. $url = $base;
  519. }
  520. $content = '';
  521. $nodes = $xpath->query(new Gt\CssXPath\Translator($path));
  522. if ($nodes != false) {
  523. foreach ($nodes as $node) {
  524. $content .= $doc->saveHtml($node) . "\n";
  525. }
  526. }
  527. $html = trim(sanitizeHTML($content, $url));
  528. return $html;
  529. } else {
  530. throw new Exception();
  531. }
  532. }
  533. public function loadCompleteContent(bool $force = false): bool {
  534. // Gestion du contenu
  535. // Trying to fetch full article content even when feeds do not propose it
  536. $feed = $this->feed(true);
  537. if ($feed != null && trim($feed->pathEntries()) != '') {
  538. $entryDAO = FreshRSS_Factory::createEntryDao();
  539. $entry = $force ? null : $entryDAO->searchByGuid($this->feedId, $this->guid);
  540. if ($entry) {
  541. // l’article existe déjà en BDD, en se contente de recharger ce contenu
  542. $this->content = $entry->content();
  543. } else {
  544. try {
  545. // l’article n’est pas en BDD, on va le chercher sur le site
  546. $fullContent = self::getContentByParsing(
  547. htmlspecialchars_decode($this->link(), ENT_QUOTES),
  548. $feed->pathEntries(),
  549. $feed->attributes()
  550. );
  551. if ('' !== $fullContent) {
  552. $fullContent = "<!-- FULLCONTENT start //-->{$fullContent}<!-- FULLCONTENT end //-->";
  553. $originalContent = preg_replace('#<!-- FULLCONTENT start //-->.*<!-- FULLCONTENT end //-->#s', '', $this->content());
  554. switch ($feed->attributes('content_action')) {
  555. case 'prepend':
  556. $this->content = $fullContent . $originalContent;
  557. break;
  558. case 'append':
  559. $this->content = $originalContent . $fullContent;
  560. break;
  561. case 'replace':
  562. default:
  563. $this->content = $fullContent;
  564. break;
  565. }
  566. return true;
  567. }
  568. } catch (Exception $e) {
  569. // rien à faire, on garde l’ancien contenu(requête a échoué)
  570. Minz_Log::warning($e->getMessage());
  571. }
  572. }
  573. }
  574. return false;
  575. }
  576. public function toArray(): array {
  577. return array(
  578. 'id' => $this->id(),
  579. 'guid' => $this->guid(),
  580. 'title' => $this->title(),
  581. 'author' => $this->authors(true),
  582. 'content' => $this->content(),
  583. 'link' => $this->link(),
  584. 'date' => $this->date(true),
  585. 'hash' => $this->hash(),
  586. 'is_read' => $this->isRead(),
  587. 'is_favorite' => $this->isFavorite(),
  588. 'id_feed' => $this->feed(),
  589. 'tags' => $this->tags(true),
  590. 'attributes' => $this->attributes(),
  591. );
  592. }
  593. }