Entry.php 29 KB

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