]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/finishopenidlogin.php
Merge branch '0.9.x' of gitorious.org:statusnet/mainline into 0.9.x
[quix0rs-gnu-social.git] / plugins / OpenID / finishopenidlogin.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, 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('STATUSNET')) {
21     exit(1);
22 }
23
24 require_once INSTALLDIR.'/plugins/OpenID/openid.php';
25
26 class FinishopenidloginAction extends Action
27 {
28     var $error = null;
29     var $username = null;
30     var $message = null;
31
32     function handle($args)
33     {
34         parent::handle($args);
35         if (common_is_real_login()) {
36             // TRANS: Client error message trying to log on with OpenID while already logged on.
37             $this->clientError(_m('Already logged in.'));
38         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
39             $token = $this->trimmed('token');
40             if (!$token || $token != common_session_token()) {
41                 // TRANS: Message given when there is a problem with the user's session token.
42                 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
43                 return;
44             }
45             if ($this->arg('create')) {
46                 if (!$this->boolean('license')) {
47                     // TRANS: Message given if user does not agree with the site's license.
48                     $this->showForm(_m('You can\'t register if you don\'t agree to the license.'),
49                                     $this->trimmed('newname'));
50                     return;
51                 }
52                 $this->createNewUser();
53             } else if ($this->arg('connect')) {
54                 $this->connectUser();
55             } else {
56                 // TRANS: Messag given on an unknown error.
57                 $this->showForm(_m('An unknown error has occured.'),
58                                 $this->trimmed('newname'));
59             }
60         } else {
61             $this->tryLogin();
62         }
63     }
64
65     function showPageNotice()
66     {
67         if ($this->error) {
68             $this->element('div', array('class' => 'error'), $this->error);
69         } else {
70             $this->element('div', 'instructions',
71                            // TRANS: Instructions given after a first successful logon using OpenID.
72                            // TRANS: %s is the site name.
73                            sprintf(_m('This is the first time you\'ve logged into %s so we must connect your OpenID to a local account. You can either create a new account, or connect with your existing account, if you have one.'), common_config('site', 'name')));
74         }
75     }
76
77     function title()
78     {
79         // TRANS: Title
80         return _m('OpenID Account Setup');
81     }
82
83     function showForm($error=null, $username=null)
84     {
85         $this->error = $error;
86         $this->username = $username;
87
88         $this->showPage();
89     }
90
91     /**
92      * @fixme much of this duplicates core code, which is very fragile.
93      * Should probably be replaced with an extensible mini version of
94      * the core registration form.
95      */
96     function showContent()
97     {
98         if (!empty($this->message_text)) {
99             $this->element('div', array('class' => 'error'), $this->message_text);
100             return;
101         }
102
103         // We don't recognize this OpenID, so we're going to give the user
104         // two options, each in its own mini-form.
105         //
106         // First, they can create a new account using their OpenID auth
107         // info. The profile will be pre-populated with whatever name,
108         // email, and location we can get from the OpenID provider, so
109         // all we ask for is the license confirmation.
110         $this->elementStart('form', array('method' => 'post',
111                                           'id' => 'account_create',
112                                           'class' => 'form_settings',
113                                           'action' => common_local_url('finishopenidlogin')));
114         $this->hidden('token', common_session_token());
115         $this->elementStart('fieldset', array('id' => 'form_openid_createaccount'));
116         $this->element('legend', null,
117                        _m('Create new account'));
118         $this->element('p', null,
119                        _m('Create a new user with this nickname.'));
120         $this->elementStart('ul', 'form_data');
121
122         // Hook point for captcha etc
123         Event::handle('StartRegistrationFormData', array($this));
124
125         $this->elementStart('li');
126         $this->input('newname', _m('New nickname'),
127                      ($this->username) ? $this->username : '',
128                      _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
129         $this->elementEnd('li');
130         $this->elementStart('li');
131         $this->input('email', _('Email'), $this->getEmail(),
132                      _('Used only for updates, announcements, '.
133                        'and password recovery'));
134         $this->elementEnd('li');
135
136         // Hook point for captcha etc
137         Event::handle('EndRegistrationFormData', array($this));
138
139         $this->elementStart('li');
140         $this->element('input', array('type' => 'checkbox',
141                                       'id' => 'license',
142                                       'class' => 'checkbox',
143                                       'name' => 'license',
144                                       'value' => 'true'));
145         $this->elementStart('label', array('for' => 'license',
146                                           'class' => 'checkbox'));
147         // TRANS: OpenID plugin link text.
148         // TRANS: %s is a link to a licese with the license name as link text.
149         $message = _('My text and files are available under %s ' .
150                      'except this private data: password, ' .
151                      'email address, IM address, and phone number.');
152         $link = '<a href="' .
153                 htmlspecialchars(common_config('license', 'url')) .
154                 '">' .
155                 htmlspecialchars(common_config('license', 'title')) .
156                 '</a>';
157         $this->raw(sprintf(htmlspecialchars($message), $link));
158         $this->elementEnd('label');
159         $this->elementEnd('li');
160         $this->elementEnd('ul');
161         // TRANS: Button label in form in which to create a new user on the site for an OpenID.
162         $this->submit('create', _m('BUTTON', 'Create'));
163         $this->elementEnd('fieldset');
164         $this->elementEnd('form');
165
166         // The second option is to attach this OpenID to an existing account
167         // on the local system, which they need to provide a password for.
168         $this->elementStart('form', array('method' => 'post',
169                                           'id' => 'account_connect',
170                                           'class' => 'form_settings',
171                                           'action' => common_local_url('finishopenidlogin')));
172         $this->hidden('token', common_session_token());
173         $this->elementStart('fieldset', array('id' => 'form_openid_createaccount'));
174         $this->element('legend', null,
175                        // TRANS: Used as form legend for form in which to connect an OpenID to an existing user on the site.
176                        _m('Connect existing account'));
177         $this->element('p', null,
178                        // TRANS: User instructions for form in which to connect an OpenID to an existing user on the site.
179                        _m('If you already have an account, login with your username and password to connect it to your OpenID.'));
180         $this->elementStart('ul', 'form_data');
181         $this->elementStart('li');
182         // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
183         $this->input('nickname', _m('Existing nickname'));
184         $this->elementEnd('li');
185         $this->elementStart('li');
186         // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
187         $this->password('password', _m('Password'));
188         $this->elementEnd('li');
189         $this->elementEnd('ul');
190         // TRANS: Button label in form in which to connect an OpenID to an existing user on the site.
191         $this->submit('connect', _m('BUTTON', 'Connect'));
192         $this->elementEnd('fieldset');
193         $this->elementEnd('form');
194     }
195
196     /**
197      * Get specified e-mail from the form, or the OpenID sreg info, or the
198      * invite code.
199      *
200      * @return string
201      */
202     function getEmail()
203     {
204         $email = $this->trimmed('email');
205         if (!empty($email)) {
206             return $email;
207         }
208
209         // Pull from openid thingy
210         list($display, $canonical, $sreg) = $this->getSavedValues();
211         if (!empty($sreg['email'])) {
212             return $sreg['email'];
213         }
214
215         // Terrible hack for invites...
216         if (common_config('site', 'inviteonly')) {
217             $code = $_SESSION['invitecode'];
218             if ($code) {
219                 $invite = Invitation::staticGet($code);
220
221                 if ($invite && $invite->address_type == 'email') {
222                     return $invite->address;
223                 }
224             }
225         }
226         return '';
227     }
228
229     function tryLogin()
230     {
231         $consumer = oid_consumer();
232
233         $response = $consumer->complete(common_local_url('finishopenidlogin'));
234
235         if ($response->status == Auth_OpenID_CANCEL) {
236             // TRANS: Status message in case the response from the OpenID provider is that the logon attempt was cancelled.
237             $this->message(_m('OpenID authentication cancelled.'));
238             return;
239         } else if ($response->status == Auth_OpenID_FAILURE) {
240             // TRANS: OpenID authentication failed; display the error message. %s is the error message.
241             $this->message(sprintf(_m('OpenID authentication failed: %s'), $response->message));
242         } else if ($response->status == Auth_OpenID_SUCCESS) {
243             // This means the authentication succeeded; extract the
244             // identity URL and Simple Registration data (if it was
245             // returned).
246             $display = $response->getDisplayIdentifier();
247             $canonical = ($response->endpoint->canonicalID) ?
248               $response->endpoint->canonicalID : $response->getDisplayIdentifier();
249
250             oid_assert_allowed($display);
251             oid_assert_allowed($canonical);
252
253             $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
254
255             if ($sreg_resp) {
256                 $sreg = $sreg_resp->contents();
257             }
258
259             // Launchpad teams extension
260             if (!oid_check_teams($response)) {
261                 $this->message(_m('OpenID authentication aborted: you are not allowed to login to this site.'));
262                 return;
263             }
264
265             $user = oid_get_user($canonical);
266
267             if ($user) {
268                 oid_set_last($display);
269                 # XXX: commented out at @edd's request until better
270                 # control over how data flows from OpenID provider.
271                 # oid_update_user($user, $sreg);
272                 common_set_user($user);
273                 common_real_login(true);
274                 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
275                     common_rememberme($user);
276                 }
277                 unset($_SESSION['openid_rememberme']);
278                 $this->goHome($user->nickname);
279             } else {
280                 $this->saveValues($display, $canonical, $sreg);
281                 $this->showForm(null, $this->bestNewNickname($display, $sreg));
282             }
283         }
284     }
285
286     function message($msg)
287     {
288         $this->message_text = $msg;
289         $this->showPage();
290     }
291
292     function saveValues($display, $canonical, $sreg)
293     {
294         common_ensure_session();
295         $_SESSION['openid_display'] = $display;
296         $_SESSION['openid_canonical'] = $canonical;
297         $_SESSION['openid_sreg'] = $sreg;
298     }
299
300     function getSavedValues()
301     {
302         return array($_SESSION['openid_display'],
303                      $_SESSION['openid_canonical'],
304                      $_SESSION['openid_sreg']);
305     }
306
307     function createNewUser()
308     {
309         # FIXME: save invite code before redirect, and check here
310
311         if (!Event::handle('StartRegistrationTry', array($this))) {
312             return;
313         }
314
315         if (common_config('site', 'closed')) {
316             // TRANS: OpenID plugin message. No new user registration is allowed on the site.
317             $this->clientError(_m('Registration not allowed.'));
318             return;
319         }
320
321         $invite = null;
322
323         if (common_config('site', 'inviteonly')) {
324             $code = $_SESSION['invitecode'];
325             if (empty($code)) {
326                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and none was provided.
327                 $this->clientError(_m('Registration not allowed.'));
328                 return;
329             }
330
331             $invite = Invitation::staticGet($code);
332
333             if (empty($invite)) {
334                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and the one provided was not valid.
335                 $this->clientError(_m('Not a valid invitation code.'));
336                 return;
337             }
338         }
339
340         try {
341             $nickname = Nickname::normalize($this->trimmed('newname'));
342         } catch (NicknameException $e) {
343             $this->showForm($e->getMessage());
344             return;
345         }
346
347         if (!User::allowed_nickname($nickname)) {
348             // TRANS: OpenID plugin message. The entered new user name is blacklisted.
349             $this->showForm(_m('Nickname not allowed.'));
350             return;
351         }
352
353         if (User::staticGet('nickname', $nickname)) {
354             // TRANS: OpenID plugin message. The entered new user name is already used.
355             $this->showForm(_m('Nickname already in use. Try another one.'));
356             return;
357         }
358
359         list($display, $canonical, $sreg) = $this->getSavedValues();
360
361         if (!$display || !$canonical) {
362             // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
363             $this->serverError(_m('Stored OpenID not found.'));
364             return;
365         }
366
367         # Possible race condition... let's be paranoid
368
369         $other = oid_get_user($canonical);
370
371         if ($other) {
372             // TRANS: OpenID plugin server error.
373             $this->serverError(_m('Creating new account for OpenID that already has a user.'));
374             return;
375         }
376
377         Event::handle('StartOpenIDCreateNewUser', array($canonical, &$sreg));
378
379         $location = '';
380         if (!empty($sreg['country'])) {
381             if ($sreg['postcode']) {
382                 # XXX: use postcode to get city and region
383                 # XXX: also, store postcode somewhere -- it's valuable!
384                 $location = $sreg['postcode'] . ', ' . $sreg['country'];
385             } else {
386                 $location = $sreg['country'];
387             }
388         }
389
390         if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
391             $fullname = $sreg['fullname'];
392         } else {
393             $fullname = '';
394         }
395
396         $email = $this->getEmail();
397
398         # XXX: add language
399         # XXX: add timezone
400
401         $args = array('nickname' => $nickname,
402                       'email' => $email,
403                       'fullname' => $fullname,
404                       'location' => $location);
405
406         if (!empty($invite)) {
407             $args['code'] = $invite->code;
408         }
409
410         $user = User::register($args);
411
412         $result = oid_link_user($user->id, $canonical, $display);
413
414         Event::handle('EndOpenIDCreateNewUser', array($user, $canonical, $sreg));
415
416         oid_set_last($display);
417         common_set_user($user);
418         common_real_login(true);
419         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
420             common_rememberme($user);
421         }
422         unset($_SESSION['openid_rememberme']);
423
424         Event::handle('EndRegistrationTry', array($this));
425
426         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
427                         303);
428     }
429
430     function connectUser()
431     {
432         $nickname = $this->trimmed('nickname');
433         $password = $this->trimmed('password');
434
435         if (!common_check_user($nickname, $password)) {
436             // TRANS: OpenID plugin message.
437             $this->showForm(_m('Invalid username or password.'));
438             return;
439         }
440
441         # They're legit!
442
443         $user = User::staticGet('nickname', $nickname);
444
445         list($display, $canonical, $sreg) = $this->getSavedValues();
446
447         if (!$display || !$canonical) {
448             // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
449             $this->serverError(_m('Stored OpenID not found.'));
450             return;
451         }
452
453         $result = oid_link_user($user->id, $canonical, $display);
454
455         if (!$result) {
456             // TRANS: OpenID plugin server error. The user or user profile could not be saved.
457             $this->serverError(_m('Error connecting user to OpenID.'));
458             return;
459         }
460
461         if (Event::handle('StartOpenIDUpdateUser', array($user, $canonical, &$sreg))) {
462             oid_update_user($user, $sreg);
463         }
464         Event::handle('EndOpenIDUpdateUser', array($user, $canonical, $sreg));
465
466         oid_set_last($display);
467         common_set_user($user);
468         common_real_login(true);
469         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
470             common_rememberme($user);
471         }
472         unset($_SESSION['openid_rememberme']);
473         $this->goHome($user->nickname);
474     }
475
476     function goHome($nickname)
477     {
478         $url = common_get_returnto();
479         if ($url) {
480             # We don't have to return to it again
481             common_set_returnto(null);
482             $url = common_inject_session($url);
483         } else {
484             $url = common_local_url('all',
485                                     array('nickname' =>
486                                           $nickname));
487         }
488         common_redirect($url, 303);
489     }
490
491     function bestNewNickname($display, $sreg)
492     {
493
494         # Try the passed-in nickname
495
496         if (!empty($sreg['nickname'])) {
497             $nickname = $this->nicknamize($sreg['nickname']);
498             if ($this->isNewNickname($nickname)) {
499                 return $nickname;
500             }
501         }
502
503         # Try the full name
504
505         if (!empty($sreg['fullname'])) {
506             $fullname = $this->nicknamize($sreg['fullname']);
507             if ($this->isNewNickname($fullname)) {
508                 return $fullname;
509             }
510         }
511
512         # Try the URL
513
514         $from_url = $this->openidToNickname($display);
515
516         if ($from_url && $this->isNewNickname($from_url)) {
517             return $from_url;
518         }
519
520         # XXX: others?
521
522         return null;
523     }
524
525     function isNewNickname($str)
526     {
527         if (!Nickname::isValid($str)) {
528             return false;
529         }
530         if (!User::allowed_nickname($str)) {
531             return false;
532         }
533         if (User::staticGet('nickname', $str)) {
534             return false;
535         }
536         return true;
537     }
538
539     function openidToNickname($openid)
540     {
541         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
542             return $this->xriToNickname($openid);
543         } else {
544             return $this->urlToNickname($openid);
545         }
546     }
547
548     # We try to use an OpenID URL as a legal StatusNet user name in this order
549     # 1. Plain hostname, like http://evanp.myopenid.com/
550     # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
551     #    or http://getopenid.com/evanprodromou
552
553     function urlToNickname($openid)
554     {
555         return common_url_to_nickname($openid);
556     }
557
558     function xriToNickname($xri)
559     {
560         $base = $this->xriBase($xri);
561
562         if (!$base) {
563             return null;
564         } else {
565             # =evan.prodromou
566             # or @gratis*evan.prodromou
567             $parts = explode('*', substr($base, 1));
568             return $this->nicknamize(array_pop($parts));
569         }
570     }
571
572     function xriBase($xri)
573     {
574         if (substr($xri, 0, 6) == 'xri://') {
575             return substr($xri, 6);
576         } else {
577             return $xri;
578         }
579     }
580
581     # Given a string, try to make it work as a nickname
582
583     function nicknamize($str)
584     {
585         return common_nicknamize($str);
586     }
587 }