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