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