Entry.php 30 KB

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