]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/finishopenidlogin.php
36af83840cee34c0963915ebf41ae0699baea3a3
[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' .
57                                     ' so we must connect your OpenID to a local account. ' .
58                                     ' You can either create a new account, or connect with ' .
59                                     ' your existing account, if you have one.'
60                                     ), $config['site']['name']));
61                 }
62         }
63
64         function show_form($error=NULL, $username=NULL) {
65                 common_show_header(_('OpenID Account Setup'), NULL, $error,
66                                                    array($this, 'show_top'));
67
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                                            _('Create a new user with this nickname.'));
75                 common_input('newname', _('New nickname'),
76                                          ($username) ? $username : '',
77                                          _('1-64 lowercase letters or numbers, no punctuation or spaces'));
78                 common_element_start('p');
79                 common_element('input', array('type' => 'checkbox',
80                                                                           'id' => 'license',
81                                                                           'name' => 'license',
82                                                                           'value' => 'true'));
83                 common_text(_('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(_(' except this private data: password, email address, IM address, phone number.'));
87                 common_element_end('p');
88                 common_submit('create', _('Create'));
89                 common_element('h2', NULL,
90                                            _('Connect existing account'));
91                 common_element('p', NULL,
92                                            _('If you already have an account, login with your username and password '.
93                                                   'to connect it to your OpenID.'));
94                 common_input('nickname', _('Existing nickname'));
95                 common_password('password', _('Password'));
96                 common_submit('connect', _('Connect'));
97                 common_element_end('form');
98                 common_show_footer();
99         }
100
101         function try_login() {
102
103                 $consumer = oid_consumer();
104
105                 $response = $consumer->complete(common_local_url('finishopenidlogin'));
106
107                 if ($response->status == Auth_OpenID_CANCEL) {
108                         $this->message(_('OpenID authentication cancelled.'));
109                         return;
110                 } else if ($response->status == Auth_OpenID_FAILURE) {
111                         // Authentication failed; display the error message.
112                         $this->message(sprintf(_('OpenID authentication failed: %s'), $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
116                         // returned).
117                         $display = $response->getDisplayIdentifier();
118                         $canonical = ($response->endpoint->canonicalID) ?
119                           $response->endpoint->canonicalID : $response->getDisplayIdentifier();
120
121                         $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
122
123                         if ($sreg_resp) {
124                                 $sreg = $sreg_resp->contents();
125                         }
126
127                         $user = oid_get_user($canonical);
128
129                         if ($user) {
130                                 oid_set_last($display);
131                                 # XXX: commented out at @edd's request until better
132                                 # control over how data flows from OpenID provider.
133                                 # oid_update_user($user, $sreg);
134                                 common_set_user($user->nickname);
135                                 common_real_login(true);
136                                 $this->go_home($user->nickname);
137                         } else {
138                                 $this->save_values($display, $canonical, $sreg);
139                                 $this->show_form(NULL, $this->best_new_nickname($display, $sreg));
140                         }
141                 }
142         }
143
144         function message($msg) {
145                 common_show_header(_('OpenID Login'));
146                 common_element('p', NULL, $msg);
147                 common_show_footer();
148         }
149
150         function save_values($display, $canonical, $sreg) {
151                 common_ensure_session();
152                 $_SESSION['openid_display'] = $display;
153                 $_SESSION['openid_canonical'] = $canonical;
154                 $_SESSION['openid_sreg'] = $sreg;
155         }
156
157         function get_saved_values() {
158                 return array($_SESSION['openid_display'],
159                                          $_SESSION['openid_canonical'],
160                                          $_SESSION['openid_sreg']);
161         }
162
163         function create_new_user() {
164
165                 $nickname = $this->trimmed('newname');
166
167                 if (!Validate::string($nickname, array('min_length' => 1,
168                                                                                            'max_length' => 64,
169                                                                                            'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
170                         $this->show_form(_('Nickname must have only letters and numbers and no spaces.'));
171                         return;
172                 }
173
174                 if (!User::allowed_nickname($nickname)) {
175                         $this->show_form(_('Nickname not allowed.'));
176                         return;
177                 }
178
179                 if (User::staticGet('nickname', $nickname)) {
180                         $this->show_form(_('Nickname already in use. Try another one.'));
181                         return;
182                 }
183
184                 list($display, $canonical, $sreg) = $this->get_saved_values();
185
186                 if (!$display || !$canonical) {
187                         common_server_error(_('Stored OpenID not found.'));
188                         return;
189                 }
190
191                 # Possible race condition... let's be paranoid
192
193                 $other = oid_get_user($canonical);
194
195                 if ($other) {
196                         common_server_error(_('Creating new account for OpenID that already has a user.'));
197                         return;
198                 }
199
200                 $profile = new Profile();
201
202                 $profile->nickname = $nickname;
203
204                 if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
205                         $profile->fullname = $sreg['fullname'];
206                 }
207
208                 if ($sreg['country']) {
209                         if ($sreg['postcode']) {
210                                 # XXX: use postcode to get city and region
211                                 # XXX: also, store postcode somewhere -- it's valuable!
212                                 $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
213                         } else {
214                                 $profile->location = $sreg['country'];
215                         }
216                 }
217
218                 # XXX save language if it's passed
219                 # XXX save timezone if it's passed
220
221                 $profile->profileurl = common_profile_url($nickname);
222
223                 $profile->created = DB_DataObject_Cast::dateTime(); # current time
224
225                 $id = $profile->insert();
226                 if (!$id) {
227                         common_server_error(_('Error saving the profile.'));
228                         return;
229                 }
230
231                 $user = new User();
232                 $user->id = $id;
233                 $user->nickname = $nickname;
234                 $user->uri = common_user_uri($user);
235
236                 if ($sreg['email'] && Validate::email($sreg['email'], true)) {
237                         $user->email = $sreg['email'];
238                 }
239
240                 $user->created = DB_DataObject_Cast::dateTime(); # current time
241
242                 $result = $user->insert();
243
244                 if (!$result) {
245                         # Try to clean up...
246                         $profile->delete();
247                 }
248
249                 $result = oid_link_user($user->id, $canonical, $display);
250
251                 if (!$result) {
252                         # Try to clean up...
253                         $user->delete();
254                         $profile->delete();
255                 }
256
257                 oid_set_last($display);
258                 common_set_user($user->nickname);
259                 common_real_login(true);
260                 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)));
261         }
262
263         function connect_user() {
264
265                 $nickname = $this->trimmed('nickname');
266                 $password = $this->trimmed('password');
267
268                 if (!common_check_user($nickname, $password)) {
269                         $this->show_form(_('Invalid username or password.'));
270                         return;
271                 }
272
273                 # They're legit!
274
275                 $user = User::staticGet('nickname', $nickname);
276
277                 list($display, $canonical, $sreg) = $this->get_saved_values();
278
279                 if (!$display || !$canonical) {
280                         common_server_error(_('Stored OpenID not found.'));
281                         return;
282                 }
283
284                 $result = oid_link_user($user->id, $canonical, $display);
285
286                 if (!$result) {
287                         common_server_error(_('Error connecting user to OpenID.'));
288                         return;
289                 }
290
291                 oid_update_user($user, $sreg);
292                 oid_set_last($display);
293                 common_set_user($user->nickname);
294                 common_real_login(true);
295                 $this->go_home($user->nickname);
296         }
297
298         function go_home($nickname) {
299                 $url = common_get_returnto();
300                 if ($url) {
301                         # We don't have to return to it again
302                         common_set_returnto(NULL);
303                 } else {
304                         $url = common_local_url('all',
305                                                                         array('nickname' =>
306                                                                                   $nickname));
307                 }
308                 common_redirect($url);
309         }
310
311         function best_new_nickname($display, $sreg) {
312
313                 # Try the passed-in nickname
314
315
316                 if ($sreg['nickname']) {
317                         $nickname = $this->nicknamize($sreg['nickname']);
318                         if ($this->is_new_nickname($nickname)) {
319                                 return $nickname;
320                         }
321                 }
322
323                 # Try the full name
324
325                 if ($sreg['fullname']) {
326                         $fullname = $this->nicknamize($sreg['fullname']);
327                         if ($this->is_new_nickname($fullname)) {
328                                 return $fullname;
329                         }
330                 }
331
332                 # Try the URL
333
334                 $from_url = $this->openid_to_nickname($display);
335
336                 if ($from_url && $this->is_new_nickname($from_url)) {
337                         return $from_url;
338                 }
339
340                 # XXX: others?
341
342                 return NULL;
343         }
344
345         function is_new_nickname($str) {
346                 if (!Validate::string($str, array('min_length' => 1,
347                                                                                   'max_length' => 64,
348                                                                                   'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
349                         return false;
350                 }
351         if (!User::allowed_nickname($str)) {
352                         return false;
353                 }
354                 if (User::staticGet('nickname', $str)) {
355                         return false;
356                 }
357                 return true;
358         }
359
360         function openid_to_nickname($openid) {
361         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
362                         return $this->xri_to_nickname($openid);
363                 } else {
364                         return $this->url_to_nickname($openid);
365                 }
366         }
367
368         # We try to use an OpenID URL as a legal Laconica user name in this order
369         # 1. Plain hostname, like http://evanp.myopenid.com/
370         # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
371         #    or http://getopenid.com/evanprodromou
372
373     function url_to_nickname($openid) {
374                 static $bad = array('query', 'user', 'password', 'port', 'fragment');
375
376             $parts = parse_url($openid);
377
378                 # If any of these parts exist, this won't work
379
380                 foreach ($bad as $badpart) {
381                         if (array_key_exists($badpart, $parts)) {
382                                 return NULL;
383                         }
384                 }
385
386                 # We just have host and/or path
387
388                 # If it's just a host...
389                 if (array_key_exists('host', $parts) &&
390                         (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
391                 {
392                         $hostparts = explode('.', $parts['host']);
393
394                         # Try to catch common idiom of nickname.service.tld
395
396                         if ((count($hostparts) > 2) &&
397                                 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
398                                 (strcmp($hostparts[0], 'www') != 0))
399                         {
400                                 return $this->nicknamize($hostparts[0]);
401                         } else {
402                                 # Do the whole hostname
403                                 return $this->nicknamize($parts['host']);
404                         }
405                 } else {
406                         if (array_key_exists('path', $parts)) {
407                                 # Strip starting, ending slashes
408                                 $path = preg_replace('@/$@', '', $parts['path']);
409                                 $path = preg_replace('@^/@', '', $path);
410                                 if (strpos($path, '/') === false) {
411                                         return $this->nicknamize($path);
412                                 }
413                         }
414                 }
415
416                 return NULL;
417         }
418
419         function xri_to_nickname($xri) {
420                 $base = $this->xri_base($xri);
421
422                 if (!$base) {
423                         return NULL;
424                 } else {
425                         # =evan.prodromou
426                         # or @gratis*evan.prodromou
427                         $parts = explode('*', substr($base, 1));
428                         return $this->nicknamize(array_pop($parts));
429                 }
430         }
431
432         function xri_base($xri) {
433                 if (substr($xri, 0, 6) == 'xri://') {
434                         return substr($xri, 6);
435                 } else {
436                         return $xri;
437                 }
438         }
439
440         # Given a string, try to make it work as a nickname
441
442         function nicknamize($str) {
443                 $str = preg_replace('/\W/', '', $str);
444                 return strtolower($str);
445         }
446 }