]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/remotesubscribe.php
14e8cb0683f1bcc20fc2ad6e04fe1ecf35aa0352
[quix0rs-gnu-social.git] / actions / remotesubscribe.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('LACONICA')) { exit(1); }
21
22 require_once(INSTALLDIR.'/lib/omb.php');
23
24 class RemotesubscribeAction extends Action {
25
26     function handle($args) {
27
28         parent::handle($args);
29
30         if (common_logged_in()) {
31             common_user_error(_('You can use the local subscription!'));
32             return;
33         }
34
35         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
36
37             # CSRF protection
38             $token = $this->trimmed('token');
39             if (!$token || $token != common_session_token()) {
40                 $this->show_form(_('There was a problem with your session token. Try again, please.'));
41                 return;
42             }
43
44             $this->remote_subscription();
45         } else {
46             $this->show_form();
47         }
48     }
49
50     function get_instructions() {
51         return _('To subscribe, you can [login](%%action.login%%),' .
52                   ' or [register](%%action.register%%) a new ' .
53                   ' account. If you already have an account ' .
54                   ' on a [compatible microblogging site](%%doc.openmublog%%), ' .
55                   ' enter your profile URL below.');
56     }
57
58     function show_top($err=NULL) {
59         if ($err) {
60             common_element('div', 'error', $err);
61         } else {
62             $instructions = $this->get_instructions();
63             $output = common_markup_to_html($instructions);
64             common_element_start('div', 'instructions');
65             common_raw($output);
66             common_element_end('p');
67         }
68     }
69
70     function show_form($err=NULL) {
71         $nickname = $this->trimmed('nickname');
72         $profile = $this->trimmed('profile_url');
73         common_show_header(_('Remote subscribe'), NULL, $err,
74                            array($this, 'show_top'));
75         # id = remotesubscribe conflicts with the
76         # button on profile page
77         common_element_start('form', array('id' => 'remsub', 'method' => 'post',
78                                            'action' => common_local_url('remotesubscribe')));
79         common_hidden('token', common_session_token());
80         common_input('nickname', _('User nickname'), $nickname,
81                      _('Nickname of the user you want to follow'));
82         common_input('profile_url', _('Profile URL'), $profile,
83                      _('URL of your profile on another compatible microblogging service'));
84         common_submit('submit', _('Subscribe'));
85         common_element_end('form');
86         common_show_footer();
87     }
88
89     function remote_subscription() {
90         $user = $this->get_user();
91
92         if (!$user) {
93             $this->show_form(_('No such user.'));
94             return;
95         }
96
97         $profile = $this->trimmed('profile_url');
98
99         if (!$profile) {
100             $this->show_form(_('No such user.'));
101             return;
102         }
103
104         if (!Validate::uri($profile, array('allowed_schemes' => array('http', 'https')))) {
105             $this->show_form(_('Invalid profile URL (bad format)'));
106             return;
107         }
108
109         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
110         $yadis = Auth_Yadis_Yadis::discover($profile, $fetcher);
111
112         if (!$yadis || $yadis->failed) {
113             $this->show_form(_('Not a valid profile URL (no YADIS document).'));
114             return;
115         }
116
117         # XXX: a little liberal for sites that accidentally put whitespace before the xml declaration
118
119         $xrds =& Auth_Yadis_XRDS::parseXRDS(trim($yadis->response_text));
120
121         if (!$xrds) {
122             $this->show_form(_('Not a valid profile URL (no XRDS defined).'));
123             return;
124         }
125
126         $omb = $this->getOmb($xrds);
127
128         if (!$omb) {
129             $this->show_form(_('Not a valid profile URL (incorrect services).'));
130             return;
131         }
132
133         if (omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]) ==
134             common_local_url('requesttoken'))
135         {
136             $this->show_form(_('That\'s a local profile! Login to subscribe.'));
137             return;
138         }
139
140         if (User::staticGet('uri', omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]))) {
141             $this->show_form(_('That\'s a local profile! Login to subscribe.'));
142             return;
143         }
144
145         list($token, $secret) = $this->request_token($omb);
146
147         if (!$token || !$secret) {
148             $this->show_form(_('Couldn\'t get a request token.'));
149             return;
150         }
151
152         $this->request_authorization($user, $omb, $token, $secret);
153     }
154
155     function get_user() {
156         $user = NULL;
157         $nickname = $this->trimmed('nickname');
158         if ($nickname) {
159             $user = User::staticGet('nickname', $nickname);
160         }
161         return $user;
162     }
163
164     function getOmb($xrds) {
165
166         static $omb_endpoints = array(OMB_ENDPOINT_UPDATEPROFILE, OMB_ENDPOINT_POSTNOTICE);
167         static $oauth_endpoints = array(OAUTH_ENDPOINT_REQUEST, OAUTH_ENDPOINT_AUTHORIZE,
168                                         OAUTH_ENDPOINT_ACCESS);
169         $omb = array();
170
171         # XXX: the following code could probably be refactored to eliminate dupes
172
173         $oauth_services = omb_get_services($xrds, OAUTH_DISCOVERY);
174
175         if (!$oauth_services) {
176             return NULL;
177         }
178
179         $oauth_service = $oauth_services[0];
180
181         $oauth_xrd = $this->getXRD($oauth_service, $xrds);
182
183         if (!$oauth_xrd) {
184             return NULL;
185         }
186
187         if (!$this->addServices($oauth_xrd, $oauth_endpoints, $omb)) {
188             return NULL;
189         }
190
191         $omb_services = omb_get_services($xrds, OMB_NAMESPACE);
192
193         if (!$omb_services) {
194             return NULL;
195         }
196
197         $omb_service = $omb_services[0];
198
199         $omb_xrd = $this->getXRD($omb_service, $xrds);
200
201         if (!$omb_xrd) {
202             return NULL;
203         }
204
205         if (!$this->addServices($omb_xrd, $omb_endpoints, $omb)) {
206             return NULL;
207         }
208
209         # XXX: check that we got all the services we needed
210
211         foreach (array_merge($omb_endpoints, $oauth_endpoints) as $type) {
212             if (!array_key_exists($type, $omb) || !$omb[$type]) {
213                 return NULL;
214             }
215         }
216
217         if (!omb_local_id($omb[OAUTH_ENDPOINT_REQUEST])) {
218             return NULL;
219         }
220
221         return $omb;
222     }
223
224     function getXRD($main_service, $main_xrds) {
225         $uri = omb_service_uri($main_service);
226         if (strpos($uri, "#") !== 0) {
227             # FIXME: more rigorous handling of external service definitions
228             return NULL;
229         }
230         $id = substr($uri, 1);
231         $nodes = $main_xrds->allXrdNodes;
232         $parser = $main_xrds->parser;
233         foreach ($nodes as $node) {
234             $attrs = $parser->attributes($node);
235             if (array_key_exists('xml:id', $attrs) &&
236                 $attrs['xml:id'] == $id) {
237                 # XXX: trick the constructor into thinking this is the only node
238                 $bogus_nodes = array($node);
239                 return new Auth_Yadis_XRDS($parser, $bogus_nodes);
240             }
241         }
242         return NULL;
243     }
244
245     function addServices($xrd, $types, &$omb) {
246         foreach ($types as $type) {
247             $matches = omb_get_services($xrd, $type);
248             if ($matches) {
249                 $omb[$type] = $matches[0];
250             } else {
251                 # no match for type
252                 return false;
253             }
254         }
255         return true;
256     }
257
258     function request_token($omb) {
259         $con = omb_oauth_consumer();
260
261         $url = omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]);
262
263         # XXX: Is this the right thing to do? Strip off GET params and make them
264         # POST params? Seems wrong to me.
265
266         $parsed = parse_url($url);
267         $params = array();
268         parse_str($parsed['query'], $params);
269
270         $req = OAuthRequest::from_consumer_and_token($con, NULL, "POST", $url, $params);
271
272         $listener = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]);
273
274         if (!$listener) {
275             return NULL;
276         }
277
278         $req->set_parameter('omb_listener', $listener);
279         $req->set_parameter('omb_version', OMB_VERSION_01);
280
281         # XXX: test to see if endpoint accepts this signature method
282
283         $req->sign_request(omb_hmac_sha1(), $con, NULL);
284
285         # We re-use this tool's fetcher, since it's pretty good
286
287         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
288
289         $result = $fetcher->post($req->get_normalized_http_url(),
290                                  $req->to_postdata(),
291                                  array('User-Agent' => 'Laconica/' . LACONICA_VERSION));
292
293         if ($result->status != 200) {
294             return NULL;
295         }
296
297         parse_str($result->body, $return);
298
299         return array($return['oauth_token'], $return['oauth_token_secret']);
300     }
301
302     function request_authorization($user, $omb, $token, $secret) {
303         global $config; # for license URL
304
305         $con = omb_oauth_consumer();
306         $tok = new OAuthToken($token, $secret);
307
308         $url = omb_service_uri($omb[OAUTH_ENDPOINT_AUTHORIZE]);
309
310         # XXX: Is this the right thing to do? Strip off GET params and make them
311         # POST params? Seems wrong to me.
312
313         $parsed = parse_url($url);
314         $params = array();
315         parse_str($parsed['query'], $params);
316
317         $req = OAuthRequest::from_consumer_and_token($con, $tok, 'GET', $url, $params);
318
319         # We send over a ton of information. This lets the other
320         # server store info about our user, and it lets the current
321         # user decide if they really want to authorize the subscription.
322
323         $req->set_parameter('omb_version', OMB_VERSION_01);
324         $req->set_parameter('omb_listener', omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]));
325         $req->set_parameter('omb_listenee', $user->uri);
326         $req->set_parameter('omb_listenee_profile', common_profile_url($user->nickname));
327         $req->set_parameter('omb_listenee_nickname', $user->nickname);
328         $req->set_parameter('omb_listenee_license', $config['license']['url']);
329
330         $profile = $user->getProfile();
331         if (!$profile) {
332             common_log_db_error($user, 'SELECT', __FILE__);
333             $this->server_error(_('User without matching profile'));
334             return;
335         }
336
337         if ($profile->fullname) {
338             $req->set_parameter('omb_listenee_fullname', $profile->fullname);
339         }
340         if ($profile->homepage) {
341             $req->set_parameter('omb_listenee_homepage', $profile->homepage);
342         }
343         if ($profile->bio) {
344             $req->set_parameter('omb_listenee_bio', $profile->bio);
345         }
346         if ($profile->location) {
347             $req->set_parameter('omb_listenee_location', $profile->location);
348         }
349         $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
350         if ($avatar) {
351             $req->set_parameter('omb_listenee_avatar', $avatar->url);
352         }
353
354         # XXX: add a nonce to prevent replay attacks
355
356         $req->set_parameter('oauth_callback', common_local_url('finishremotesubscribe'));
357
358         # XXX: test to see if endpoint accepts this signature method
359
360         $req->sign_request(omb_hmac_sha1(), $con, $tok);
361
362         # store all our info here
363
364         $omb['listenee'] = $user->nickname;
365         $omb['listener'] = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]);
366         $omb['token'] = $token;
367         $omb['secret'] = $secret;
368         # call doesn't work after bounce back so we cache; maybe serialization issue...?
369         $omb['access_token_url'] = omb_service_uri($omb[OAUTH_ENDPOINT_ACCESS]);
370         $omb['post_notice_url'] = omb_service_uri($omb[OMB_ENDPOINT_POSTNOTICE]);
371         $omb['update_profile_url'] = omb_service_uri($omb[OMB_ENDPOINT_UPDATEPROFILE]);
372
373         common_ensure_session();
374
375         $_SESSION['oauth_authorization_request'] = $omb;
376
377         # Redirect to authorization service
378
379         common_redirect($req->to_url());
380         return;
381     }
382
383     function make_nonce() {
384         return common_good_rand(16);
385     }
386 }