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