Entry.php 30 KB

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