Entry.php 29 KB

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