Entry.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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') || str_starts_with($mime, 'image') ||
  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' || str_starts_with($mime, 'audio')) {
  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' || str_starts_with($mime, 'video')) {
  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) && (str_contains($this->content, '<p class="enclosure-content'));
  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. /**
  351. * @param bool $raw Set to true to return the raw link,
  352. * false (default) to attempt a fallback to the GUID if the link is empty.
  353. * @return string HTML-encoded link of the entry
  354. */
  355. public function link(bool $raw = false): string {
  356. if ($this->link === '' && !$raw) {
  357. // Use the GUID as a fallback if it looks like a URL
  358. if (filter_var($this->guid, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE) !== null) {
  359. return $this->guid;
  360. }
  361. }
  362. return $this->link;
  363. }
  364. /**
  365. * @phpstan-return ($raw is false ? string : int)
  366. */
  367. public function date(bool $raw = false): int|string {
  368. if ($raw) {
  369. return $this->date;
  370. }
  371. return timestamptodate($this->date);
  372. }
  373. public function machineReadableDate(): string {
  374. return @date(DATE_ATOM, $this->date);
  375. }
  376. public function lastSeen(): int {
  377. return $this->lastSeen;
  378. }
  379. /**
  380. * @phpstan-return ($raw is false ? string : ($microsecond is true ? string : int))
  381. */
  382. public function dateAdded(bool $raw = false, bool $microsecond = false): int|string {
  383. if ($raw) {
  384. if ($microsecond) {
  385. return $this->date_added;
  386. } else {
  387. return (int)substr($this->date_added, 0, -6);
  388. }
  389. } else {
  390. $date = (int)substr($this->date_added, 0, -6);
  391. return timestamptodate($date);
  392. }
  393. }
  394. public function isRead(): ?bool {
  395. return $this->is_read;
  396. }
  397. public function isFavorite(): ?bool {
  398. return $this->is_favorite;
  399. }
  400. /**
  401. * Returns whether the entry has been modified since it was inserted in database.
  402. * @returns bool `true` if the entry already existed (and has been modified), `false` if the entry is new (or unmodified).
  403. */
  404. public function isUpdated(): ?bool {
  405. return $this->is_updated;
  406. }
  407. public function _isUpdated(bool $value): void {
  408. $this->is_updated = $value;
  409. }
  410. public function feed(): ?FreshRSS_Feed {
  411. if ($this->feed === null) {
  412. $feedDAO = FreshRSS_Factory::createFeedDao();
  413. $this->feed = $feedDAO->searchById($this->feedId);
  414. }
  415. return $this->feed;
  416. }
  417. public function feedId(): int {
  418. return $this->feedId;
  419. }
  420. /**
  421. * @phpstan-return ($asString is true ? string : array<string>)
  422. * @return string|array<string>
  423. */
  424. public function tags(bool $asString = false): array|string {
  425. if ($asString) {
  426. return $this->tags == null ? '' : '#' . implode(' #', $this->tags);
  427. } else {
  428. return $this->tags;
  429. }
  430. }
  431. public function hash(): string {
  432. if ($this->hash === '') {
  433. //Do not include $this->date because it may be automatically generated when lacking
  434. $this->hash = md5($this->link . $this->title . $this->authors(true) . $this->originalContent() . $this->tags(true));
  435. }
  436. return $this->hash;
  437. }
  438. public function _hash(string $value): string {
  439. $value = trim($value);
  440. if (ctype_xdigit($value)) {
  441. $this->hash = substr($value, 0, 32);
  442. }
  443. return $this->hash;
  444. }
  445. /** @param int|numeric-string $value String is for compatibility with 32-bit platforms */
  446. public function _id($value): void {
  447. if (is_int($value)) {
  448. $value = (string)$value;
  449. }
  450. $this->id = $value;
  451. if ($this->date_added == 0) {
  452. $this->date_added = $value;
  453. }
  454. }
  455. public function _guid(string $value): void {
  456. $this->guid = trim($value);
  457. }
  458. public function _title(string $value): void {
  459. $this->hash = '';
  460. $this->title = trim($value);
  461. }
  462. /** @deprecated */
  463. public function _author(string $value): void {
  464. $this->_authors($value);
  465. }
  466. /** @param array<string>|string $value */
  467. public function _authors($value): void {
  468. $this->hash = '';
  469. if (!is_array($value)) {
  470. if (str_contains($value, ';')) {
  471. $value = htmlspecialchars_decode($value, ENT_QUOTES);
  472. $value = preg_split('/\s*[;]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  473. $value = Minz_Helper::htmlspecialchars_utf8($value);
  474. } else {
  475. $value = preg_split('/\s*[,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  476. }
  477. }
  478. $this->authors = $value;
  479. }
  480. public function _content(string $value): void {
  481. $this->hash = '';
  482. $this->content = $value;
  483. }
  484. public function _link(string $value): void {
  485. $this->hash = '';
  486. $this->link = trim($value);
  487. }
  488. /** @param int|string $value */
  489. public function _date($value): void {
  490. $value = (int)$value;
  491. $this->date = $value > 1 ? $value : time();
  492. }
  493. public function _lastSeen(int $value): void {
  494. $this->lastSeen = $value > 0 ? $value : 0;
  495. }
  496. /** @param int|string $value */
  497. public function _dateAdded($value, bool $microsecond = false): void {
  498. if ($microsecond) {
  499. $this->date_added = (string)($value);
  500. } else {
  501. $this->date_added = $value . '000000';
  502. }
  503. }
  504. /** @param bool|int|null $value */
  505. public function _isRead($value): void {
  506. $this->is_read = $value === null ? null : (bool)$value;
  507. }
  508. /** @param bool|int|null $value */
  509. public function _isFavorite($value): void {
  510. $this->is_favorite = $value === null ? null : (bool)$value;
  511. }
  512. public function _feed(?FreshRSS_Feed $feed): void {
  513. $this->feed = $feed;
  514. $this->feedId = $this->feed == null ? 0 : $this->feed->id();
  515. }
  516. /** @param int|string $id */
  517. private function _feedId($id): void {
  518. $this->feed = null;
  519. $this->feedId = (int)$id;
  520. }
  521. /** @param array<string>|string $value */
  522. public function _tags($value): void {
  523. $this->hash = '';
  524. if (!is_array($value)) {
  525. $value = preg_split('/\s*[#,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  526. }
  527. $this->tags = $value;
  528. }
  529. public function matches(FreshRSS_BooleanSearch $booleanSearch): bool {
  530. $ok = true;
  531. foreach ($booleanSearch->searches() as $filter) {
  532. if ($filter instanceof FreshRSS_BooleanSearch) {
  533. // BooleanSearches are combined by AND (default) or OR or AND NOT (special cases) operators and are recursive
  534. match ($filter->operator()) {
  535. 'AND' => $ok &= $this->matches($filter),
  536. 'OR' => $ok |= $this->matches($filter),
  537. 'AND NOT' => $ok &= !$this->matches($filter),
  538. 'OR NOT' => $ok |= !$this->matches($filter),
  539. default => $ok &= $this->matches($filter),
  540. };
  541. } elseif ($filter instanceof FreshRSS_Search) {
  542. // Searches are combined by OR and are not recursive
  543. $ok = true;
  544. if ($filter->getEntryIds() !== null) {
  545. $ok &= in_array($this->id, $filter->getEntryIds(), true);
  546. }
  547. if ($ok && $filter->getNotEntryIds() !== null) {
  548. $ok &= !in_array($this->id, $filter->getNotEntryIds(), true);
  549. }
  550. if ($ok && $filter->getMinDate() !== null) {
  551. $ok &= strnatcmp($this->id, $filter->getMinDate() . '000000') >= 0;
  552. }
  553. if ($ok && $filter->getNotMinDate() !== null) {
  554. $ok &= strnatcmp($this->id, $filter->getNotMinDate() . '000000') < 0;
  555. }
  556. if ($ok && $filter->getMaxDate() !== null) {
  557. $ok &= strnatcmp($this->id, $filter->getMaxDate() . '000000') <= 0;
  558. }
  559. if ($ok && $filter->getNotMaxDate() !== null) {
  560. $ok &= strnatcmp($this->id, $filter->getNotMaxDate() . '000000') > 0;
  561. }
  562. if ($ok && $filter->getMinPubdate() !== null) {
  563. $ok &= $this->date >= $filter->getMinPubdate();
  564. }
  565. if ($ok && $filter->getNotMinPubdate() !== null) {
  566. $ok &= $this->date < $filter->getNotMinPubdate();
  567. }
  568. if ($ok && $filter->getMaxPubdate() !== null) {
  569. $ok &= $this->date <= $filter->getMaxPubdate();
  570. }
  571. if ($ok && $filter->getNotMaxPubdate() !== null) {
  572. $ok &= $this->date > $filter->getNotMaxPubdate();
  573. }
  574. if ($ok && $filter->getFeedIds() !== null) {
  575. $ok &= in_array($this->feedId, $filter->getFeedIds(), true);
  576. }
  577. if ($ok && $filter->getNotFeedIds() !== null) {
  578. $ok &= !in_array($this->feedId, $filter->getNotFeedIds(), true);
  579. }
  580. if ($ok && $filter->getAuthor() !== null) {
  581. foreach ($filter->getAuthor() as $author) {
  582. $ok &= stripos(implode(';', $this->authors), $author) !== false;
  583. }
  584. }
  585. if ($ok && $filter->getAuthorRegex() !== null) {
  586. foreach ($filter->getAuthorRegex() as $author) {
  587. $ok &= preg_match($author, implode("\n", $this->authors)) === 1;
  588. }
  589. }
  590. if ($ok && $filter->getNotAuthor() !== null) {
  591. foreach ($filter->getNotAuthor() as $author) {
  592. $ok &= stripos(implode(';', $this->authors), $author) === false;
  593. }
  594. }
  595. if ($ok && $filter->getNotAuthorRegex() !== null) {
  596. foreach ($filter->getNotAuthorRegex() as $author) {
  597. $ok &= preg_match($author, implode("\n", $this->authors)) === 0;
  598. }
  599. }
  600. if ($ok && $filter->getIntitle() !== null) {
  601. foreach ($filter->getIntitle() as $title) {
  602. $ok &= stripos($this->title, $title) !== false;
  603. }
  604. }
  605. if ($ok && $filter->getIntitleRegex() !== null) {
  606. foreach ($filter->getIntitleRegex() as $title) {
  607. $ok &= preg_match($title, $this->title) === 1;
  608. }
  609. }
  610. if ($ok && $filter->getNotIntitle() !== null) {
  611. foreach ($filter->getNotIntitle() as $title) {
  612. $ok &= stripos($this->title, $title) === false;
  613. }
  614. }
  615. if ($ok && $filter->getNotIntitleRegex() !== null) {
  616. foreach ($filter->getNotIntitleRegex() as $title) {
  617. $ok &= preg_match($title, $this->title) === 0;
  618. }
  619. }
  620. if ($ok && $filter->getTags() !== null) {
  621. foreach ($filter->getTags() as $tag2) {
  622. $found = false;
  623. foreach ($this->tags as $tag1) {
  624. $tag1 = ltrim($tag1, '#');
  625. if (strcasecmp($tag1, $tag2) === 0) {
  626. $found = true;
  627. break;
  628. }
  629. }
  630. $ok &= $found;
  631. }
  632. }
  633. if ($ok && $filter->getTagsRegex() !== null) {
  634. foreach ($filter->getTagsRegex() as $tag2) {
  635. $found = false;
  636. foreach ($this->tags as $tag1) {
  637. $tag1 = ltrim($tag1, '#');
  638. if (preg_match($tag2, $tag1) === 1) {
  639. $found = true;
  640. break;
  641. }
  642. }
  643. $ok &= $found;
  644. }
  645. }
  646. if ($ok && $filter->getNotTags() !== null) {
  647. foreach ($filter->getNotTags() as $tag2) {
  648. $found = false;
  649. foreach ($this->tags as $tag1) {
  650. $tag1 = ltrim($tag1, '#');
  651. if (strcasecmp($tag1, $tag2) === 0) {
  652. $found = true;
  653. break;
  654. }
  655. }
  656. $ok &= !$found;
  657. }
  658. }
  659. if ($ok && $filter->getNotTagsRegex() !== null) {
  660. foreach ($filter->getNotTagsRegex() as $tag2) {
  661. $found = false;
  662. foreach ($this->tags as $tag1) {
  663. $tag1 = ltrim($tag1, '#');
  664. if (preg_match($tag2, $tag1) === 1) {
  665. $found = true;
  666. break;
  667. }
  668. }
  669. $ok &= !$found;
  670. }
  671. }
  672. if ($ok && $filter->getInurl() !== null) {
  673. foreach ($filter->getInurl() as $url) {
  674. $ok &= stripos($this->link, $url) !== false;
  675. }
  676. }
  677. if ($ok && $filter->getInurlRegex() !== null) {
  678. foreach ($filter->getInurlRegex() as $url) {
  679. $ok &= preg_match($url, $this->link) === 1;
  680. }
  681. }
  682. if ($ok && $filter->getNotInurl() !== null) {
  683. foreach ($filter->getNotInurl() as $url) {
  684. $ok &= stripos($this->link, $url) === false;
  685. }
  686. }
  687. if ($ok && $filter->getNotInurlRegex() !== null) {
  688. foreach ($filter->getNotInurlRegex() as $url) {
  689. $ok &= preg_match($url, $this->link) === 0;
  690. }
  691. }
  692. if ($ok && $filter->getSearch() !== null) {
  693. foreach ($filter->getSearch() as $needle) {
  694. $ok &= (stripos($this->title, $needle) !== false || stripos($this->content, $needle) !== false);
  695. }
  696. }
  697. if ($ok && $filter->getNotSearch() !== null) {
  698. foreach ($filter->getNotSearch() as $needle) {
  699. $ok &= (stripos($this->title, $needle) === false && stripos($this->content, $needle) === false);
  700. }
  701. }
  702. if ($ok && $filter->getSearchRegex() !== null) {
  703. foreach ($filter->getSearchRegex() as $needle) {
  704. $ok &= (preg_match($needle, $this->title) === 1 || preg_match($needle, $this->content) === 1);
  705. }
  706. }
  707. if ($ok && $filter->getNotSearchRegex() !== null) {
  708. foreach ($filter->getNotSearchRegex() as $needle) {
  709. $ok &= (preg_match($needle, $this->title) === 0 && preg_match($needle, $this->content) === 0);
  710. }
  711. }
  712. if ($ok) {
  713. return true;
  714. }
  715. }
  716. }
  717. return (bool)$ok;
  718. }
  719. /** @param array<string,bool|int> $titlesAsRead */
  720. public function applyFilterActions(array $titlesAsRead = []): void {
  721. $feed = $this->feed;
  722. if ($feed === null) {
  723. return;
  724. }
  725. if (!$this->isRead()) {
  726. if ($feed->attributeBoolean('read_upon_reception') ?? FreshRSS_Context::userConf()->mark_when['reception']) {
  727. $this->_isRead(true);
  728. Minz_ExtensionManager::callHook('entry_auto_read', $this, 'upon_reception');
  729. }
  730. if (!empty($titlesAsRead[$this->title()])) {
  731. Minz_Log::debug('Mark title as read: ' . $this->title());
  732. $this->_isRead(true);
  733. Minz_ExtensionManager::callHook('entry_auto_read', $this, 'same_title_in_feed');
  734. }
  735. }
  736. FreshRSS_Context::userConf()->applyFilterActions($this);
  737. $feed->category()?->applyFilterActions($this);
  738. $feed->applyFilterActions($this);
  739. }
  740. public function isDay(int $day, int $today): bool {
  741. $date = $this->dateAdded(true);
  742. switch ($day) {
  743. case FreshRSS_Days::TODAY:
  744. $tomorrow = $today + 86400;
  745. return $date >= $today && $date < $tomorrow;
  746. case FreshRSS_Days::YESTERDAY:
  747. $yesterday = $today - 86400;
  748. return $date >= $yesterday && $date < $today;
  749. case FreshRSS_Days::BEFORE_YESTERDAY:
  750. $yesterday = $today - 86400;
  751. return $date < $yesterday;
  752. default:
  753. return false;
  754. }
  755. }
  756. /**
  757. * @param string $url Overridden URL. Will default to the entry URL.
  758. * @throws Minz_Exception
  759. */
  760. public function getContentByParsing(string $url = '', int $maxRedirs = 3): string {
  761. $url = $url ?: htmlspecialchars_decode($this->link(), ENT_QUOTES);
  762. $feed = $this->feed();
  763. if ($url === '' || $feed === null || $feed->pathEntries() === '') {
  764. return '';
  765. }
  766. $cachePath = $feed->cacheFilename($url . '#' . $feed->pathEntries());
  767. $html = httpGet($url, $cachePath, 'html', $feed->attributes(), $feed->curlOptions());
  768. if (strlen($html) > 0) {
  769. $doc = new DOMDocument();
  770. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  771. $xpath = new DOMXPath($doc);
  772. if ($maxRedirs > 0) {
  773. //Follow any HTML redirection
  774. $metas = $xpath->query('//meta[@content]') ?: [];
  775. foreach ($metas as $meta) {
  776. if ($meta instanceof DOMElement && strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') {
  777. $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content')));
  778. $refresh = is_string($refresh) ? \SimplePie\Misc::absolutize_url($refresh, $url) : false;
  779. if ($refresh != false && $refresh !== $url) {
  780. return $this->getContentByParsing($refresh, $maxRedirs - 1);
  781. }
  782. }
  783. }
  784. }
  785. $base = $xpath->evaluate('normalize-space(//base/@href)');
  786. if ($base == false || !is_string($base)) {
  787. $base = $url;
  788. } elseif (str_starts_with($base, '//')) {
  789. //Protocol-relative URLs "//www.example.net"
  790. $base = (parse_url($url, PHP_URL_SCHEME) ?? 'https') . ':' . $base;
  791. }
  792. unset($xpath, $doc);
  793. $html = sanitizeHTML($html, $base);
  794. $doc = new DOMDocument();
  795. $utf8BOM = "\xEF\xBB\xBF";
  796. $doc->loadHTML($utf8BOM . $html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  797. $xpath = new DOMXPath($doc);
  798. $html = '';
  799. $cssSelector = htmlspecialchars_decode($feed->pathEntries(), ENT_QUOTES);
  800. $cssSelector = trim($cssSelector, ', ');
  801. $nodes = $xpath->query((new Gt\CssXPath\Translator($cssSelector, '//'))->asXPath());
  802. if ($nodes != false) {
  803. $path_entries_filter = trim($feed->attributeString('path_entries_filter') ?? '');
  804. $filter_xpath = $path_entries_filter === '' ? '' : (new Gt\CssXPath\Translator($path_entries_filter, 'descendant-or-self::'))->asXPath();
  805. foreach ($nodes as $node) {
  806. if ($filter_xpath !== '') {
  807. $filterednodes = $xpath->query($filter_xpath, $node) ?: [];
  808. foreach ($filterednodes as $filterednode) {
  809. if ($filterednode === $node) {
  810. continue 2;
  811. }
  812. if (!($filterednode instanceof DOMElement) || $filterednode->parentNode === null) {
  813. continue;
  814. }
  815. $filterednode->parentNode->removeChild($filterednode);
  816. }
  817. }
  818. $html .= $doc->saveHTML($node) . "\n";
  819. }
  820. }
  821. return trim($html);
  822. } else {
  823. throw new Minz_Exception();
  824. }
  825. }
  826. /**
  827. * @return bool True if the content was modified, false otherwise
  828. */
  829. public function loadCompleteContent(bool $force = false): bool {
  830. // Gestion du contenu
  831. // Trying to fetch full article content even when feeds do not propose it
  832. $feed = $this->feed();
  833. if ($feed === null) {
  834. return false;
  835. }
  836. if (trim($feed->pathEntries()) != '') {
  837. $entryDAO = FreshRSS_Factory::createEntryDao();
  838. $entry = $force ? null : $entryDAO->searchByGuid($this->feedId, $this->guid);
  839. if ($entry !== null) {
  840. // l’article existe déjà en BDD, en se contente de recharger ce contenu
  841. $this->content = $entry->content(false);
  842. } else {
  843. try {
  844. // The article is not yet in the database, so let’s fetch it
  845. $fullContent = $this->getContentByParsing();
  846. if ('' !== $fullContent) {
  847. $fullContent = "<!-- FULLCONTENT start //-->{$fullContent}<!-- FULLCONTENT end //-->";
  848. $originalContent = $this->originalContent();
  849. switch ($feed->attributeString('content_action')) {
  850. case 'prepend':
  851. $this->_attribute('original_content');
  852. $this->content = $fullContent . $originalContent;
  853. break;
  854. case 'append':
  855. $this->_attribute('original_content');
  856. $this->content = $originalContent . $fullContent;
  857. break;
  858. case 'replace':
  859. default:
  860. $this->_attribute('original_content', $originalContent);
  861. $this->content = $fullContent;
  862. break;
  863. }
  864. return true;
  865. }
  866. } catch (Exception $e) {
  867. // rien à faire, on garde l’ancien contenu(requête a échoué)
  868. Minz_Log::warning($e->getMessage());
  869. }
  870. }
  871. } elseif (trim($feed->attributeString('path_entries_filter') ?? '') !== '') {
  872. $originalContent = $this->attributeString('original_content') ?? $this->content;
  873. $doc = new DOMDocument();
  874. $utf8BOM = "\xEF\xBB\xBF";
  875. if (!$doc->loadHTML($utf8BOM . $originalContent, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) {
  876. return false;
  877. }
  878. $xpath = new DOMXPath($doc);
  879. $filterednodes = $xpath->query((new Gt\CssXPath\Translator($feed->attributeString('path_entries_filter') ?? '', '//'))->asXPath()) ?: [];
  880. foreach ($filterednodes as $filterednode) {
  881. if (!($filterednode instanceof DOMElement) || $filterednode->parentNode === null) {
  882. continue;
  883. }
  884. $filterednode->parentNode->removeChild($filterednode);
  885. }
  886. $html = $doc->saveHTML($doc->getElementsByTagName('body')->item(0) ?? $doc->firstElementChild);
  887. if (!is_string($html)) {
  888. return false;
  889. }
  890. $html = preg_replace('%^\s*<body>\s*|\s*</body>\s*$%i', '', $html);
  891. $this->_attribute('original_content');
  892. if (is_string($html) && $this->content !== $html) {
  893. $this->_attribute('original_content', $originalContent);
  894. $this->content = $html;
  895. return true;
  896. }
  897. } else {
  898. $originalContent = $this->originalContent();
  899. if ($originalContent !== $this->content) {
  900. $this->content = $originalContent;
  901. return true;
  902. }
  903. }
  904. return false;
  905. }
  906. /**
  907. * @return array{'id':string,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,'lastSeen':int,
  908. * 'hash':string,'is_read':?bool,'is_favorite':?bool,'id_feed':int,'tags':string,'attributes':array<string,mixed>}
  909. */
  910. public function toArray(): array {
  911. return [
  912. 'id' => $this->id(),
  913. 'guid' => $this->guid(),
  914. 'title' => $this->title(),
  915. 'author' => $this->authors(true),
  916. 'content' => $this->content(false),
  917. 'link' => $this->link(raw: true),
  918. 'date' => $this->date(true),
  919. 'lastSeen' => $this->lastSeen(),
  920. 'hash' => $this->hash(),
  921. 'is_read' => $this->isRead(),
  922. 'is_favorite' => $this->isFavorite(),
  923. 'id_feed' => $this->feedId(),
  924. 'tags' => $this->tags(true),
  925. 'attributes' => $this->attributes(),
  926. ];
  927. }
  928. /**
  929. * @return array{array<string>,array<string>} Array of first tags to show, then array of remaining tags
  930. */
  931. public function tagsFormattingHelper(): array {
  932. $firstTags = [];
  933. $remainingTags = [];
  934. if (FreshRSS_Context::hasUserConf() && in_array(FreshRSS_Context::userConf()->show_tags, ['b', 'f', 'h'], true)) {
  935. $maxTagsDisplayed = (int)FreshRSS_Context::userConf()->show_tags_max;
  936. $tags = $this->tags();
  937. if (!empty($tags)) {
  938. if ($maxTagsDisplayed > 0) {
  939. $firstTags = array_slice($tags, 0, $maxTagsDisplayed);
  940. $remainingTags = array_slice($tags, $maxTagsDisplayed);
  941. } else {
  942. $firstTags = $tags;
  943. }
  944. }
  945. }
  946. return [$firstTags,$remainingTags];
  947. }
  948. /**
  949. * Integer format conversion for Google Reader API format
  950. * @param numeric-string|int $dec Decimal number
  951. * @return string 64-bit hexa http://code.google.com/p/google-reader-api/wiki/ItemId
  952. */
  953. private static function dec2hex($dec): string {
  954. return PHP_INT_SIZE < 8 ? // 32-bit ?
  955. str_pad(gmp_strval(gmp_init($dec, 10), 16), 16, '0', STR_PAD_LEFT) :
  956. str_pad(dechex((int)($dec)), 16, '0', STR_PAD_LEFT);
  957. }
  958. /**
  959. * Some clients (tested with News+) would fail if sending too long item content
  960. * @var int
  961. */
  962. public const API_MAX_COMPAT_CONTENT_LENGTH = 500000;
  963. /**
  964. * N.B.: To avoid expensive lookups, ensure to set `$entry->_feed($feed)` before calling this function.
  965. * @param string $mode Set to `'compat'` to use an alternative Unicode representation for problematic HTML special characters not decoded by some clients;
  966. * set to `'freshrss'` for using FreshRSS additions for internal use (e.g. export/import).
  967. * @param array<string> $labels List of labels associated to this entry.
  968. * @return array<string,mixed> A representation of this entry in a format compatible with Google Reader API
  969. */
  970. public function toGReader(string $mode = '', array $labels = []): array {
  971. $feed = $this->feed();
  972. $category = $feed == null ? null : $feed->category();
  973. $item = [
  974. 'id' => 'tag:google.com,2005:reader/item/' . self::dec2hex($this->id()),
  975. 'crawlTimeMsec' => substr($this->dateAdded(true, true), 0, -3),
  976. 'timestampUsec' => '' . $this->dateAdded(true, true), //EasyRSS & Reeder
  977. 'published' => $this->date(true),
  978. // 'updated' => $this->date(true),
  979. 'title' => $this->title(),
  980. 'canonical' => [
  981. ['href' => htmlspecialchars_decode($this->link(), ENT_QUOTES)],
  982. ],
  983. 'alternate' => [
  984. [
  985. 'href' => htmlspecialchars_decode($this->link(), ENT_QUOTES),
  986. 'type' => 'text/html',
  987. ],
  988. ],
  989. 'categories' => [
  990. 'user/-/state/com.google/reading-list',
  991. ],
  992. 'origin' => [
  993. 'streamId' => 'feed/' . $this->feedId,
  994. ],
  995. ];
  996. if ($mode === 'compat') {
  997. $item['title'] = escapeToUnicodeAlternative($this->title(), false);
  998. unset($item['alternate'][0]['type']);
  999. $item['summary'] = [
  1000. 'content' => mb_strcut($this->content(true), 0, self::API_MAX_COMPAT_CONTENT_LENGTH, 'UTF-8'),
  1001. ];
  1002. } else {
  1003. $item['content'] = [
  1004. 'content' => $this->content(false),
  1005. ];
  1006. }
  1007. if ($mode === 'freshrss') {
  1008. $item['guid'] = $this->guid();
  1009. }
  1010. if ($category != null && $mode !== 'freshrss') {
  1011. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($category->name(), ENT_QUOTES);
  1012. }
  1013. if ($feed !== null) {
  1014. $item['origin']['htmlUrl'] = htmlspecialchars_decode($feed->website());
  1015. $item['origin']['title'] = $feed->name(); //EasyRSS
  1016. if ($mode === 'compat') {
  1017. $item['origin']['title'] = escapeToUnicodeAlternative($feed->name(), true);
  1018. } elseif ($mode === 'freshrss') {
  1019. $item['origin']['feedUrl'] = htmlspecialchars_decode($feed->url());
  1020. }
  1021. }
  1022. foreach ($this->enclosures() as $enclosure) {
  1023. if (!empty($enclosure['url'])) {
  1024. $media = [
  1025. 'href' => $enclosure['url'],
  1026. 'type' => $enclosure['type'] ?? $enclosure['medium'] ??
  1027. (self::enclosureIsImage($enclosure) ? 'image' : ''),
  1028. ];
  1029. if (!empty($enclosure['length'])) {
  1030. $media['length'] = (int)$enclosure['length'];
  1031. }
  1032. $item['enclosure'][] = $media;
  1033. }
  1034. }
  1035. $author = $this->authors(true);
  1036. $author = trim($author, '; ');
  1037. if ($author != '') {
  1038. if ($mode === 'compat') {
  1039. $item['author'] = escapeToUnicodeAlternative($author, false);
  1040. } else {
  1041. $item['author'] = $author;
  1042. }
  1043. }
  1044. if ($this->isRead()) {
  1045. $item['categories'][] = 'user/-/state/com.google/read';
  1046. } elseif ($mode === 'freshrss') {
  1047. $item['categories'][] = 'user/-/state/com.google/unread';
  1048. }
  1049. if ($this->isFavorite()) {
  1050. $item['categories'][] = 'user/-/state/com.google/starred';
  1051. }
  1052. foreach ($labels as $labelName) {
  1053. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($labelName, ENT_QUOTES);
  1054. }
  1055. foreach ($this->tags() as $tagName) {
  1056. $item['categories'][] = htmlspecialchars_decode($tagName, ENT_QUOTES);
  1057. }
  1058. return $item;
  1059. }
  1060. }