Entry.php 30 KB

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