Entry.php 16 KB

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