Entry.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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 = $enclosure['description'] ?? '';
  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. if (!empty($thumbnail['url'])) {
  279. return $thumbnail;
  280. }
  281. if ($searchEnclosures) {
  282. foreach ($this->enclosures(true) as $enclosure) {
  283. if (self::enclosureIsImage($enclosure)) {
  284. return $enclosure;
  285. }
  286. }
  287. }
  288. return null;
  289. }
  290. /** @return string HTML-encoded link of the entry */
  291. public function link(): string {
  292. return $this->link;
  293. }
  294. /**
  295. * @phpstan-return ($raw is false ? string : int)
  296. * @return string|int
  297. */
  298. public function date(bool $raw = false) {
  299. if ($raw) {
  300. return $this->date;
  301. }
  302. return timestamptodate($this->date);
  303. }
  304. public function machineReadableDate(): string {
  305. return @date (DATE_ATOM, $this->date);
  306. }
  307. public function lastSeen(): int {
  308. return $this->lastSeen;
  309. }
  310. /**
  311. * @phpstan-return ($raw is false ? string : ($microsecond is true ? string : int))
  312. * @return int|string
  313. */
  314. public function dateAdded(bool $raw = false, bool $microsecond = false) {
  315. if ($raw) {
  316. if ($microsecond) {
  317. return $this->date_added;
  318. } else {
  319. return intval(substr($this->date_added, 0, -6));
  320. }
  321. } else {
  322. $date = intval(substr($this->date_added, 0, -6));
  323. return timestamptodate($date);
  324. }
  325. }
  326. public function isRead(): ?bool {
  327. return $this->is_read;
  328. }
  329. public function isFavorite(): ?bool {
  330. return $this->is_favorite;
  331. }
  332. public function feed(): ?FreshRSS_Feed {
  333. if ($this->feed === null) {
  334. $feedDAO = FreshRSS_Factory::createFeedDao();
  335. $this->feed = $feedDAO->searchById($this->feedId);
  336. }
  337. return $this->feed;
  338. }
  339. public function feedId(): int {
  340. return $this->feedId;
  341. }
  342. /**
  343. * @phpstan-return ($asString is true ? string : array<string>)
  344. * @return string|array<string>
  345. */
  346. public function tags(bool $asString = false) {
  347. if ($asString) {
  348. return $this->tags == null ? '' : '#' . implode(' #', $this->tags);
  349. } else {
  350. return $this->tags;
  351. }
  352. }
  353. /**
  354. * @phpstan-return ($key is non-empty-string ? mixed : array<string,mixed>)
  355. * @return array<string,mixed>|mixed|null
  356. */
  357. public function attributes(string $key = '') {
  358. if ($key === '') {
  359. return $this->attributes;
  360. } else {
  361. return $this->attributes[$key] ?? null;
  362. }
  363. }
  364. /** @param string|array<mixed>|bool|int|null $value Value, not HTML-encoded */
  365. public function _attributes(string $key, $value): void {
  366. if ($key == '') {
  367. if (is_string($value)) {
  368. $value = json_decode($value, true);
  369. }
  370. if (is_array($value)) {
  371. $this->attributes = $value;
  372. }
  373. } elseif ($value === null) {
  374. unset($this->attributes[$key]);
  375. } else {
  376. $this->attributes[$key] = $value;
  377. }
  378. }
  379. public function hash(): string {
  380. if ($this->hash == '') {
  381. //Do not include $this->date because it may be automatically generated when lacking
  382. $this->hash = md5($this->link . $this->title . $this->authors(true) . $this->originalContent() . $this->tags(true));
  383. }
  384. return $this->hash;
  385. }
  386. public function _hash(string $value): string {
  387. $value = trim($value);
  388. if (ctype_xdigit($value)) {
  389. $this->hash = substr($value, 0, 32);
  390. }
  391. return $this->hash;
  392. }
  393. public function _id(string $value): void {
  394. $this->id = $value;
  395. if ($this->date_added == 0) {
  396. $this->date_added = $value;
  397. }
  398. }
  399. public function _guid(string $value): void {
  400. $value = trim($value);
  401. if (empty($value)) {
  402. $value = $this->link;
  403. if (empty($value)) {
  404. $value = $this->hash();
  405. }
  406. }
  407. $this->guid = $value;
  408. }
  409. public function _title(string $value): void {
  410. $this->hash = '';
  411. $this->title = trim($value);
  412. }
  413. /** @deprecated */
  414. public function _author(string $value): void {
  415. $this->_authors($value);
  416. }
  417. /** @param array<string>|string $value */
  418. public function _authors($value): void {
  419. $this->hash = '';
  420. if (!is_array($value)) {
  421. if (strpos($value, ';') !== false) {
  422. $value = htmlspecialchars_decode($value, ENT_QUOTES);
  423. $value = preg_split('/\s*[;]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  424. $value = Minz_Helper::htmlspecialchars_utf8($value);
  425. } else {
  426. $value = preg_split('/\s*[,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  427. }
  428. }
  429. $this->authors = $value;
  430. }
  431. public function _content(string $value): void {
  432. $this->hash = '';
  433. $this->content = $value;
  434. }
  435. public function _link(string $value): void {
  436. $this->hash = '';
  437. $this->link = trim($value);
  438. }
  439. /** @param int|string $value */
  440. public function _date($value): void {
  441. $value = intval($value);
  442. $this->date = $value > 1 ? $value : time();
  443. }
  444. public function _lastSeen(int $value): void {
  445. $this->lastSeen = $value > 0 ? $value : 0;
  446. }
  447. /** @param int|string $value */
  448. public function _dateAdded($value, bool $microsecond = false): void {
  449. if ($microsecond) {
  450. $this->date_added = (string)($value);
  451. } else {
  452. $this->date_added = $value . '000000';
  453. }
  454. }
  455. /** @param bool|int|null $value */
  456. public function _isRead($value): void {
  457. $this->is_read = $value === null ? null : (bool)$value;
  458. }
  459. /** @param bool|int|null $value */
  460. public function _isFavorite($value): void {
  461. $this->is_favorite = $value === null ? null : (bool)$value;
  462. }
  463. public function _feed(?FreshRSS_Feed $feed): void {
  464. $this->feed = $feed;
  465. $this->feedId = $this->feed == null ? 0 : $this->feed->id();
  466. }
  467. /** @param int|string $id */
  468. private function _feedId($id): void {
  469. $this->feed = null;
  470. $this->feedId = intval($id);
  471. }
  472. /** @param array<string>|string $value */
  473. public function _tags($value): void {
  474. $this->hash = '';
  475. if (!is_array($value)) {
  476. $value = preg_split('/\s*[#,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  477. }
  478. $this->tags = $value;
  479. }
  480. public function matches(FreshRSS_BooleanSearch $booleanSearch): bool {
  481. $ok = true;
  482. foreach ($booleanSearch->searches() as $filter) {
  483. if ($filter instanceof FreshRSS_BooleanSearch) {
  484. // BooleanSearches are combined by AND (default) or OR or AND NOT (special cases) operators and are recursive
  485. if ($filter->operator() === 'OR') {
  486. $ok |= $this->matches($filter);
  487. } elseif ($filter->operator() === 'AND NOT') {
  488. $ok &= !$this->matches($filter);
  489. } else { // AND
  490. $ok &= $this->matches($filter);
  491. }
  492. } elseif ($filter instanceof FreshRSS_Search) {
  493. // Searches are combined by OR and are not recursive
  494. $ok = true;
  495. if ($filter->getEntryIds()) {
  496. $ok &= in_array($this->id, $filter->getEntryIds(), true);
  497. }
  498. if ($ok && $filter->getNotEntryIds()) {
  499. $ok &= !in_array($this->id, $filter->getNotEntryIds(), true);
  500. }
  501. if ($ok && $filter->getMinDate()) {
  502. $ok &= strnatcmp($this->id, $filter->getMinDate() . '000000') >= 0;
  503. }
  504. if ($ok && $filter->getNotMinDate()) {
  505. $ok &= strnatcmp($this->id, $filter->getNotMinDate() . '000000') < 0;
  506. }
  507. if ($ok && $filter->getMaxDate()) {
  508. $ok &= strnatcmp($this->id, $filter->getMaxDate() . '000000') <= 0;
  509. }
  510. if ($ok && $filter->getNotMaxDate()) {
  511. $ok &= strnatcmp($this->id, $filter->getNotMaxDate() . '000000') > 0;
  512. }
  513. if ($ok && $filter->getMinPubdate()) {
  514. $ok &= $this->date >= $filter->getMinPubdate();
  515. }
  516. if ($ok && $filter->getNotMinPubdate()) {
  517. $ok &= $this->date < $filter->getNotMinPubdate();
  518. }
  519. if ($ok && $filter->getMaxPubdate()) {
  520. $ok &= $this->date <= $filter->getMaxPubdate();
  521. }
  522. if ($ok && $filter->getNotMaxPubdate()) {
  523. $ok &= $this->date > $filter->getNotMaxPubdate();
  524. }
  525. if ($ok && $filter->getFeedIds()) {
  526. $ok &= in_array($this->feedId, $filter->getFeedIds(), true);
  527. }
  528. if ($ok && $filter->getNotFeedIds()) {
  529. $ok &= !in_array($this->feedId, $filter->getFeedIds(), true);
  530. }
  531. if ($ok && $filter->getAuthor()) {
  532. foreach ($filter->getAuthor() as $author) {
  533. $ok &= stripos(implode(';', $this->authors), $author) !== false;
  534. }
  535. }
  536. if ($ok && $filter->getNotAuthor()) {
  537. foreach ($filter->getNotAuthor() as $author) {
  538. $ok &= stripos(implode(';', $this->authors), $author) === false;
  539. }
  540. }
  541. if ($ok && $filter->getIntitle()) {
  542. foreach ($filter->getIntitle() as $title) {
  543. $ok &= stripos($this->title, $title) !== false;
  544. }
  545. }
  546. if ($ok && $filter->getNotIntitle()) {
  547. foreach ($filter->getNotIntitle() as $title) {
  548. $ok &= stripos($this->title, $title) === false;
  549. }
  550. }
  551. if ($ok && $filter->getTags()) {
  552. foreach ($filter->getTags() as $tag2) {
  553. $found = false;
  554. foreach ($this->tags as $tag1) {
  555. if (strcasecmp($tag1, $tag2) === 0) {
  556. $found = true;
  557. }
  558. }
  559. $ok &= $found;
  560. }
  561. }
  562. if ($ok && $filter->getNotTags()) {
  563. foreach ($filter->getNotTags() as $tag2) {
  564. $found = false;
  565. foreach ($this->tags as $tag1) {
  566. if (strcasecmp($tag1, $tag2) === 0) {
  567. $found = true;
  568. }
  569. }
  570. $ok &= !$found;
  571. }
  572. }
  573. if ($ok && $filter->getInurl()) {
  574. foreach ($filter->getInurl() as $url) {
  575. $ok &= stripos($this->link, $url) !== false;
  576. }
  577. }
  578. if ($ok && $filter->getNotInurl()) {
  579. foreach ($filter->getNotInurl() as $url) {
  580. $ok &= stripos($this->link, $url) === false;
  581. }
  582. }
  583. if ($ok && $filter->getSearch()) {
  584. foreach ($filter->getSearch() as $needle) {
  585. $ok &= (stripos($this->title, $needle) !== false || stripos($this->content, $needle) !== false);
  586. }
  587. }
  588. if ($ok && $filter->getNotSearch()) {
  589. foreach ($filter->getNotSearch() as $needle) {
  590. $ok &= (stripos($this->title, $needle) === false && stripos($this->content, $needle) === false);
  591. }
  592. }
  593. if ($ok) {
  594. return true;
  595. }
  596. }
  597. }
  598. return (bool)$ok;
  599. }
  600. /** @param array<string,bool> $titlesAsRead */
  601. public function applyFilterActions(array $titlesAsRead = []): void {
  602. if ($this->feed != null) {
  603. if (!$this->isRead()) {
  604. if ($this->feed->attributes('read_upon_reception') ||
  605. ($this->feed->attributes('read_upon_reception') === null && FreshRSS_Context::$user_conf->mark_when['reception'])) {
  606. $this->_isRead(true);
  607. Minz_ExtensionManager::callHook('entry_auto_read', $this, 'upon_reception');
  608. }
  609. if (!empty($titlesAsRead[$this->title()])) {
  610. Minz_Log::debug('Mark title as read: ' . $this->title());
  611. $this->_isRead(true);
  612. Minz_ExtensionManager::callHook('entry_auto_read', $this, 'same_title_in_feed');
  613. }
  614. }
  615. foreach ($this->feed->filterActions() as $filterAction) {
  616. if ($this->matches($filterAction->booleanSearch())) {
  617. foreach ($filterAction->actions() as $action) {
  618. switch ($action) {
  619. case 'read':
  620. if (!$this->isRead()) {
  621. $this->_isRead(true);
  622. Minz_ExtensionManager::callHook('entry_auto_read', $this, 'filter');
  623. }
  624. break;
  625. case 'star':
  626. $this->_isFavorite(true);
  627. break;
  628. case 'label':
  629. //TODO: Implement more actions
  630. break;
  631. }
  632. }
  633. }
  634. }
  635. }
  636. }
  637. public function isDay(int $day, int $today): bool {
  638. $date = $this->dateAdded(true);
  639. switch ($day) {
  640. case FreshRSS_Days::TODAY:
  641. $tomorrow = $today + 86400;
  642. return $date >= $today && $date < $tomorrow;
  643. case FreshRSS_Days::YESTERDAY:
  644. $yesterday = $today - 86400;
  645. return $date >= $yesterday && $date < $today;
  646. case FreshRSS_Days::BEFORE_YESTERDAY:
  647. $yesterday = $today - 86400;
  648. return $date < $yesterday;
  649. default:
  650. return false;
  651. }
  652. }
  653. /**
  654. * @param array<string,mixed> $attributes
  655. */
  656. public static function getContentByParsing(string $url, string $path, array $attributes = [], int $maxRedirs = 3): string {
  657. $cachePath = FreshRSS_Feed::cacheFilename($url, $attributes, FreshRSS_Feed::KIND_HTML_XPATH);
  658. $html = httpGet($url, $cachePath, 'html', $attributes);
  659. if (strlen($html) > 0) {
  660. $doc = new DOMDocument();
  661. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  662. $xpath = new DOMXPath($doc);
  663. if ($maxRedirs > 0) {
  664. //Follow any HTML redirection
  665. $metas = $xpath->query('//meta[@content]');
  666. /** @var array<DOMElement> $metas */
  667. foreach ($metas as $meta) {
  668. if (strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') {
  669. $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content')));
  670. $refresh = SimplePie_Misc::absolutize_url($refresh, $url);
  671. if ($refresh != false && $refresh !== $url) {
  672. return self::getContentByParsing($refresh, $path, $attributes, $maxRedirs - 1);
  673. }
  674. }
  675. }
  676. }
  677. $base = $xpath->evaluate('normalize-space(//base/@href)');
  678. if ($base == false || !is_string($base)) {
  679. $base = $url;
  680. } elseif (substr($base, 0, 2) === '//') {
  681. //Protocol-relative URLs "//www.example.net"
  682. $base = (parse_url($url, PHP_URL_SCHEME) ?? 'https') . ':' . $base;
  683. }
  684. $content = '';
  685. $nodes = $xpath->query(new Gt\CssXPath\Translator($path));
  686. if ($nodes != false) {
  687. foreach ($nodes as $node) {
  688. if (!empty($attributes['path_entries_filter'])) {
  689. $filterednodes = $xpath->query(new Gt\CssXPath\Translator($attributes['path_entries_filter']), $node) ?: [];
  690. foreach ($filterednodes as $filterednode) {
  691. $filterednode->parentNode->removeChild($filterednode);
  692. }
  693. }
  694. $content .= $doc->saveHTML($node) . "\n";
  695. }
  696. }
  697. $html = trim(sanitizeHTML($content, $base));
  698. return $html;
  699. } else {
  700. throw new Exception();
  701. }
  702. }
  703. public function loadCompleteContent(bool $force = false): bool {
  704. // Gestion du contenu
  705. // Trying to fetch full article content even when feeds do not propose it
  706. $feed = $this->feed();
  707. if ($feed != null && trim($feed->pathEntries()) != '') {
  708. $entryDAO = FreshRSS_Factory::createEntryDao();
  709. $entry = $force ? null : $entryDAO->searchByGuid($this->feedId, $this->guid);
  710. if ($entry) {
  711. // l’article existe déjà en BDD, en se contente de recharger ce contenu
  712. $this->content = $entry->content(false);
  713. } else {
  714. try {
  715. // The article is not yet in the database, so let’s fetch it
  716. $fullContent = self::getContentByParsing(
  717. htmlspecialchars_decode($this->link(), ENT_QUOTES),
  718. htmlspecialchars_decode($feed->pathEntries(), ENT_QUOTES),
  719. $feed->attributes()
  720. );
  721. if ('' !== $fullContent) {
  722. $fullContent = "<!-- FULLCONTENT start //-->{$fullContent}<!-- FULLCONTENT end //-->";
  723. $originalContent = $this->originalContent();
  724. switch ($feed->attributes('content_action')) {
  725. case 'prepend':
  726. $this->content = $fullContent . $originalContent;
  727. break;
  728. case 'append':
  729. $this->content = $originalContent . $fullContent;
  730. break;
  731. case 'replace':
  732. default:
  733. $this->content = $fullContent;
  734. break;
  735. }
  736. return true;
  737. }
  738. } catch (Exception $e) {
  739. // rien à faire, on garde l’ancien contenu(requête a échoué)
  740. Minz_Log::warning($e->getMessage());
  741. }
  742. }
  743. }
  744. return false;
  745. }
  746. /**
  747. * @return array{'id':string,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,'lastSeen':int,
  748. * 'hash':string,'is_read':?bool,'is_favorite':?bool,'id_feed':int,'tags':string,'attributes':array<string,mixed>}
  749. */
  750. public function toArray(): array {
  751. return [
  752. 'id' => $this->id(),
  753. 'guid' => $this->guid(),
  754. 'title' => $this->title(),
  755. 'author' => $this->authors(true),
  756. 'content' => $this->content(false),
  757. 'link' => $this->link(),
  758. 'date' => $this->date(true),
  759. 'lastSeen' => $this->lastSeen(),
  760. 'hash' => $this->hash(),
  761. 'is_read' => $this->isRead(),
  762. 'is_favorite' => $this->isFavorite(),
  763. 'id_feed' => $this->feedId(),
  764. 'tags' => $this->tags(true),
  765. 'attributes' => $this->attributes(),
  766. ];
  767. }
  768. /**
  769. * Integer format conversion for Google Reader API format
  770. * @param string|int $dec Decimal number
  771. * @return string 64-bit hexa http://code.google.com/p/google-reader-api/wiki/ItemId
  772. */
  773. private static function dec2hex($dec): string {
  774. return PHP_INT_SIZE < 8 ? // 32-bit ?
  775. str_pad(gmp_strval(gmp_init($dec, 10), 16), 16, '0', STR_PAD_LEFT) :
  776. str_pad(dechex((int)($dec)), 16, '0', STR_PAD_LEFT);
  777. }
  778. /**
  779. * Some clients (tested with News+) would fail if sending too long item content
  780. * @var int
  781. */
  782. public const API_MAX_COMPAT_CONTENT_LENGTH = 500000;
  783. /**
  784. * N.B.: To avoid expensive lookups, ensure to set `$entry->_feed($feed)` before calling this function.
  785. * @param string $mode Set to `'compat'` to use an alternative Unicode representation for problematic HTML special characters not decoded by some clients;
  786. * set to `'freshrss'` for using FreshRSS additions for internal use (e.g. export/import).
  787. * @param array<string> $labels List of labels associated to this entry.
  788. * @return array<string,mixed> A representation of this entry in a format compatible with Google Reader API
  789. */
  790. public function toGReader(string $mode = '', array $labels = []): array {
  791. $feed = $this->feed();
  792. $category = $feed == null ? null : $feed->category();
  793. $item = [
  794. 'id' => 'tag:google.com,2005:reader/item/' . self::dec2hex($this->id()),
  795. 'crawlTimeMsec' => substr($this->dateAdded(true, true), 0, -3),
  796. 'timestampUsec' => '' . $this->dateAdded(true, true), //EasyRSS & Reeder
  797. 'published' => $this->date(true),
  798. // 'updated' => $this->date(true),
  799. 'title' => $this->title(),
  800. 'canonical' => [
  801. ['href' => htmlspecialchars_decode($this->link(), ENT_QUOTES)],
  802. ],
  803. 'alternate' => [
  804. [
  805. 'href' => htmlspecialchars_decode($this->link(), ENT_QUOTES),
  806. 'type' => 'text/html',
  807. ],
  808. ],
  809. 'categories' => [
  810. 'user/-/state/com.google/reading-list',
  811. ],
  812. 'origin' => [
  813. 'streamId' => 'feed/' . $this->feedId,
  814. ],
  815. ];
  816. if ($mode === 'compat') {
  817. $item['title'] = escapeToUnicodeAlternative($this->title(), false);
  818. unset($item['alternate'][0]['type']);
  819. $item['summary'] = [
  820. 'content' => mb_strcut($this->content(true), 0, self::API_MAX_COMPAT_CONTENT_LENGTH, 'UTF-8'),
  821. ];
  822. } else {
  823. $item['content'] = [
  824. 'content' => $this->content(false),
  825. ];
  826. }
  827. if ($mode === 'freshrss') {
  828. $item['guid'] = $this->guid();
  829. }
  830. if ($category != null && $mode !== 'freshrss') {
  831. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($category->name(), ENT_QUOTES);
  832. }
  833. if ($feed != null) {
  834. $item['origin']['htmlUrl'] = htmlspecialchars_decode($feed->website());
  835. $item['origin']['title'] = $feed->name(); //EasyRSS
  836. if ($mode === 'compat') {
  837. $item['origin']['title'] = escapeToUnicodeAlternative($feed->name(), true);
  838. } elseif ($mode === 'freshrss') {
  839. $item['origin']['feedUrl'] = htmlspecialchars_decode($feed->url());
  840. }
  841. }
  842. foreach ($this->enclosures() as $enclosure) {
  843. if (!empty($enclosure['url'])) {
  844. $media = [
  845. 'href' => $enclosure['url'],
  846. 'type' => $enclosure['type'] ?? $enclosure['medium'] ??
  847. (self::enclosureIsImage($enclosure) ? 'image' : ''),
  848. ];
  849. if (!empty($enclosure['length'])) {
  850. $media['length'] = intval($enclosure['length']);
  851. }
  852. $item['enclosure'][] = $media;
  853. }
  854. }
  855. $author = $this->authors(true);
  856. $author = trim($author, '; ');
  857. if ($author != '') {
  858. if ($mode === 'compat') {
  859. $item['author'] = escapeToUnicodeAlternative($author, false);
  860. } else {
  861. $item['author'] = $author;
  862. }
  863. }
  864. if ($this->isRead()) {
  865. $item['categories'][] = 'user/-/state/com.google/read';
  866. } elseif ($mode === 'freshrss') {
  867. $item['categories'][] = 'user/-/state/com.google/unread';
  868. }
  869. if ($this->isFavorite()) {
  870. $item['categories'][] = 'user/-/state/com.google/starred';
  871. }
  872. foreach ($labels as $labelName) {
  873. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($labelName, ENT_QUOTES);
  874. }
  875. foreach ($this->tags() as $tagName) {
  876. $item['categories'][] = htmlspecialchars_decode($tagName, ENT_QUOTES);
  877. }
  878. return $item;
  879. }
  880. }