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