]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/finishopenidlogin.php
base class is_readonly() now returns false by default
[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                         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'));
35                                         return;
36                                 }
37                                 $this->create_new_user();
38                         } else if ($this->arg('connect')) {
39                                 $this->connect_user();
40                         } else {
41                                 common_debug(print_r($this->args, true), __FILE__);
42                                 $this->show_form(_('Something weird happened.'),
43                                                                  $this->trimmed('newname'));
44                         }
45                 } else {
46                         $this->try_login();
47                 }
48         }
49
50         function show_top($error=NULL) {
51                 if ($error) {
52                         common_element('div', array('class' => 'error'), $error);
53                 } else {
54                         global $config;
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']));
57                 }
58         }
59
60         function show_form($error=NULL, $username=NULL) {
61                 common_show_header(_('OpenID Account Setup'), NULL, $error,
62                                                    array($this, 'show_top'));
63
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',
76                                                                           'id' => 'license',
77                                                                           'name' => 'license',
78                                                                           'value' => 'true'));
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');
93                 common_show_footer();
94         }
95
96         function try_login() {
97
98                 $consumer = oid_consumer();
99
100                 $response = $consumer->complete(common_local_url('finishopenidlogin'));
101
102                 if ($response->status == Auth_OpenID_CANCEL) {
103                         $this->message(_('OpenID authentication cancelled.'));
104                         return;
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
111                         // returned).
112                         $display = $response->getDisplayIdentifier();
113                         $canonical = ($response->endpoint->canonicalID) ?
114                           $response->endpoint->canonicalID : $response->getDisplayIdentifier();
115
116                         $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
117
118                         if ($sreg_resp) {
119                                 $sreg = $sreg_resp->contents();
120                         }
121
122                         $user = oid_get_user($canonical);
123
124                         if ($user) {
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);
132                         } else {
133                                 $this->save_values($display, $canonical, $sreg);
134                                 $this->show_form(NULL, $this->best_new_nickname($display, $sreg));
135                         }
136                 }
137         }
138
139         function message($msg) {
140                 common_show_header(_('OpenID Login'));
141                 common_element('p', NULL, $msg);
142                 common_show_footer();
143         }
144
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;
150         }
151
152         function get_saved_values() {
153                 return array($_SESSION['openid_display'],
154                                          $_SESSION['openid_canonical'],
155                                          $_SESSION['openid_sreg']);
156         }
157
158         function create_new_user() {
159
160                 $nickname = $this->trimmed('newname');
161
162                 if (!Validate::string($nickname, array('min_length' => 1,
163                                                                                            'max_length' => 64,
164                                                                                            'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
165                         $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.'));
166                         return;
167                 }
168
169                 if (!User::allowed_nickname($nickname)) {
170                         $this->show_form(_('Nickname not allowed.'));
171                         return;
172                 }
173
174                 if (User::staticGet('nickname', $nickname)) {
175                         $this->show_form(_('Nickname already in use. Try another one.'));
176                         return;
177                 }
178
179                 list($display, $canonical, $sreg) = $this->get_saved_values();
180
181                 if (!$display || !$canonical) {
182                         common_server_error(_('Stored OpenID not found.'));
183                         return;
184                 }
185
186                 # Possible race condition... let's be paranoid
187
188                 $other = oid_get_user($canonical);
189
190                 if ($other) {
191                         common_server_error(_('Creating new account for OpenID that already has a user.'));
192                         return;
193                 }
194
195                 $profile = new Profile();
196
197                 $profile->nickname = $nickname;
198
199                 if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
200                         $profile->fullname = $sreg['fullname'];
201                 }
202
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'];
208                         } else {
209                                 $profile->location = $sreg['country'];
210                         }
211                 }
212
213                 # XXX save language if it's passed
214                 # XXX save timezone if it's passed
215
216                 $profile->profileurl = common_profile_url($nickname);
217
218                 $profile->created = DB_DataObject_Cast::dateTime(); # current time
219
220                 $id = $profile->insert();
221                 if (!$id) {
222                         common_server_error(_('Error saving the profile.'));
223                         return;
224                 }
225
226                 $user = new User();
227                 $user->id = $id;
228                 $user->nickname = $nickname;
229                 $user->uri = common_user_uri($user);
230
231                 if ($sreg['email'] && Validate::email($sreg['email'], true)) {
232                         $user->email = $sreg['email'];
233                 }
234
235                 $user->created = DB_DataObject_Cast::dateTime(); # current time
236
237                 $result = $user->insert();
238
239                 if (!$result) {
240                         # Try to clean up...
241                         $profile->delete();
242                 }
243
244                 $result = oid_link_user($user->id, $canonical, $display);
245
246                 if (!$result) {
247                         # Try to clean up...
248                         $user->delete();
249                         $profile->delete();
250                 }
251
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)));
256         }
257
258         function connect_user() {
259
260                 $nickname = $this->trimmed('nickname');
261                 $password = $this->trimmed('password');
262
263                 if (!common_check_user($nickname, $password)) {
264                         $this->show_form(_('Invalid username or password.'));
265                         return;
266                 }
267
268                 # They're legit!
269
270                 $user = User::staticGet('nickname', $nickname);
271
272                 list($display, $canonical, $sreg) = $this->get_saved_values();
273
274                 if (!$display || !$canonical) {
275                         common_server_error(_('Stored OpenID not found.'));
276                         return;
277                 }
278
279                 $result = oid_link_user($user->id, $canonical, $display);
280
281                 if (!$result) {
282                         common_server_error(_('Error connecting user to OpenID.'));
283                         return;
284                 }
285
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);
291         }
292
293         function go_home($nickname) {
294                 $url = common_get_returnto();
295                 if ($url) {
296                         # We don't have to return to it again
297                         common_set_returnto(NULL);
298                 } else {
299                         $url = common_local_url('all',
300                                                                         array('nickname' =>
301                                                                                   $nickname));
302                 }
303                 common_redirect($url);
304         }
305
306         function best_new_nickname($display, $sreg) {
307
308                 # Try the passed-in nickname
309
310
311                 if ($sreg['nickname']) {
312                         $nickname = $this->nicknamize($sreg['nickname']);
313                         if ($this->is_new_nickname($nickname)) {
314                                 return $nickname;
315                         }
316                 }
317
318                 # Try the full name
319
320                 if ($sreg['fullname']) {
321                         $fullname = $this->nicknamize($sreg['fullname']);
322                         if ($this->is_new_nickname($fullname)) {
323                                 return $fullname;
324                         }
325                 }
326
327                 # Try the URL
328
329                 $from_url = $this->openid_to_nickname($display);
330
331                 if ($from_url && $this->is_new_nickname($from_url)) {
332                         return $from_url;
333                 }
334
335                 # XXX: others?
336
337                 return NULL;
338         }
339
340         function is_new_nickname($str) {
341                 if (!Validate::string($str, array('min_length' => 1,
342                                                                                   'max_length' => 64,
343                                                                                   'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
344                         return false;
345                 }
346         if (!User::allowed_nickname($str)) {
347                         return false;
348                 }
349                 if (User::staticGet('nickname', $str)) {
350                         return false;
351                 }
352                 return true;
353         }
354
355         function openid_to_nickname($openid) {
356         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
357                         return $this->xri_to_nickname($openid);
358                 } else {
359                         return $this->url_to_nickname($openid);
360                 }
361         }
362
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
367
368     function url_to_nickname($openid) {
369                 static $bad = array('query', 'user', 'password', 'port', 'fragment');
370
371             $parts = parse_url($openid);
372
373                 # If any of these parts exist, this won't work
374
375                 foreach ($bad as $badpart) {
376                         if (array_key_exists($badpart, $parts)) {
377                                 return NULL;
378                         }
379                 }
380
381                 # We just have host and/or path
382
383                 # If it's just a host...
384                 if (array_key_exists('host', $parts) &&
385                         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
386                 {
387                         $hostparts = explode('.', $parts['host']);
388
389                         # Try to catch common idiom of nickname.service.tld
390
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))
394                         {
395                                 return $this->nicknamize($hostparts[0]);
396                         } else {
397                                 # Do the whole hostname
398                                 return $this->nicknamize($parts['host']);
399                         }
400                 } else {
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);
407                                 }
408                         }
409                 }
410
411                 return NULL;
412         }
413
414         function xri_to_nickname($xri) {
415                 $base = $this->xri_base($xri);
416
417                 if (!$base) {
418                         return NULL;
419                 } else {
420                         # =evan.prodromou
421                         # or @gratis*evan.prodromou
422                         $parts = explode('*', substr($base, 1));
423                         return $this->nicknamize(array_pop($parts));
424                 }
425         }
426
427         function xri_base($xri) {
428                 if (substr($xri, 0, 6) == 'xri://') {
429                         return substr($xri, 6);
430                 } else {
431                         return $xri;
432                 }
433         }
434
435         # Given a string, try to make it work as a nickname
436
437         function nicknamize($str) {
438                 $str = preg_replace('/\W/', '', $str);
439                 return strtolower($str);
440         }
441 }