Entry.php 31 KB

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