]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/FacebookBridge/actions/facebookfinishlogin.php
common_redirect and clientError exits, so refactor
[quix0rs-gnu-social.git] / plugins / FacebookBridge / actions / facebookfinishlogin.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Login or register a local user based on a Facebook user
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Plugin
23  * @package   StatusNet
24  * @author    Zach Copley <zach@status.net>
25  * @copyright 2010-2011 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 class FacebookfinishloginAction extends Action
35 {
36     private $fbuid       = null; // Facebook user ID
37     private $fbuser      = null; // Facebook user object (JSON)
38     private $accessToken = null; // Access token provided by Facebook JS API
39
40     function prepare($args) {
41         parent::prepare($args);
42
43         // Check cookie for a valid access_token
44
45         if (isset($_COOKIE['fb_access_token'])) {
46             $this->accessToken = $_COOKIE['fb_access_token'];
47         }
48
49         if (empty($this->accessToken)) {
50             $this->clientError(_m("Unable to authenticate you with Facebook."));
51             return false;
52         }
53
54         $graphUrl = 'https://graph.facebook.com/me?access_token=' . urlencode($this->accessToken);
55         $this->fbuser = json_decode(file_get_contents($graphUrl));
56
57         if (empty($this->fbuser)) {
58             // log badness
59
60             list($proxy, $ip) = common_client_ip();
61
62             common_log(
63                 LOG_WARNING,
64                     sprintf(
65                         'Failed Facebook authentication attempt, proxy = %s, ip = %s.',
66                          $proxy,
67                          $ip
68                     ),
69                     __FILE__
70             );
71
72             $this->clientError(
73                 // TRANS: Client error displayed when trying to connect to Facebook while not logged in.
74                 _m('You must be logged into Facebook to register a local account using Facebook.')
75             );
76         }
77
78         $this->fbuid  = $this->fbuser->id;
79         // OKAY, all is well... proceed to register
80         return true;
81     }
82
83     function handle($args)
84     {
85         parent::handle($args);
86
87         if (common_is_real_login()) {
88
89             // This will throw a client exception if the user already
90             // has some sort of foreign_link to Facebook.
91
92             $this->checkForExistingLink();
93
94             // Possibly reconnect an existing account
95
96             $this->connectUser();
97
98         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
99             $this->handlePost();
100         } else {
101             $this->tryLogin();
102         }
103     }
104
105     function checkForExistingLink() {
106
107         // User is already logged in, are her accounts already linked?
108
109         $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
110
111         if (!empty($flink)) {
112
113             // User already has a linked Facebook account and shouldn't be here!
114
115             $this->clientError(
116                 // TRANS: Client error displayed when trying to connect to a Facebook account that is already linked
117                 // TRANS: in the same StatusNet site.
118                 _m('There is already a local account linked with that Facebook account.')
119             );
120
121             return;
122        }
123
124        $cur = common_current_user();
125        $flink = Foreign_link::getByUserID($cur->id, FACEBOOK_SERVICE);
126
127        if (!empty($flink)) {
128
129             // There's already a local user linked to this Facebook account.
130
131             $this->clientError(
132                 // TRANS: Client error displayed when trying to connect to a Facebook account that is already linked
133                 // TRANS: in the same StatusNet site.
134                 _m('There is already a local account linked with that Facebook account.')
135             );
136
137             return;
138         }
139     }
140
141     function handlePost()
142     {
143         $token = $this->trimmed('token');
144
145         // CSRF protection
146         if (!$token || $token != common_session_token()) {
147             $this->showForm(
148                 // TRANS: Client error displayed when the session token does not match or is not given.
149                 _m('There was a problem with your session token. Try again, please.')
150             );
151             return;
152         }
153
154         if ($this->arg('create')) {
155
156             if (!$this->boolean('license')) {
157                 $this->showForm(
158                     // TRANS: Form validation error displayed when user has not agreed to the license.
159                     _m('You cannot register if you do not agree to the license.'),
160                     $this->trimmed('newname')
161                 );
162                 return;
163             }
164
165             // We has a valid Facebook session and the Facebook user has
166             // agreed to the SN license, so create a new user
167             $this->createNewUser();
168
169         } else if ($this->arg('connect')) {
170
171             $this->connectNewUser();
172
173         } else {
174
175             $this->showForm(
176                 // TRANS: Form validation error displayed when an unhandled error occurs.
177                 _m('An unknown error has occured.'),
178                 $this->trimmed('newname')
179             );
180         }
181     }
182
183     function showPageNotice()
184     {
185         if ($this->error) {
186
187             $this->element('div', array('class' => 'error'), $this->error);
188
189         } else {
190
191             $this->element(
192                 'div', 'instructions',
193                 sprintf(
194                     // TRANS: Form instructions for connecting to Facebook.
195                     // TRANS: %s is the site name.
196                     _m('This is the first time you have logged into %s so we must connect your Facebook to a local account. You can either create a new local account, or connect with an existing local account.'),
197                     common_config('site', 'name')
198                 )
199             );
200         }
201     }
202
203     function title()
204     {
205         // TRANS: Page title.
206         return _m('Facebook Setup');
207     }
208
209     function showForm($error=null, $username=null)
210     {
211         $this->error = $error;
212         $this->username = $username;
213
214         $this->showPage();
215     }
216
217     function showPage()
218     {
219         parent::showPage();
220     }
221
222     /**
223      * @todo FIXME: Much of this duplicates core code, which is very fragile.
224      * Should probably be replaced with an extensible mini version of
225      * the core registration form.
226      */
227     function showContent()
228     {
229         if (!empty($this->message_text)) {
230             $this->element('p', null, $this->message);
231             return;
232         }
233
234         $this->elementStart('form', array('method' => 'post',
235                                           'id' => 'form_settings_facebook_connect',
236                                           'class' => 'form_settings',
237                                           'action' => common_local_url('facebookfinishlogin')));
238         $this->elementStart('fieldset', array('id' => 'settings_facebook_connect_options'));
239         // TRANS: Fieldset legend.
240         $this->element('legend', null, _m('Connection options'));
241         $this->elementStart('ul', 'form_data');
242         $this->elementStart('li');
243         $this->element('input', array('type' => 'checkbox',
244                                       'id' => 'license',
245                                       'class' => 'checkbox',
246                                       'name' => 'license',
247                                       'value' => 'true'));
248         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
249         // TRANS: %s is the name of the license used by the user for their status updates.
250         $message = _m('My text and files are available under %s ' .
251                      'except this private data: password, ' .
252                      'email address, IM address, and phone number.');
253         $link = '<a href="' .
254                 htmlspecialchars(common_config('license', 'url')) .
255                 '">' .
256                 htmlspecialchars(common_config('license', 'title')) .
257                 '</a>';
258         $this->raw(sprintf(htmlspecialchars($message), $link));
259         $this->elementEnd('label');
260         $this->elementEnd('li');
261         $this->elementEnd('ul');
262
263         $this->elementStart('fieldset');
264         $this->hidden('token', common_session_token());
265         $this->element('legend', null,
266                        // TRANS: Fieldset legend.
267                        _m('Create new account'));
268         $this->element('p', null,
269                        // TRANS: Form instructions.
270                        _m('Create a new user with this nickname.'));
271         $this->elementStart('ul', 'form_data');
272
273         // Hook point for captcha etc
274         Event::handle('StartRegistrationFormData', array($this));
275
276         $this->elementStart('li');
277         // TRANS: Field label.
278         $this->input('newname', _m('New nickname'),
279                      ($this->username) ? $this->username : '',
280                      // TRANS: Field title.
281                      _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
282         $this->elementEnd('li');
283
284         // Hook point for captcha etc
285         Event::handle('EndRegistrationFormData', array($this));
286
287         $this->elementEnd('ul');
288         // TRANS: Submit button to create a new account.
289         $this->submit('create', _m('BUTTON','Create'));
290         $this->elementEnd('fieldset');
291
292         $this->elementStart('fieldset');
293         $this->element('legend', null,
294                        // TRANS: Fieldset legend.
295                        _m('Connect existing account'));
296         $this->element('p', null,
297                        // TRANS: Form instructions.
298                        _m('If you already have an account, login with your username and password to connect it to your Facebook.'));
299         $this->elementStart('ul', 'form_data');
300         $this->elementStart('li');
301         // TRANS: Field label.
302         $this->input('nickname', _m('Existing nickname'));
303         $this->elementEnd('li');
304         $this->elementStart('li');
305         // TRANS: Field label.
306         $this->password('password', _m('Password'));
307         $this->elementEnd('li');
308         $this->elementEnd('ul');
309         // TRANS: Submit button to connect a Facebook account to an existing StatusNet account.
310         $this->submit('connect', _m('BUTTON','Connect'));
311         $this->elementEnd('fieldset');
312
313         $this->elementEnd('fieldset');
314         $this->elementEnd('form');
315     }
316
317     function message($msg)
318     {
319         $this->message_text = $msg;
320         $this->showPage();
321     }
322
323     function createNewUser()
324     {
325         if (!Event::handle('StartRegistrationTry', array($this))) {
326             return;
327         }
328
329         if (common_config('site', 'closed')) {
330             // TRANS: Client error trying to register with registrations not allowed.
331             $this->clientError(_m('Registration not allowed.'));
332             return;
333         }
334
335         $invite = null;
336
337         if (common_config('site', 'inviteonly')) {
338             $code = $_SESSION['invitecode'];
339             if (empty($code)) {
340                 // TRANS: Client error trying to register with registrations 'invite only'.
341                 $this->clientError(_m('Registration not allowed.'));
342                 return;
343             }
344
345             $invite = Invitation::getKV($code);
346
347             if (empty($invite)) {
348                 // TRANS: Client error trying to register with an invalid invitation code.
349                 $this->clientError(_m('Not a valid invitation code.'));
350                 return;
351             }
352         }
353
354         try {
355             $nickname = Nickname::normalize($this->trimmed('newname'), true);
356         } catch (NicknameException $e) {
357             $this->showForm($e->getMessage());
358             return;
359         }
360
361         $args = array(
362             'nickname' => $nickname,
363             'fullname' => $this->fbuser->name,
364             'homepage' => $this->fbuser->website,
365             'location' => $this->fbuser->location->name
366         );
367
368         // It's possible that the email address is already in our
369         // DB. It's a unique key, so we need to check
370         if ($this->isNewEmail($this->fbuser->email)) {
371             $args['email']           = $this->fbuser->email;
372             if (isset($this->fuser->verified) && $this->fuser->verified == true) {
373                 $args['email_confirmed'] = true;
374             }
375         }
376
377         if (!empty($invite)) {
378             $args['code'] = $invite->code;
379         }
380
381         $user   = User::register($args);
382         $result = $this->flinkUser($user->id, $this->fbuid);
383
384         if (!$result) {
385             // TRANS: Server error displayed when connecting to Facebook fails.
386             $this->serverError(_m('Error connecting user to Facebook.'));
387             return;
388         }
389
390         // Add a Foreign_user record
391         Facebookclient::addFacebookUser($this->fbuser);
392
393         $this->setAvatar($user);
394
395         common_set_user($user);
396         common_real_login(true);
397
398         common_log(
399             LOG_INFO,
400             sprintf(
401                 'Registered new user %s (%d) from Facebook user %s, (fbuid %d)',
402                 $user->nickname,
403                 $user->id,
404                 $this->fbuser->name,
405                 $this->fbuid
406             ),
407             __FILE__
408         );
409
410         Event::handle('EndRegistrationTry', array($this));
411
412         $this->goHome($user->nickname);
413     }
414
415     /*
416      * Attempt to download the user's Facebook picture and create a
417      * StatusNet avatar for the new user.
418      */
419     function setAvatar($user)
420     {
421          try {
422             $picUrl = sprintf(
423                 'http://graph.facebook.com/%d/picture?type=large',
424                 $this->fbuser->id
425             );
426
427             // fetch the picture from Facebook
428             $client = new HTTPClient();
429
430             // fetch the actual picture
431             $response = $client->get($picUrl);
432
433             if ($response->isOk()) {
434
435                 // seems to always be jpeg, but not sure
436                 $tmpname = "facebook-avatar-tmp-" . common_random_hexstr(4);
437
438                 $ok = file_put_contents(
439                     Avatar::path($tmpname),
440                     $response->getBody()
441                 );
442
443                 if (!$ok) {
444                     common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__);
445                 } else {
446                     // save it as an avatar
447
448                     $file = new ImageFile($user->id, Avatar::path($tmpname));
449                     $filename = $file->resize(180); // size of the biggest img we get from Facebook
450
451                     $profile   = $user->getProfile();
452
453                     if ($profile->setOriginal($filename)) {
454                         common_log(
455                             LOG_INFO,
456                             sprintf(
457                                 'Saved avatar for %s (%d) from Facebook picture for '
458                                     . '%s (fbuid %d), filename = %s',
459                                  $user->nickname,
460                                  $user->id,
461                                  $this->fbuser->name,
462                                  $this->fbuid,
463                                  $filename
464                              ),
465                              __FILE__
466                         );
467
468                         // clean up tmp file
469                         @unlink(Avatar::path($tmpname));
470                     }
471
472                 }
473             }
474         } catch (Exception $e) {
475             common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__);
476             // error isn't fatal, continue
477         }
478     }
479
480     function connectNewUser()
481     {
482         $nickname = $this->trimmed('nickname');
483         $password = $this->trimmed('password');
484
485         if (!common_check_user($nickname, $password)) {
486             // TRANS: Form validation error displayed when username/password combination is incorrect.
487             $this->showForm(_m('Invalid username or password.'));
488             return;
489         }
490
491         $user = User::getKV('nickname', $nickname);
492
493         $this->tryLinkUser($user);
494
495         common_set_user($user);
496         common_real_login(true);
497
498         // clear out the stupid cookie
499         setcookie('fb_access_token', '', time() - 3600); // one hour ago
500
501         $this->goHome($user->nickname);
502     }
503
504     function connectUser()
505     {
506         $user = common_current_user();
507         $this->tryLinkUser($user);
508
509         // clear out the stupid cookie
510         setcookie('fb_access_token', '', time() - 3600); // one hour ago
511         common_redirect(common_local_url('facebookfinishlogin'), 303);
512     }
513
514     function tryLinkUser($user)
515     {
516         $result = $this->flinkUser($user->id, $this->fbuid);
517
518         if (empty($result)) {
519             // TRANS: Server error displayed when connecting to Facebook fails.
520             $this->serverError(_m('Error connecting user to Facebook.'));
521             return;
522         }
523     }
524
525     function tryLogin()
526     {
527         $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
528
529         if (!empty($flink)) {
530             $user = $flink->getUser();
531
532             if (!empty($user)) {
533
534                 common_log(
535                     LOG_INFO,
536                     sprintf(
537                         'Logged in Facebook user %s as user %d (%s)',
538                         $this->fbuid,
539                         $user->nickname,
540                         $user->id
541                     ),
542                     __FILE__
543                 );
544
545                 common_set_user($user);
546                 common_real_login(true);
547
548                 // clear out the stupid cookie
549                 setcookie('fb_access_token', '', time() - 3600); // one hour ago
550
551                 $this->goHome($user->nickname);
552             }
553
554         } else {
555             $this->showForm(null, $this->bestNewNickname());
556         }
557     }
558
559     function goHome($nickname)
560     {
561         $url = common_get_returnto();
562         if ($url) {
563             // We don't have to return to it again
564             common_set_returnto(null);
565         } else {
566             $url = common_local_url('all',
567                                     array('nickname' =>
568                                           $nickname));
569         }
570
571         common_redirect($url, 303);
572     }
573
574     function flinkUser($user_id, $fbuid)
575     {
576         $flink = new Foreign_link();
577
578         $flink->user_id     = $user_id;
579         $flink->foreign_id  = $fbuid;
580         $flink->service     = FACEBOOK_SERVICE;
581         $flink->credentials = $this->accessToken;
582         $flink->created     = common_sql_now();
583
584         $flink_id = $flink->insert();
585
586         return $flink_id;
587     }
588
589     function bestNewNickname()
590     {
591         try {
592             $nickname = Nickname::normalize($this->fbuser->username, true);
593             return $nickname;
594         } catch (NicknameException $e) {
595             // Failed to normalize nickname, but let's try the full name
596         }
597
598         try {
599             $nickname = Nickname::normalize($this->fbuser->name, true);
600             return $nickname;
601         } catch (NicknameException $e) {
602             // Any more ideas? Nope.
603         }
604
605         return null;
606     }
607
608     /*
609      * Do we already have a user record with this email?
610      * (emails have to be unique but they can change)
611      *
612      * @param string $email the email address to check
613      *
614      * @return boolean result
615      */
616      function isNewEmail($email)
617      {
618          // we shouldn't have to validate the format
619          $result = User::getKV('email', $email);
620
621          if (empty($result)) {
622              return true;
623          }
624
625          return false;
626      }
627 }