Entry.php 36 KB

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