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