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