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