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