Entry.php 36 KB

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