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 if ($this->arg('create')) {
32 if (!$this->boolean('license')) {
33 $this->show_form(_('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(_('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 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']));
60 function show_form($error=NULL, $username=NULL) {
61 common_show_header(_('OpenID Account Setup'), NULL, $error,
62 array($this, 'show_top'));
64 common_element_start('form', array('method' => 'post',
65 'id' => 'account_connect',
66 'action' => common_local_url('finishopenidlogin')));
67 common_element('h2', NULL,
68 _('Create new account'));
69 common_element('p', NULL,
70 _('Create a new user with this nickname.'));
71 common_input('newname', _('New nickname'),
72 ($username) ? $username : '',
73 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
74 common_element_start('p');
75 common_element('input', array('type' => 'checkbox',
79 common_text(_('My text and files are available under '));
80 common_element('a', array(href => common_config('license', 'url')),
81 common_config('license', 'title'));
82 common_text(_(' except this private data: password, email address, IM address, phone number.'));
83 common_element_end('p');
84 common_submit('create', _('Create'));
85 common_element('h2', NULL,
86 _('Connect existing account'));
87 common_element('p', NULL,
88 _('If you already have an account, login with your username and password to connect it to your OpenID.'));
89 common_input('nickname', _('Existing nickname'));
90 common_password('password', _('Password'));
91 common_submit('connect', _('Connect'));
92 common_element_end('form');
96 function try_login() {
98 $consumer = oid_consumer();
100 $response = $consumer->complete(common_local_url('finishopenidlogin'));
102 if ($response->status == Auth_OpenID_CANCEL) {
103 $this->message(_('OpenID authentication cancelled.'));
105 } else if ($response->status == Auth_OpenID_FAILURE) {
106 // Authentication failed; display the error message.
107 $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message));
108 } else if ($response->status == Auth_OpenID_SUCCESS) {
109 // This means the authentication succeeded; extract the
110 // identity URL and Simple Registration data (if it was
112 $display = $response->getDisplayIdentifier();
113 $canonical = ($response->endpoint->canonicalID) ?
114 $response->endpoint->canonicalID : $response->getDisplayIdentifier();
116 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
119 $sreg = $sreg_resp->contents();
122 $user = oid_get_user($canonical);
125 oid_set_last($display);
126 # XXX: commented out at @edd's request until better
127 # control over how data flows from OpenID provider.
128 # oid_update_user($user, $sreg);
129 common_set_user($user->nickname);
130 common_real_login(true);
131 $this->go_home($user->nickname);
133 $this->save_values($display, $canonical, $sreg);
134 $this->show_form(NULL, $this->best_new_nickname($display, $sreg));
139 function message($msg) {
140 common_show_header(_('OpenID Login'));
141 common_element('p', NULL, $msg);
142 common_show_footer();
145 function save_values($display, $canonical, $sreg) {
146 common_ensure_session();
147 $_SESSION['openid_display'] = $display;
148 $_SESSION['openid_canonical'] = $canonical;
149 $_SESSION['openid_sreg'] = $sreg;
152 function get_saved_values() {
153 return array($_SESSION['openid_display'],
154 $_SESSION['openid_canonical'],
155 $_SESSION['openid_sreg']);
158 function create_new_user() {
160 $nickname = $this->trimmed('newname');
162 if (!Validate::string($nickname, array('min_length' => 1,
164 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
165 $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.'));
169 if (!User::allowed_nickname($nickname)) {
170 $this->show_form(_('Nickname not allowed.'));
174 if (User::staticGet('nickname', $nickname)) {
175 $this->show_form(_('Nickname already in use. Try another one.'));
179 list($display, $canonical, $sreg) = $this->get_saved_values();
181 if (!$display || !$canonical) {
182 common_server_error(_('Stored OpenID not found.'));
186 # Possible race condition... let's be paranoid
188 $other = oid_get_user($canonical);
191 common_server_error(_('Creating new account for OpenID that already has a user.'));
195 $profile = new Profile();
197 $profile->nickname = $nickname;
199 if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
200 $profile->fullname = $sreg['fullname'];
203 if ($sreg['country']) {
204 if ($sreg['postcode']) {
205 # XXX: use postcode to get city and region
206 # XXX: also, store postcode somewhere -- it's valuable!
207 $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
209 $profile->location = $sreg['country'];
213 # XXX save language if it's passed
214 # XXX save timezone if it's passed
216 $profile->profileurl = common_profile_url($nickname);
218 $profile->created = DB_DataObject_Cast::dateTime(); # current time
220 $id = $profile->insert();
222 common_server_error(_('Error saving the profile.'));
228 $user->nickname = $nickname;
229 $user->uri = common_user_uri($user);
231 if ($sreg['email'] && Validate::email($sreg['email'], true)) {
232 $user->email = $sreg['email'];
235 $user->created = DB_DataObject_Cast::dateTime(); # current time
237 $result = $user->insert();
244 $result = oid_link_user($user->id, $canonical, $display);
252 oid_set_last($display);
253 common_set_user($user->nickname);
254 common_real_login(true);
255 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)));
258 function connect_user() {
260 $nickname = $this->trimmed('nickname');
261 $password = $this->trimmed('password');
263 if (!common_check_user($nickname, $password)) {
264 $this->show_form(_('Invalid username or password.'));
270 $user = User::staticGet('nickname', $nickname);
272 list($display, $canonical, $sreg) = $this->get_saved_values();
274 if (!$display || !$canonical) {
275 common_server_error(_('Stored OpenID not found.'));
279 $result = oid_link_user($user->id, $canonical, $display);
282 common_server_error(_('Error connecting user to OpenID.'));
286 oid_update_user($user, $sreg);
287 oid_set_last($display);
288 common_set_user($user->nickname);
289 common_real_login(true);
290 $this->go_home($user->nickname);
293 function go_home($nickname) {
294 $url = common_get_returnto();
296 # We don't have to return to it again
297 common_set_returnto(NULL);
299 $url = common_local_url('all',
303 common_redirect($url);
306 function best_new_nickname($display, $sreg) {
308 # Try the passed-in nickname
311 if ($sreg['nickname']) {
312 $nickname = $this->nicknamize($sreg['nickname']);
313 if ($this->is_new_nickname($nickname)) {
320 if ($sreg['fullname']) {
321 $fullname = $this->nicknamize($sreg['fullname']);
322 if ($this->is_new_nickname($fullname)) {
329 $from_url = $this->openid_to_nickname($display);
331 if ($from_url && $this->is_new_nickname($from_url)) {
340 function is_new_nickname($str) {
341 if (!Validate::string($str, array('min_length' => 1,
343 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
346 if (!User::allowed_nickname($str)) {
349 if (User::staticGet('nickname', $str)) {
355 function openid_to_nickname($openid) {
356 if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
357 return $this->xri_to_nickname($openid);
359 return $this->url_to_nickname($openid);
363 # We try to use an OpenID URL as a legal Laconica user name in this order
364 # 1. Plain hostname, like http://evanp.myopenid.com/
365 # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
366 # or http://getopenid.com/evanprodromou
368 function url_to_nickname($openid) {
369 static $bad = array('query', 'user', 'password', 'port', 'fragment');
371 $parts = parse_url($openid);
373 # If any of these parts exist, this won't work
375 foreach ($bad as $badpart) {
376 if (array_key_exists($badpart, $parts)) {
381 # We just have host and/or path
383 # If it's just a host...
384 if (array_key_exists('host', $parts) &&
385 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
387 $hostparts = explode('.', $parts['host']);
389 # Try to catch common idiom of nickname.service.tld
391 if ((count($hostparts) > 2) &&
392 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
393 (strcmp($hostparts[0], 'www') != 0))
395 return $this->nicknamize($hostparts[0]);
397 # Do the whole hostname
398 return $this->nicknamize($parts['host']);
401 if (array_key_exists('path', $parts)) {
402 # Strip starting, ending slashes
403 $path = preg_replace('@/$@', '', $parts['path']);
404 $path = preg_replace('@^/@', '', $path);
405 if (strpos($path, '/') === false) {
406 return $this->nicknamize($path);
414 function xri_to_nickname($xri) {
415 $base = $this->xri_base($xri);
421 # or @gratis*evan.prodromou
422 $parts = explode('*', substr($base, 1));
423 return $this->nicknamize(array_pop($parts));
427 function xri_base($xri) {
428 if (substr($xri, 0, 6) == 'xri://') {
429 return substr($xri, 6);
435 # Given a string, try to make it work as a nickname
437 function nicknamize($str) {
438 $str = preg_replace('/\W/', '', $str);
439 return strtolower($str);