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')) {
24 require_once INSTALLDIR.'/plugins/OpenID/openid.php';
26 class FinishopenidloginAction extends Action
32 function handle($args)
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.'));
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'));
52 $this->createNewUser();
53 } else if ($this->arg('connect')) {
56 // TRANS: Messag given on an unknown error.
57 $this->showForm(_m('An unknown error has occured.'),
58 $this->trimmed('newname'));
65 function showPageNotice()
68 $this->element('div', array('class' => 'error'), $this->error);
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')));
80 return _m('OpenID Account Setup');
83 function showForm($error=null, $username=null)
85 $this->error = $error;
86 $this->username = $username;
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.
96 function showContent()
98 if (!empty($this->message_text)) {
99 $this->element('div', array('class' => 'error'), $this->message_text);
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',
122 'class' => 'checkbox',
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')) .
135 htmlspecialchars(common_config('license', 'title')) .
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');
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');
170 $consumer = oid_consumer();
172 $response = $consumer->complete(common_local_url('finishopenidlogin'));
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.'));
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
185 $display = $response->getDisplayIdentifier();
186 $canonical = ($response->endpoint->canonicalID) ?
187 $response->endpoint->canonicalID : $response->getDisplayIdentifier();
189 oid_assert_allowed($display);
190 oid_assert_allowed($canonical);
192 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
195 $sreg = $sreg_resp->contents();
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.'));
204 $user = oid_get_user($canonical);
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);
216 unset($_SESSION['openid_rememberme']);
217 $this->goHome($user->nickname);
219 $this->saveValues($display, $canonical, $sreg);
220 $this->showForm(null, $this->bestNewNickname($display, $sreg));
225 function message($msg)
227 $this->message_text = $msg;
231 function saveValues($display, $canonical, $sreg)
233 common_ensure_session();
234 $_SESSION['openid_display'] = $display;
235 $_SESSION['openid_canonical'] = $canonical;
236 $_SESSION['openid_sreg'] = $sreg;
239 function getSavedValues()
241 return array($_SESSION['openid_display'],
242 $_SESSION['openid_canonical'],
243 $_SESSION['openid_sreg']);
246 function createNewUser()
248 # FIXME: save invite code before redirect, and check here
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.'));
258 if (common_config('site', 'inviteonly')) {
259 $code = $_SESSION['invitecode'];
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.'));
266 $invite = Invitation::staticGet($code);
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.'));
276 $nickname = Nickname::validate($this->trimmed('newname'));
277 } catch (NicknameException $e) {
278 $this->showForm($e->getMessage());
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.'));
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.'));
294 list($display, $canonical, $sreg) = $this->getSavedValues();
296 if (!$display || !$canonical) {
297 // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
298 $this->serverError(_m('Stored OpenID not found.'));
302 # Possible race condition... let's be paranoid
304 $other = oid_get_user($canonical);
307 // TRANS: OpenID plugin server error.
308 $this->serverError(_m('Creating new account for OpenID that already has a user.'));
312 Event::handle('StartOpenIDCreateNewUser', array($canonical, &$sreg));
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'];
321 $location = $sreg['country'];
325 if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
326 $fullname = $sreg['fullname'];
331 if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
332 $email = $sreg['email'];
340 $args = array('nickname' => $nickname,
342 'fullname' => $fullname,
343 'location' => $location);
345 if (!empty($invite)) {
346 $args['code'] = $invite->code;
349 $user = User::register($args);
351 $result = oid_link_user($user->id, $canonical, $display);
353 Event::handle('EndOpenIDCreateNewUser', array($user, $canonical, $sreg));
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);
361 unset($_SESSION['openid_rememberme']);
362 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
366 function connectUser()
368 $nickname = $this->trimmed('nickname');
369 $password = $this->trimmed('password');
371 if (!common_check_user($nickname, $password)) {
372 // TRANS: OpenID plugin message.
373 $this->showForm(_m('Invalid username or password.'));
379 $user = User::staticGet('nickname', $nickname);
381 list($display, $canonical, $sreg) = $this->getSavedValues();
383 if (!$display || !$canonical) {
384 // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
385 $this->serverError(_m('Stored OpenID not found.'));
389 $result = oid_link_user($user->id, $canonical, $display);
392 // TRANS: OpenID plugin server error. The user or user profile could not be saved.
393 $this->serverError(_m('Error connecting user to OpenID.'));
397 if (Event::handle('StartOpenIDUpdateUser', array($user, $canonical, &$sreg))) {
398 oid_update_user($user, $sreg);
400 Event::handle('EndOpenIDUpdateUser', array($user, $canonical, $sreg));
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);
408 unset($_SESSION['openid_rememberme']);
409 $this->goHome($user->nickname);
412 function goHome($nickname)
414 $url = common_get_returnto();
416 # We don't have to return to it again
417 common_set_returnto(null);
418 $url = common_inject_session($url);
420 $url = common_local_url('all',
424 common_redirect($url, 303);
427 function bestNewNickname($display, $sreg)
430 # Try the passed-in nickname
432 if (!empty($sreg['nickname'])) {
433 $nickname = $this->nicknamize($sreg['nickname']);
434 if ($this->isNewNickname($nickname)) {
441 if (!empty($sreg['fullname'])) {
442 $fullname = $this->nicknamize($sreg['fullname']);
443 if ($this->isNewNickname($fullname)) {
450 $from_url = $this->openidToNickname($display);
452 if ($from_url && $this->isNewNickname($from_url)) {
461 function isNewNickname($str)
463 if (!Nickname::isValid($str)) {
466 if (!User::allowed_nickname($str)) {
469 if (User::staticGet('nickname', $str)) {
475 function openidToNickname($openid)
477 if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
478 return $this->xriToNickname($openid);
480 return $this->urlToNickname($openid);
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
489 function urlToNickname($openid)
491 return common_url_to_nickname($openid);
494 function xriToNickname($xri)
496 $base = $this->xriBase($xri);
502 # or @gratis*evan.prodromou
503 $parts = explode('*', substr($base, 1));
504 return $this->nicknamize(array_pop($parts));
508 function xriBase($xri)
510 if (substr($xri, 0, 6) == 'xri://') {
511 return substr($xri, 6);
517 # Given a string, try to make it work as a nickname
519 function nicknamize($str)
521 return common_nicknamize($str);