]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/finishopenidlogin.php
Link rtsp, mms & tel URI schemes, correct pseudo-protocol ones.
[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     var $error = null;
27     var $username = null;
28     var $message = null;
29
30     function handle($args)
31     {
32         parent::handle($args);
33         if (common_logged_in()) {
34             $this->clientError(_('Already logged in.'));
35         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
36             $token = $this->trimmed('token');
37             if (!$token || $token != common_session_token()) {
38                 $this->showForm(_('There was a problem with your session token. Try again, please.'));
39                 return;
40             }
41             if ($this->arg('create')) {
42                 if (!$this->boolean('license')) {
43                     $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
44                                     $this->trimmed('newname'));
45                     return;
46                 }
47                 $this->createNewUser();
48             } else if ($this->arg('connect')) {
49                 $this->connectUser();
50             } else {
51                 common_debug(print_r($this->args, true), __FILE__);
52                 $this->showForm(_('Something weird happened.'),
53                                 $this->trimmed('newname'));
54             }
55         } else {
56             $this->tryLogin();
57         }
58     }
59
60     function showPageNotice()
61     {
62         if ($this->error) {
63             $this->element('div', array('class' => 'error'), $this->error);
64         } else {
65             global $config;
66             $this->element('div', 'instructions',
67                            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']));
68         }
69     }
70
71     function title()
72     {
73         return _('OpenID Account Setup');
74     }
75
76     function showForm($error=null, $username=null)
77     {
78         $this->error = $error;
79         $this->username = $username;
80
81         $this->showPage();
82     }
83
84     function showContent()
85     {
86         if ($this->message_text) {
87             $this->element('p', null, $this->message);
88             return;
89         }
90
91         $this->elementStart('form', array('method' => 'post',
92                                           'id' => 'account_connect',
93                                           'action' => common_local_url('finishopenidlogin')));
94         $this->hidden('token', common_session_token());
95         $this->element('h2', null,
96                        _('Create new account'));
97         $this->element('p', null,
98                        _('Create a new user with this nickname.'));
99         $this->input('newname', _('New nickname'),
100                      ($this->username) ? $this->username : '',
101                      _('1-64 lowercase letters or numbers, no punctuation or spaces'));
102         $this->elementStart('p');
103         $this->element('input', array('type' => 'checkbox',
104                                       'id' => 'license',
105                                       'name' => 'license',
106                                       'value' => 'true'));
107         $this->text(_('My text and files are available under '));
108         $this->element('a', array('href' => common_config('license', 'url')),
109                        common_config('license', 'title'));
110         $this->text(_(' except this private data: password, email address, IM address, phone number.'));
111         $this->elementEnd('p');
112         $this->submit('create', _('Create'));
113         $this->element('h2', null,
114                        _('Connect existing account'));
115         $this->element('p', null,
116                        _('If you already have an account, login with your username and password to connect it to your OpenID.'));
117         $this->input('nickname', _('Existing nickname'));
118         $this->password('password', _('Password'));
119         $this->submit('connect', _('Connect'));
120         $this->elementEnd('form');
121     }
122
123     function tryLogin()
124     {
125         $consumer = oid_consumer();
126
127         $response = $consumer->complete(common_local_url('finishopenidlogin'));
128
129         if ($response->status == Auth_OpenID_CANCEL) {
130             $this->message(_('OpenID authentication cancelled.'));
131             return;
132         } else if ($response->status == Auth_OpenID_FAILURE) {
133             // Authentication failed; display the error message.
134             $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message));
135         } else if ($response->status == Auth_OpenID_SUCCESS) {
136             // This means the authentication succeeded; extract the
137             // identity URL and Simple Registration data (if it was
138             // returned).
139             $display = $response->getDisplayIdentifier();
140             $canonical = ($response->endpoint->canonicalID) ?
141               $response->endpoint->canonicalID : $response->getDisplayIdentifier();
142
143             $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
144
145             if ($sreg_resp) {
146                 $sreg = $sreg_resp->contents();
147             }
148
149             $user = oid_get_user($canonical);
150
151             if ($user) {
152                 oid_set_last($display);
153                 # XXX: commented out at @edd's request until better
154                 # control over how data flows from OpenID provider.
155                 # oid_update_user($user, $sreg);
156                 common_set_user($user);
157                 common_real_login(true);
158                 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
159                     common_rememberme($user);
160                 }
161                 unset($_SESSION['openid_rememberme']);
162                 $this->goHome($user->nickname);
163             } else {
164                 $this->saveValues($display, $canonical, $sreg);
165                 $this->showForm(null, $this->bestNewNickname($display, $sreg));
166             }
167         }
168     }
169
170     function message($msg)
171     {
172         $this->message_text = $msg;
173         $this->showPage();
174     }
175
176     function saveValues($display, $canonical, $sreg)
177     {
178         common_ensure_session();
179         $_SESSION['openid_display'] = $display;
180         $_SESSION['openid_canonical'] = $canonical;
181         $_SESSION['openid_sreg'] = $sreg;
182     }
183
184     function getSavedValues()
185     {
186         return array($_SESSION['openid_display'],
187                      $_SESSION['openid_canonical'],
188                      $_SESSION['openid_sreg']);
189     }
190
191     function createNewUser()
192     {
193         # FIXME: save invite code before redirect, and check here
194
195         if (common_config('site', 'closed') || common_config('site', 'inviteonly')) {
196             $this->clientError(_('Registration not allowed.'));
197             return;
198         }
199
200         $nickname = $this->trimmed('newname');
201
202         if (!Validate::string($nickname, array('min_length' => 1,
203                                                'max_length' => 64,
204                                                'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
205             $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
206             return;
207         }
208
209         if (!User::allowed_nickname($nickname)) {
210             $this->showForm(_('Nickname not allowed.'));
211             return;
212         }
213
214         if (User::staticGet('nickname', $nickname)) {
215             $this->showForm(_('Nickname already in use. Try another one.'));
216             return;
217         }
218
219         list($display, $canonical, $sreg) = $this->getSavedValues();
220
221         if (!$display || !$canonical) {
222             $this->serverError(_('Stored OpenID not found.'));
223             return;
224         }
225
226         # Possible race condition... let's be paranoid
227
228         $other = oid_get_user($canonical);
229
230         if ($other) {
231             $this->serverError(_('Creating new account for OpenID that already has a user.'));
232             return;
233         }
234
235         if ($sreg['country']) {
236             if ($sreg['postcode']) {
237                 # XXX: use postcode to get city and region
238                 # XXX: also, store postcode somewhere -- it's valuable!
239                 $location = $sreg['postcode'] . ', ' . $sreg['country'];
240             } else {
241                 $location = $sreg['country'];
242             }
243         }
244
245         if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
246             $fullname = $sreg['fullname'];
247         }
248
249         if ($sreg['email'] && Validate::email($sreg['email'], true)) {
250             $email = $sreg['email'];
251         }
252
253         # XXX: add language
254         # XXX: add timezone
255
256         $user = User::register(array('nickname' => $nickname,
257                                      'email' => $email,
258                                      'fullname' => $fullname,
259                                      'location' => $location));
260
261         $result = oid_link_user($user->id, $canonical, $display);
262
263         oid_set_last($display);
264         common_set_user($user);
265         common_real_login(true);
266         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
267             common_rememberme($user);
268         }
269         unset($_SESSION['openid_rememberme']);
270         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)));
271     }
272
273     function connectUser()
274     {
275         $nickname = $this->trimmed('nickname');
276         $password = $this->trimmed('password');
277
278         if (!common_check_user($nickname, $password)) {
279             $this->showForm(_('Invalid username or password.'));
280             return;
281         }
282
283         # They're legit!
284
285         $user = User::staticGet('nickname', $nickname);
286
287         list($display, $canonical, $sreg) = $this->getSavedValues();
288
289         if (!$display || !$canonical) {
290             $this->serverError(_('Stored OpenID not found.'));
291             return;
292         }
293
294         $result = oid_link_user($user->id, $canonical, $display);
295
296         if (!$result) {
297             $this->serverError(_('Error connecting user to OpenID.'));
298             return;
299         }
300
301         oid_update_user($user, $sreg);
302         oid_set_last($display);
303         common_set_user($user);
304         common_real_login(true);
305         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
306             common_rememberme($user);
307         }
308         unset($_SESSION['openid_rememberme']);
309         $this->goHome($user->nickname);
310     }
311
312     function goHome($nickname)
313     {
314         $url = common_get_returnto();
315         if ($url) {
316             # We don't have to return to it again
317             common_set_returnto(null);
318         } else {
319             $url = common_local_url('all',
320                                     array('nickname' =>
321                                           $nickname));
322         }
323         common_redirect($url);
324     }
325
326     function bestNewNickname($display, $sreg)
327     {
328
329         # Try the passed-in nickname
330
331         if ($sreg['nickname']) {
332             $nickname = $this->nicknamize($sreg['nickname']);
333             if ($this->isNewNickname($nickname)) {
334                 return $nickname;
335             }
336         }
337
338         # Try the full name
339
340         if ($sreg['fullname']) {
341             $fullname = $this->nicknamize($sreg['fullname']);
342             if ($this->isNewNickname($fullname)) {
343                 return $fullname;
344             }
345         }
346
347         # Try the URL
348
349         $from_url = $this->openidToNickname($display);
350
351         if ($from_url && $this->isNewNickname($from_url)) {
352             return $from_url;
353         }
354
355         # XXX: others?
356
357         return null;
358     }
359
360     function isNewNickname($str)
361     {
362         if (!Validate::string($str, array('min_length' => 1,
363                                           'max_length' => 64,
364                                           'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
365             return false;
366         }
367         if (!User::allowed_nickname($str)) {
368             return false;
369         }
370         if (User::staticGet('nickname', $str)) {
371             return false;
372         }
373         return true;
374     }
375
376     function openidToNickname($openid)
377     {
378         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
379             return $this->xriToNickname($openid);
380         } else {
381             return $this->urlToNickname($openid);
382         }
383     }
384
385     # We try to use an OpenID URL as a legal Laconica user name in this order
386     # 1. Plain hostname, like http://evanp.myopenid.com/
387     # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
388     #    or http://getopenid.com/evanprodromou
389
390     function urlToNickname($openid)
391     {
392         static $bad = array('query', 'user', 'password', 'port', 'fragment');
393
394         $parts = parse_url($openid);
395
396         # If any of these parts exist, this won't work
397
398         foreach ($bad as $badpart) {
399             if (array_key_exists($badpart, $parts)) {
400                 return null;
401             }
402         }
403
404         # We just have host and/or path
405
406         # If it's just a host...
407         if (array_key_exists('host', $parts) &&
408             (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
409         {
410             $hostparts = explode('.', $parts['host']);
411
412             # Try to catch common idiom of nickname.service.tld
413
414             if ((count($hostparts) > 2) &&
415                 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
416                 (strcmp($hostparts[0], 'www') != 0))
417             {
418                 return $this->nicknamize($hostparts[0]);
419             } else {
420                 # Do the whole hostname
421                 return $this->nicknamize($parts['host']);
422             }
423         } else {
424             if (array_key_exists('path', $parts)) {
425                 # Strip starting, ending slashes
426                 $path = preg_replace('@/$@', '', $parts['path']);
427                 $path = preg_replace('@^/@', '', $path);
428                 if (strpos($path, '/') === false) {
429                     return $this->nicknamize($path);
430                 }
431             }
432         }
433
434         return null;
435     }
436
437     function xriToNickname($xri)
438     {
439         $base = $this->xriBase($xri);
440
441         if (!$base) {
442             return null;
443         } else {
444             # =evan.prodromou
445             # or @gratis*evan.prodromou
446             $parts = explode('*', substr($base, 1));
447             return $this->nicknamize(array_pop($parts));
448         }
449     }
450
451     function xriBase($xri)
452     {
453         if (substr($xri, 0, 6) == 'xri://') {
454             return substr($xri, 6);
455         } else {
456             return $xri;
457         }
458     }
459
460     # Given a string, try to make it work as a nickname
461
462     function nicknamize($str)
463     {
464         $str = preg_replace('/\W/', '', $str);
465         return strtolower($str);
466     }
467 }