pshb.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. <?php
  2. declare(strict_types=1);
  3. require dirname(__DIR__, 2) . '/constants.php';
  4. require LIB_PATH . '/lib_rss.php'; //Includes class autoloader
  5. const MAX_PAYLOAD = 3_145_728;
  6. header('Content-Type: text/plain; charset=UTF-8');
  7. header("Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; sandbox");
  8. header('X-Content-Type-Options: nosniff');
  9. $ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, MAX_PAYLOAD) ?: '';
  10. FreshRSS_Context::initSystem();
  11. if (!FreshRSS_Context::hasSystemConf()) {
  12. header('HTTP/1.1 500 Internal Server Error');
  13. die('Invalid system init!');
  14. }
  15. FreshRSS_Context::systemConf()->auth_type = 'none'; // avoid necessity to be logged in (not saved!)
  16. // Minz_Log::debug(print_r(['_SERVER' => $_SERVER, '_GET' => $_GET, '_POST' => $_POST, 'INPUT' => $ORIGINAL_INPUT], true), PSHB_LOG);
  17. $key = isset($_GET['k']) && is_string($_GET['k']) ? substr($_GET['k'], 0, 128) : '';
  18. if (!ctype_xdigit($key)) {
  19. header('HTTP/1.1 422 Unprocessable Entity');
  20. die('Invalid feed key format!');
  21. }
  22. chdir(PSHB_PATH);
  23. $canonical = @file_get_contents('keys/' . $key . '.txt');
  24. if ($canonical === false) {
  25. if (!empty($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] === 'unsubscribe') {
  26. Minz_Log::warning('Warning: Accept unknown unsubscribe', PSHB_LOG);
  27. header('Connection: close');
  28. exit($_REQUEST['hub_challenge'] ?? '');
  29. }
  30. // https://github.com/w3c/websub/issues/106 , https://w3c.github.io/websub/#content-distribution
  31. header('HTTP/1.1 410 Gone');
  32. Minz_Log::warning('Warning: Feed key not found!: ' . $key, PSHB_LOG);
  33. die('Feed key not found!');
  34. }
  35. $canonical = trim($canonical);
  36. $canonicalHash = sha1($canonical);
  37. $hubFile = @file_get_contents('feeds/' . $canonicalHash . '/!hub.json');
  38. if ($hubFile === false) {
  39. header('HTTP/1.1 410 Gone');
  40. unlink('keys/' . $key . '.txt');
  41. Minz_Log::error('Error: Feed info not found!: ' . $canonical, PSHB_LOG);
  42. die('Feed info not found!');
  43. }
  44. $hubJson = json_decode($hubFile, true);
  45. if (!is_array($hubJson) || empty($hubJson['key']) || $hubJson['key'] !== $key) {
  46. header('HTTP/1.1 500 Internal Server Error');
  47. Minz_Log::error('Error: Invalid key cross-check!: ' . $key, PSHB_LOG);
  48. die('Invalid key cross-check!');
  49. }
  50. chdir('feeds/' . $canonicalHash);
  51. $users = glob('*.txt', GLOB_NOSORT);
  52. if (empty($users)) {
  53. header('HTTP/1.1 410 Gone');
  54. Minz_Log::warning('Warning: Nobody subscribes to this feed anymore!: ' . $canonical, PSHB_LOG);
  55. unlink('../../keys/' . $key . '.txt');
  56. $feed = new FreshRSS_Feed($canonical);
  57. $feed->pubSubHubbubSubscribe(false);
  58. unlink('!hub.json');
  59. chdir('..');
  60. recursive_unlink('feeds/' . $canonicalHash);
  61. die('Nobody subscribes to this feed anymore!');
  62. }
  63. if (!empty($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] === 'subscribe') {
  64. $leaseSeconds = empty($_REQUEST['hub_lease_seconds']) || !is_numeric($_REQUEST['hub_lease_seconds']) ? 0 : (int)$_REQUEST['hub_lease_seconds'];
  65. if ($leaseSeconds > 60) {
  66. $hubJson['lease_end'] = time() + $leaseSeconds;
  67. } else {
  68. unset($hubJson['lease_end']);
  69. }
  70. $hubJson['lease_start'] = time();
  71. if (!isset($hubJson['error'])) {
  72. $hubJson['error'] = true; //Do not assume that WebSub works until the first successful push
  73. }
  74. file_put_contents('./!hub.json', json_encode($hubJson));
  75. header('Connection: close');
  76. exit($_REQUEST['hub_challenge'] ?? '');
  77. }
  78. if (!empty($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] === 'unsubscribe') {
  79. if (empty($hubJson['lease_end']) || $hubJson['lease_end'] < time()) {
  80. header('Connection: close');
  81. exit($_REQUEST['hub_challenge'] ?? '');
  82. } else {
  83. header('HTTP/1.1 422 Unprocessable Entity');
  84. die('We did not ask to unsubscribe!');
  85. }
  86. }
  87. if ($ORIGINAL_INPUT == '') {
  88. header('HTTP/1.1 422 Unprocessable Entity');
  89. die('Missing XML payload!');
  90. }
  91. $simplePie = new FreshRSS_SimplePieCustom();
  92. $simplePie->enable_cache(false);
  93. $simplePie->set_raw_data($ORIGINAL_INPUT);
  94. $simplePie->init();
  95. unset($ORIGINAL_INPUT);
  96. $links = $simplePie->get_links('self');
  97. $self = $links[0] ?? '';
  98. // Support HTTP header `Link: <http://example.net/hub.php>; rel="hub", <http://example.net/feed.php>; rel="self"`
  99. $httpLink = is_string($_SERVER['HTTP_LINK'] ?? null) ? $_SERVER['HTTP_LINK'] : '';
  100. if ($httpLink !== '' && preg_match_all('/<([^>]+)>;\\s*rel="([^"]+)"/', $httpLink, $matches, PREG_SET_ORDER)) {
  101. $links = [];
  102. foreach ($matches as $match) {
  103. if (!empty($match[1]) && !empty($match[2])) {
  104. $links[$match[2]] = $match[1];
  105. }
  106. }
  107. // if (!empty($links['hub'])) {
  108. // // TODO: Support WebSub hub redirection
  109. // }
  110. if (!empty($links['self'])) {
  111. $httpSelf = FreshRSS_http_Util::checkUrl($links['self']) ?: '';
  112. if ($self !== '' && $self !== $httpSelf) {
  113. Minz_Log::warning('Warning: Self URL mismatch between XML [' . $self . '] and HTTP!: ' . $httpSelf, PSHB_LOG);
  114. }
  115. $self = $httpSelf;
  116. }
  117. }
  118. if ($self !== $canonical) {
  119. //header('HTTP/1.1 422 Unprocessable Entity');
  120. Minz_Log::warning('Warning: Self URL [' . $self . '] does not match registered canonical URL!: ' . $canonical, PSHB_LOG);
  121. //die('Self URL does not match registered canonical URL!');
  122. }
  123. Minz_ExtensionManager::init();
  124. Minz_Translate::init();
  125. $nb = 0;
  126. foreach ($users as $userFilename) {
  127. $username = basename($userFilename, '.txt');
  128. if (!file_exists(USERS_PATH . '/' . $username . '/config.php')) {
  129. Minz_Log::warning('Warning: Removing broken user link: ' . $username . ' for ' . $canonical, PSHB_LOG);
  130. unlink($userFilename);
  131. continue;
  132. }
  133. try {
  134. FreshRSS_Context::initUser($username);
  135. if (!FreshRSS_Context::hasUserConf() || !FreshRSS_Context::userConf()->enabled) {
  136. Minz_Log::warning('FreshRSS skip disabled user ' . $username);
  137. continue;
  138. }
  139. Minz_ExtensionManager::enableByList(FreshRSS_Context::userConf()->extensions_enabled, 'user');
  140. Minz_Translate::reset(FreshRSS_Context::userConf()->language);
  141. [$nbUpdatedFeeds, ] = FreshRSS_feed_Controller::actualizeFeedsAndCommit(feed_url: $canonical, simplePiePush: $simplePie, selfUrl: $self);
  142. if ($nbUpdatedFeeds > 0) {
  143. $nb++;
  144. } else {
  145. Minz_Log::warning('Warning: User ' . $username . ' does not subscribe anymore to ' . $canonical, PSHB_LOG);
  146. unlink($userFilename);
  147. }
  148. } catch (Exception $e) {
  149. Minz_Log::error('Error: ' . $e->getMessage() . ' for user ' . $username . ' and feed ' . $canonical, PSHB_LOG);
  150. }
  151. }
  152. $simplePie->__destruct(); //http://simplepie.org/wiki/faq/i_m_getting_memory_leaks
  153. unset($simplePie);
  154. if ($nb === 0) {
  155. header('HTTP/1.1 410 Gone');
  156. Minz_Log::warning('Warning: Nobody subscribes to this feed anymore after all!: ' . $canonical, PSHB_LOG);
  157. die('Nobody subscribes to this feed anymore after all!');
  158. } elseif (!empty($hubJson['error'])) {
  159. $hubJson['error'] = false;
  160. file_put_contents('./!hub.json', json_encode($hubJson));
  161. }
  162. Minz_Log::notice('WebSub ' . $canonical . ' done: ' . $nb, PSHB_LOG);
  163. exit('Done: ' . $nb . "\n");