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