Entry.php 36 KB

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