3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
22 require_once INSTALLDIR.'/plugins/OpenID/openid.php';
24 class FinishopenidloginAction extends Action
30 function handle($args)
32 parent::handle($args);
33 if (common_is_real_login()) {
34 $this->clientError(_('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(_('There was a problem with your session token. Try again, please.'));
41 if ($this->arg('create')) {
42 if (!$this->boolean('license')) {
43 $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
44 $this->trimmed('newname'));
47 $this->createNewUser();
48 } else if ($this->arg('connect')) {
51 common_debug(print_r($this->args, true), __FILE__);
52 $this->showForm(_('Something weird happened.'),
53 $this->trimmed('newname'));
60 function showPageNotice()
63 $this->element('div', array('class' => 'error'), $this->error);
65 $this->element('div', 'instructions',
66 sprintf(_('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 return _('OpenID Account Setup');
75 function showForm($error=null, $username=null)
77 $this->error = $error;
78 $this->username = $username;
83 function showContent()
85 if (!empty($this->message_text)) {
86 $this->element('div', array('class' => 'error'), $this->message_text);
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 _('Create new account'));
98 $this->element('p', null,
99 _('Create a new user with this nickname.'));
100 $this->elementStart('ul', 'form_data');
101 $this->elementStart('li');
102 $this->input('newname', _('New nickname'),
103 ($this->username) ? $this->username : '',
104 _('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',
109 'class' => 'checkbox',
112 $this->elementStart('label', array('for' => 'license',
113 'class' => 'checkbox'));
114 $this->text(_('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(_(' 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', _('Create'));
122 $this->elementEnd('fieldset');
124 $this->elementStart('fieldset', array('id' => 'form_openid_createaccount'));
125 $this->element('legend', null,
126 _('Connect existing account'));
127 $this->element('p', null,
128 _('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', _('Existing nickname'));
132 $this->elementEnd('li');
133 $this->elementStart('li');
134 $this->password('password', _('Password'));
135 $this->elementEnd('li');
136 $this->elementEnd('ul');
137 $this->submit('connect', _('Connect'));
138 $this->elementEnd('fieldset');
139 $this->elementEnd('form');
144 $consumer = oid_consumer();
146 $response = $consumer->complete(common_local_url('finishopenidlogin'));
148 if ($response->status == Auth_OpenID_CANCEL) {
149 $this->message(_('OpenID authentication cancelled.'));
151 } else if ($response->status == Auth_OpenID_FAILURE) {
152 // Authentication failed; display the error message.
153 $this->message(sprintf(_('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
158 $display = $response->getDisplayIdentifier();
159 $canonical = ($response->endpoint->canonicalID) ?
160 $response->endpoint->canonicalID : $response->getDisplayIdentifier();
162 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
165 $sreg = $sreg_resp->contents();
168 $user = oid_get_user($canonical);
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);
180 unset($_SESSION['openid_rememberme']);
181 $this->goHome($user->nickname);
183 $this->saveValues($display, $canonical, $sreg);
184 $this->showForm(null, $this->bestNewNickname($display, $sreg));
189 function message($msg)
191 $this->message_text = $msg;
195 function saveValues($display, $canonical, $sreg)
197 common_ensure_session();
198 $_SESSION['openid_display'] = $display;
199 $_SESSION['openid_canonical'] = $canonical;
200 $_SESSION['openid_sreg'] = $sreg;
203 function getSavedValues()
205 return array($_SESSION['openid_display'],
206 $_SESSION['openid_canonical'],
207 $_SESSION['openid_sreg']);
210 function createNewUser()
212 # FIXME: save invite code before redirect, and check here
214 if (common_config('site', 'closed')) {
215 $this->clientError(_('Registration not allowed.'));
221 if (common_config('site', 'inviteonly')) {
222 $code = $_SESSION['invitecode'];
224 $this->clientError(_('Registration not allowed.'));
228 $invite = Invitation::staticGet($code);
230 if (empty($invite)) {
231 $this->clientError(_('Not a valid invitation code.'));
236 $nickname = $this->trimmed('newname');
238 if (!Validate::string($nickname, array('min_length' => 1,
240 'format' => NICKNAME_FMT))) {
241 $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
245 if (!User::allowed_nickname($nickname)) {
246 $this->showForm(_('Nickname not allowed.'));
250 if (User::staticGet('nickname', $nickname)) {
251 $this->showForm(_('Nickname already in use. Try another one.'));
255 list($display, $canonical, $sreg) = $this->getSavedValues();
257 if (!$display || !$canonical) {
258 $this->serverError(_('Stored OpenID not found.'));
262 # Possible race condition... let's be paranoid
264 $other = oid_get_user($canonical);
267 $this->serverError(_('Creating new account for OpenID that already has a user.'));
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'];
278 $location = $sreg['country'];
282 if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
283 $fullname = $sreg['fullname'];
288 if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
289 $email = $sreg['email'];
297 $args = array('nickname' => $nickname,
299 'fullname' => $fullname,
300 'location' => $location);
302 if (!empty($invite)) {
303 $args['code'] = $invite->code;
306 $user = User::register($args);
308 $result = oid_link_user($user->id, $canonical, $display);
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);
316 unset($_SESSION['openid_rememberme']);
317 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
321 function connectUser()
323 $nickname = $this->trimmed('nickname');
324 $password = $this->trimmed('password');
326 if (!common_check_user($nickname, $password)) {
327 $this->showForm(_('Invalid username or password.'));
333 $user = User::staticGet('nickname', $nickname);
335 list($display, $canonical, $sreg) = $this->getSavedValues();
337 if (!$display || !$canonical) {
338 $this->serverError(_('Stored OpenID not found.'));
342 $result = oid_link_user($user->id, $canonical, $display);
345 $this->serverError(_('Error connecting user to OpenID.'));
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);
356 unset($_SESSION['openid_rememberme']);
357 $this->goHome($user->nickname);
360 function goHome($nickname)
362 $url = common_get_returnto();
364 # We don't have to return to it again
365 common_set_returnto(null);
367 $url = common_local_url('all',
371 common_redirect($url, 303);
374 function bestNewNickname($display, $sreg)
377 # Try the passed-in nickname
379 if (!empty($sreg['nickname'])) {
380 $nickname = $this->nicknamize($sreg['nickname']);
381 if ($this->isNewNickname($nickname)) {
388 if (!empty($sreg['fullname'])) {
389 $fullname = $this->nicknamize($sreg['fullname']);
390 if ($this->isNewNickname($fullname)) {
397 $from_url = $this->openidToNickname($display);
399 if ($from_url && $this->isNewNickname($from_url)) {
408 function isNewNickname($str)
410 if (!Validate::string($str, array('min_length' => 1,
412 'format' => NICKNAME_FMT))) {
415 if (!User::allowed_nickname($str)) {
418 if (User::staticGet('nickname', $str)) {
424 function openidToNickname($openid)
426 if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
427 return $this->xriToNickname($openid);
429 return $this->urlToNickname($openid);
433 # We try to use an OpenID URL as a legal StatusNet user name in this order
434 # 1. Plain hostname, like http://evanp.myopenid.com/
435 # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
436 # or http://getopenid.com/evanprodromou
438 function urlToNickname($openid)
440 static $bad = array('query', 'user', 'password', 'port', 'fragment');
442 $parts = parse_url($openid);
444 # If any of these parts exist, this won't work
446 foreach ($bad as $badpart) {
447 if (array_key_exists($badpart, $parts)) {
452 # We just have host and/or path
454 # If it's just a host...
455 if (array_key_exists('host', $parts) &&
456 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
458 $hostparts = explode('.', $parts['host']);
460 # Try to catch common idiom of nickname.service.tld
462 if ((count($hostparts) > 2) &&
463 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
464 (strcmp($hostparts[0], 'www') != 0))
466 return $this->nicknamize($hostparts[0]);
468 # Do the whole hostname
469 return $this->nicknamize($parts['host']);
472 if (array_key_exists('path', $parts)) {
473 # Strip starting, ending slashes
474 $path = preg_replace('@/$@', '', $parts['path']);
475 $path = preg_replace('@^/@', '', $path);
476 if (strpos($path, '/') === false) {
477 return $this->nicknamize($path);
485 function xriToNickname($xri)
487 $base = $this->xriBase($xri);
493 # or @gratis*evan.prodromou
494 $parts = explode('*', substr($base, 1));
495 return $this->nicknamize(array_pop($parts));
499 function xriBase($xri)
501 if (substr($xri, 0, 6) == 'xri://') {
502 return substr($xri, 6);
508 # Given a string, try to make it work as a nickname
510 function nicknamize($str)
512 $str = preg_replace('/\W/', '', $str);
513 return strtolower($str);