3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, Controlez-Vous, 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
27 function handle($args)
29 parent::handle($args);
30 if (common_logged_in()) {
31 common_user_error(_('Already logged in.'));
32 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
33 $token = $this->trimmed('token');
34 if (!$token || $token != common_session_token()) {
35 $this->show_form(_('There was a problem with your session token. Try again, please.'));
38 if ($this->arg('create')) {
39 if (!$this->boolean('license')) {
40 $this->show_form(_('You can\'t register if you don\'t agree to the license.'),
41 $this->trimmed('newname'));
44 $this->create_new_user();
45 } else if ($this->arg('connect')) {
46 $this->connect_user();
48 common_debug(print_r($this->args, true), __FILE__);
49 $this->show_form(_('Something weird happened.'),
50 $this->trimmed('newname'));
57 function show_top($error=null)
60 common_element('div', array('class' => 'error'), $error);
63 common_element('div', 'instructions',
64 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.'), $config['site']['name']));
68 function show_form($error=null, $username=null)
70 common_show_header(_('OpenID Account Setup'), null, $error,
71 array($this, 'show_top'));
73 common_element_start('form', array('method' => 'post',
74 'id' => 'account_connect',
75 'action' => common_local_url('finishopenidlogin')));
76 common_hidden('token', common_session_token());
77 common_element('h2', null,
78 _('Create new account'));
79 common_element('p', null,
80 _('Create a new user with this nickname.'));
81 common_input('newname', _('New nickname'),
82 ($username) ? $username : '',
83 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
84 common_element_start('p');
85 common_element('input', array('type' => 'checkbox',
89 common_text(_('My text and files are available under '));
90 common_element('a', array(href => common_config('license', 'url')),
91 common_config('license', 'title'));
92 common_text(_(' except this private data: password, email address, IM address, phone number.'));
93 common_element_end('p');
94 common_submit('create', _('Create'));
95 common_element('h2', null,
96 _('Connect existing account'));
97 common_element('p', null,
98 _('If you already have an account, login with your username and password to connect it to your OpenID.'));
99 common_input('nickname', _('Existing nickname'));
100 common_password('password', _('Password'));
101 common_submit('connect', _('Connect'));
102 common_element_end('form');
103 common_show_footer();
109 $consumer = oid_consumer();
111 $response = $consumer->complete(common_local_url('finishopenidlogin'));
113 if ($response->status == Auth_OpenID_CANCEL) {
114 $this->message(_('OpenID authentication cancelled.'));
116 } else if ($response->status == Auth_OpenID_FAILURE) {
117 // Authentication failed; display the error message.
118 $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message));
119 } else if ($response->status == Auth_OpenID_SUCCESS) {
120 // This means the authentication succeeded; extract the
121 // identity URL and Simple Registration data (if it was
123 $display = $response->getDisplayIdentifier();
124 $canonical = ($response->endpoint->canonicalID) ?
125 $response->endpoint->canonicalID : $response->getDisplayIdentifier();
127 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
130 $sreg = $sreg_resp->contents();
133 $user = oid_get_user($canonical);
136 oid_set_last($display);
137 # XXX: commented out at @edd's request until better
138 # control over how data flows from OpenID provider.
139 # oid_update_user($user, $sreg);
140 common_set_user($user);
141 common_real_login(true);
142 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
143 common_rememberme($user);
145 unset($_SESSION['openid_rememberme']);
146 $this->go_home($user->nickname);
148 $this->save_values($display, $canonical, $sreg);
149 $this->show_form(null, $this->best_new_nickname($display, $sreg));
154 function message($msg)
156 common_show_header(_('OpenID Login'));
157 common_element('p', null, $msg);
158 common_show_footer();
161 function save_values($display, $canonical, $sreg)
163 common_ensure_session();
164 $_SESSION['openid_display'] = $display;
165 $_SESSION['openid_canonical'] = $canonical;
166 $_SESSION['openid_sreg'] = $sreg;
169 function get_saved_values()
171 return array($_SESSION['openid_display'],
172 $_SESSION['openid_canonical'],
173 $_SESSION['openid_sreg']);
176 function create_new_user()
179 # FIXME: save invite code before redirect, and check here
181 if (common_config('site', 'closed') || common_config('site', 'inviteonly')) {
182 common_user_error(_('Registration not allowed.'));
186 $nickname = $this->trimmed('newname');
188 if (!Validate::string($nickname, array('min_length' => 1,
190 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
191 $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.'));
195 if (!User::allowed_nickname($nickname)) {
196 $this->show_form(_('Nickname not allowed.'));
200 if (User::staticGet('nickname', $nickname)) {
201 $this->show_form(_('Nickname already in use. Try another one.'));
205 list($display, $canonical, $sreg) = $this->get_saved_values();
207 if (!$display || !$canonical) {
208 common_server_error(_('Stored OpenID not found.'));
212 # Possible race condition... let's be paranoid
214 $other = oid_get_user($canonical);
217 common_server_error(_('Creating new account for OpenID that already has a user.'));
221 if ($sreg['country']) {
222 if ($sreg['postcode']) {
223 # XXX: use postcode to get city and region
224 # XXX: also, store postcode somewhere -- it's valuable!
225 $location = $sreg['postcode'] . ', ' . $sreg['country'];
227 $location = $sreg['country'];
231 if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
232 $fullname = $sreg['fullname'];
235 if ($sreg['email'] && Validate::email($sreg['email'], true)) {
236 $email = $sreg['email'];
242 $user = User::register(array('nickname' => $nickname,
244 'fullname' => $fullname,
245 'location' => $location));
247 $result = oid_link_user($user->id, $canonical, $display);
249 oid_set_last($display);
250 common_set_user($user);
251 common_real_login(true);
252 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
253 common_rememberme($user);
255 unset($_SESSION['openid_rememberme']);
256 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)));
259 function connect_user()
262 $nickname = $this->trimmed('nickname');
263 $password = $this->trimmed('password');
265 if (!common_check_user($nickname, $password)) {
266 $this->show_form(_('Invalid username or password.'));
272 $user = User::staticGet('nickname', $nickname);
274 list($display, $canonical, $sreg) = $this->get_saved_values();
276 if (!$display || !$canonical) {
277 common_server_error(_('Stored OpenID not found.'));
281 $result = oid_link_user($user->id, $canonical, $display);
284 common_server_error(_('Error connecting user to OpenID.'));
288 oid_update_user($user, $sreg);
289 oid_set_last($display);
290 common_set_user($user);
291 common_real_login(true);
292 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
293 common_rememberme($user);
295 unset($_SESSION['openid_rememberme']);
296 $this->go_home($user->nickname);
299 function go_home($nickname)
301 $url = common_get_returnto();
303 # We don't have to return to it again
304 common_set_returnto(null);
306 $url = common_local_url('all',
310 common_redirect($url);
313 function best_new_nickname($display, $sreg)
316 # Try the passed-in nickname
318 if ($sreg['nickname']) {
319 $nickname = $this->nicknamize($sreg['nickname']);
320 if ($this->is_new_nickname($nickname)) {
327 if ($sreg['fullname']) {
328 $fullname = $this->nicknamize($sreg['fullname']);
329 if ($this->is_new_nickname($fullname)) {
336 $from_url = $this->openid_to_nickname($display);
338 if ($from_url && $this->is_new_nickname($from_url)) {
347 function is_new_nickname($str)
349 if (!Validate::string($str, array('min_length' => 1,
351 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
354 if (!User::allowed_nickname($str)) {
357 if (User::staticGet('nickname', $str)) {
363 function openid_to_nickname($openid)
365 if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
366 return $this->xri_to_nickname($openid);
368 return $this->url_to_nickname($openid);
372 # We try to use an OpenID URL as a legal Laconica user name in this order
373 # 1. Plain hostname, like http://evanp.myopenid.com/
374 # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
375 # or http://getopenid.com/evanprodromou
377 function url_to_nickname($openid)
379 static $bad = array('query', 'user', 'password', 'port', 'fragment');
381 $parts = parse_url($openid);
383 # If any of these parts exist, this won't work
385 foreach ($bad as $badpart) {
386 if (array_key_exists($badpart, $parts)) {
391 # We just have host and/or path
393 # If it's just a host...
394 if (array_key_exists('host', $parts) &&
395 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
397 $hostparts = explode('.', $parts['host']);
399 # Try to catch common idiom of nickname.service.tld
401 if ((count($hostparts) > 2) &&
402 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
403 (strcmp($hostparts[0], 'www') != 0))
405 return $this->nicknamize($hostparts[0]);
407 # Do the whole hostname
408 return $this->nicknamize($parts['host']);
411 if (array_key_exists('path', $parts)) {
412 # Strip starting, ending slashes
413 $path = preg_replace('@/$@', '', $parts['path']);
414 $path = preg_replace('@^/@', '', $path);
415 if (strpos($path, '/') === false) {
416 return $this->nicknamize($path);
424 function xri_to_nickname($xri)
426 $base = $this->xri_base($xri);
432 # or @gratis*evan.prodromou
433 $parts = explode('*', substr($base, 1));
434 return $this->nicknamize(array_pop($parts));
438 function xri_base($xri)
440 if (substr($xri, 0, 6) == 'xri://') {
441 return substr($xri, 6);
447 # Given a string, try to make it work as a nickname
449 function nicknamize($str)
451 $str = preg_replace('/\W/', '', $str);
452 return strtolower($str);