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