Entry.php 31 KB

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