Feed.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_Feed extends Minz_Model {
  4. use FreshRSS_AttributesTrait, FreshRSS_FilterActionsTrait;
  5. /**
  6. * Normal RSS or Atom feed
  7. * @var int
  8. */
  9. public const KIND_RSS = 0;
  10. /**
  11. * Invalid RSS or Atom feed
  12. * @var int
  13. */
  14. public const KIND_RSS_FORCED = 2;
  15. /**
  16. * Normal HTML with XPath scraping
  17. * @var int
  18. */
  19. public const KIND_HTML_XPATH = 10;
  20. /**
  21. * Normal XML with XPath scraping
  22. * @var int
  23. */
  24. public const KIND_XML_XPATH = 15;
  25. /**
  26. * Normal JSON with XPath scraping
  27. * @var int
  28. */
  29. public const KIND_JSON_XPATH = 20;
  30. public const KIND_JSONFEED = 25;
  31. public const KIND_JSON_DOTNOTATION = 30;
  32. public const PRIORITY_IMPORTANT = 20;
  33. public const PRIORITY_MAIN_STREAM = 10;
  34. public const PRIORITY_CATEGORY = 0;
  35. public const PRIORITY_ARCHIVED = -10;
  36. public const TTL_DEFAULT = 0;
  37. public const ARCHIVING_RETENTION_COUNT_LIMIT = 10000;
  38. public const ARCHIVING_RETENTION_PERIOD = 'P3M';
  39. private int $id = 0;
  40. private string $url = '';
  41. private int $kind = 0;
  42. private int $categoryId = 0;
  43. private ?FreshRSS_Category $category;
  44. private int $nbEntries = -1;
  45. private int $nbNotRead = -1;
  46. private string $name = '';
  47. private string $website = '';
  48. private string $description = '';
  49. private int $lastUpdate = 0;
  50. private int $priority = self::PRIORITY_MAIN_STREAM;
  51. private string $pathEntries = '';
  52. private string $httpAuth = '';
  53. private bool $error = false;
  54. private int $ttl = self::TTL_DEFAULT;
  55. private bool $mute = false;
  56. private string $hash = '';
  57. private string $lockPath = '';
  58. private string $hubUrl = '';
  59. private string $selfUrl = '';
  60. /**
  61. * @throws FreshRSS_BadUrl_Exception
  62. */
  63. public function __construct(string $url, bool $validate = true) {
  64. if ($validate) {
  65. $this->_url($url);
  66. } else {
  67. $this->url = $url;
  68. }
  69. }
  70. public static function default(): FreshRSS_Feed {
  71. $f = new FreshRSS_Feed('http://example.net/', false);
  72. $f->faviconPrepare();
  73. return $f;
  74. }
  75. public function id(): int {
  76. return $this->id;
  77. }
  78. public function hash(): string {
  79. if ($this->hash == '') {
  80. $salt = FreshRSS_Context::systemConf()->salt;
  81. $this->hash = hash('crc32b', $salt . $this->url);
  82. }
  83. return $this->hash;
  84. }
  85. public function url(bool $includeCredentials = true): string {
  86. return $includeCredentials ? $this->url : SimplePie_Misc::url_remove_credentials($this->url);
  87. }
  88. public function selfUrl(): string {
  89. return $this->selfUrl;
  90. }
  91. public function kind(): int {
  92. return $this->kind;
  93. }
  94. public function hubUrl(): string {
  95. return $this->hubUrl;
  96. }
  97. public function category(): ?FreshRSS_Category {
  98. if ($this->category === null && $this->categoryId > 0) {
  99. $catDAO = FreshRSS_Factory::createCategoryDao();
  100. $this->category = $catDAO->searchById($this->categoryId);
  101. }
  102. return $this->category;
  103. }
  104. public function categoryId(): int {
  105. if ($this->category !== null) {
  106. return $this->category->id() ?: $this->categoryId;
  107. }
  108. return $this->categoryId;
  109. }
  110. /**
  111. * @return array<FreshRSS_Entry>|null
  112. * @deprecated
  113. */
  114. public function entries(): ?array {
  115. Minz_Log::warning(__method__ . ' is deprecated since FreshRSS 1.16.1!');
  116. $simplePie = $this->load(false, true);
  117. return $simplePie == null ? [] : iterator_to_array($this->loadEntries($simplePie));
  118. }
  119. public function name(bool $raw = false): string {
  120. return $raw || $this->name != '' ? $this->name : (preg_replace('%^https?://(www[.])?%i', '', $this->url) ?? '');
  121. }
  122. /** @return string HTML-encoded URL of the Web site of the feed */
  123. public function website(): string {
  124. return $this->website;
  125. }
  126. public function description(): string {
  127. return $this->description;
  128. }
  129. public function lastUpdate(): int {
  130. return $this->lastUpdate;
  131. }
  132. public function priority(): int {
  133. return $this->priority;
  134. }
  135. /** @return string HTML-encoded CSS selector */
  136. public function pathEntries(): string {
  137. return $this->pathEntries;
  138. }
  139. /**
  140. * @phpstan-return ($raw is true ? string : array{'username':string,'password':string})
  141. * @return array{'username':string,'password':string}|string
  142. */
  143. public function httpAuth(bool $raw = true) {
  144. if ($raw) {
  145. return $this->httpAuth;
  146. } else {
  147. $pos_colon = strpos($this->httpAuth, ':');
  148. if ($pos_colon !== false) {
  149. $user = substr($this->httpAuth, 0, $pos_colon);
  150. $pass = substr($this->httpAuth, $pos_colon + 1);
  151. } else {
  152. $user = '';
  153. $pass = '';
  154. }
  155. return [
  156. 'username' => $user,
  157. 'password' => $pass,
  158. ];
  159. }
  160. }
  161. /** @return array<int,mixed> */
  162. public function curlOptions(): array {
  163. $curl_options = [];
  164. if ($this->httpAuth !== '') {
  165. $curl_options[CURLOPT_USERPWD] = htmlspecialchars_decode($this->httpAuth, ENT_QUOTES);
  166. }
  167. return $curl_options;
  168. }
  169. public function inError(): bool {
  170. return $this->error;
  171. }
  172. /**
  173. * @param bool $raw true for database version combined with mute information, false otherwise
  174. */
  175. public function ttl(bool $raw = false): int {
  176. if ($raw) {
  177. $ttl = $this->ttl;
  178. if ($this->mute && FreshRSS_Feed::TTL_DEFAULT === $ttl) {
  179. $ttl = FreshRSS_Context::userConf()->ttl_default;
  180. }
  181. return $ttl * ($this->mute ? -1 : 1);
  182. }
  183. if ($this->mute && $this->ttl === FreshRSS_Context::userConf()->ttl_default) {
  184. return FreshRSS_Feed::TTL_DEFAULT;
  185. }
  186. return $this->ttl;
  187. }
  188. public function mute(): bool {
  189. return $this->mute;
  190. }
  191. public function nbEntries(): int {
  192. if ($this->nbEntries < 0) {
  193. $feedDAO = FreshRSS_Factory::createFeedDao();
  194. $this->nbEntries = $feedDAO->countEntries($this->id());
  195. }
  196. return $this->nbEntries;
  197. }
  198. public function nbNotRead(): int {
  199. if ($this->nbNotRead < 0) {
  200. $feedDAO = FreshRSS_Factory::createFeedDao();
  201. $this->nbNotRead = $feedDAO->countNotRead($this->id());
  202. }
  203. return $this->nbNotRead;
  204. }
  205. public function faviconPrepare(): void {
  206. require_once(LIB_PATH . '/favicons.php');
  207. $url = $this->website;
  208. if ($url == '') {
  209. $url = $this->url;
  210. }
  211. $txt = FAVICONS_DIR . $this->hash() . '.txt';
  212. if (@file_get_contents($txt) !== $url) {
  213. file_put_contents($txt, $url);
  214. }
  215. if (FreshRSS_Context::$isCli) {
  216. $ico = FAVICONS_DIR . $this->hash() . '.ico';
  217. $ico_mtime = @filemtime($ico);
  218. $txt_mtime = @filemtime($txt);
  219. if ($txt_mtime != false &&
  220. ($ico_mtime == false || $ico_mtime < $txt_mtime || ($ico_mtime < time() - (14 * 86400)))) {
  221. // no ico file or we should download a new one.
  222. $url = file_get_contents($txt);
  223. if ($url == false || !download_favicon($url, $ico)) {
  224. touch($ico);
  225. }
  226. }
  227. }
  228. }
  229. public static function faviconDelete(string $hash): void {
  230. $path = DATA_PATH . '/favicons/' . $hash;
  231. @unlink($path . '.ico');
  232. @unlink($path . '.txt');
  233. }
  234. public function favicon(): string {
  235. return Minz_Url::display('/f.php?' . $this->hash());
  236. }
  237. public function _id(int $value): void {
  238. $this->id = $value;
  239. }
  240. /**
  241. * @throws FreshRSS_BadUrl_Exception
  242. */
  243. public function _url(string $value, bool $validate = true): void {
  244. $this->hash = '';
  245. $url = $value;
  246. if ($validate) {
  247. $url = checkUrl($url);
  248. }
  249. if ($url == false) {
  250. throw new FreshRSS_BadUrl_Exception($value);
  251. }
  252. $this->url = $url;
  253. }
  254. public function _kind(int $value): void {
  255. $this->kind = $value;
  256. }
  257. public function _category(?FreshRSS_Category $cat): void {
  258. $this->category = $cat;
  259. $this->categoryId = $this->category == null ? 0 : $this->category->id();
  260. }
  261. /** @param int|string $id */
  262. public function _categoryId($id): void {
  263. $this->category = null;
  264. $this->categoryId = intval($id);
  265. }
  266. public function _name(string $value): void {
  267. $this->name = $value == '' ? '' : trim($value);
  268. }
  269. public function _website(string $value, bool $validate = true): void {
  270. if ($validate) {
  271. $value = checkUrl($value);
  272. }
  273. if ($value == false) {
  274. $value = '';
  275. }
  276. $this->website = $value;
  277. }
  278. public function _description(string $value): void {
  279. $this->description = $value == '' ? '' : $value;
  280. }
  281. public function _lastUpdate(int $value): void {
  282. $this->lastUpdate = $value;
  283. }
  284. public function _priority(int $value): void {
  285. $this->priority = $value;
  286. }
  287. /** @param string $value HTML-encoded CSS selector */
  288. public function _pathEntries(string $value): void {
  289. $this->pathEntries = $value;
  290. }
  291. public function _httpAuth(string $value): void {
  292. $this->httpAuth = $value;
  293. }
  294. /** @param bool|int $value */
  295. public function _error($value): void {
  296. $this->error = (bool)$value;
  297. }
  298. public function _mute(bool $value): void {
  299. $this->mute = $value;
  300. }
  301. public function _ttl(int $value): void {
  302. $value = min($value, 100000000);
  303. $this->ttl = abs($value);
  304. $this->mute = $value < self::TTL_DEFAULT;
  305. }
  306. public function _nbNotRead(int $value): void {
  307. $this->nbNotRead = $value;
  308. }
  309. public function _nbEntries(int $value): void {
  310. $this->nbEntries = $value;
  311. }
  312. /**
  313. * @throws Minz_FileNotExistException
  314. * @throws FreshRSS_Feed_Exception
  315. */
  316. public function load(bool $loadDetails = false, bool $noCache = false): ?SimplePie {
  317. if ($this->url != '') {
  318. /**
  319. * @throws Minz_FileNotExistException
  320. * @phpstan-ignore if.alwaysFalse
  321. */
  322. if (CACHE_PATH == '') {
  323. throw new Minz_FileNotExistException(
  324. 'CACHE_PATH',
  325. Minz_Exception::ERROR
  326. );
  327. } else {
  328. $simplePie = customSimplePie($this->attributes(), $this->curlOptions());
  329. $url = htmlspecialchars_decode($this->url, ENT_QUOTES);
  330. if (substr($url, -11) === '#force_feed') {
  331. $simplePie->force_feed(true);
  332. $url = substr($url, 0, -11);
  333. }
  334. $simplePie->set_feed_url($url);
  335. if (!$loadDetails) { //Only activates auto-discovery when adding a new feed
  336. $simplePie->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);
  337. }
  338. if ($this->attributeBoolean('clear_cache')) {
  339. // Do not use `$simplePie->enable_cache(false);` as it would prevent caching in multiuser context
  340. $this->clearCache();
  341. }
  342. Minz_ExtensionManager::callHook('simplepie_before_init', $simplePie, $this);
  343. $mtime = $simplePie->init();
  344. if ((!$mtime) || $simplePie->error()) {
  345. $errorMessage = $simplePie->error();
  346. if (empty($errorMessage)) {
  347. $errorMessage = '';
  348. } elseif (is_array($errorMessage)) {
  349. $errorMessage = json_encode($errorMessage, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS) ?: '';
  350. }
  351. throw new FreshRSS_Feed_Exception(
  352. ($errorMessage == '' ? 'Unknown error for feed' : $errorMessage) .
  353. ' [' . $this->url . ']',
  354. $simplePie->status_code()
  355. );
  356. }
  357. $links = $simplePie->get_links('self');
  358. $this->selfUrl = empty($links[0]) ? '' : (checkUrl($links[0]) ?: '');
  359. $links = $simplePie->get_links('hub');
  360. $this->hubUrl = empty($links[0]) ? '' : (checkUrl($links[0]) ?: '');
  361. if ($loadDetails) {
  362. // si on a utilisé l’auto-discover, notre url va avoir changé
  363. $subscribe_url = $simplePie->subscribe_url(false) ?? '';
  364. if ($this->name(true) === '') {
  365. //HTML to HTML-PRE //ENT_COMPAT except '&'
  366. $title = strtr(html_only_entity_decode($simplePie->get_title()), ['<' => '&lt;', '>' => '&gt;', '"' => '&quot;']);
  367. $this->_name($title == '' ? $this->url : $title);
  368. }
  369. if ($this->website() === '') {
  370. $this->_website(html_only_entity_decode($simplePie->get_link()));
  371. }
  372. if ($this->description() === '') {
  373. $this->_description(html_only_entity_decode($simplePie->get_description()));
  374. }
  375. } else {
  376. //The case of HTTP 301 Moved Permanently
  377. $subscribe_url = $simplePie->subscribe_url(true) ?? '';
  378. }
  379. $clean_url = SimplePie_Misc::url_remove_credentials($subscribe_url);
  380. if ($subscribe_url !== '' && $subscribe_url !== $url) {
  381. $this->_url($clean_url);
  382. }
  383. if (($mtime === true) || ($mtime > $this->lastUpdate) || $noCache) {
  384. //Minz_Log::debug('FreshRSS no cache ' . $mtime . ' > ' . $this->lastUpdate . ' for ' . $clean_url);
  385. return $simplePie;
  386. }
  387. //Minz_Log::debug('FreshRSS use cache for ' . $clean_url);
  388. }
  389. }
  390. return null;
  391. }
  392. /**
  393. * @return array<string>
  394. */
  395. public function loadGuids(SimplePie $simplePie): array {
  396. $hasUniqueGuids = true;
  397. $testGuids = [];
  398. $guids = [];
  399. $links = [];
  400. $hadBadGuids = $this->attributeBoolean('hasBadGuids');
  401. $items = $simplePie->get_items();
  402. if (empty($items)) {
  403. return $guids;
  404. }
  405. for ($i = count($items) - 1; $i >= 0; $i--) {
  406. $item = $items[$i];
  407. if ($item == null) {
  408. continue;
  409. }
  410. $guid = safe_ascii($item->get_id(false, false));
  411. $hasUniqueGuids &= empty($testGuids['_' . $guid]);
  412. $testGuids['_' . $guid] = true;
  413. $guids[] = $guid;
  414. $permalink = $item->get_permalink();
  415. if ($permalink != null) {
  416. $links[] = $permalink;
  417. }
  418. }
  419. if ($hadBadGuids != !$hasUniqueGuids) {
  420. if ($hadBadGuids) {
  421. Minz_Log::warning('Feed has invalid GUIDs: ' . $this->url);
  422. } else {
  423. Minz_Log::warning('Feed has valid GUIDs again: ' . $this->url);
  424. }
  425. $feedDAO = FreshRSS_Factory::createFeedDao();
  426. $feedDAO->updateFeedAttribute($this, 'hasBadGuids', !$hasUniqueGuids);
  427. }
  428. return $hasUniqueGuids ? $guids : $links;
  429. }
  430. /** @return Traversable<FreshRSS_Entry> */
  431. public function loadEntries(SimplePie $simplePie): Traversable {
  432. $hasBadGuids = $this->attributeBoolean('hasBadGuids');
  433. $items = $simplePie->get_items();
  434. if (empty($items)) {
  435. return;
  436. }
  437. // We want chronological order and SimplePie uses reverse order.
  438. for ($i = count($items) - 1; $i >= 0; $i--) {
  439. $item = $items[$i];
  440. if ($item == null) {
  441. continue;
  442. }
  443. $title = html_only_entity_decode(strip_tags($item->get_title() ?? ''));
  444. $authors = $item->get_authors();
  445. $link = $item->get_permalink();
  446. $date = @strtotime((string)($item->get_date() ?? '')) ?: 0;
  447. //Tag processing (tag == category)
  448. $categories = $item->get_categories();
  449. $tags = array();
  450. if (is_array($categories)) {
  451. foreach ($categories as $category) {
  452. $text = html_only_entity_decode($category->get_label());
  453. //Some feeds use a single category with comma-separated tags
  454. $labels = explode(',', $text);
  455. if (!empty($labels)) {
  456. foreach ($labels as $label) {
  457. $tags[] = trim($label);
  458. }
  459. }
  460. }
  461. $tags = array_unique($tags);
  462. }
  463. $content = html_only_entity_decode($item->get_content());
  464. $attributeThumbnail = $item->get_thumbnail() ?? [];
  465. if (empty($attributeThumbnail['url'])) {
  466. $attributeThumbnail['url'] = '';
  467. }
  468. $attributeEnclosures = [];
  469. if (!empty($item->get_enclosures())) {
  470. foreach ($item->get_enclosures() as $enclosure) {
  471. $elink = $enclosure->get_link();
  472. if ($elink != '') {
  473. $etitle = $enclosure->get_title() ?? '';
  474. $credits = $enclosure->get_credits() ?? null;
  475. $description = $enclosure->get_description() ?? '';
  476. $mime = strtolower($enclosure->get_type() ?? '');
  477. $medium = strtolower($enclosure->get_medium() ?? '');
  478. $height = $enclosure->get_height();
  479. $width = $enclosure->get_width();
  480. $length = $enclosure->get_length();
  481. $attributeEnclosure = [
  482. 'url' => $elink,
  483. ];
  484. if ($etitle != '') {
  485. $attributeEnclosure['title'] = $etitle;
  486. }
  487. if (is_array($credits)) {
  488. $attributeEnclosure['credit'] = [];
  489. foreach ($credits as $credit) {
  490. $attributeEnclosure['credit'][] = $credit->get_name();
  491. }
  492. }
  493. if ($description != '') {
  494. $attributeEnclosure['description'] = $description;
  495. }
  496. if ($mime != '') {
  497. $attributeEnclosure['type'] = $mime;
  498. }
  499. if ($medium != '') {
  500. $attributeEnclosure['medium'] = $medium;
  501. }
  502. if ($length != '') {
  503. $attributeEnclosure['length'] = intval($length);
  504. }
  505. if ($height != '') {
  506. $attributeEnclosure['height'] = intval($height);
  507. }
  508. if ($width != '') {
  509. $attributeEnclosure['width'] = intval($width);
  510. }
  511. if (!empty($enclosure->get_thumbnails())) {
  512. foreach ($enclosure->get_thumbnails() as $thumbnail) {
  513. if ($thumbnail !== $attributeThumbnail['url']) {
  514. $attributeEnclosure['thumbnails'][] = $thumbnail;
  515. }
  516. }
  517. }
  518. $attributeEnclosures[] = $attributeEnclosure;
  519. }
  520. }
  521. }
  522. $guid = safe_ascii($item->get_id(false, false));
  523. unset($item);
  524. $authorNames = '';
  525. if (is_array($authors)) {
  526. foreach ($authors as $author) {
  527. $authorName = $author->name != '' ? $author->name : $author->email;
  528. if ($authorName != '') {
  529. $authorNames .= escapeToUnicodeAlternative(strip_tags($authorName), true) . '; ';
  530. }
  531. }
  532. }
  533. $authorNames = substr($authorNames, 0, -2) ?: '';
  534. $entry = new FreshRSS_Entry(
  535. $this->id(),
  536. $hasBadGuids ? '' : $guid,
  537. $title == '' ? '' : $title,
  538. $authorNames,
  539. $content == '' ? '' : $content,
  540. $link == null ? '' : $link,
  541. $date ?: time()
  542. );
  543. $entry->_tags($tags);
  544. $entry->_feed($this);
  545. if (!empty($attributeThumbnail['url'])) {
  546. $entry->_attribute('thumbnail', $attributeThumbnail);
  547. }
  548. $entry->_attribute('enclosures', $attributeEnclosures);
  549. $entry->hash(); //Must be computed before loading full content
  550. $entry->loadCompleteContent(); // Optionally load full content for truncated feeds
  551. yield $entry;
  552. }
  553. }
  554. /**
  555. * Given a feed content generated from a FreshRSS_View
  556. * returns a SimplePie initialized already with that content
  557. * @param string $feedContent the content of the feed, typically generated via FreshRSS_View::renderToString()
  558. */
  559. private function simplePieFromContent(string $feedContent): SimplePie {
  560. $simplePie = customSimplePie();
  561. $simplePie->set_raw_data($feedContent);
  562. $simplePie->init();
  563. return $simplePie;
  564. }
  565. /** @return array<string,string> */
  566. private function dotNotationForStandardJsonFeed(): array {
  567. return [
  568. 'feedTitle' => 'title',
  569. 'item' => 'items',
  570. 'itemTitle' => 'title',
  571. 'itemContent' => 'content_text',
  572. 'itemContentHTML' => 'content_html',
  573. 'itemUri' => 'url',
  574. 'itemTimestamp' => 'date_published',
  575. 'itemTimeFormat' => DateTimeInterface::RFC3339_EXTENDED,
  576. 'itemThumbnail' => 'image',
  577. 'itemCategories' => 'tags',
  578. 'itemUid' => 'id',
  579. 'itemAttachment' => 'attachments',
  580. 'itemAttachmentUrl' => 'url',
  581. 'itemAttachmentType' => 'mime_type',
  582. 'itemAttachmentLength' => 'size_in_bytes',
  583. ];
  584. }
  585. public function loadJson(): ?SimplePie {
  586. if ($this->url == '') {
  587. return null;
  588. }
  589. $feedSourceUrl = htmlspecialchars_decode($this->url, ENT_QUOTES);
  590. if ($feedSourceUrl == null) {
  591. return null;
  592. }
  593. $httpAccept = 'json';
  594. $json = httpGet($feedSourceUrl, $this->cacheFilename(), $httpAccept, $this->attributes(), $this->curlOptions());
  595. if (strlen($json) <= 0) {
  596. return null;
  597. }
  598. //check if the content is actual JSON
  599. $jf = json_decode($json, true);
  600. if (json_last_error() !== JSON_ERROR_NONE) {
  601. return null;
  602. }
  603. /** @var array<string,string> $json_dotnotation */
  604. $json_dotnotation = $this->attributeArray('json_dotnotation') ?? [];
  605. $dotnotations = $this->kind() === FreshRSS_Feed::KIND_JSONFEED ? $this->dotNotationForStandardJsonFeed() : $json_dotnotation;
  606. $feedContent = FreshRSS_dotNotation_Util::convertJsonToRss($jf, $feedSourceUrl, $dotnotations, $this->name());
  607. if ($feedContent == null) {
  608. return null;
  609. }
  610. return $this->simplePieFromContent($feedContent);
  611. }
  612. public function loadHtmlXpath(): ?SimplePie {
  613. if ($this->url == '') {
  614. return null;
  615. }
  616. $feedSourceUrl = htmlspecialchars_decode($this->url, ENT_QUOTES);
  617. if ($feedSourceUrl == null) {
  618. return null;
  619. }
  620. // Same naming conventions than https://rss-bridge.github.io/rss-bridge/Bridge_API/XPathAbstract.html
  621. // https://rss-bridge.github.io/rss-bridge/Bridge_API/BridgeAbstract.html#collectdata
  622. /** @var array<string,string> $xPathSettings */
  623. $xPathSettings = $this->attributeArray('xpath');
  624. $xPathFeedTitle = $xPathSettings['feedTitle'] ?? '';
  625. $xPathItem = $xPathSettings['item'] ?? '';
  626. $xPathItemTitle = $xPathSettings['itemTitle'] ?? '';
  627. $xPathItemContent = $xPathSettings['itemContent'] ?? '';
  628. $xPathItemUri = $xPathSettings['itemUri'] ?? '';
  629. $xPathItemAuthor = $xPathSettings['itemAuthor'] ?? '';
  630. $xPathItemTimestamp = $xPathSettings['itemTimestamp'] ?? '';
  631. $xPathItemTimeFormat = $xPathSettings['itemTimeFormat'] ?? '';
  632. $xPathItemThumbnail = $xPathSettings['itemThumbnail'] ?? '';
  633. $xPathItemCategories = $xPathSettings['itemCategories'] ?? '';
  634. $xPathItemUid = $xPathSettings['itemUid'] ?? '';
  635. if ($xPathItem == '') {
  636. return null;
  637. }
  638. $httpAccept = $this->kind() === FreshRSS_Feed::KIND_XML_XPATH ? 'xml' : 'html';
  639. $html = httpGet($feedSourceUrl, $this->cacheFilename(), $httpAccept, $this->attributes(), $this->curlOptions());
  640. if (strlen($html) <= 0) {
  641. return null;
  642. }
  643. $view = new FreshRSS_View();
  644. $view->_path('index/rss.phtml');
  645. $view->internal_rendering = true;
  646. $view->rss_url = htmlspecialchars($feedSourceUrl, ENT_COMPAT, 'UTF-8');
  647. $view->html_url = $view->rss_url;
  648. $view->entries = [];
  649. try {
  650. $doc = new DOMDocument();
  651. $doc->recover = true;
  652. $doc->strictErrorChecking = false;
  653. $ok = false;
  654. switch ($this->kind()) {
  655. case FreshRSS_Feed::KIND_HTML_XPATH:
  656. $ok = $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) !== false;
  657. break;
  658. case FreshRSS_Feed::KIND_XML_XPATH:
  659. $ok = $doc->loadXML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) !== false;
  660. break;
  661. }
  662. if (!$ok) {
  663. return null;
  664. }
  665. $xpath = new DOMXPath($doc);
  666. $view->rss_title = $xPathFeedTitle == '' ? $this->name() :
  667. htmlspecialchars(@$xpath->evaluate('normalize-space(' . $xPathFeedTitle . ')'), ENT_COMPAT, 'UTF-8');
  668. $view->rss_base = htmlspecialchars(trim($xpath->evaluate('normalize-space(//base/@href)')), ENT_COMPAT, 'UTF-8');
  669. $nodes = $xpath->query($xPathItem);
  670. if ($nodes === false || $nodes->length === 0) {
  671. return null;
  672. }
  673. foreach ($nodes as $node) {
  674. $item = [];
  675. $item['title'] = $xPathItemTitle == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemTitle . ')', $node);
  676. $item['content'] = '';
  677. if ($xPathItemContent != '') {
  678. $result = @$xpath->evaluate($xPathItemContent, $node);
  679. if ($result instanceof DOMNodeList) {
  680. // List of nodes, save as HTML
  681. $content = '';
  682. foreach ($result as $child) {
  683. $content .= $doc->saveHTML($child) . "\n";
  684. }
  685. $item['content'] = $content;
  686. } else {
  687. // Typed expression, save as-is
  688. $item['content'] = (string)$result;
  689. }
  690. }
  691. $item['link'] = $xPathItemUri == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemUri . ')', $node);
  692. $item['author'] = $xPathItemAuthor == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemAuthor . ')', $node);
  693. $item['timestamp'] = $xPathItemTimestamp == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemTimestamp . ')', $node);
  694. if ($xPathItemTimeFormat != '') {
  695. $dateTime = DateTime::createFromFormat($xPathItemTimeFormat, $item['timestamp'] ?? '');
  696. if ($dateTime != false) {
  697. $item['timestamp'] = $dateTime->format(DateTime::ATOM);
  698. }
  699. }
  700. $item['thumbnail'] = $xPathItemThumbnail == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemThumbnail . ')', $node);
  701. if ($xPathItemCategories != '') {
  702. $itemCategories = @$xpath->evaluate($xPathItemCategories, $node);
  703. if (is_string($itemCategories) && $itemCategories !== '') {
  704. $item['tags'] = [$itemCategories];
  705. } elseif ($itemCategories instanceof DOMNodeList && $itemCategories->length > 0) {
  706. $item['tags'] = [];
  707. /** @var DOMNode $itemCategory */
  708. foreach ($itemCategories as $itemCategory) {
  709. $item['tags'][] = $itemCategory->textContent;
  710. }
  711. }
  712. }
  713. if ($xPathItemUid != '') {
  714. $item['guid'] = @$xpath->evaluate('normalize-space(' . $xPathItemUid . ')', $node);
  715. }
  716. if (empty($item['guid'])) {
  717. $item['guid'] = 'urn:sha1:' . sha1($item['title'] . $item['content'] . $item['link']);
  718. }
  719. if ($item['title'] != '' || $item['content'] != '' || $item['link'] != '') {
  720. // HTML-encoding/escaping of the relevant fields (all except 'content')
  721. foreach (['author', 'guid', 'link', 'thumbnail', 'timestamp', 'tags', 'title'] as $key) {
  722. if (!empty($item[$key]) && is_string($item[$key])) {
  723. $item[$key] = Minz_Helper::htmlspecialchars_utf8($item[$key]);
  724. }
  725. }
  726. // CDATA protection
  727. $item['content'] = str_replace(']]>', ']]&gt;', $item['content']);
  728. $view->entries[] = FreshRSS_Entry::fromArray($item);
  729. }
  730. }
  731. } catch (Exception $ex) {
  732. Minz_Log::warning($ex->getMessage());
  733. return null;
  734. }
  735. return $this->simplePieFromContent($view->renderToString());
  736. }
  737. /**
  738. * @return int|null The max number of unread articles to keep, or null if disabled.
  739. */
  740. public function keepMaxUnread() {
  741. $keepMaxUnread = $this->attributeInt('keep_max_n_unread');
  742. if ($keepMaxUnread === null) {
  743. $keepMaxUnread = FreshRSS_Context::userConf()->mark_when['max_n_unread'];
  744. }
  745. return is_int($keepMaxUnread) && $keepMaxUnread >= 0 ? $keepMaxUnread : null;
  746. }
  747. /**
  748. * @return int|false The number of articles marked as read, of false if error
  749. */
  750. public function markAsReadMaxUnread() {
  751. $keepMaxUnread = $this->keepMaxUnread();
  752. if ($keepMaxUnread === null) {
  753. return false;
  754. }
  755. $feedDAO = FreshRSS_Factory::createFeedDao();
  756. $affected = $feedDAO->markAsReadMaxUnread($this->id(), $keepMaxUnread);
  757. if ($affected > 0) {
  758. Minz_Log::debug(__METHOD__ . " $affected items [" . $this->url(false) . ']');
  759. }
  760. return $affected;
  761. }
  762. /**
  763. * Applies the *mark as read upon gone* policy, if enabled.
  764. * Remember to call `updateCachedValue($id_feed)` or `updateCachedValues()` just after.
  765. * @return int|false the number of lines affected, or false if not applicable
  766. */
  767. public function markAsReadUponGone(bool $upstreamIsEmpty, int $maxTimestamp = 0) {
  768. $readUponGone = $this->attributeBoolean('read_upon_gone');
  769. if ($readUponGone === null) {
  770. $readUponGone = FreshRSS_Context::userConf()->mark_when['gone'];
  771. }
  772. if (!$readUponGone) {
  773. return false;
  774. }
  775. if ($upstreamIsEmpty) {
  776. if ($maxTimestamp <= 0) {
  777. $maxTimestamp = time();
  778. }
  779. $entryDAO = FreshRSS_Factory::createEntryDao();
  780. $affected = $entryDAO->markReadFeed($this->id(), $maxTimestamp . '000000');
  781. } else {
  782. $feedDAO = FreshRSS_Factory::createFeedDao();
  783. $affected = $feedDAO->markAsReadUponGone($this->id());
  784. }
  785. if ($affected > 0) {
  786. Minz_Log::debug(__METHOD__ . " $affected items" . ($upstreamIsEmpty ? ' (all)' : '') . ' [' . $this->url(false) . ']');
  787. }
  788. return $affected;
  789. }
  790. /**
  791. * Remember to call `updateCachedValue($id_feed)` or `updateCachedValues()` just after
  792. * @return int|false
  793. */
  794. public function cleanOldEntries() {
  795. /** @var array<string,bool|int|string>|null $archiving */
  796. $archiving = $this->attributeArray('archiving');
  797. if ($archiving === null) {
  798. $catDAO = FreshRSS_Factory::createCategoryDao();
  799. $category = $catDAO->searchById($this->categoryId);
  800. $archiving = $category === null ? null : $category->attributeArray('archiving');
  801. /** @var array<string,bool|int|string>|null $archiving */
  802. if ($archiving === null) {
  803. $archiving = FreshRSS_Context::userConf()->archiving;
  804. }
  805. }
  806. if (is_array($archiving)) {
  807. $entryDAO = FreshRSS_Factory::createEntryDao();
  808. $nb = $entryDAO->cleanOldEntries($this->id(), $archiving);
  809. if ($nb > 0) {
  810. Minz_Log::debug($nb . ' entries cleaned in feed [' . $this->url(false) . '] with: ' . json_encode($archiving));
  811. }
  812. return $nb;
  813. }
  814. return false;
  815. }
  816. /**
  817. * @param string $url Overridden URL. Will default to the feed URL.
  818. * @throws FreshRSS_Context_Exception
  819. */
  820. public function cacheFilename(string $url = ''): string {
  821. $simplePie = customSimplePie($this->attributes(), $this->curlOptions());
  822. $url = $url ?: htmlspecialchars_decode($this->url);
  823. $filename = $simplePie->get_cache_filename($url);
  824. if ($this->kind === FreshRSS_Feed::KIND_HTML_XPATH) {
  825. return CACHE_PATH . '/' . $filename . '.html';
  826. } elseif ($this->kind === FreshRSS_Feed::KIND_XML_XPATH) {
  827. return CACHE_PATH . '/' . $filename . '.xml';
  828. } else {
  829. return CACHE_PATH . '/' . $filename . '.spc';
  830. }
  831. }
  832. public function clearCache(): bool {
  833. return @unlink($this->cacheFilename());
  834. }
  835. /** @return int|false */
  836. public function cacheModifiedTime() {
  837. $filename = $this->cacheFilename();
  838. clearstatcache(true, $filename);
  839. return @filemtime($filename);
  840. }
  841. public function lock(): bool {
  842. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  843. if (file_exists($this->lockPath) && ((time() - (@filemtime($this->lockPath) ?: 0)) > 3600)) {
  844. @unlink($this->lockPath);
  845. }
  846. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  847. return false;
  848. }
  849. //register_shutdown_function('unlink', $this->lockPath);
  850. @fclose($handle);
  851. return true;
  852. }
  853. public function unlock(): bool {
  854. return @unlink($this->lockPath);
  855. }
  856. //<WebSub>
  857. public function pubSubHubbubEnabled(): bool {
  858. $url = $this->selfUrl ?: $this->url;
  859. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  860. if ($hubFile = @file_get_contents($hubFilename)) {
  861. $hubJson = json_decode($hubFile, true);
  862. if (is_array($hubJson) && empty($hubJson['error']) &&
  863. (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
  864. return true;
  865. }
  866. }
  867. return false;
  868. }
  869. public function pubSubHubbubError(bool $error = true): bool {
  870. $url = $this->selfUrl ?: $this->url;
  871. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  872. $hubFile = @file_get_contents($hubFilename);
  873. $hubJson = is_string($hubFile) ? json_decode($hubFile, true) : null;
  874. if (is_array($hubJson) && !isset($hubJson['error']) || $hubJson['error'] !== $error) {
  875. $hubJson['error'] = $error;
  876. file_put_contents($hubFilename, json_encode($hubJson));
  877. Minz_Log::warning('Set error to ' . ($error ? 1 : 0) . ' for ' . $url, PSHB_LOG);
  878. }
  879. return false;
  880. }
  881. /**
  882. * @return string|false
  883. */
  884. public function pubSubHubbubPrepare() {
  885. $key = '';
  886. if (Minz_Request::serverIsPublic(FreshRSS_Context::systemConf()->base_url) &&
  887. $this->hubUrl && $this->selfUrl && @is_dir(PSHB_PATH)) {
  888. $path = PSHB_PATH . '/feeds/' . sha1($this->selfUrl);
  889. $hubFilename = $path . '/!hub.json';
  890. if ($hubFile = @file_get_contents($hubFilename)) {
  891. $hubJson = json_decode($hubFile, true);
  892. if (!is_array($hubJson) || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  893. $text = 'Invalid JSON for WebSub: ' . $this->url;
  894. Minz_Log::warning($text);
  895. Minz_Log::warning($text, PSHB_LOG);
  896. return false;
  897. }
  898. if ((!empty($hubJson['lease_end'])) && ($hubJson['lease_end'] < (time() + (3600 * 23)))) { //TODO: Make a better policy
  899. $text = 'WebSub lease ends at '
  900. . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
  901. . ' and needs renewal: ' . $this->url;
  902. Minz_Log::warning($text);
  903. Minz_Log::warning($text, PSHB_LOG);
  904. $key = $hubJson['key']; //To renew our lease
  905. } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
  906. (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
  907. $key = $hubJson['key']; //To renew our lease
  908. }
  909. } else {
  910. @mkdir($path, 0770, true);
  911. $key = sha1($path . FreshRSS_Context::systemConf()->salt);
  912. $hubJson = [
  913. 'hub' => $this->hubUrl,
  914. 'key' => $key,
  915. ];
  916. file_put_contents($hubFilename, json_encode($hubJson));
  917. @mkdir(PSHB_PATH . '/keys/', 0770, true);
  918. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', $this->selfUrl);
  919. $text = 'WebSub prepared for ' . $this->url;
  920. Minz_Log::debug($text);
  921. Minz_Log::debug($text, PSHB_LOG);
  922. }
  923. $currentUser = Minz_User::name() ?? '';
  924. if (FreshRSS_user_Controller::checkUsername($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  925. touch($path . '/' . $currentUser . '.txt');
  926. }
  927. }
  928. return $key;
  929. }
  930. //Parameter true to subscribe, false to unsubscribe.
  931. public function pubSubHubbubSubscribe(bool $state): bool {
  932. if ($state) {
  933. $url = $this->selfUrl ?: $this->url;
  934. } else {
  935. $url = $this->url; //Always use current URL during unsubscribe
  936. }
  937. if ($url && (Minz_Request::serverIsPublic(FreshRSS_Context::systemConf()->base_url) || !$state)) {
  938. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  939. $hubFile = @file_get_contents($hubFilename);
  940. if ($hubFile === false) {
  941. Minz_Log::warning('JSON not found for WebSub: ' . $this->url);
  942. return false;
  943. }
  944. $hubJson = json_decode($hubFile, true);
  945. if (!is_array($hubJson) || empty($hubJson['key']) || !ctype_xdigit($hubJson['key']) || empty($hubJson['hub'])) {
  946. Minz_Log::warning('Invalid JSON for WebSub: ' . $this->url);
  947. return false;
  948. }
  949. $callbackUrl = checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
  950. if ($callbackUrl == '') {
  951. Minz_Log::warning('Invalid callback for WebSub: ' . $this->url);
  952. return false;
  953. }
  954. if (!$state) { //unsubscribe
  955. $hubJson['lease_end'] = time() - 60;
  956. file_put_contents($hubFilename, json_encode($hubJson));
  957. }
  958. $ch = curl_init();
  959. curl_setopt_array($ch, [
  960. CURLOPT_URL => $hubJson['hub'],
  961. CURLOPT_RETURNTRANSFER => true,
  962. CURLOPT_POSTFIELDS => http_build_query([
  963. 'hub.verify' => 'sync',
  964. 'hub.mode' => $state ? 'subscribe' : 'unsubscribe',
  965. 'hub.topic' => $url,
  966. 'hub.callback' => $callbackUrl,
  967. ]),
  968. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  969. CURLOPT_MAXREDIRS => 10,
  970. CURLOPT_FOLLOWLOCATION => true,
  971. CURLOPT_ENCODING => '', //Enable all encodings
  972. ]);
  973. $response = curl_exec($ch);
  974. $info = curl_getinfo($ch);
  975. Minz_Log::warning('WebSub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $url .
  976. ' via hub ' . $hubJson['hub'] .
  977. ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response, PSHB_LOG);
  978. if (substr('' . $info['http_code'], 0, 1) == '2') {
  979. return true;
  980. } else {
  981. $hubJson['lease_start'] = time(); //Prevent trying again too soon
  982. $hubJson['error'] = true;
  983. file_put_contents($hubFilename, json_encode($hubJson));
  984. return false;
  985. }
  986. }
  987. return false;
  988. }
  989. //</WebSub>
  990. }