Entry.php 30 KB

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