Entry.php 34 KB

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