Entry.php 28 KB

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