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