]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/finishopenidlogin.php
79bcd3f319aabd4309b7bfab7a04c74686b4dab1
[quix0rs-gnu-social.git] / actions / finishopenidlogin.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 if (!defined('LACONICA')) { exit(1); }
21
22 require_once(INSTALLDIR.'/lib/openid.php');
23
24 class FinishopenidloginAction extends Action {
25
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.'));
34                                 return;
35                         }
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'));
40                                         return;
41                                 }
42                                 $this->create_new_user();
43                         } else if ($this->arg('connect')) {
44                                 $this->connect_user();
45                         } else {
46                                 common_debug(print_r($this->args, true), __FILE__);
47                                 $this->show_form(_('Something weird happened.'),
48                                                                  $this->trimmed('newname'));
49                         }
50                 } else {
51                         $this->try_login();
52                 }
53         }
54
55         function show_top($error=NULL) {
56                 if ($error) {
57                         common_element('div', array('class' => 'error'), $error);
58                 } else {
59                         global $config;
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']));
62                 }
63         }
64
65         function show_form($error=NULL, $username=NULL) {
66                 common_show_header(_('OpenID Account Setup'), NULL, $error,
67                                                    array($this, 'show_top'));
68
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',
82                                                                           'id' => 'license',
83                                                                           'name' => 'license',
84                                                                           'value' => 'true'));
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');
99                 common_show_footer();
100         }
101
102         function try_login() {
103
104                 $consumer = oid_consumer();
105
106                 $response = $consumer->complete(common_local_url('finishopenidlogin'));
107
108                 if ($response->status == Auth_OpenID_CANCEL) {
109                         $this->message(_('OpenID authentication cancelled.'));
110                         return;
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
117                         // returned).
118                         $display = $response->getDisplayIdentifier();
119                         $canonical = ($response->endpoint->canonicalID) ?
120                           $response->endpoint->canonicalID : $response->getDisplayIdentifier();
121
122                         $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
123
124                         if ($sreg_resp) {
125                                 $sreg = $sreg_resp->contents();
126                         }
127
128                         $user = oid_get_user($canonical);
129
130                         if ($user) {
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);
136                                 common_real_login(true);
137                                 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
138                                         common_rememberme($user);
139                                 }
140                 unset($_SESSION['openid_rememberme']);
141                                 $this->go_home($user->nickname);
142                         } else {
143                                 $this->save_values($display, $canonical, $sreg);
144                                 $this->show_form(NULL, $this->best_new_nickname($display, $sreg));
145                         }
146                 }
147         }
148
149         function message($msg) {
150                 common_show_header(_('OpenID Login'));
151                 common_element('p', NULL, $msg);
152                 common_show_footer();
153         }
154
155         function save_values($display, $canonical, $sreg) {
156                 common_ensure_session();
157                 $_SESSION['openid_display'] = $display;
158                 $_SESSION['openid_canonical'] = $canonical;
159                 $_SESSION['openid_sreg'] = $sreg;
160         }
161
162         function get_saved_values() {
163                 return array($_SESSION['openid_display'],
164                                          $_SESSION['openid_canonical'],
165                                          $_SESSION['openid_sreg']);
166         }
167
168         function create_new_user() {
169
170                 $nickname = $this->trimmed('newname');
171
172                 if (!Validate::string($nickname, array('min_length' => 1,
173                                                                                            'max_length' => 64,
174                                                                                            'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
175                         $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.'));
176                         return;
177                 }
178
179                 if (!User::allowed_nickname($nickname)) {
180                         $this->show_form(_('Nickname not allowed.'));
181                         return;
182                 }
183
184                 if (User::staticGet('nickname', $nickname)) {
185                         $this->show_form(_('Nickname already in use. Try another one.'));
186                         return;
187                 }
188
189                 list($display, $canonical, $sreg) = $this->get_saved_values();
190
191                 if (!$display || !$canonical) {
192                         common_server_error(_('Stored OpenID not found.'));
193                         return;
194                 }
195
196                 # Possible race condition... let's be paranoid
197
198                 $other = oid_get_user($canonical);
199
200                 if ($other) {
201                         common_server_error(_('Creating new account for OpenID that already has a user.'));
202                         return;
203                 }
204
205                 if ($sreg['country']) {
206                         if ($sreg['postcode']) {
207                                 # XXX: use postcode to get city and region
208                                 # XXX: also, store postcode somewhere -- it's valuable!
209                                 $location = $sreg['postcode'] . ', ' . $sreg['country'];
210                         } else {
211                                 $location = $sreg['country'];
212                         }
213                 }
214
215                 if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
216                         $fullname = $sreg['fullname'];
217                 }
218
219                 if ($sreg['email'] && Validate::email($sreg['email'], true)) {
220                         $email = $sreg['email'];
221                 }
222
223                 # XXX: add language
224                 # XXX: add timezone
225
226                 $user = User::register(array('nickname' => $nickname,
227                                                                          'email' => $email,
228                                                                          'fullname' => $fullname,
229                                                                          'location' => $location));
230
231                 $result = oid_link_user($user->id, $canonical, $display);
232
233                 oid_set_last($display);
234                 common_set_user($user);
235                 common_real_login(true);
236         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
237                         common_rememberme($user);
238                 }
239         unset($_SESSION['openid_rememberme']);
240                 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)));
241         }
242
243         function connect_user() {
244
245                 $nickname = $this->trimmed('nickname');
246                 $password = $this->trimmed('password');
247
248                 if (!common_check_user($nickname, $password)) {
249                         $this->show_form(_('Invalid username or password.'));
250                         return;
251                 }
252
253                 # They're legit!
254
255                 $user = User::staticGet('nickname', $nickname);
256
257                 list($display, $canonical, $sreg) = $this->get_saved_values();
258
259                 if (!$display || !$canonical) {
260                         common_server_error(_('Stored OpenID not found.'));
261                         return;
262                 }
263
264                 $result = oid_link_user($user->id, $canonical, $display);
265
266                 if (!$result) {
267                         common_server_error(_('Error connecting user to OpenID.'));
268                         return;
269                 }
270
271                 oid_update_user($user, $sreg);
272                 oid_set_last($display);
273                 common_set_user($user);
274                 common_real_login(true);
275         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
276                         common_rememberme($user);
277                 }
278                 unset($_SESSION['openid_rememberme']);
279                 $this->go_home($user->nickname);
280         }
281
282         function go_home($nickname) {
283                 $url = common_get_returnto();
284                 if ($url) {
285                         # We don't have to return to it again
286                         common_set_returnto(NULL);
287                 } else {
288                         $url = common_local_url('all',
289                                                                         array('nickname' =>
290                                                                                   $nickname));
291                 }
292                 common_redirect($url);
293         }
294
295         function best_new_nickname($display, $sreg) {
296
297                 # Try the passed-in nickname
298
299                 if ($sreg['nickname']) {
300                         $nickname = $this->nicknamize($sreg['nickname']);
301                         if ($this->is_new_nickname($nickname)) {
302                                 return $nickname;
303                         }
304                 }
305
306                 # Try the full name
307
308                 if ($sreg['fullname']) {
309                         $fullname = $this->nicknamize($sreg['fullname']);
310                         if ($this->is_new_nickname($fullname)) {
311                                 return $fullname;
312                         }
313                 }
314
315                 # Try the URL
316
317                 $from_url = $this->openid_to_nickname($display);
318
319                 if ($from_url && $this->is_new_nickname($from_url)) {
320                         return $from_url;
321                 }
322
323                 # XXX: others?
324
325                 return NULL;
326         }
327
328         function is_new_nickname($str) {
329                 if (!Validate::string($str, array('min_length' => 1,
330                                                                                   'max_length' => 64,
331                                                                                   'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
332                         return false;
333                 }
334         if (!User::allowed_nickname($str)) {
335                         return false;
336                 }
337                 if (User::staticGet('nickname', $str)) {
338                         return false;
339                 }
340                 return true;
341         }
342
343         function openid_to_nickname($openid) {
344         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
345                         return $this->xri_to_nickname($openid);
346                 } else {
347                         return $this->url_to_nickname($openid);
348                 }
349         }
350
351         # We try to use an OpenID URL as a legal Laconica user name in this order
352         # 1. Plain hostname, like http://evanp.myopenid.com/
353         # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
354         #    or http://getopenid.com/evanprodromou
355
356     function url_to_nickname($openid) {
357                 static $bad = array('query', 'user', 'password', 'port', 'fragment');
358
359             $parts = parse_url($openid);
360
361                 # If any of these parts exist, this won't work
362
363                 foreach ($bad as $badpart) {
364                         if (array_key_exists($badpart, $parts)) {
365                                 return NULL;
366                         }
367                 }
368
369                 # We just have host and/or path
370
371                 # If it's just a host...
372                 if (array_key_exists('host', $parts) &&
373                         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
374                 {
375                         $hostparts = explode('.', $parts['host']);
376
377                         # Try to catch common idiom of nickname.service.tld
378
379                         if ((count($hostparts) > 2) &&
380                                 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
381                                 (strcmp($hostparts[0], 'www') != 0))
382                         {
383                                 return $this->nicknamize($hostparts[0]);
384                         } else {
385                                 # Do the whole hostname
386                                 return $this->nicknamize($parts['host']);
387                         }
388                 } else {
389                         if (array_key_exists('path', $parts)) {
390                                 # Strip starting, ending slashes
391                                 $path = preg_replace('@/$@', '', $parts['path']);
392                                 $path = preg_replace('@^/@', '', $path);
393                                 if (strpos($path, '/') === false) {
394                                         return $this->nicknamize($path);
395                                 }
396                         }
397                 }
398
399                 return NULL;
400         }
401
402         function xri_to_nickname($xri) {
403                 $base = $this->xri_base($xri);
404
405                 if (!$base) {
406                         return NULL;
407                 } else {
408                         # =evan.prodromou
409                         # or @gratis*evan.prodromou
410                         $parts = explode('*', substr($base, 1));
411                         return $this->nicknamize(array_pop($parts));
412                 }
413         }
414
415         function xri_base($xri) {
416                 if (substr($xri, 0, 6) == 'xri://') {
417                         return substr($xri, 6);
418                 } else {
419                         return $xri;
420                 }
421         }
422
423         # Given a string, try to make it work as a nickname
424
425         function nicknamize($str) {
426                 $str = preg_replace('/\W/', '', $str);
427                 return strtolower($str);
428         }
429 }