]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/finishopenidlogin.php
Merge branch '1.1.x' of gitorious.org:statusnet/mainline into 1.1.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 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::staticGet($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::staticGet($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'));
349         } catch (NicknameException $e) {
350             $this->showForm($e->getMessage());
351             return;
352         }
353
354         if (!User::allowed_nickname($nickname)) {
355             // TRANS: OpenID plugin message. The entered new user name is blacklisted.
356             $this->showForm(_m('Nickname not allowed.'));
357             return;
358         }
359
360         if (User::staticGet('nickname', $nickname)) {
361             // TRANS: OpenID plugin message. The entered new user name is already used.
362             $this->showForm(_m('Nickname already in use. Try another one.'));
363             return;
364         }
365
366         list($display, $canonical, $sreg) = $this->getSavedValues();
367
368         if (!$display || !$canonical) {
369             // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
370             $this->serverError(_m('Stored OpenID not found.'));
371             return;
372         }
373
374         // Possible race condition... let's be paranoid
375
376         $other = oid_get_user($canonical);
377
378         if ($other) {
379             // TRANS: OpenID plugin server error.
380             $this->serverError(_m('Creating new account for OpenID that already has a user.'));
381             return;
382         }
383
384         Event::handle('StartOpenIDCreateNewUser', array($canonical, &$sreg));
385
386         $location = '';
387         if (!empty($sreg['country'])) {
388             if ($sreg['postcode']) {
389                 // XXX: use postcode to get city and region
390                 // XXX: also, store postcode somewhere -- it's valuable!
391                 $location = $sreg['postcode'] . ', ' . $sreg['country'];
392             } else {
393                 $location = $sreg['country'];
394             }
395         }
396
397         if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
398             $fullname = $sreg['fullname'];
399         } else {
400             $fullname = '';
401         }
402
403         $email = $this->getEmail();
404
405         // XXX: add language
406         // XXX: add timezone
407
408         $args = array('nickname' => $nickname,
409                       'email' => $email,
410                       'fullname' => $fullname,
411                       'location' => $location);
412
413         if (!empty($invite)) {
414             $args['code'] = $invite->code;
415         }
416
417         $user = User::register($args);
418
419         $result = oid_link_user($user->id, $canonical, $display);
420
421         Event::handle('EndOpenIDCreateNewUser', array($user, $canonical, $sreg));
422
423         oid_set_last($display);
424         common_set_user($user);
425         common_real_login(true);
426         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
427             common_rememberme($user);
428         }
429         unset($_SESSION['openid_rememberme']);
430
431         Event::handle('EndRegistrationTry', array($this));
432
433         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
434                         303);
435     }
436
437     function connectUser()
438     {
439         $nickname = $this->trimmed('nickname');
440         $password = $this->trimmed('password');
441
442         if (!common_check_user($nickname, $password)) {
443             // TRANS: OpenID plugin message.
444             $this->showForm(_m('Invalid username or password.'));
445             return;
446         }
447
448         // They're legit!
449
450         $user = User::staticGet('nickname', $nickname);
451
452         list($display, $canonical, $sreg) = $this->getSavedValues();
453
454         if (!$display || !$canonical) {
455             // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
456             $this->serverError(_m('Stored OpenID not found.'));
457             return;
458         }
459
460         $result = oid_link_user($user->id, $canonical, $display);
461
462         if (!$result) {
463             // TRANS: OpenID plugin server error. The user or user profile could not be saved.
464             $this->serverError(_m('Error connecting user to OpenID.'));
465             return;
466         }
467
468         if (Event::handle('StartOpenIDUpdateUser', array($user, $canonical, &$sreg))) {
469             oid_update_user($user, $sreg);
470         }
471         Event::handle('EndOpenIDUpdateUser', array($user, $canonical, $sreg));
472
473         oid_set_last($display);
474         common_set_user($user);
475         common_real_login(true);
476         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
477             common_rememberme($user);
478         }
479         unset($_SESSION['openid_rememberme']);
480         $this->goHome($user->nickname);
481     }
482
483     function goHome($nickname)
484     {
485         $url = common_get_returnto();
486         if ($url) {
487             // We don't have to return to it again
488             common_set_returnto(null);
489             $url = common_inject_session($url);
490         } else {
491             $url = common_local_url('all',
492                                     array('nickname' =>
493                                           $nickname));
494         }
495         common_redirect($url, 303);
496     }
497
498     function bestNewNickname($display, $sreg)
499     {
500         // Try the passed-in nickname
501
502         if (!empty($sreg['nickname'])) {
503             $nickname = $this->nicknamize($sreg['nickname']);
504             if ($this->isNewNickname($nickname)) {
505                 return $nickname;
506             }
507         }
508
509         // Try the full name
510
511         if (!empty($sreg['fullname'])) {
512             $fullname = $this->nicknamize($sreg['fullname']);
513             if ($this->isNewNickname($fullname)) {
514                 return $fullname;
515             }
516         }
517
518         // Try the URL
519
520         $from_url = $this->openidToNickname($display);
521
522         if ($from_url && $this->isNewNickname($from_url)) {
523             return $from_url;
524         }
525
526         // XXX: others?
527
528         return null;
529     }
530
531     function isNewNickname($str)
532     {
533         if (!Nickname::isValid($str)) {
534             return false;
535         }
536         if (!User::allowed_nickname($str)) {
537             return false;
538         }
539         if (User::staticGet('nickname', $str)) {
540             return false;
541         }
542         return true;
543     }
544
545     function openidToNickname($openid)
546     {
547         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
548             return $this->xriToNickname($openid);
549         } else {
550             return $this->urlToNickname($openid);
551         }
552     }
553
554     // We try to use an OpenID URL as a legal StatusNet user name in this order
555     // 1. Plain hostname, like http://evanp.myopenid.com/
556     // 2. One element in path, like http://profile.typekey.com/EvanProdromou/
557     //    or http://getopenid.com/evanprodromou
558     function urlToNickname($openid)
559     {
560         return common_url_to_nickname($openid);
561     }
562
563     function xriToNickname($xri)
564     {
565         $base = $this->xriBase($xri);
566
567         if (!$base) {
568             return null;
569         } else {
570             // =evan.prodromou
571             // or @gratis*evan.prodromou
572             $parts = explode('*', substr($base, 1));
573             return $this->nicknamize(array_pop($parts));
574         }
575     }
576
577     function xriBase($xri)
578     {
579         if (substr($xri, 0, 6) == 'xri://') {
580             return substr($xri, 6);
581         } else {
582             return $xri;
583         }
584     }
585
586     // Given a string, try to make it work as a nickname
587     function nicknamize($str)
588     {
589         return common_nicknamize($str);
590     }
591 }