Entry.php 30 KB

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