3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, Control Yourself, 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('LACONICA')) { exit(1); }
22 require_once(INSTALLDIR.'/lib/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('p', null, $this->message);
90 $this->elementStart('form', array('method' => 'post',
91 'id' => 'account_connect',
92 'action' => common_local_url('finishopenidlogin')));
93 $this->hidden('token', common_session_token());
94 $this->element('h2', null,
95 _('Create new account'));
96 $this->element('p', null,
97 _('Create a new user with this nickname.'));
98 $this->input('newname', _('New nickname'),
99 ($this->username) ? $this->username : '',
100 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
101 $this->elementStart('p');
102 $this->element('input', array('type' => 'checkbox',
106 $this->text(_('My text and files are available under '));
107 $this->element('a', array('href' => common_config('license', 'url')),
108 common_config('license', 'title'));
109 $this->text(_(' except this private data: password, email address, IM address, phone number.'));
110 $this->elementEnd('p');
111 $this->submit('create', _('Create'));
112 $this->element('h2', null,
113 _('Connect existing account'));
114 $this->element('p', null,
115 _('If you already have an account, login with your username and password to connect it to your OpenID.'));
116 $this->input('nickname', _('Existing nickname'));
117 $this->password('password', _('Password'));
118 $this->submit('connect', _('Connect'));
119 $this->elementEnd('form');
124 $consumer = oid_consumer();
126 $response = $consumer->complete(common_local_url('finishopenidlogin'));
128 if ($response->status == Auth_OpenID_CANCEL) {
129 $this->message(_('OpenID authentication cancelled.'));
131 } else if ($response->status == Auth_OpenID_FAILURE) {
132 // Authentication failed; display the error message.
133 $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message));
134 } else if ($response->status == Auth_OpenID_SUCCESS) {
135 // This means the authentication succeeded; extract the
136 // identity URL and Simple Registration data (if it was
138 $display = $response->getDisplayIdentifier();
139 $canonical = ($response->endpoint->canonicalID) ?
140 $response->endpoint->canonicalID : $response->getDisplayIdentifier();
142 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
145 $sreg = $sreg_resp->contents();
148 $user = oid_get_user($canonical);
151 oid_set_last($display);
152 # XXX: commented out at @edd's request until better
153 # control over how data flows from OpenID provider.
154 # oid_update_user($user, $sreg);
155 common_set_user($user);
156 common_real_login(true);
157 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
158 common_rememberme($user);
160 unset($_SESSION['openid_rememberme']);
161 $this->goHome($user->nickname);
163 $this->saveValues($display, $canonical, $sreg);
164 $this->showForm(null, $this->bestNewNickname($display, $sreg));
169 function message($msg)
171 $this->message_text = $msg;
175 function saveValues($display, $canonical, $sreg)
177 common_ensure_session();
178 $_SESSION['openid_display'] = $display;
179 $_SESSION['openid_canonical'] = $canonical;
180 $_SESSION['openid_sreg'] = $sreg;
183 function getSavedValues()
185 return array($_SESSION['openid_display'],
186 $_SESSION['openid_canonical'],
187 $_SESSION['openid_sreg']);
190 function createNewUser()
192 # FIXME: save invite code before redirect, and check here
194 if (common_config('site', 'closed')) {
195 $this->clientError(_('Registration not allowed.'));
201 if (common_config('site', 'inviteonly')) {
202 $code = $_SESSION['invitecode'];
204 $this->clientError(_('Registration not allowed.'));
208 $invite = Invitation::staticGet($code);
210 if (empty($invite)) {
211 $this->clientError(_('Not a valid invitation code.'));
216 $nickname = $this->trimmed('newname');
218 if (!Validate::string($nickname, array('min_length' => 1,
220 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
221 $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
225 if (!User::allowed_nickname($nickname)) {
226 $this->showForm(_('Nickname not allowed.'));
230 if (User::staticGet('nickname', $nickname)) {
231 $this->showForm(_('Nickname already in use. Try another one.'));
235 list($display, $canonical, $sreg) = $this->getSavedValues();
237 if (!$display || !$canonical) {
238 $this->serverError(_('Stored OpenID not found.'));
242 # Possible race condition... let's be paranoid
244 $other = oid_get_user($canonical);
247 $this->serverError(_('Creating new account for OpenID that already has a user.'));
252 if (!empty($sreg['country'])) {
253 if ($sreg['postcode']) {
254 # XXX: use postcode to get city and region
255 # XXX: also, store postcode somewhere -- it's valuable!
256 $location = $sreg['postcode'] . ', ' . $sreg['country'];
258 $location = $sreg['country'];
262 if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
263 $fullname = $sreg['fullname'];
268 if (!empty($sreg['email']) && Validate::email($sreg['email'], true)) {
269 $email = $sreg['email'];
277 $args = array('nickname' => $nickname,
279 'fullname' => $fullname,
280 'location' => $location);
282 if (!empty($invite)) {
283 $args['code'] = $invite->code;
286 $user = User::register($args);
288 $result = oid_link_user($user->id, $canonical, $display);
290 oid_set_last($display);
291 common_set_user($user);
292 common_real_login(true);
293 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
294 common_rememberme($user);
296 unset($_SESSION['openid_rememberme']);
297 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
301 function connectUser()
303 $nickname = $this->trimmed('nickname');
304 $password = $this->trimmed('password');
306 if (!common_check_user($nickname, $password)) {
307 $this->showForm(_('Invalid username or password.'));
313 $user = User::staticGet('nickname', $nickname);
315 list($display, $canonical, $sreg) = $this->getSavedValues();
317 if (!$display || !$canonical) {
318 $this->serverError(_('Stored OpenID not found.'));
322 $result = oid_link_user($user->id, $canonical, $display);
325 $this->serverError(_('Error connecting user to OpenID.'));
329 oid_update_user($user, $sreg);
330 oid_set_last($display);
331 common_set_user($user);
332 common_real_login(true);
333 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
334 common_rememberme($user);
336 unset($_SESSION['openid_rememberme']);
337 $this->goHome($user->nickname);
340 function goHome($nickname)
342 $url = common_get_returnto();
344 # We don't have to return to it again
345 common_set_returnto(null);
347 $url = common_local_url('all',
351 common_redirect($url, 303);
354 function bestNewNickname($display, $sreg)
357 # Try the passed-in nickname
359 if (!empty($sreg['nickname'])) {
360 $nickname = $this->nicknamize($sreg['nickname']);
361 if ($this->isNewNickname($nickname)) {
368 if (!empty($sreg['fullname'])) {
369 $fullname = $this->nicknamize($sreg['fullname']);
370 if ($this->isNewNickname($fullname)) {
377 $from_url = $this->openidToNickname($display);
379 if ($from_url && $this->isNewNickname($from_url)) {
388 function isNewNickname($str)
390 if (!Validate::string($str, array('min_length' => 1,
392 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
395 if (!User::allowed_nickname($str)) {
398 if (User::staticGet('nickname', $str)) {
404 function openidToNickname($openid)
406 if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
407 return $this->xriToNickname($openid);
409 return $this->urlToNickname($openid);
413 # We try to use an OpenID URL as a legal Laconica user name in this order
414 # 1. Plain hostname, like http://evanp.myopenid.com/
415 # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
416 # or http://getopenid.com/evanprodromou
418 function urlToNickname($openid)
420 static $bad = array('query', 'user', 'password', 'port', 'fragment');
422 $parts = parse_url($openid);
424 # If any of these parts exist, this won't work
426 foreach ($bad as $badpart) {
427 if (array_key_exists($badpart, $parts)) {
432 # We just have host and/or path
434 # If it's just a host...
435 if (array_key_exists('host', $parts) &&
436 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
438 $hostparts = explode('.', $parts['host']);
440 # Try to catch common idiom of nickname.service.tld
442 if ((count($hostparts) > 2) &&
443 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
444 (strcmp($hostparts[0], 'www') != 0))
446 return $this->nicknamize($hostparts[0]);
448 # Do the whole hostname
449 return $this->nicknamize($parts['host']);
452 if (array_key_exists('path', $parts)) {
453 # Strip starting, ending slashes
454 $path = preg_replace('@/$@', '', $parts['path']);
455 $path = preg_replace('@^/@', '', $path);
456 if (strpos($path, '/') === false) {
457 return $this->nicknamize($path);
465 function xriToNickname($xri)
467 $base = $this->xriBase($xri);
473 # or @gratis*evan.prodromou
474 $parts = explode('*', substr($base, 1));
475 return $this->nicknamize(array_pop($parts));
479 function xriBase($xri)
481 if (substr($xri, 0, 6) == 'xri://') {
482 return substr($xri, 6);
488 # Given a string, try to make it work as a nickname
490 function nicknamize($str)
492 $str = preg_replace('/\W/', '', $str);
493 return strtolower($str);