rsscloudrequestnotify.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Action to let RSSCloud aggregators request update notification when
  18. * user profile feeds change.
  19. *
  20. * @category Plugin
  21. * @package GNUsocial
  22. * @author Zach Copley <zach@status.net>
  23. * @copyright 2009 StatusNet, Inc.
  24. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  25. */
  26. defined('GNUSOCIAL') || die();
  27. /**
  28. * Action class to handle RSSCloud notification (subscription) requests
  29. *
  30. * @category Plugin
  31. * @package GNUsocial
  32. * @author Zach Copley <zach@status.net>
  33. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  34. */
  35. class RSSCloudRequestNotifyAction extends Action
  36. {
  37. /**
  38. * Initialization.
  39. *
  40. * @param array $args Web and URL arguments
  41. * @return bool false if user doesn't exist
  42. */
  43. public function prepare(array $args = [])
  44. {
  45. parent::prepare($args);
  46. $this->ip = $_SERVER['REMOTE_ADDR'];
  47. $this->port = $this->arg('port');
  48. $this->path = $this->arg('path');
  49. if ($this->path[0] != '/') {
  50. $this->path = '/' . $this->path;
  51. }
  52. $this->protocol = $this->arg('protocol');
  53. $this->procedure = $this->arg('notifyProcedure');
  54. $this->domain = $this->arg('domain');
  55. $this->feeds = $this->getFeeds();
  56. return true;
  57. }
  58. /**
  59. * Handle the request
  60. *
  61. * Checks for all the required parameters for a subscription,
  62. * validates that the feed being subscribed to is real, and then
  63. * saves the subsctiption.
  64. *
  65. * @param array $args $_REQUEST data (unused)
  66. *
  67. * @return void
  68. */
  69. public function handle()
  70. {
  71. parent::handle();
  72. if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  73. // TRANS: Form validation error displayed when POST is not used.
  74. $this->showResult(false, _m('Request must be POST.'));
  75. return;
  76. }
  77. $missing = array();
  78. if (empty($this->port)) {
  79. $missing[] = 'port';
  80. }
  81. if (empty($this->path)) {
  82. $missing[] = 'path';
  83. }
  84. if (empty($this->protocol)) {
  85. $missing[] = 'protocol';
  86. } elseif (strtolower($this->protocol) !== 'http-post') {
  87. // TRANS: Form validation error displayed when HTTP POST is not used.
  88. $msg = _m('Only HTTP POST notifications are supported at this time.');
  89. $this->showResult(false, $msg);
  90. return;
  91. }
  92. if (!isset($this->procedure)) {
  93. $missing[] = 'notifyProcedure';
  94. }
  95. if (!empty($missing)) {
  96. // TRANS: List separator.
  97. $separator = _m('SEPARATOR', ', ');
  98. // TRANS: Form validation error displayed when a request body is missing expected parameters.
  99. // TRANS: %s is a list of parameters separated by a list separator (default: ", ").
  100. $msg = sprintf(
  101. _m('The following parameters were missing from the request body: %s.'),
  102. implode($separator, $missing)
  103. );
  104. $this->showResult(false, $msg);
  105. return;
  106. }
  107. if (empty($this->feeds)) {
  108. // TRANS: Form validation error displayed when not providing any valid profile feed URLs.
  109. $msg = _m('You must provide at least one valid profile feed URL ' .
  110. '(url1, url2, url3 ... urlN).');
  111. $this->showResult(false, $msg);
  112. return;
  113. }
  114. // We have to validate everything before saving anything.
  115. // We only return one success or failure no matter how
  116. // many feeds the subscriber is trying to subscribe to
  117. foreach ($this->feeds as $feed) {
  118. if (!$this->validateFeed($feed)) {
  119. $nh = $this->getNotifyUrl();
  120. common_log(
  121. LOG_WARNING,
  122. "RSSCloud plugin - {$nh} tried to subscribe to invalid feed: {$feed}"
  123. );
  124. // TRANS: Form validation error displayed when not providing a valid feed URL.
  125. $msg = _m('Feed subscription failed: Not a valid feed.');
  126. $this->showResult(false, $msg);
  127. return;
  128. }
  129. if (!$this->testNotificationHandler($feed)) {
  130. // TRANS: Form validation error displayed when feed subscription failed.
  131. $msg = _m('Feed subscription failed: ' .
  132. 'Notification handler does not respond correctly.');
  133. $this->showResult(false, $msg);
  134. return;
  135. }
  136. }
  137. foreach ($this->feeds as $feed) {
  138. $this->saveSubscription($feed);
  139. }
  140. // XXX: What to do about deleting stale subscriptions?
  141. // 25 hours seems harsh. WordPress doesn't ever remove
  142. // subscriptions.
  143. // TRANS: Success message after subscribing to one or more feeds.
  144. $msg = _m('Thanks for the subscription. ' .
  145. 'When the feed(s) update(s), you will be notified.');
  146. $this->showResult(true, $msg);
  147. }
  148. /**
  149. * Validate that the requested feed is one we serve
  150. * up via RSSCloud.
  151. *
  152. * @param string $feed the feed in question
  153. * @return bool
  154. */
  155. private function validateFeed(string $feed): bool
  156. {
  157. $user = $this->userFromFeed($feed);
  158. if (empty($user)) {
  159. return false;
  160. }
  161. return true;
  162. }
  163. /**
  164. * Pull all of the urls (url1, url2, url3...urlN) that
  165. * the subscriber wants to subscribe to.
  166. *
  167. * @return array $feeds the list of feeds
  168. */
  169. public function getFeeds()
  170. {
  171. $feeds = [];
  172. foreach ($this->args as $key => $feed) {
  173. if (preg_match('/^url\d*$/', $key)) {
  174. $feeds[] = $feed;
  175. }
  176. }
  177. return $feeds;
  178. }
  179. /**
  180. * Test that a notification handler is there and is reponding
  181. * correctly. This is called before adding a subscription.
  182. *
  183. * @param string $feed the feed to verify
  184. * @return bool success result
  185. */
  186. private function testNotificationHandler(string $feed): bool
  187. {
  188. $notifyUrl = $this->getNotifyUrl();
  189. $notifier = new RSSCloudNotifier();
  190. if (isset($this->domain)) {
  191. // 'domain' param set, so we have to use GET and send a challenge
  192. common_log(
  193. LOG_INFO,
  194. 'RSSCloud plugin - Testing notification handler with '
  195. . "challenge: {$notifyUrl}"
  196. );
  197. return $notifier->challenge($notifyUrl, $feed);
  198. } else {
  199. common_log(
  200. LOG_INFO,
  201. 'RSSCloud plugin - Testing notification handler: '
  202. . $notifyUrl
  203. );
  204. return $notifier->postUpdate($notifyUrl, $feed);
  205. }
  206. }
  207. /**
  208. * Build the URL for the notification handler based on the
  209. * parameters passed in with the subscription request.
  210. *
  211. * @return string notification handler url
  212. */
  213. private function getNotifyUrl(): string
  214. {
  215. if (isset($this->domain)) {
  216. return 'http://' . $this->domain . ':' . $this->port . $this->path;
  217. } else {
  218. return 'http://' . $this->ip . ':' . $this->port . $this->path;
  219. }
  220. }
  221. /**
  222. * Uses the nickname part of the subscribed feed URL to figure out
  223. * whethere there's really a user with such a feed. Used to
  224. * validate feeds before adding a subscription.
  225. *
  226. * @param string $feed the feed in question
  227. * @return bool success
  228. */
  229. private function userFromFeed(string $feed): bool
  230. {
  231. // We only do canonical RSS2 profile feeds (specified by ID), e.g.:
  232. // http://www.example.com/api/statuses/user_timeline/2.rss
  233. $path = common_path('api/statuses/user_timeline/');
  234. $valid = '%^' . $path . '(?<id>.*)\.rss$%';
  235. if (preg_match($valid, $feed, $matches)) {
  236. $user = User::getKV('id', $matches['id']);
  237. if (!empty($user)) {
  238. return $user;
  239. }
  240. }
  241. return false;
  242. }
  243. /**
  244. * Save an RSSCloud subscription
  245. *
  246. * @param string $feed a valid profile feed
  247. * @return bool success result
  248. */
  249. private function saveSubscription(string $feed): bool
  250. {
  251. $user = $this->userFromFeed($feed);
  252. $notifyUrl = $this->getNotifyUrl();
  253. $sub = RSSCloudSubscription::getSubscription($user->id, $notifyUrl);
  254. if ($sub) {
  255. common_log(LOG_INFO, "RSSCloud plugin - $notifyUrl refreshed subscription" .
  256. " to user $user->nickname (id: $user->id).");
  257. } else {
  258. $sub = new RSSCloudSubscription();
  259. $sub->subscribed = $user->id;
  260. $sub->url = $notifyUrl;
  261. $sub->created = common_sql_now();
  262. if (!$sub->insert()) {
  263. common_log_db_error($sub, 'INSERT', __FILE__);
  264. return false;
  265. }
  266. common_log(LOG_INFO, "RSSCloud plugin - $notifyUrl subscribed" .
  267. " to user $user->nickname (id: $user->id)");
  268. }
  269. return true;
  270. }
  271. /**
  272. * Show an XML message indicating the subscription
  273. * was successful or failed.
  274. *
  275. * @param bool $success whether it was good or bad
  276. * @param string $msg the message to output
  277. *
  278. * @return bool success result
  279. */
  280. public function showResult(bool $success, string $msg): bool
  281. {
  282. $this->startXML();
  283. $this->elementStart('notifyResult', [
  284. 'success' => ($success ? 'true' : 'false'),
  285. 'msg' => $msg,
  286. ]);
  287. $this->endXML();
  288. }
  289. }