]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/FacebookBridge/actions/facebookfinishlogin.php
Replace common_good_random with common_random_hexstr
[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::getKV($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'), true);
359         } catch (NicknameException $e) {
360             $this->showForm($e->getMessage());
361             return;
362         }
363
364         $args = array(
365             'nickname' => $nickname,
366             'fullname' => $this->fbuser->name,
367             'homepage' => $this->fbuser->website,
368             'location' => $this->fbuser->location->name
369         );
370
371         // It's possible that the email address is already in our
372         // DB. It's a unique key, so we need to check
373         if ($this->isNewEmail($this->fbuser->email)) {
374             $args['email']           = $this->fbuser->email;
375             if (isset($this->fuser->verified) && $this->fuser->verified == true) {
376                 $args['email_confirmed'] = true;
377             }
378         }
379
380         if (!empty($invite)) {
381             $args['code'] = $invite->code;
382         }
383
384         $user   = User::register($args);
385         $result = $this->flinkUser($user->id, $this->fbuid);
386
387         if (!$result) {
388             // TRANS: Server error displayed when connecting to Facebook fails.
389             $this->serverError(_m('Error connecting user to Facebook.'));
390             return;
391         }
392
393         // Add a Foreign_user record
394         Facebookclient::addFacebookUser($this->fbuser);
395
396         $this->setAvatar($user);
397
398         common_set_user($user);
399         common_real_login(true);
400
401         common_log(
402             LOG_INFO,
403             sprintf(
404                 'Registered new user %s (%d) from Facebook user %s, (fbuid %d)',
405                 $user->nickname,
406                 $user->id,
407                 $this->fbuser->name,
408                 $this->fbuid
409             ),
410             __FILE__
411         );
412
413         Event::handle('EndRegistrationTry', array($this));
414
415         $this->goHome($user->nickname);
416     }
417
418     /*
419      * Attempt to download the user's Facebook picture and create a
420      * StatusNet avatar for the new user.
421      */
422     function setAvatar($user)
423     {
424          try {
425             $picUrl = sprintf(
426                 'http://graph.facebook.com/%d/picture?type=large',
427                 $this->fbuser->id
428             );
429
430             // fetch the picture from Facebook
431             $client = new HTTPClient();
432
433             // fetch the actual picture
434             $response = $client->get($picUrl);
435
436             if ($response->isOk()) {
437
438                 // seems to always be jpeg, but not sure
439                 $tmpname = "facebook-avatar-tmp-" . common_random_hexstr(4);
440
441                 $ok = file_put_contents(
442                     Avatar::path($tmpname),
443                     $response->getBody()
444                 );
445
446                 if (!$ok) {
447                     common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__);
448                 } else {
449                     // save it as an avatar
450
451                     $file = new ImageFile($user->id, Avatar::path($tmpname));
452                     $filename = $file->resize(180); // size of the biggest img we get from Facebook
453
454                     $profile   = $user->getProfile();
455
456                     if ($profile->setOriginal($filename)) {
457                         common_log(
458                             LOG_INFO,
459                             sprintf(
460                                 'Saved avatar for %s (%d) from Facebook picture for '
461                                     . '%s (fbuid %d), filename = %s',
462                                  $user->nickname,
463                                  $user->id,
464                                  $this->fbuser->name,
465                                  $this->fbuid,
466                                  $filename
467                              ),
468                              __FILE__
469                         );
470
471                         // clean up tmp file
472                         @unlink(Avatar::path($tmpname));
473                     }
474
475                 }
476             }
477         } catch (Exception $e) {
478             common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__);
479             // error isn't fatal, continue
480         }
481     }
482
483     function connectNewUser()
484     {
485         $nickname = $this->trimmed('nickname');
486         $password = $this->trimmed('password');
487
488         if (!common_check_user($nickname, $password)) {
489             // TRANS: Form validation error displayed when username/password combination is incorrect.
490             $this->showForm(_m('Invalid username or password.'));
491             return;
492         }
493
494         $user = User::getKV('nickname', $nickname);
495
496         $this->tryLinkUser($user);
497
498         common_set_user($user);
499         common_real_login(true);
500
501         // clear out the stupid cookie
502         setcookie('fb_access_token', '', time() - 3600); // one hour ago
503
504         $this->goHome($user->nickname);
505     }
506
507     function connectUser()
508     {
509         $user = common_current_user();
510         $this->tryLinkUser($user);
511
512         // clear out the stupid cookie
513         setcookie('fb_access_token', '', time() - 3600); // one hour ago
514         common_redirect(common_local_url('facebookfinishlogin'), 303);
515     }
516
517     function tryLinkUser($user)
518     {
519         $result = $this->flinkUser($user->id, $this->fbuid);
520
521         if (empty($result)) {
522             // TRANS: Server error displayed when connecting to Facebook fails.
523             $this->serverError(_m('Error connecting user to Facebook.'));
524             return;
525         }
526     }
527
528     function tryLogin()
529     {
530         $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
531
532         if (!empty($flink)) {
533             $user = $flink->getUser();
534
535             if (!empty($user)) {
536
537                 common_log(
538                     LOG_INFO,
539                     sprintf(
540                         'Logged in Facebook user %s as user %d (%s)',
541                         $this->fbuid,
542                         $user->nickname,
543                         $user->id
544                     ),
545                     __FILE__
546                 );
547
548                 common_set_user($user);
549                 common_real_login(true);
550
551                 // clear out the stupid cookie
552                 setcookie('fb_access_token', '', time() - 3600); // one hour ago
553
554                 $this->goHome($user->nickname);
555             }
556
557         } else {
558             $this->showForm(null, $this->bestNewNickname());
559         }
560     }
561
562     function goHome($nickname)
563     {
564         $url = common_get_returnto();
565         if ($url) {
566             // We don't have to return to it again
567             common_set_returnto(null);
568         } else {
569             $url = common_local_url('all',
570                                     array('nickname' =>
571                                           $nickname));
572         }
573
574         common_redirect($url, 303);
575     }
576
577     function flinkUser($user_id, $fbuid)
578     {
579         $flink = new Foreign_link();
580
581         $flink->user_id     = $user_id;
582         $flink->foreign_id  = $fbuid;
583         $flink->service     = FACEBOOK_SERVICE;
584         $flink->credentials = $this->accessToken;
585         $flink->created     = common_sql_now();
586
587         $flink_id = $flink->insert();
588
589         return $flink_id;
590     }
591
592     function bestNewNickname()
593     {
594         try {
595             $nickname = Nickname::normalize($this->fbuser->username, true);
596             return $nickname;
597         } catch (NicknameException $e) {
598             // Failed to normalize nickname, but let's try the full name
599         }
600
601         try {
602             $nickname = Nickname::normalize($this->fbuser->name, true);
603             return $nickname;
604         } catch (NicknameException $e) {
605             // Any more ideas? Nope.
606         }
607
608         return null;
609     }
610
611     /*
612      * Do we already have a user record with this email?
613      * (emails have to be unique but they can change)
614      *
615      * @param string $email the email address to check
616      *
617      * @return boolean result
618      */
619      function isNewEmail($email)
620      {
621          // we shouldn't have to validate the format
622          $result = User::getKV('email', $email);
623
624          if (empty($result)) {
625              return true;
626          }
627
628          return false;
629      }
630 }