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(_t('Already logged in.'));
30 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
31 if ($this->arg('create')) {
32 if (!$this->boolean('license')) {
33 $this->show_form(_t('You can\'t register if you don\'t agree to the license.'),
34 $this->trimmed('newname'));
37 $this->create_new_user();
38 } else if ($this->arg('connect')) {
39 $this->connect_user();
41 common_debug(print_r($this->args, true), __FILE__);
42 $this->show_form(_t('Something weird happened.'),
43 $this->trimmed('newname'));
50 function show_top($error=NULL) {
52 common_element('div', array('class' => 'error'), $error);
55 common_element('div', 'instructions',
56 _t('This is the first time you\'ve logged into ') .
57 $config['site']['name'] .
58 _t(' so we must connect your OpenID to a local account. ' .
59 ' You can either create a new account, or connect with ' .
60 ' your existing account, if you have one.'));
64 function show_form($error=NULL, $username=NULL) {
65 common_show_header(_t('OpenID Account Setup'), NULL, $error,
66 array($this, 'show_top'));
68 common_element_start('form', array('method' => 'post',
69 'id' => 'account_connect',
70 'action' => common_local_url('finishopenidlogin')));
71 common_element('h2', NULL,
72 'Create new account');
73 common_element('p', NULL,
74 _t('Create a new user with this nickname.'));
75 common_input('newname', _t('New nickname'),
76 ($username) ? $username : '',
77 _t('1-64 lowercase letters or numbers, no punctuation or spaces'));
78 common_element_start('p');
79 common_element('input', array('type' => 'checkbox',
83 common_text(_t('My text and files are available under '));
84 common_element('a', array(href => common_config('license', 'url')),
85 common_config('license', 'title'));
86 common_text(_t(' except this private data: password, email address, IM address, phone number.'));
87 common_element_end('p');
88 common_submit('create', _t('Create'));
89 common_element('h2', NULL,
90 'Connect existing account');
91 common_element('p', NULL,
92 _t('If you already have an account, login with your username and password '.
93 'to connect it to your OpenID.'));
94 common_input('nickname', _t('Existing nickname'));
95 common_password('password', _t('Password'));
96 common_submit('connect', _t('Connect'));
97 common_element_end('form');
101 function try_login() {
103 $consumer = oid_consumer();
105 $response = $consumer->complete(common_local_url('finishopenidlogin'));
107 if ($response->status == Auth_OpenID_CANCEL) {
108 $this->message(_t('OpenID authentication cancelled.'));
110 } else if ($response->status == Auth_OpenID_FAILURE) {
111 // Authentication failed; display the error message.
112 $this->message(_t('OpenID authentication failed: ') . $response->message);
113 } else if ($response->status == Auth_OpenID_SUCCESS) {
114 // This means the authentication succeeded; extract the
115 // identity URL and Simple Registration data (if it was
117 $display = $response->getDisplayIdentifier();
118 $canonical = ($response->endpoint->canonicalID) ?
119 $response->endpoint->canonicalID : $response->getDisplayIdentifier();
121 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
124 $sreg = $sreg_resp->contents();
127 $user = oid_get_user($canonical);
130 oid_set_last($display);
131 oid_update_user($user, $sreg);
132 common_set_user($user->nickname);
133 common_real_login(true);
134 $this->go_home($user->nickname);
136 $this->save_values($display, $canonical, $sreg);
137 $this->show_form(NULL, $this->best_new_nickname($display, $sreg));
142 function message($msg) {
143 common_show_header(_t('OpenID Login'));
144 common_element('p', NULL, $msg);
145 common_show_footer();
148 function save_values($display, $canonical, $sreg) {
149 common_ensure_session();
150 $_SESSION['openid_display'] = $display;
151 $_SESSION['openid_canonical'] = $canonical;
152 $_SESSION['openid_sreg'] = $sreg;
155 function get_saved_values() {
156 return array($_SESSION['openid_display'],
157 $_SESSION['openid_canonical'],
158 $_SESSION['openid_sreg']);
161 function create_new_user() {
163 $nickname = $this->trimmed('newname');
165 if (!Validate::string($nickname, array('min_length' => 1,
167 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
168 $this->show_form(_t('Nickname must have only letters and numbers and no spaces.'));
172 if (!User::allowed_nickname($nickname)) {
173 $this->show_form(_t('Nickname not allowed.'));
177 if (User::staticGet('nickname', $nickname)) {
178 $this->show_form(_t('Nickname already in use. Try another one.'));
182 list($display, $canonical, $sreg) = $this->get_saved_values();
184 if (!$display || !$canonical) {
185 common_server_error(_t('Stored OpenID not found.'));
189 # Possible race condition... let's be paranoid
191 $other = oid_get_user($canonical);
194 common_server_error(_t('Creating new account for OpenID that already has a user.'));
198 $profile = new Profile();
200 $profile->nickname = $nickname;
202 if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
203 $profile->fullname = $sreg['fullname'];
206 if ($sreg['country']) {
207 if ($sreg['postcode']) {
208 # XXX: use postcode to get city and region
209 # XXX: also, store postcode somewhere -- it's valuable!
210 $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
212 $profile->location = $sreg['country'];
216 # XXX save language if it's passed
217 # XXX save timezone if it's passed
219 $profile->profileurl = common_profile_url($nickname);
221 $profile->created = DB_DataObject_Cast::dateTime(); # current time
223 $id = $profile->insert();
225 common_server_error(_t('Error saving the profile.'));
231 $user->nickname = $nickname;
232 $user->uri = common_user_uri($user);
234 if ($sreg['email'] && Validate::email($sreg['email'], true)) {
235 $user->email = $sreg['email'];
238 $user->created = DB_DataObject_Cast::dateTime(); # current time
240 $result = $user->insert();
247 $result = oid_link_user($user->id, $canonical, $display);
255 oid_set_last($display);
256 common_set_user($user->nickname);
257 common_real_login(true);
258 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)));
261 function connect_user() {
263 $nickname = $this->trimmed('nickname');
264 $password = $this->trimmed('password');
266 if (!common_check_user($nickname, $password)) {
267 $this->show_form(_t('Invalid username or password.'));
273 $user = User::staticGet('nickname', $nickname);
275 list($display, $canonical, $sreg) = $this->get_saved_values();
277 if (!$display || !$canonical) {
278 common_server_error(_t('Stored OpenID not found.'));
282 $result = oid_link_user($user->id, $canonical, $display);
285 common_server_error(_t('Error connecting user to OpenID.'));
289 oid_update_user($user, $sreg);
290 oid_set_last($display);
291 common_set_user($user->nickname);
292 common_real_login(true);
293 $this->go_home($user->nickname);
296 function go_home($nickname) {
297 $url = common_get_returnto();
299 # We don't have to return to it again
300 common_set_returnto(NULL);
302 $url = common_local_url('all',
306 common_redirect($url);
309 function best_new_nickname($display, $sreg) {
311 # Try the passed-in nickname
314 if ($sreg['nickname']) {
315 $nickname = $this->nicknamize($sreg['nickname']);
316 if ($this->is_new_nickname($nickname)) {
323 if ($sreg['fullname']) {
324 $fullname = $this->nicknamize($sreg['fullname']);
325 if ($this->is_new_nickname($fullname)) {
332 $from_url = $this->openid_to_nickname($display);
334 if ($from_url && $this->is_new_nickname($from_url)) {
343 function is_new_nickname($str) {
344 if (!Validate::string($str, array('min_length' => 1,
346 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
349 if (!User::allowed_nickname($str)) {
352 if (User::staticGet('nickname', $str)) {
358 function openid_to_nickname($openid) {
359 if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
360 return $this->xri_to_nickname($openid);
362 return $this->url_to_nickname($openid);
366 # We try to use an OpenID URL as a legal Laconica user name in this order
367 # 1. Plain hostname, like http://evanp.myopenid.com/
368 # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
369 # or http://getopenid.com/evanprodromou
371 function url_to_nickname($openid) {
372 static $bad = array('query', 'user', 'password', 'port', 'fragment');
374 $parts = parse_url($openid);
376 # If any of these parts exist, this won't work
378 foreach ($bad as $badpart) {
379 if (array_key_exists($badpart, $parts)) {
384 # We just have host and/or path
386 # If it's just a host...
387 if (array_key_exists('host', $parts) &&
388 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
390 $hostparts = explode('.', $parts['host']);
392 # Try to catch common idiom of nickname.service.tld
394 if ((count($hostparts) > 2) &&
395 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
396 (strcmp($hostparts[0], 'www') != 0))
398 return $this->nicknamize($hostparts[0]);
400 # Do the whole hostname
401 return $this->nicknamize($parts['host']);
404 if (array_key_exists('path', $parts)) {
405 # Strip starting, ending slashes
406 $path = preg_replace('@/$@', '', $parts['path']);
407 $path = preg_replace('@^/@', '', $path);
408 if (strpos($path, '/') === false) {
409 return $this->nicknamize($path);
417 function xri_to_nickname($xri) {
418 $base = $this->xri_base($xri);
424 # or @gratis*evan.prodromou
425 $parts = explode('*', substr($base, 1));
426 return $this->nicknamize(array_pop($parts));
430 function xri_base($xri) {
431 if (substr($xri, 0, 6) == 'xri://') {
432 return substr($xri, 6);
438 # Given a string, try to make it work as a nickname
440 function nicknamize($str) {
441 $str = preg_replace('/\W/', '', $str);
442 return strtolower($str);