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