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