Entry.php 32 KB

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