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 // We don't recognize this OpenID, so we're going to give the user
104 // two options, each in its own mini-form.
106 // First, they can create a new account using their OpenID auth
107 // info. The profile will be pre-populated with whatever name,
108 // email, and location we can get from the OpenID provider, so
109 // all we ask for is the license confirmation.
110 $this->elementStart('form', array('method' => 'post',
111 'id' => 'account_create',
112 'class' => 'form_settings',
113 'action' => common_local_url('finishopenidlogin')));
114 $this->hidden('token', common_session_token());
115 $this->elementStart('fieldset', array('id' => 'form_openid_createaccount'));
116 $this->element('legend', null,
117 _m('Create new account'));
118 $this->element('p', null,
119 _m('Create a new user with this nickname.'));
120 $this->elementStart('ul', 'form_data');
122 // Hook point for captcha etc
123 Event::handle('StartRegistrationFormData', array($this));
125 $this->elementStart('li');
126 $this->input('newname', _m('New nickname'),
127 ($this->username) ? $this->username : '',
128 _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
129 $this->elementEnd('li');
131 // Hook point for captcha etc
132 Event::handle('EndRegistrationFormData', array($this));
134 $this->elementStart('li');
135 $this->element('input', array('type' => 'checkbox',
137 'class' => 'checkbox',
140 $this->elementStart('label', array('for' => 'license',
141 'class' => 'checkbox'));
142 // TRANS: OpenID plugin link text.
143 // TRANS: %s is a link to a licese with the license name as link text.
144 $message = _('My text and files are available under %s ' .
145 'except this private data: password, ' .
146 'email address, IM address, and phone number.');
147 $link = '<a href="' .
148 htmlspecialchars(common_config('license', 'url')) .
150 htmlspecialchars(common_config('license', 'title')) .
152 $this->raw(sprintf(htmlspecialchars($message), $link));
153 $this->elementEnd('label');
154 $this->elementEnd('li');
155 $this->elementEnd('ul');
156 // TRANS: Button label in form in which to create a new user on the site for an OpenID.
157 $this->submit('create', _m('BUTTON', 'Create'));
158 $this->elementEnd('fieldset');
159 $this->elementEnd('form');
161 // The second option is to attach this OpenID to an existing account
162 // on the local system, which they need to provide a password for.
163 $this->elementStart('form', array('method' => 'post',
164 'id' => 'account_connect',
165 'class' => 'form_settings',
166 'action' => common_local_url('finishopenidlogin')));
167 $this->hidden('token', common_session_token());
168 $this->elementStart('fieldset', array('id' => 'form_openid_createaccount'));
169 $this->element('legend', null,
170 // TRANS: Used as form legend for form in which to connect an OpenID to an existing user on the site.
171 _m('Connect existing account'));
172 $this->element('p', null,
173 // TRANS: User instructions for form in which to connect an OpenID to an existing user on the site.
174 _m('If you already have an account, login with your username and password to connect it to your OpenID.'));
175 $this->elementStart('ul', 'form_data');
176 $this->elementStart('li');
177 // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
178 $this->input('nickname', _m('Existing nickname'));
179 $this->elementEnd('li');
180 $this->elementStart('li');
181 // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
182 $this->password('password', _m('Password'));
183 $this->elementEnd('li');
184 $this->elementEnd('ul');
185 // TRANS: Button label in form in which to connect an OpenID to an existing user on the site.
186 $this->submit('connect', _m('BUTTON', 'Connect'));
187 $this->elementEnd('fieldset');
188 $this->elementEnd('form');
193 $consumer = oid_consumer();
195 $response = $consumer->complete(common_local_url('finishopenidlogin'));
197 if ($response->status == Auth_OpenID_CANCEL) {
198 // TRANS: Status message in case the response from the OpenID provider is that the logon attempt was cancelled.
199 $this->message(_m('OpenID authentication cancelled.'));
201 } else if ($response->status == Auth_OpenID_FAILURE) {
202 // TRANS: OpenID authentication failed; display the error message. %s is the error message.
203 $this->message(sprintf(_m('OpenID authentication failed: %s'), $response->message));
204 } else if ($response->status == Auth_OpenID_SUCCESS) {
205 // This means the authentication succeeded; extract the
206 // identity URL and Simple Registration data (if it was
208 $display = $response->getDisplayIdentifier();
209 $canonical = ($response->endpoint->canonicalID) ?
210 $response->endpoint->canonicalID : $response->getDisplayIdentifier();
212 oid_assert_allowed($display);
213 oid_assert_allowed($canonical);
215 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
218 $sreg = $sreg_resp->contents();
221 // Launchpad teams extension
222 if (!oid_check_teams($response)) {
223 $this->message(_m('OpenID authentication aborted: you are not allowed to login to this site.'));
227 $user = oid_get_user($canonical);
230 oid_set_last($display);
231 # XXX: commented out at @edd's request until better
232 # control over how data flows from OpenID provider.
233 # oid_update_user($user, $sreg);
234 common_set_user($user);
235 common_real_login(true);
236 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
237 common_rememberme($user);
239 unset($_SESSION['openid_rememberme']);
240 $this->goHome($user->nickname);
242 $this->saveValues($display, $canonical, $sreg);
243 $this->showForm(null, $this->bestNewNickname($display, $sreg));
248 function message($msg)
250 $this->message_text = $msg;
254 function saveValues($display, $canonical, $sreg)
256 common_ensure_session();
257 $_SESSION['openid_display'] = $display;
258 $_SESSION['openid_canonical'] = $canonical;
259 $_SESSION['openid_sreg'] = $sreg;
262 function getSavedValues()
264 return array($_SESSION['openid_display'],
265 $_SESSION['openid_canonical'],
266 $_SESSION['openid_sreg']);
269 function createNewUser()
271 # FIXME: save invite code before redirect, and check here
273 if (!Event::handle('StartRegistrationTry', array($this))) {
277 if (common_config('site', 'closed')) {
278 // TRANS: OpenID plugin message. No new user registration is allowed on the site.
279 $this->clientError(_m('Registration not allowed.'));
285 if (common_config('site', 'inviteonly')) {
286 $code = $_SESSION['invitecode'];
288 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and none was provided.
289 $this->clientError(_m('Registration not allowed.'));
293 $invite = Invitation::staticGet($code);
295 if (empty($invite)) {
296 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and the one provided was not valid.
297 $this->clientError(_m('Not a valid invitation code.'));
303 $nickname = Nickname::normalize($this->trimmed('newname'));
304 } catch (NicknameException $e) {
305 $this->showForm($e->getMessage());
309 if (!User::allowed_nickname($nickname)) {
310 // TRANS: OpenID plugin message. The entered new user name is blacklisted.
311 $this->showForm(_m('Nickname not allowed.'));
315 if (User::staticGet('nickname', $nickname)) {
316 // TRANS: OpenID plugin message. The entered new user name is already used.
317 $this->showForm(_m('Nickname already in use. Try another one.'));
321 list($display, $canonical, $sreg) = $this->getSavedValues();
323 if (!$display || !$canonical) {
324 // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
325 $this->serverError(_m('Stored OpenID not found.'));
329 # Possible race condition... let's be paranoid
331 $other = oid_get_user($canonical);
334 // TRANS: OpenID plugin server error.
335 $this->serverError(_m('Creating new account for OpenID that already has a user.'));
339 Event::handle('StartOpenIDCreateNewUser', array($canonical, &$sreg));
342 if (!empty($sreg['country'])) {
343 if ($sreg['postcode']) {
344 # XXX: use postcode to get city and region
345 # XXX: also, store postcode somewhere -- it's valuable!
346 $location = $sreg['postcode'] . ', ' . $sreg['country'];
348 $location = $sreg['country'];
352 if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
353 $fullname = $sreg['fullname'];
358 if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
359 $email = $sreg['email'];
367 $args = array('nickname' => $nickname,
369 'fullname' => $fullname,
370 'location' => $location);
372 if (!empty($invite)) {
373 $args['code'] = $invite->code;
376 $user = User::register($args);
378 $result = oid_link_user($user->id, $canonical, $display);
380 Event::handle('EndOpenIDCreateNewUser', array($user, $canonical, $sreg));
382 oid_set_last($display);
383 common_set_user($user);
384 common_real_login(true);
385 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
386 common_rememberme($user);
388 unset($_SESSION['openid_rememberme']);
390 Event::handle('EndRegistrationTry', array($this));
392 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
396 function connectUser()
398 $nickname = $this->trimmed('nickname');
399 $password = $this->trimmed('password');
401 if (!common_check_user($nickname, $password)) {
402 // TRANS: OpenID plugin message.
403 $this->showForm(_m('Invalid username or password.'));
409 $user = User::staticGet('nickname', $nickname);
411 list($display, $canonical, $sreg) = $this->getSavedValues();
413 if (!$display || !$canonical) {
414 // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
415 $this->serverError(_m('Stored OpenID not found.'));
419 $result = oid_link_user($user->id, $canonical, $display);
422 // TRANS: OpenID plugin server error. The user or user profile could not be saved.
423 $this->serverError(_m('Error connecting user to OpenID.'));
427 if (Event::handle('StartOpenIDUpdateUser', array($user, $canonical, &$sreg))) {
428 oid_update_user($user, $sreg);
430 Event::handle('EndOpenIDUpdateUser', array($user, $canonical, $sreg));
432 oid_set_last($display);
433 common_set_user($user);
434 common_real_login(true);
435 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
436 common_rememberme($user);
438 unset($_SESSION['openid_rememberme']);
439 $this->goHome($user->nickname);
442 function goHome($nickname)
444 $url = common_get_returnto();
446 # We don't have to return to it again
447 common_set_returnto(null);
448 $url = common_inject_session($url);
450 $url = common_local_url('all',
454 common_redirect($url, 303);
457 function bestNewNickname($display, $sreg)
460 # Try the passed-in nickname
462 if (!empty($sreg['nickname'])) {
463 $nickname = $this->nicknamize($sreg['nickname']);
464 if ($this->isNewNickname($nickname)) {
471 if (!empty($sreg['fullname'])) {
472 $fullname = $this->nicknamize($sreg['fullname']);
473 if ($this->isNewNickname($fullname)) {
480 $from_url = $this->openidToNickname($display);
482 if ($from_url && $this->isNewNickname($from_url)) {
491 function isNewNickname($str)
493 if (!Nickname::isValid($str)) {
496 if (!User::allowed_nickname($str)) {
499 if (User::staticGet('nickname', $str)) {
505 function openidToNickname($openid)
507 if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
508 return $this->xriToNickname($openid);
510 return $this->urlToNickname($openid);
514 # We try to use an OpenID URL as a legal StatusNet user name in this order
515 # 1. Plain hostname, like http://evanp.myopenid.com/
516 # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
517 # or http://getopenid.com/evanprodromou
519 function urlToNickname($openid)
521 return common_url_to_nickname($openid);
524 function xriToNickname($xri)
526 $base = $this->xriBase($xri);
532 # or @gratis*evan.prodromou
533 $parts = explode('*', substr($base, 1));
534 return $this->nicknamize(array_pop($parts));
538 function xriBase($xri)
540 if (substr($xri, 0, 6) == 'xri://') {
541 return substr($xri, 6);
547 # Given a string, try to make it work as a nickname
549 function nicknamize($str)
551 return common_nicknamize($str);