4
0

Entry.php 32 KB

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