]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/finishopenidlogin.php
fe9894e52b0a5cbee7f1a90c576d1801ab95091d
[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(_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'));
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(_t('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                                                    _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.'));
61                 }               
62         }
63         
64         function show_form($error=NULL, $username=NULL) {
65                 common_show_header(_t('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                                            _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',
80                                                                           'id' => 'license',
81                                                                           'name' => 'license',
82                                                                           'value' => 'true'));
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');
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(_t('OpenID authentication cancelled.'));
109                         return;
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
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                                 oid_update_user($user, $sreg);
132                                 common_set_user($user->nickname);
133                                 $this->go_home($user->nickname);
134                         } else {
135                                 $this->save_values($display, $canonical, $sreg);
136                                 $this->show_form(NULL, $this->best_new_nickname($display, $sreg));
137                         }
138                 }
139         }
140
141         function message($msg) {
142                 common_show_header(_t('OpenID Login'));
143                 common_element('p', NULL, $msg);
144                 common_show_footer();
145         }
146         
147         function save_values($display, $canonical, $sreg) {
148                 common_ensure_session();
149                 $_SESSION['openid_display'] = $display;
150                 $_SESSION['openid_canonical'] = $canonical;             
151                 $_SESSION['openid_sreg'] = $sreg;                               
152         }
153
154         function get_saved_values() {
155                 return array($_SESSION['openid_display'],
156                                          $_SESSION['openid_canonical'],
157                                          $_SESSION['openid_sreg']);
158         }
159         
160         function create_new_user() {
161                 
162                 $nickname = $this->trimmed('newname');
163                 
164                 if (!Validate::string($nickname, array('min_length' => 1,
165                                                                                            'max_length' => 64,
166                                                                                            'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
167                         $this->show_form(_t('Nickname must have only letters and numbers and no spaces.'));
168                         return;
169                 }
170
171                 if (!User::allowed_nickname($nickname)) {
172                         $this->show_form(_t('Nickname not allowed.'));
173                         return;
174                 }
175                 
176                 if (User::staticGet('nickname', $nickname)) {
177                         $this->show_form(_t('Nickname already in use. Try another one.'));
178                         return;
179                 }
180                 
181                 list($display, $canonical, $sreg) = $this->get_saved_values();
182                 
183                 if (!$display || !$canonical) {
184                         common_server_error(_t('Stored OpenID not found.'));
185                         return;
186                 }
187                 
188                 # Possible race condition... let's be paranoid
189                 
190                 $other = oid_get_user($canonical);
191                 
192                 if ($other) {
193                         common_server_error(_t('Creating new account for OpenID that already has a user.'));
194                         return;
195                 }
196                 
197                 $profile = new Profile();
198                 
199                 $profile->nickname = $nickname;
200                 
201                 if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
202                         $profile->fullname = $sreg['fullname'];
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                                 $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
210                         } else {
211                                 $profile->location = $sreg['country'];
212                         }
213                 }
214
215                 # XXX save language if it's passed
216                 # XXX save timezone if it's passed
217                 
218                 $profile->profileurl = common_profile_url($nickname);
219                   
220                 $profile->created = DB_DataObject_Cast::dateTime(); # current time
221                 
222                 $id = $profile->insert();
223                 if (!$id) {
224                         common_server_error(_t('Error saving the profile.'));
225                         return;
226                 }
227                 
228                 $user = new User();
229                 $user->id = $id;
230                 $user->nickname = $nickname;
231                 $user->uri = common_user_uri($user);
232                 
233                 if ($sreg['email'] && Validate::email($sreg['email'], true)) {
234                         $user->email = $sreg['email'];
235                 }
236                 
237                 $user->created = DB_DataObject_Cast::dateTime(); # current time
238                 
239                 $result = $user->insert();
240                 
241                 if (!$result) {
242                         # Try to clean up...
243                         $profile->delete();
244                 }
245
246                 $result = oid_link_user($user->id, $canonical, $display);
247                 
248                 if (!$result) {
249                         # Try to clean up...
250                         $user->delete();
251                         $profile->delete();
252                 }
253                 
254                 oid_set_last($display);
255                 common_set_user($user->nickname);
256                 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)));
257         }
258         
259         function connect_user() {
260                 
261                 $nickname = $this->trimmed('nickname');
262                 $password = $this->trimmed('password');
263
264                 if (!common_check_user($nickname, $password)) {
265                         $this->show_form(_t('Invalid username or password.'));
266                         return;
267                 }
268
269                 # They're legit!
270                 
271                 $user = User::staticGet('nickname', $nickname);
272
273                 list($display, $canonical, $sreg) = $this->get_saved_values();
274
275                 if (!$display || !$canonical) {
276                         common_server_error(_t('Stored OpenID not found.'));
277                         return;
278                 }
279                 
280                 $result = oid_link_user($user->id, $canonical, $display);
281                 
282                 if (!$result) {
283                         common_server_error(_t('Error connecting user to OpenID.'));
284                         return;
285                 }
286                 
287                 oid_update_user($user, $sreg);
288                 oid_set_last($display);
289                 common_set_user($user->nickname);
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 }