]> 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             $user = oid_get_user($canonical);
197
198             if ($user) {
199                 oid_set_last($display);
200                 # XXX: commented out at @edd's request until better
201                 # control over how data flows from OpenID provider.
202                 # oid_update_user($user, $sreg);
203                 common_set_user($user);
204                 common_real_login(true);
205                 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
206                     common_rememberme($user);
207                 }
208                 unset($_SESSION['openid_rememberme']);
209                 $this->goHome($user->nickname);
210             } else {
211                 $this->saveValues($display, $canonical, $sreg);
212                 $this->showForm(null, $this->bestNewNickname($display, $sreg));
213             }
214         }
215     }
216
217     function message($msg)
218     {
219         $this->message_text = $msg;
220         $this->showPage();
221     }
222
223     function saveValues($display, $canonical, $sreg)
224     {
225         common_ensure_session();
226         $_SESSION['openid_display'] = $display;
227         $_SESSION['openid_canonical'] = $canonical;
228         $_SESSION['openid_sreg'] = $sreg;
229     }
230
231     function getSavedValues()
232     {
233         return array($_SESSION['openid_display'],
234                      $_SESSION['openid_canonical'],
235                      $_SESSION['openid_sreg']);
236     }
237
238     function createNewUser()
239     {
240         # FIXME: save invite code before redirect, and check here
241
242         if (common_config('site', 'closed')) {
243             // TRANS: OpenID plugin message. No new user registration is allowed on the site.
244             $this->clientError(_m('Registration not allowed.'));
245             return;
246         }
247
248         $invite = null;
249
250         if (common_config('site', 'inviteonly')) {
251             $code = $_SESSION['invitecode'];
252             if (empty($code)) {
253                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and none was provided.
254                 $this->clientError(_m('Registration not allowed.'));
255                 return;
256             }
257
258             $invite = Invitation::staticGet($code);
259
260             if (empty($invite)) {
261                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and the one provided was not valid.
262                 $this->clientError(_m('Not a valid invitation code.'));
263                 return;
264             }
265         }
266
267         $nickname = $this->trimmed('newname');
268
269         if (!Validate::string($nickname, array('min_length' => 1,
270                                                'max_length' => 64,
271                                                'format' => NICKNAME_FMT))) {
272             // TRANS: OpenID plugin message. The entered new user name did not conform to the requirements.
273             $this->showForm(_m('Nickname must have only lowercase letters and numbers and no spaces.'));
274             return;
275         }
276
277         if (!User::allowed_nickname($nickname)) {
278             // TRANS: OpenID plugin message. The entered new user name is blacklisted.
279             $this->showForm(_m('Nickname not allowed.'));
280             return;
281         }
282
283         if (User::staticGet('nickname', $nickname)) {
284             // TRANS: OpenID plugin message. The entered new user name is already used.
285             $this->showForm(_m('Nickname already in use. Try another one.'));
286             return;
287         }
288
289         list($display, $canonical, $sreg) = $this->getSavedValues();
290
291         if (!$display || !$canonical) {
292             // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
293             $this->serverError(_m('Stored OpenID not found.'));
294             return;
295         }
296
297         # Possible race condition... let's be paranoid
298
299         $other = oid_get_user($canonical);
300
301         if ($other) {
302             // TRANS: OpenID plugin server error.
303             $this->serverError(_m('Creating new account for OpenID that already has a user.'));
304             return;
305         }
306
307         $location = '';
308         if (!empty($sreg['country'])) {
309             if ($sreg['postcode']) {
310                 # XXX: use postcode to get city and region
311                 # XXX: also, store postcode somewhere -- it's valuable!
312                 $location = $sreg['postcode'] . ', ' . $sreg['country'];
313             } else {
314                 $location = $sreg['country'];
315             }
316         }
317
318         if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
319             $fullname = $sreg['fullname'];
320         } else {
321             $fullname = '';
322         }
323
324         if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
325             $email = $sreg['email'];
326         } else {
327             $email = '';
328         }
329
330         # XXX: add language
331         # XXX: add timezone
332
333         $args = array('nickname' => $nickname,
334                       'email' => $email,
335                       'fullname' => $fullname,
336                       'location' => $location);
337
338         if (!empty($invite)) {
339             $args['code'] = $invite->code;
340         }
341
342         $user = User::register($args);
343
344         $result = oid_link_user($user->id, $canonical, $display);
345
346         oid_set_last($display);
347         common_set_user($user);
348         common_real_login(true);
349         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
350             common_rememberme($user);
351         }
352         unset($_SESSION['openid_rememberme']);
353         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
354                         303);
355     }
356
357     function connectUser()
358     {
359         $nickname = $this->trimmed('nickname');
360         $password = $this->trimmed('password');
361
362         if (!common_check_user($nickname, $password)) {
363             // TRANS: OpenID plugin message.
364             $this->showForm(_m('Invalid username or password.'));
365             return;
366         }
367
368         # They're legit!
369
370         $user = User::staticGet('nickname', $nickname);
371
372         list($display, $canonical, $sreg) = $this->getSavedValues();
373
374         if (!$display || !$canonical) {
375             // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
376             $this->serverError(_m('Stored OpenID not found.'));
377             return;
378         }
379
380         $result = oid_link_user($user->id, $canonical, $display);
381
382         if (!$result) {
383             // TRANS: OpenID plugin server error. The user or user profile could not be saved.
384             $this->serverError(_m('Error connecting user to OpenID.'));
385             return;
386         }
387
388         oid_update_user($user, $sreg);
389         oid_set_last($display);
390         common_set_user($user);
391         common_real_login(true);
392         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
393             common_rememberme($user);
394         }
395         unset($_SESSION['openid_rememberme']);
396         $this->goHome($user->nickname);
397     }
398
399     function goHome($nickname)
400     {
401         $url = common_get_returnto();
402         if ($url) {
403             # We don't have to return to it again
404             common_set_returnto(null);
405             $url = common_inject_session($url);
406         } else {
407             $url = common_local_url('all',
408                                     array('nickname' =>
409                                           $nickname));
410         }
411         common_redirect($url, 303);
412     }
413
414     function bestNewNickname($display, $sreg)
415     {
416
417         # Try the passed-in nickname
418
419         if (!empty($sreg['nickname'])) {
420             $nickname = $this->nicknamize($sreg['nickname']);
421             if ($this->isNewNickname($nickname)) {
422                 return $nickname;
423             }
424         }
425
426         # Try the full name
427
428         if (!empty($sreg['fullname'])) {
429             $fullname = $this->nicknamize($sreg['fullname']);
430             if ($this->isNewNickname($fullname)) {
431                 return $fullname;
432             }
433         }
434
435         # Try the URL
436
437         $from_url = $this->openidToNickname($display);
438
439         if ($from_url && $this->isNewNickname($from_url)) {
440             return $from_url;
441         }
442
443         # XXX: others?
444
445         return null;
446     }
447
448     function isNewNickname($str)
449     {
450         if (!Validate::string($str, array('min_length' => 1,
451                                           'max_length' => 64,
452                                           'format' => NICKNAME_FMT))) {
453             return false;
454         }
455         if (!User::allowed_nickname($str)) {
456             return false;
457         }
458         if (User::staticGet('nickname', $str)) {
459             return false;
460         }
461         return true;
462     }
463
464     function openidToNickname($openid)
465     {
466         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
467             return $this->xriToNickname($openid);
468         } else {
469             return $this->urlToNickname($openid);
470         }
471     }
472
473     # We try to use an OpenID URL as a legal StatusNet user name in this order
474     # 1. Plain hostname, like http://evanp.myopenid.com/
475     # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
476     #    or http://getopenid.com/evanprodromou
477
478     function urlToNickname($openid)
479     {
480         return common_url_to_nickname($openid);
481     }
482
483     function xriToNickname($xri)
484     {
485         $base = $this->xriBase($xri);
486
487         if (!$base) {
488             return null;
489         } else {
490             # =evan.prodromou
491             # or @gratis*evan.prodromou
492             $parts = explode('*', substr($base, 1));
493             return $this->nicknamize(array_pop($parts));
494         }
495     }
496
497     function xriBase($xri)
498     {
499         if (substr($xri, 0, 6) == 'xri://') {
500             return substr($xri, 6);
501         } else {
502             return $xri;
503         }
504     }
505
506     # Given a string, try to make it work as a nickname
507
508     function nicknamize($str)
509     {
510         return common_nicknamize($str);
511     }
512 }