]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/finishopenidlogin.php
86dd1c669b95ed30a4334d52c49ca588307e849e
[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 (common_config('site', 'closed')) {
251             // TRANS: OpenID plugin message. No new user registration is allowed on the site.
252             $this->clientError(_m('Registration not allowed.'));
253             return;
254         }
255
256         $invite = null;
257
258         if (common_config('site', 'inviteonly')) {
259             $code = $_SESSION['invitecode'];
260             if (empty($code)) {
261                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and none was provided.
262                 $this->clientError(_m('Registration not allowed.'));
263                 return;
264             }
265
266             $invite = Invitation::staticGet($code);
267
268             if (empty($invite)) {
269                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and the one provided was not valid.
270                 $this->clientError(_m('Not a valid invitation code.'));
271                 return;
272             }
273         }
274
275         try {
276             $nickname = Nickname::validate($this->trimmed('newname'));
277         } catch (NicknameException $e) {
278             $this->showForm($e->getMessage());
279             return;
280         }
281
282         if (!User::allowed_nickname($nickname)) {
283             // TRANS: OpenID plugin message. The entered new user name is blacklisted.
284             $this->showForm(_m('Nickname not allowed.'));
285             return;
286         }
287
288         if (User::staticGet('nickname', $nickname)) {
289             // TRANS: OpenID plugin message. The entered new user name is already used.
290             $this->showForm(_m('Nickname already in use. Try another one.'));
291             return;
292         }
293
294         list($display, $canonical, $sreg) = $this->getSavedValues();
295
296         if (!$display || !$canonical) {
297             // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
298             $this->serverError(_m('Stored OpenID not found.'));
299             return;
300         }
301
302         # Possible race condition... let's be paranoid
303
304         $other = oid_get_user($canonical);
305
306         if ($other) {
307             // TRANS: OpenID plugin server error.
308             $this->serverError(_m('Creating new account for OpenID that already has a user.'));
309             return;
310         }
311
312         Event::handle('StartOpenIDCreateNewUser', array($canonical, &$sreg));
313
314         $location = '';
315         if (!empty($sreg['country'])) {
316             if ($sreg['postcode']) {
317                 # XXX: use postcode to get city and region
318                 # XXX: also, store postcode somewhere -- it's valuable!
319                 $location = $sreg['postcode'] . ', ' . $sreg['country'];
320             } else {
321                 $location = $sreg['country'];
322             }
323         }
324
325         if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
326             $fullname = $sreg['fullname'];
327         } else {
328             $fullname = '';
329         }
330
331         if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
332             $email = $sreg['email'];
333         } else {
334             $email = '';
335         }
336
337         # XXX: add language
338         # XXX: add timezone
339
340         $args = array('nickname' => $nickname,
341                       'email' => $email,
342                       'fullname' => $fullname,
343                       'location' => $location);
344
345         if (!empty($invite)) {
346             $args['code'] = $invite->code;
347         }
348
349         $user = User::register($args);
350
351         $result = oid_link_user($user->id, $canonical, $display);
352
353         Event::handle('EndOpenIDCreateNewUser', array($user, $canonical, $sreg));
354
355         oid_set_last($display);
356         common_set_user($user);
357         common_real_login(true);
358         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
359             common_rememberme($user);
360         }
361         unset($_SESSION['openid_rememberme']);
362         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
363                         303);
364     }
365
366     function connectUser()
367     {
368         $nickname = $this->trimmed('nickname');
369         $password = $this->trimmed('password');
370
371         if (!common_check_user($nickname, $password)) {
372             // TRANS: OpenID plugin message.
373             $this->showForm(_m('Invalid username or password.'));
374             return;
375         }
376
377         # They're legit!
378
379         $user = User::staticGet('nickname', $nickname);
380
381         list($display, $canonical, $sreg) = $this->getSavedValues();
382
383         if (!$display || !$canonical) {
384             // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
385             $this->serverError(_m('Stored OpenID not found.'));
386             return;
387         }
388
389         $result = oid_link_user($user->id, $canonical, $display);
390
391         if (!$result) {
392             // TRANS: OpenID plugin server error. The user or user profile could not be saved.
393             $this->serverError(_m('Error connecting user to OpenID.'));
394             return;
395         }
396
397         if (Event::handle('StartOpenIDUpdateUser', array($user, $canonical, &$sreg))) {
398             oid_update_user($user, $sreg);
399         }
400         Event::handle('EndOpenIDUpdateUser', array($user, $canonical, $sreg));
401
402         oid_set_last($display);
403         common_set_user($user);
404         common_real_login(true);
405         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
406             common_rememberme($user);
407         }
408         unset($_SESSION['openid_rememberme']);
409         $this->goHome($user->nickname);
410     }
411
412     function goHome($nickname)
413     {
414         $url = common_get_returnto();
415         if ($url) {
416             # We don't have to return to it again
417             common_set_returnto(null);
418             $url = common_inject_session($url);
419         } else {
420             $url = common_local_url('all',
421                                     array('nickname' =>
422                                           $nickname));
423         }
424         common_redirect($url, 303);
425     }
426
427     function bestNewNickname($display, $sreg)
428     {
429
430         # Try the passed-in nickname
431
432         if (!empty($sreg['nickname'])) {
433             $nickname = $this->nicknamize($sreg['nickname']);
434             if ($this->isNewNickname($nickname)) {
435                 return $nickname;
436             }
437         }
438
439         # Try the full name
440
441         if (!empty($sreg['fullname'])) {
442             $fullname = $this->nicknamize($sreg['fullname']);
443             if ($this->isNewNickname($fullname)) {
444                 return $fullname;
445             }
446         }
447
448         # Try the URL
449
450         $from_url = $this->openidToNickname($display);
451
452         if ($from_url && $this->isNewNickname($from_url)) {
453             return $from_url;
454         }
455
456         # XXX: others?
457
458         return null;
459     }
460
461     function isNewNickname($str)
462     {
463         if (!Nickname::isValid($str)) {
464             return false;
465         }
466         if (!User::allowed_nickname($str)) {
467             return false;
468         }
469         if (User::staticGet('nickname', $str)) {
470             return false;
471         }
472         return true;
473     }
474
475     function openidToNickname($openid)
476     {
477         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
478             return $this->xriToNickname($openid);
479         } else {
480             return $this->urlToNickname($openid);
481         }
482     }
483
484     # We try to use an OpenID URL as a legal StatusNet user name in this order
485     # 1. Plain hostname, like http://evanp.myopenid.com/
486     # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
487     #    or http://getopenid.com/evanprodromou
488
489     function urlToNickname($openid)
490     {
491         return common_url_to_nickname($openid);
492     }
493
494     function xriToNickname($xri)
495     {
496         $base = $this->xriBase($xri);
497
498         if (!$base) {
499             return null;
500         } else {
501             # =evan.prodromou
502             # or @gratis*evan.prodromou
503             $parts = explode('*', substr($base, 1));
504             return $this->nicknamize(array_pop($parts));
505         }
506     }
507
508     function xriBase($xri)
509     {
510         if (substr($xri, 0, 6) == 'xri://') {
511             return substr($xri, 6);
512         } else {
513             return $xri;
514         }
515     }
516
517     # Given a string, try to make it work as a nickname
518
519     function nicknamize($str)
520     {
521         return common_nicknamize($str);
522     }
523 }