]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/actions/finishopenidlogin.php
Merge remote-tracking branch 'upstream/master' into social-master
[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(array $args=array())
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 instanceof 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
282                 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
283                     common_rememberme($user);
284                 }
285
286                 unset($_SESSION['openid_rememberme']);
287                 $this->goHome($user->nickname);
288             } else {
289                 $this->saveValues($display, $canonical, $sreg);
290                 $this->showForm(null, $this->bestNewNickname($display, $sreg));
291             }
292         }
293     }
294
295     function message($msg)
296     {
297         $this->message_text = $msg;
298         $this->showPage();
299     }
300
301     function saveValues($display, $canonical, $sreg)
302     {
303         common_ensure_session();
304         $_SESSION['openid_display'] = $display;
305         $_SESSION['openid_canonical'] = $canonical;
306         $_SESSION['openid_sreg'] = $sreg;
307     }
308
309     function getSavedValues()
310     {
311         return array($_SESSION['openid_display'],
312                      $_SESSION['openid_canonical'],
313                      $_SESSION['openid_sreg']);
314     }
315
316     function createNewUser()
317     {
318         // FIXME: save invite code before redirect, and check here
319
320         if (!Event::handle('StartRegistrationTry', array($this))) {
321             return;
322         }
323
324         if (common_config('site', 'closed')) {
325             // TRANS: OpenID plugin message. No new user registration is allowed on the site.
326             $this->clientError(_m('Registration not allowed.'));
327         }
328
329         $invite = null;
330
331         if (common_config('site', 'inviteonly')) {
332             $code = $_SESSION['invitecode'];
333             if (empty($code)) {
334                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and none was provided.
335                 $this->clientError(_m('Registration not allowed.'));
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             }
344         }
345
346         try {
347             $nickname = Nickname::normalize($this->trimmed('newname'), true);
348         } catch (NicknameException $e) {
349             $this->showForm($e->getMessage());
350             return;
351         }
352
353         list($display, $canonical, $sreg) = $this->getSavedValues();
354
355         if (!$display || !$canonical) {
356             // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
357             $this->serverError(_m('Stored OpenID not found.'));
358         }
359
360         // Possible race condition... let's be paranoid
361
362         $other = oid_get_user($canonical);
363
364         if ($other) {
365             // TRANS: OpenID plugin server error.
366             $this->serverError(_m('Creating new account for OpenID that already has a user.'));
367         }
368
369         Event::handle('StartOpenIDCreateNewUser', array($canonical, &$sreg));
370
371         $location = '';
372         if (!empty($sreg['country'])) {
373             if ($sreg['postcode']) {
374                 // XXX: use postcode to get city and region
375                 // XXX: also, store postcode somewhere -- it's valuable!
376                 $location = $sreg['postcode'] . ', ' . $sreg['country'];
377             } else {
378                 $location = $sreg['country'];
379             }
380         }
381
382         if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
383             $fullname = $sreg['fullname'];
384         } else {
385             $fullname = '';
386         }
387
388         $email = $this->getEmail();
389
390         // XXX: add language
391         // XXX: add timezone
392
393         $args = array('nickname' => $nickname,
394                       'email' => $email,
395                       'fullname' => $fullname,
396                       'location' => $location);
397
398         if (!empty($invite)) {
399             $args['code'] = $invite->code;
400         }
401
402         $user = User::register($args);
403
404         $result = oid_link_user($user->id, $canonical, $display);
405
406         Event::handle('EndOpenIDCreateNewUser', array($user, $canonical, $sreg));
407
408         oid_set_last($display);
409         common_set_user($user);
410         common_real_login(true);
411         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
412             common_rememberme($user);
413         }
414         unset($_SESSION['openid_rememberme']);
415
416         Event::handle('EndRegistrationTry', array($this));
417
418         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)), 303);
419     }
420
421     function connectUser()
422     {
423         $nickname = $this->trimmed('nickname');
424         $password = $this->trimmed('password');
425
426         if (!common_check_user($nickname, $password)) {
427             // TRANS: OpenID plugin message.
428             $this->showForm(_m('Invalid username or password.'));
429             return;
430         }
431
432         // They're legit!
433
434         $user = User::getKV('nickname', $nickname);
435
436         list($display, $canonical, $sreg) = $this->getSavedValues();
437
438         if (!$display || !$canonical) {
439             // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
440             $this->serverError(_m('Stored OpenID not found.'));
441         }
442
443         $result = oid_link_user($user->id, $canonical, $display);
444
445         if (!$result) {
446             // TRANS: OpenID plugin server error. The user or user profile could not be saved.
447             $this->serverError(_m('Error connecting user to OpenID.'));
448         }
449
450         if (Event::handle('StartOpenIDUpdateUser', array($user, $canonical, &$sreg))) {
451             oid_update_user($user, $sreg);
452         }
453         Event::handle('EndOpenIDUpdateUser', array($user, $canonical, $sreg));
454
455         oid_set_last($display);
456         common_set_user($user);
457         common_real_login(true);
458         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
459             common_rememberme($user);
460         }
461         unset($_SESSION['openid_rememberme']);
462         $this->goHome($user->nickname);
463     }
464
465     function goHome($nickname)
466     {
467         $url = common_get_returnto();
468         if ($url) {
469             // We don't have to return to it again
470             common_set_returnto(null);
471             $url = common_inject_session($url);
472         } else {
473             $url = common_local_url('all',
474                                     array('nickname' =>
475                                           $nickname));
476         }
477         common_redirect($url, 303);
478     }
479
480     function bestNewNickname($display, $sreg)
481     {
482         // Try the passed-in nickname
483
484         if (!empty($sreg['nickname'])) {
485             $nickname = common_nicknamize($sreg['nickname']);
486             if (Nickname::isValid($nickname, true)) {
487                 return $nickname;
488             }
489         }
490
491         // Try the full name
492
493         if (!empty($sreg['fullname'])) {
494             $fullname = common_nicknamize($sreg['fullname']);
495             if (Nickname::isValid($fullname, true)) {
496                 return $fullname;
497             }
498         }
499
500         // Try the URL
501
502         $from_url = $this->openidToNickname($display);
503
504         if ($from_url && Nickname::isValid($from_url, true)) {
505             return $from_url;
506         }
507
508         // XXX: others?
509
510         return null;
511     }
512
513     function openidToNickname($openid)
514     {
515         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
516             return $this->xriToNickname($openid);
517         } else {
518             return $this->urlToNickname($openid);
519         }
520     }
521
522     // We try to use an OpenID URL as a legal StatusNet user name in this order
523     // 1. Plain hostname, like http://evanp.myopenid.com/
524     // 2. One element in path, like http://profile.typekey.com/EvanProdromou/
525     //    or http://getopenid.com/evanprodromou
526     function urlToNickname($openid)
527     {
528         return common_url_to_nickname($openid);
529     }
530
531     function xriToNickname($xri)
532     {
533         $base = $this->xriBase($xri);
534
535         if (!$base) {
536             return null;
537         } else {
538             // =evan.prodromou
539             // or @gratis*evan.prodromou
540             $parts = explode('*', substr($base, 1));
541             return common_nicknamize(array_pop($parts));
542         }
543     }
544
545     function xriBase($xri)
546     {
547         if (substr($xri, 0, 6) == 'xri://') {
548             return substr($xri, 6);
549         } else {
550             return $xri;
551         }
552     }
553 }