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 {
26 function handle($args) {
27 parent::handle($args);
28 if (common_logged_in()) {
29 common_user_error(_('Already logged in.'));
30 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
31 $token = $this->trimmed('token');
32 if (!$token || $token != common_session_token()) {
33 $this->show_form(_('There was a problem with your session token. Try again, please.'));
36 if ($this->arg('create')) {
37 if (!$this->boolean('license')) {
38 $this->show_form(_('You can\'t register if you don\'t agree to the license.'),
39 $this->trimmed('newname'));
42 $this->create_new_user();
43 } else if ($this->arg('connect')) {
44 $this->connect_user();
46 common_debug(print_r($this->args, true), __FILE__);
47 $this->show_form(_('Something weird happened.'),
48 $this->trimmed('newname'));
55 function show_top($error=NULL) {
57 common_element('div', array('class' => 'error'), $error);
60 common_element('div', 'instructions',
61 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']));
65 function show_form($error=NULL, $username=NULL) {
66 common_show_header(_('OpenID Account Setup'), NULL, $error,
67 array($this, 'show_top'));
69 common_element_start('form', array('method' => 'post',
70 'id' => 'account_connect',
71 'action' => common_local_url('finishopenidlogin')));
72 common_hidden('token', common_session_token());
73 common_element('h2', NULL,
74 _('Create new account'));
75 common_element('p', NULL,
76 _('Create a new user with this nickname.'));
77 common_input('newname', _('New nickname'),
78 ($username) ? $username : '',
79 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
80 common_element_start('p');
81 common_element('input', array('type' => 'checkbox',
85 common_text(_('My text and files are available under '));
86 common_element('a', array(href => common_config('license', 'url')),
87 common_config('license', 'title'));
88 common_text(_(' except this private data: password, email address, IM address, phone number.'));
89 common_element_end('p');
90 common_submit('create', _('Create'));
91 common_element('h2', NULL,
92 _('Connect existing account'));
93 common_element('p', NULL,
94 _('If you already have an account, login with your username and password to connect it to your OpenID.'));
95 common_input('nickname', _('Existing nickname'));
96 common_password('password', _('Password'));
97 common_submit('connect', _('Connect'));
98 common_element_end('form');
102 function try_login() {
104 $consumer = oid_consumer();
106 $response = $consumer->complete(common_local_url('finishopenidlogin'));
108 if ($response->status == Auth_OpenID_CANCEL) {
109 $this->message(_('OpenID authentication cancelled.'));
111 } else if ($response->status == Auth_OpenID_FAILURE) {
112 // Authentication failed; display the error message.
113 $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message));
114 } else if ($response->status == Auth_OpenID_SUCCESS) {
115 // This means the authentication succeeded; extract the
116 // identity URL and Simple Registration data (if it was
118 $display = $response->getDisplayIdentifier();
119 $canonical = ($response->endpoint->canonicalID) ?
120 $response->endpoint->canonicalID : $response->getDisplayIdentifier();
122 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
125 $sreg = $sreg_resp->contents();
128 $user = oid_get_user($canonical);
131 oid_set_last($display);
132 # XXX: commented out at @edd's request until better
133 # control over how data flows from OpenID provider.
134 # oid_update_user($user, $sreg);
135 common_set_user($user->nickname);
136 common_real_login(true);
137 $this->go_home($user->nickname);
139 $this->save_values($display, $canonical, $sreg);
140 $this->show_form(NULL, $this->best_new_nickname($display, $sreg));
145 function message($msg) {
146 common_show_header(_('OpenID Login'));
147 common_element('p', NULL, $msg);
148 common_show_footer();
151 function save_values($display, $canonical, $sreg) {
152 common_ensure_session();
153 $_SESSION['openid_display'] = $display;
154 $_SESSION['openid_canonical'] = $canonical;
155 $_SESSION['openid_sreg'] = $sreg;
158 function get_saved_values() {
159 return array($_SESSION['openid_display'],
160 $_SESSION['openid_canonical'],
161 $_SESSION['openid_sreg']);
164 function create_new_user() {
166 $nickname = $this->trimmed('newname');
168 if (!Validate::string($nickname, array('min_length' => 1,
170 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
171 $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.'));
175 if (!User::allowed_nickname($nickname)) {
176 $this->show_form(_('Nickname not allowed.'));
180 if (User::staticGet('nickname', $nickname)) {
181 $this->show_form(_('Nickname already in use. Try another one.'));
185 list($display, $canonical, $sreg) = $this->get_saved_values();
187 if (!$display || !$canonical) {
188 common_server_error(_('Stored OpenID not found.'));
192 # Possible race condition... let's be paranoid
194 $other = oid_get_user($canonical);
197 common_server_error(_('Creating new account for OpenID that already has a user.'));
201 if ($sreg['country']) {
202 if ($sreg['postcode']) {
203 # XXX: use postcode to get city and region
204 # XXX: also, store postcode somewhere -- it's valuable!
205 $location = $sreg['postcode'] . ', ' . $sreg['country'];
207 $location = $sreg['country'];
211 if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
212 $fullname = $sreg['fullname'];
215 if ($sreg['email'] && Validate::email($sreg['email'], true)) {
216 $email = $sreg['email'];
222 $user = User::register(array('nickname' => $nickname,
224 'fullname' => $fullname,
225 'location' => $location));
227 $result = oid_link_user($user->id, $canonical, $display);
229 oid_set_last($display);
230 common_set_user($user->nickname);
231 common_real_login(true);
232 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)));
235 function connect_user() {
237 $nickname = $this->trimmed('nickname');
238 $password = $this->trimmed('password');
240 if (!common_check_user($nickname, $password)) {
241 $this->show_form(_('Invalid username or password.'));
247 $user = User::staticGet('nickname', $nickname);
249 list($display, $canonical, $sreg) = $this->get_saved_values();
251 if (!$display || !$canonical) {
252 common_server_error(_('Stored OpenID not found.'));
256 $result = oid_link_user($user->id, $canonical, $display);
259 common_server_error(_('Error connecting user to OpenID.'));
263 oid_update_user($user, $sreg);
264 oid_set_last($display);
265 common_set_user($user->nickname);
266 common_real_login(true);
267 $this->go_home($user->nickname);
270 function go_home($nickname) {
271 $url = common_get_returnto();
273 # We don't have to return to it again
274 common_set_returnto(NULL);
276 $url = common_local_url('all',
280 common_redirect($url);
283 function best_new_nickname($display, $sreg) {
285 # Try the passed-in nickname
288 if ($sreg['nickname']) {
289 $nickname = $this->nicknamize($sreg['nickname']);
290 if ($this->is_new_nickname($nickname)) {
297 if ($sreg['fullname']) {
298 $fullname = $this->nicknamize($sreg['fullname']);
299 if ($this->is_new_nickname($fullname)) {
306 $from_url = $this->openid_to_nickname($display);
308 if ($from_url && $this->is_new_nickname($from_url)) {
317 function is_new_nickname($str) {
318 if (!Validate::string($str, array('min_length' => 1,
320 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
323 if (!User::allowed_nickname($str)) {
326 if (User::staticGet('nickname', $str)) {
332 function openid_to_nickname($openid) {
333 if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
334 return $this->xri_to_nickname($openid);
336 return $this->url_to_nickname($openid);
340 # We try to use an OpenID URL as a legal Laconica user name in this order
341 # 1. Plain hostname, like http://evanp.myopenid.com/
342 # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
343 # or http://getopenid.com/evanprodromou
345 function url_to_nickname($openid) {
346 static $bad = array('query', 'user', 'password', 'port', 'fragment');
348 $parts = parse_url($openid);
350 # If any of these parts exist, this won't work
352 foreach ($bad as $badpart) {
353 if (array_key_exists($badpart, $parts)) {
358 # We just have host and/or path
360 # If it's just a host...
361 if (array_key_exists('host', $parts) &&
362 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
364 $hostparts = explode('.', $parts['host']);
366 # Try to catch common idiom of nickname.service.tld
368 if ((count($hostparts) > 2) &&
369 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
370 (strcmp($hostparts[0], 'www') != 0))
372 return $this->nicknamize($hostparts[0]);
374 # Do the whole hostname
375 return $this->nicknamize($parts['host']);
378 if (array_key_exists('path', $parts)) {
379 # Strip starting, ending slashes
380 $path = preg_replace('@/$@', '', $parts['path']);
381 $path = preg_replace('@^/@', '', $path);
382 if (strpos($path, '/') === false) {
383 return $this->nicknamize($path);
391 function xri_to_nickname($xri) {
392 $base = $this->xri_base($xri);
398 # or @gratis*evan.prodromou
399 $parts = explode('*', substr($base, 1));
400 return $this->nicknamize(array_pop($parts));
404 function xri_base($xri) {
405 if (substr($xri, 0, 6) == 'xri://') {
406 return substr($xri, 6);
412 # Given a string, try to make it work as a nickname
414 function nicknamize($str) {
415 $str = preg_replace('/\W/', '', $str);
416 return strtolower($str);