Entry.php 30 KB

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