Entry.php 32 KB

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