Entry.php 35 KB

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