]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/actions/finishopenidlogin.php
Better use of Nickname validation functions
[quix0rs-gnu-social.git] / plugins / OpenID / actions / 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 cannot register if you do not 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 have 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('TITLE','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                        // TRANS: Fieldset legend.
118                        _m('Create new account'));
119         $this->element('p', null,
120                        // TRANS: Form guide.
121                        _m('Create a new user with this nickname.'));
122         $this->elementStart('ul', 'form_data');
123
124         // Hook point for captcha etc
125         Event::handle('StartRegistrationFormData', array($this));
126
127         $this->elementStart('li');
128         // TRANS: Field label.
129         $this->input('newname', _m('New nickname'),
130                      ($this->username) ? $this->username : '',
131                      // TRANS: Field title.
132                      _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
133         $this->elementEnd('li');
134         $this->elementStart('li');
135         // TRANS: Field label.
136         $this->input('email', _m('Email'), $this->getEmail(),
137                      // TRANS: Field title.
138                      _m('Used only for updates, announcements, '.
139                        'and password recovery.'));
140         $this->elementEnd('li');
141
142         // Hook point for captcha etc
143         Event::handle('EndRegistrationFormData', array($this));
144
145         $this->elementStart('li');
146         $this->element('input', array('type' => 'checkbox',
147                                       'id' => 'license',
148                                       'class' => 'checkbox',
149                                       'name' => 'license',
150                                       'value' => 'true'));
151         $this->elementStart('label', array('for' => 'license',
152                                           'class' => 'checkbox'));
153         // TRANS: OpenID plugin link text.
154         // TRANS: %s is a link to a license with the license name as link text.
155         $message = _m('My text and files are available under %s ' .
156                      'except this private data: password, ' .
157                      'email address, IM address, and phone number.');
158         $link = '<a href="' .
159                 htmlspecialchars(common_config('license', 'url')) .
160                 '">' .
161                 htmlspecialchars(common_config('license', 'title')) .
162                 '</a>';
163         $this->raw(sprintf(htmlspecialchars($message), $link));
164         $this->elementEnd('label');
165         $this->elementEnd('li');
166         $this->elementEnd('ul');
167         // TRANS: Button label in form in which to create a new user on the site for an OpenID.
168         $this->submit('create', _m('BUTTON', 'Create'));
169         $this->elementEnd('fieldset');
170         $this->elementEnd('form');
171
172         // The second option is to attach this OpenID to an existing account
173         // on the local system, which they need to provide a password for.
174         $this->elementStart('form', array('method' => 'post',
175                                           'id' => 'account_connect',
176                                           'class' => 'form_settings',
177                                           'action' => common_local_url('finishopenidlogin')));
178         $this->hidden('token', common_session_token());
179         $this->elementStart('fieldset', array('id' => 'form_openid_createaccount'));
180         $this->element('legend', null,
181                        // TRANS: Used as form legend for form in which to connect an OpenID to an existing user on the site.
182                        _m('Connect existing account'));
183         $this->element('p', null,
184                        // TRANS: User instructions for form in which to connect an OpenID to an existing user on the site.
185                        _m('If you already have an account, login with your username and password to connect it to your OpenID.'));
186         $this->elementStart('ul', 'form_data');
187         $this->elementStart('li');
188         // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
189         $this->input('nickname', _m('Existing nickname'));
190         $this->elementEnd('li');
191         $this->elementStart('li');
192         // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
193         $this->password('password', _m('Password'));
194         $this->elementEnd('li');
195         $this->elementEnd('ul');
196         // TRANS: Button text in form in which to connect an OpenID to an existing user on the site.
197         $this->submit('connect', _m('BUTTON', 'Connect'));
198         $this->elementEnd('fieldset');
199         $this->elementEnd('form');
200     }
201
202     /**
203      * Get specified e-mail from the form, or the OpenID sreg info, or the
204      * invite code.
205      *
206      * @return string
207      */
208     function getEmail()
209     {
210         $email = $this->trimmed('email');
211         if (!empty($email)) {
212             return $email;
213         }
214
215         // Pull from openid thingy
216         list($display, $canonical, $sreg) = $this->getSavedValues();
217         if (!empty($sreg['email'])) {
218             return $sreg['email'];
219         }
220
221         // Terrible hack for invites...
222         if (common_config('site', 'inviteonly')) {
223             $code = $_SESSION['invitecode'];
224             if ($code) {
225                 $invite = Invitation::getKV($code);
226
227                 if ($invite && $invite->address_type == 'email') {
228                     return $invite->address;
229                 }
230             }
231         }
232         return '';
233     }
234
235     function tryLogin()
236     {
237         $consumer = oid_consumer();
238
239         $response = $consumer->complete(common_local_url('finishopenidlogin'));
240
241         if ($response->status == Auth_OpenID_CANCEL) {
242             // TRANS: Status message in case the response from the OpenID provider is that the logon attempt was cancelled.
243             $this->message(_m('OpenID authentication cancelled.'));
244             return;
245         } else if ($response->status == Auth_OpenID_FAILURE) {
246             // TRANS: OpenID authentication failed; display the error message. %s is the error message.
247             $this->message(sprintf(_m('OpenID authentication failed: %s.'), $response->message));
248         } else if ($response->status == Auth_OpenID_SUCCESS) {
249             // This means the authentication succeeded; extract the
250             // identity URL and Simple Registration data (if it was
251             // returned).
252             $display = $response->getDisplayIdentifier();
253             $canonical = ($response->endpoint->canonicalID) ?
254               $response->endpoint->canonicalID : $response->getDisplayIdentifier();
255
256             oid_assert_allowed($display);
257             oid_assert_allowed($canonical);
258
259             $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
260
261             if ($sreg_resp) {
262                 $sreg = $sreg_resp->contents();
263             }
264
265             // Launchpad teams extension
266             if (!oid_check_teams($response)) {
267                 // TRANS: Message displayed when OpenID authentication is aborted.
268                 $this->message(_m('OpenID authentication aborted: You are not allowed to login to this site.'));
269                 return;
270             }
271
272             $user = oid_get_user($canonical);
273
274             if ($user) {
275                 oid_set_last($display);
276                 // XXX: commented out at @edd's request until better
277                 // control over how data flows from OpenID provider.
278                 // oid_update_user($user, $sreg);
279                 common_set_user($user);
280                 common_real_login(true);
281                 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
282                     common_rememberme($user);
283                 }
284                 unset($_SESSION['openid_rememberme']);
285                 $this->goHome($user->nickname);
286             } else {
287                 $this->saveValues($display, $canonical, $sreg);
288                 $this->showForm(null, $this->bestNewNickname($display, $sreg));
289             }
290         }
291     }
292
293     function message($msg)
294     {
295         $this->message_text = $msg;
296         $this->showPage();
297     }
298
299     function saveValues($display, $canonical, $sreg)
300     {
301         common_ensure_session();
302         $_SESSION['openid_display'] = $display;
303         $_SESSION['openid_canonical'] = $canonical;
304         $_SESSION['openid_sreg'] = $sreg;
305     }
306
307     function getSavedValues()
308     {
309         return array($_SESSION['openid_display'],
310                      $_SESSION['openid_canonical'],
311                      $_SESSION['openid_sreg']);
312     }
313
314     function createNewUser()
315     {
316         // FIXME: save invite code before redirect, and check here
317
318         if (!Event::handle('StartRegistrationTry', array($this))) {
319             return;
320         }
321
322         if (common_config('site', 'closed')) {
323             // TRANS: OpenID plugin message. No new user registration is allowed on the site.
324             $this->clientError(_m('Registration not allowed.'));
325             return;
326         }
327
328         $invite = null;
329
330         if (common_config('site', 'inviteonly')) {
331             $code = $_SESSION['invitecode'];
332             if (empty($code)) {
333                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and none was provided.
334                 $this->clientError(_m('Registration not allowed.'));
335                 return;
336             }
337
338             $invite = Invitation::getKV($code);
339
340             if (empty($invite)) {
341                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and the one provided was not valid.
342                 $this->clientError(_m('Not a valid invitation code.'));
343                 return;
344             }
345         }
346
347         try {
348             $nickname = Nickname::normalize($this->trimmed('newname'), true);
349         } catch (NicknameException $e) {
350             $this->showForm($e->getMessage());
351             return;
352         }
353
354         list($display, $canonical, $sreg) = $this->getSavedValues();
355
356         if (!$display || !$canonical) {
357             // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
358             $this->serverError(_m('Stored OpenID not found.'));
359             return;
360         }
361
362         // Possible race condition... let's be paranoid
363
364         $other = oid_get_user($canonical);
365
366         if ($other) {
367             // TRANS: OpenID plugin server error.
368             $this->serverError(_m('Creating new account for OpenID that already has a user.'));
369             return;
370         }
371
372         Event::handle('StartOpenIDCreateNewUser', array($canonical, &$sreg));
373
374         $location = '';
375         if (!empty($sreg['country'])) {
376             if ($sreg['postcode']) {
377                 // XXX: use postcode to get city and region
378                 // XXX: also, store postcode somewhere -- it's valuable!
379                 $location = $sreg['postcode'] . ', ' . $sreg['country'];
380             } else {
381                 $location = $sreg['country'];
382             }
383         }
384
385         if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
386             $fullname = $sreg['fullname'];
387         } else {
388             $fullname = '';
389         }
390
391         $email = $this->getEmail();
392
393         // XXX: add language
394         // XXX: add timezone
395
396         $args = array('nickname' => $nickname,
397                       'email' => $email,
398                       'fullname' => $fullname,
399                       'location' => $location);
400
401         if (!empty($invite)) {
402             $args['code'] = $invite->code;
403         }
404
405         $user = User::register($args);
406
407         $result = oid_link_user($user->id, $canonical, $display);
408
409         Event::handle('EndOpenIDCreateNewUser', array($user, $canonical, $sreg));
410
411         oid_set_last($display);
412         common_set_user($user);
413         common_real_login(true);
414         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
415             common_rememberme($user);
416         }
417         unset($_SESSION['openid_rememberme']);
418
419         Event::handle('EndRegistrationTry', array($this));
420
421         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
422                         303);
423     }
424
425     function connectUser()
426     {
427         $nickname = $this->trimmed('nickname');
428         $password = $this->trimmed('password');
429
430         if (!common_check_user($nickname, $password)) {
431             // TRANS: OpenID plugin message.
432             $this->showForm(_m('Invalid username or password.'));
433             return;
434         }
435
436         // They're legit!
437
438         $user = User::getKV('nickname', $nickname);
439
440         list($display, $canonical, $sreg) = $this->getSavedValues();
441
442         if (!$display || !$canonical) {
443             // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
444             $this->serverError(_m('Stored OpenID not found.'));
445             return;
446         }
447
448         $result = oid_link_user($user->id, $canonical, $display);
449
450         if (!$result) {
451             // TRANS: OpenID plugin server error. The user or user profile could not be saved.
452             $this->serverError(_m('Error connecting user to OpenID.'));
453             return;
454         }
455
456         if (Event::handle('StartOpenIDUpdateUser', array($user, $canonical, &$sreg))) {
457             oid_update_user($user, $sreg);
458         }
459         Event::handle('EndOpenIDUpdateUser', array($user, $canonical, $sreg));
460
461         oid_set_last($display);
462         common_set_user($user);
463         common_real_login(true);
464         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
465             common_rememberme($user);
466         }
467         unset($_SESSION['openid_rememberme']);
468         $this->goHome($user->nickname);
469     }
470
471     function goHome($nickname)
472     {
473         $url = common_get_returnto();
474         if ($url) {
475             // We don't have to return to it again
476             common_set_returnto(null);
477             $url = common_inject_session($url);
478         } else {
479             $url = common_local_url('all',
480                                     array('nickname' =>
481                                           $nickname));
482         }
483         common_redirect($url, 303);
484     }
485
486     function bestNewNickname($display, $sreg)
487     {
488         // Try the passed-in nickname
489
490         if (!empty($sreg['nickname'])) {
491             $nickname = common_nicknamize($sreg['nickname']);
492             if (Nickname::isValid($nickname, true)) {
493                 return $nickname;
494             }
495         }
496
497         // Try the full name
498
499         if (!empty($sreg['fullname'])) {
500             $fullname = common_nicknamize($sreg['fullname']);
501             if (Nickname::isValid($fullname, true)) {
502                 return $fullname;
503             }
504         }
505
506         // Try the URL
507
508         $from_url = $this->openidToNickname($display);
509
510         if ($from_url && Nickname::isValid($from_url, true)) {
511             return $from_url;
512         }
513
514         // XXX: others?
515
516         return null;
517     }
518
519     function openidToNickname($openid)
520     {
521         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
522             return $this->xriToNickname($openid);
523         } else {
524             return $this->urlToNickname($openid);
525         }
526     }
527
528     // We try to use an OpenID URL as a legal StatusNet user name in this order
529     // 1. Plain hostname, like http://evanp.myopenid.com/
530     // 2. One element in path, like http://profile.typekey.com/EvanProdromou/
531     //    or http://getopenid.com/evanprodromou
532     function urlToNickname($openid)
533     {
534         return common_url_to_nickname($openid);
535     }
536
537     function xriToNickname($xri)
538     {
539         $base = $this->xriBase($xri);
540
541         if (!$base) {
542             return null;
543         } else {
544             // =evan.prodromou
545             // or @gratis*evan.prodromou
546             $parts = explode('*', substr($base, 1));
547             return common_nicknamize(array_pop($parts));
548         }
549     }
550
551     function xriBase($xri)
552     {
553         if (substr($xri, 0, 6) == 'xri://') {
554             return substr($xri, 6);
555         } else {
556             return $xri;
557         }
558     }
559 }