]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/actions/finishopenidlogin.php
[OpenID] s/sync/synch
[quix0rs-gnu-social.git] / plugins / OpenID / actions / finishopenidlogin.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, 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('STATUSNET')) {
21     exit(1);
22 }
23
24 require_once INSTALLDIR.'/plugins/OpenID/openid.php';
25
26 class FinishopenidloginAction extends Action
27 {
28     public $error = null;
29     public $username = null;
30     public $message = null;
31
32     public function handle()
33     {
34         parent::handle();
35         if (common_is_real_login()) {
36             // TRANS: Client error message trying to log on with OpenID while already logged on.
37             $this->clientError(_m('Already logged in.'));
38         } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
39             $token = $this->trimmed('token');
40             if (!$token || $token != common_session_token()) {
41                 // TRANS: Message given when there is a problem with the user's session token.
42                 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
43                 return;
44             }
45             if ($this->arg('create')) {
46                 if (!$this->boolean('license')) {
47                     // TRANS: Message given if user does not agree with the site's license.
48                     $this->showForm(
49                         _m('You cannot register if you do not agree to the license.'),
50                         $this->trimmed('newname')
51                     );
52                     return;
53                 }
54                 $this->createNewUser();
55             } elseif ($this->arg('connect')) {
56                 $this->connectUser();
57             } else {
58                 // TRANS: Messag given on an unknown error.
59                 $this->showForm(
60                     _m('An unknown error has occured.'),
61                     $this->trimmed('newname')
62                 );
63             }
64         } else {
65             $this->tryLogin();
66         }
67     }
68
69     public function showPageNotice()
70     {
71         if ($this->error) {
72             $this->element('div', ['class' => 'error'], $this->error);
73         } else {
74             $this->element('div', 'instructions',
75                            // TRANS: Instructions given after a first successful logon using OpenID.
76                            // TRANS: %s is the site name.
77                            sprintf(_m('This is the first time you have 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')));
78         }
79     }
80
81     public function title()
82     {
83         // TRANS: Title
84         return _m('TITLE', 'OpenID Account Setup');
85     }
86
87     public function showForm($error=null, $username=null)
88     {
89         $this->error = $error;
90         $this->username = $username;
91
92         $this->showPage();
93     }
94
95     /**
96      * @fixme much of this duplicates core code, which is very fragile.
97      * Should probably be replaced with an extensible mini version of
98      * the core registration form.
99      */
100     public function showContent()
101     {
102         if (!empty($this->message_text)) {
103             $this->element('div', ['class' => 'error'], $this->message_text);
104             return;
105         }
106
107         // We don't recognize this OpenID, so we're going to give the user
108         // two options, each in its own mini-form.
109         //
110         // First, they can create a new account using their OpenID auth
111         // info. The profile will be pre-populated with whatever name,
112         // email, and location we can get from the OpenID provider, so
113         // all we ask for is the license confirmation.
114         $this->elementStart('form', ['method' => 'post',
115                                      'id' => 'account_create',
116                                      'class' => 'form_settings',
117                                      'action' => common_local_url('finishopenidlogin')]);
118         $this->hidden('token', common_session_token());
119         $this->elementStart('fieldset', ['id' => 'form_openid_createaccount']);
120         $this->element('legend', null,
121                        // TRANS: Fieldset legend.
122                        _m('Create new account'));
123         $this->element('p', null,
124                        // TRANS: Form guide.
125                        _m('Create a new user with this nickname.'));
126         $this->elementStart('ul', 'form_data');
127
128         // Hook point for captcha etc
129         Event::handle('StartRegistrationFormData', [$this]);
130
131         $this->elementStart('li');
132         // TRANS: Field label.
133         $this->input('newname',
134                      _m('New nickname'),
135                      ($this->username) ? $this->username : '',
136                      // TRANS: Field title.
137                      _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
138         $this->elementEnd('li');
139         $this->elementStart('li');
140         // TRANS: Field label.
141         $this->input('email', _m('Email'),
142                      $this->getEmail(),
143                      // TRANS: Field title.
144                      _m('Used only for updates, announcements, '.
145                         'and password recovery.'));
146         $this->elementEnd('li');
147
148         // Hook point for captcha etc
149         Event::handle('EndRegistrationFormData', [$this]);
150
151         $this->elementStart('li');
152         $this->element('input', ['type' => 'checkbox',
153                                  'id' => 'license',
154                                  'class' => 'checkbox',
155                                  'name' => 'license',
156                                  'value' => 'true']);
157         $this->elementStart('label', ['for' => 'license',
158                                       'class' => 'checkbox']);
159         // TRANS: OpenID plugin link text.
160         // TRANS: %s is a link to a license with the license name as link text.
161         $message = _m('My text and files are available under %s ' .
162                       'except this private data: password, ' .
163                       'email address, IM address, and phone number.');
164         $link = '<a href="' .
165                 htmlspecialchars(common_config('license', 'url')) .
166                 '">' .
167                 htmlspecialchars(common_config('license', 'title')) .
168                 '</a>';
169         $this->raw(sprintf(htmlspecialchars($message), $link));
170         $this->elementEnd('label');
171         $this->elementEnd('li');
172         $this->elementEnd('ul');
173         // TRANS: Button label in form in which to create a new user on the site for an OpenID.
174         $this->submit('create', _m('BUTTON', 'Create'));
175         $this->elementEnd('fieldset');
176         $this->elementEnd('form');
177
178         // The second option is to attach this OpenID to an existing account
179         // on the local system, which they need to provide a password for.
180         $this->elementStart('form', ['method' => 'post',
181                                      'id' => 'account_connect',
182                                      'class' => 'form_settings',
183                                      'action' => common_local_url('finishopenidlogin')]);
184         $this->hidden('token', common_session_token());
185         $this->elementStart('fieldset', ['id' => 'form_openid_createaccount']);
186         $this->element('legend', null,
187                        // TRANS: Used as form legend for form in which to connect an OpenID to an existing user on the site.
188                        _m('Connect existing account'));
189         $this->element('p', null,
190                        // TRANS: User instructions for form in which to connect an OpenID to an existing user on the site.
191                        _m('If you already have an account, login with your username and password to connect it to your OpenID.'));
192         $this->elementStart('ul', 'form_data');
193         $this->elementStart('li');
194         // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
195         $this->input('nickname', _m('Existing nickname'));
196         $this->elementEnd('li');
197         $this->elementStart('li');
198         // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
199         $this->password('password', _m('Password'));
200         $this->elementEnd('li');
201         $this->elementStart('li');
202         // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
203         $this->checkbox('openid-synch', _m('Synchronize Account'), false,
204                         _m('Synchronize GNU social profile with this OpenID identity.'));
205         $this->elementEnd('li');
206         $this->elementEnd('ul');
207         // TRANS: Button text in form in which to connect an OpenID to an existing user on the site.
208         $this->submit('connect', _m('BUTTON', 'Connect'));
209         $this->elementEnd('fieldset');
210         $this->elementEnd('form');
211     }
212
213     /**
214      * Get specified e-mail from the form, or the OpenID sreg info, or the
215      * invite code.
216      *
217      * @return string
218      */
219     public function getEmail()
220     {
221         $email = $this->trimmed('email');
222         if (!empty($email)) {
223             return $email;
224         }
225
226         // Pull from openid thingy
227         list($display, $canonical, $sreg) = $this->getSavedValues();
228         if (!empty($sreg['email'])) {
229             return $sreg['email'];
230         }
231
232         // Terrible hack for invites...
233         if (common_config('site', 'inviteonly')) {
234             $code = $_SESSION['invitecode'];
235             if ($code) {
236                 $invite = Invitation::getKV($code);
237
238                 if ($invite && $invite->address_type == 'email') {
239                     return $invite->address;
240                 }
241             }
242         }
243         return '';
244     }
245
246     public function tryLogin()
247     {
248         $consumer = oid_consumer();
249
250         $response = $consumer->complete(common_local_url('finishopenidlogin'));
251
252         if ($response->status == Auth_OpenID_CANCEL) {
253             // TRANS: Status message in case the response from the OpenID provider is that the logon attempt was cancelled.
254             $this->message(_m('OpenID authentication cancelled.'));
255             return;
256         } elseif ($response->status == Auth_OpenID_FAILURE) {
257             // TRANS: OpenID authentication failed; display the error message. %s is the error message.
258             $this->message(sprintf(_m('OpenID authentication failed: %s.'), $response->message));
259         } elseif ($response->status == Auth_OpenID_SUCCESS) {
260             // This means the authentication succeeded; extract the
261             // identity URL and Simple Registration data (if it was
262             // returned).
263             $display = $response->getDisplayIdentifier();
264             $canonical = ($response->endpoint->canonicalID) ?
265               $response->endpoint->canonicalID : $response->getDisplayIdentifier();
266
267             oid_assert_allowed($display);
268             oid_assert_allowed($canonical);
269
270             $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
271
272             if ($sreg_resp) {
273                 $sreg = $sreg_resp->contents();
274             }
275
276             // Launchpad teams extension
277             if (!oid_check_teams($response)) {
278                 // TRANS: Message displayed when OpenID authentication is aborted.
279                 $this->message(_m('OpenID authentication aborted: You are not allowed to login to this site.'));
280                 return;
281             }
282
283             $user = oid_get_user($canonical);
284
285             if ($user) {
286                 oid_set_last($display);
287                 // XXX: commented out at @edd's request until better
288                 // control over how data flows from OpenID provider.
289                 // oid_update_user($user, $sreg);
290                 common_set_user($user);
291                 common_real_login(true);
292                 if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
293                     common_rememberme($user);
294                 }
295                 unset($_SESSION['openid_rememberme']);
296                 $this->goHome($user->nickname);
297             } else {
298                 $this->saveValues($display, $canonical, $sreg);
299                 $this->showForm(null, $this->bestNewNickname($display, $sreg));
300             }
301         }
302     }
303
304     public function message($msg)
305     {
306         $this->message_text = $msg;
307         $this->showPage();
308     }
309
310     public function saveValues($display, $canonical, $sreg)
311     {
312         common_ensure_session();
313         $_SESSION['openid_display'] = $display;
314         $_SESSION['openid_canonical'] = $canonical;
315         $_SESSION['openid_sreg'] = $sreg;
316     }
317
318     public function getSavedValues()
319     {
320         return [$_SESSION['openid_display'],
321                 $_SESSION['openid_canonical'],
322                 $_SESSION['openid_sreg']];
323     }
324
325     public function createNewUser()
326     {
327         // FIXME: save invite code before redirect, and check here
328
329         if (!Event::handle('StartRegistrationTry', [$this])) {
330             return;
331         }
332
333         if (common_config('site', 'closed')) {
334             // TRANS: OpenID plugin message. No new user registration is allowed on the site.
335             $this->clientError(_m('Registration not allowed.'));
336         }
337
338         $invite = null;
339
340         if (common_config('site', 'inviteonly')) {
341             $code = $_SESSION['invitecode'];
342             if (empty($code)) {
343                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and none was provided.
344                 $this->clientError(_m('Registration not allowed.'));
345             }
346
347             $invite = Invitation::getKV($code);
348
349             if (empty($invite)) {
350                 // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and the one provided was not valid.
351                 $this->clientError(_m('Not a valid invitation code.'));
352             }
353         }
354
355         try {
356             $nickname = Nickname::normalize($this->trimmed('newname'), true);
357         } catch (NicknameException $e) {
358             $this->showForm($e->getMessage());
359             return;
360         }
361
362         list($display, $canonical, $sreg) = $this->getSavedValues();
363
364         if (!$display || !$canonical) {
365             // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
366             $this->serverError(_m('Stored OpenID not found.'));
367         }
368
369         // Possible race condition... let's be paranoid
370
371         $other = oid_get_user($canonical);
372
373         if ($other) {
374             // TRANS: OpenID plugin server error.
375             $this->serverError(_m('Creating new account for OpenID that already has a user.'));
376         }
377
378         Event::handle('StartOpenIDCreateNewUser', [$canonical, &$sreg]);
379
380         $location = '';
381         if (!empty($sreg['country'])) {
382             if ($sreg['postcode']) {
383                 // XXX: use postcode to get city and region
384                 // XXX: also, store postcode somewhere -- it's valuable!
385                 $location = $sreg['postcode'] . ', ' . $sreg['country'];
386             } else {
387                 $location = $sreg['country'];
388             }
389         }
390
391         if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
392             $fullname = $sreg['fullname'];
393         } else {
394             $fullname = '';
395         }
396
397         $email = $this->getEmail();
398
399         // XXX: add language
400         // XXX: add timezone
401
402         $args = ['nickname' => $nickname,
403                  'email' => $email,
404                  'fullname' => $fullname,
405                  'location' => $location];
406
407         if (!empty($invite)) {
408             $args['code'] = $invite->code;
409         }
410
411         $user = User::register($args);
412
413         $result = oid_link_user($user->id, $canonical, $display);
414
415         Event::handle('EndOpenIDCreateNewUser', [$user, $canonical, $sreg]);
416
417         oid_set_last($display);
418         common_set_user($user);
419         common_real_login(true);
420         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
421             common_rememberme($user);
422         }
423         unset($_SESSION['openid_rememberme']);
424
425         Event::handle('EndRegistrationTry', [$this]);
426
427         common_redirect(common_local_url('showstream', ['nickname' => $user->nickname]), 303);
428     }
429
430     public function connectUser()
431     {
432         $nickname = $this->trimmed('nickname');
433         $password = $this->trimmed('password');
434         $synch     = $this->boolean('openid-synch');
435
436         if (!common_check_user($nickname, $password)) {
437             // TRANS: OpenID plugin message.
438             $this->showForm(_m('Invalid username or password.'));
439             return;
440         }
441
442         // They're legit!
443
444         $user = User::getKV('nickname', $nickname);
445
446         list($display, $canonical, $sreg) = $this->getSavedValues();
447
448         if (!$display || !$canonical) {
449             // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
450             $this->serverError(_m('Stored OpenID not found.'));
451         }
452
453         $result = oid_link_user($user->id, $canonical, $display);
454
455         if (!$result) {
456             // TRANS: OpenID plugin server error. The user or user profile could not be saved.
457             $this->serverError(_m('Error connecting user to OpenID.'));
458         }
459
460         if ($synch) {
461             if (Event::handle('StartOpenIDUpdateUser', [$user, $canonical, &$sreg])) {
462                 oid_update_user($user, $sreg);
463             }
464             Event::handle('EndOpenIDUpdateUser', [$user, $canonical, $sreg]);
465         }
466
467         oid_set_last($display);
468         common_set_user($user);
469         common_real_login(true);
470         if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
471             common_rememberme($user);
472         }
473         unset($_SESSION['openid_rememberme']);
474         $this->goHome($user->nickname);
475     }
476
477     public function goHome($nickname)
478     {
479         $url = common_get_returnto();
480         if ($url) {
481             // We don't have to return to it again
482             common_set_returnto(null);
483             $url = common_inject_session($url);
484         } else {
485             $url = common_local_url('all', ['nickname' => $nickname]);
486         }
487         common_redirect($url, 303);
488     }
489
490     public function bestNewNickname($display, $sreg)
491     {
492         // Try the passed-in nickname
493
494         if (!empty($sreg['nickname'])) {
495             $nickname = common_nicknamize($sreg['nickname']);
496             if (Nickname::isValid($nickname, true)) {
497                 return $nickname;
498             }
499         }
500
501         // Try the full name
502
503         if (!empty($sreg['fullname'])) {
504             $fullname = common_nicknamize($sreg['fullname']);
505             if (Nickname::isValid($fullname, true)) {
506                 return $fullname;
507             }
508         }
509
510         // Try the URL
511
512         $from_url = $this->openidToNickname($display);
513
514         if ($from_url && Nickname::isValid($from_url, true)) {
515             return $from_url;
516         }
517
518         // XXX: others?
519
520         return null;
521     }
522
523     public function openidToNickname($openid)
524     {
525         if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
526             return $this->xriToNickname($openid);
527         } else {
528             return $this->urlToNickname($openid);
529         }
530     }
531
532     // We try to use an OpenID URL as a legal StatusNet user name in this order
533     // 1. Plain hostname, like http://evanp.myopenid.com/
534     // 2. One element in path, like http://profile.typekey.com/EvanProdromou/
535     //    or http://getopenid.com/evanprodromou
536     public function urlToNickname($openid)
537     {
538         return common_url_to_nickname($openid);
539     }
540
541     public function xriToNickname($xri)
542     {
543         $base = $this->xriBase($xri);
544
545         if (!$base) {
546             return null;
547         } else {
548             // =evan.prodromou
549             // or @gratis*evan.prodromou
550             $parts = explode('*', substr($base, 1));
551             return common_nicknamize(array_pop($parts));
552         }
553     }
554
555     public function xriBase($xri)
556     {
557         if (substr($xri, 0, 6) == 'xri://') {
558             return substr($xri, 6);
559         } else {
560             return $xri;
561         }
562     }
563 }