4
0

Entry.php 30 KB

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