3 * StatusNet, the distributed open-source microblogging tool
5 * Login or register a local user based on a Facebook user
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.
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.
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/>.
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/
30 if (!defined('STATUSNET')) {
34 class FacebookfinishloginAction extends Action
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
40 function prepare($args) {
41 parent::prepare($args);
43 // Check cookie for a valid access_token
45 if (isset($_COOKIE['fb_access_token'])) {
46 $this->accessToken = $_COOKIE['fb_access_token'];
49 if (empty($this->accessToken)) {
50 $this->clientError(_m("Unable to authenticate you with Facebook."));
54 $graphUrl = 'https://graph.facebook.com/me?access_token=' . urlencode($this->accessToken);
55 $this->fbuser = json_decode(file_get_contents($graphUrl));
57 if (empty($this->fbuser)) {
60 list($proxy, $ip) = common_client_ip();
65 'Failed Facebook authentication attempt, proxy = %s, ip = %s.',
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.')
78 $this->fbuid = $this->fbuser->id;
79 // OKAY, all is well... proceed to register
83 function handle($args)
85 parent::handle($args);
87 if (common_is_real_login()) {
89 // This will throw a client exception if the user already
90 // has some sort of foreign_link to Facebook.
92 $this->checkForExistingLink();
94 // Possibly reconnect an existing account
98 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
105 function checkForExistingLink() {
107 // User is already logged in, are her accounts already linked?
109 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
111 if (!empty($flink)) {
113 // User already has a linked Facebook account and shouldn't be here!
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.')
124 $cur = common_current_user();
125 $flink = Foreign_link::getByUserID($cur->id, FACEBOOK_SERVICE);
127 if (!empty($flink)) {
129 // There's already a local user linked to this Facebook account.
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.')
141 function handlePost()
143 $token = $this->trimmed('token');
146 if (!$token || $token != common_session_token()) {
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.')
154 if ($this->arg('create')) {
156 if (!$this->boolean('license')) {
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')
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();
169 } else if ($this->arg('connect')) {
171 $this->connectNewUser();
176 // TRANS: Form validation error displayed when an unhandled error occurs.
177 _m('An unknown error has occured.'),
178 $this->trimmed('newname')
183 function showPageNotice()
187 $this->element('div', array('class' => 'error'), $this->error);
192 'div', 'instructions',
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')
205 // TRANS: Page title.
206 return _m('Facebook Setup');
209 function showForm($error=null, $username=null)
211 $this->error = $error;
212 $this->username = $username;
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.
227 function showContent()
229 if (!empty($this->message_text)) {
230 $this->element('p', null, $this->message);
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',
245 'class' => 'checkbox',
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')) .
256 htmlspecialchars(common_config('license', 'title')) .
258 $this->raw(sprintf(htmlspecialchars($message), $link));
259 $this->elementEnd('label');
260 $this->elementEnd('li');
261 $this->elementEnd('ul');
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');
273 // Hook point for captcha etc
274 Event::handle('StartRegistrationFormData', array($this));
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');
284 // Hook point for captcha etc
285 Event::handle('EndRegistrationFormData', array($this));
287 $this->elementEnd('ul');
288 // TRANS: Submit button to create a new account.
289 $this->submit('create', _m('BUTTON','Create'));
290 $this->elementEnd('fieldset');
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');
313 $this->elementEnd('fieldset');
314 $this->elementEnd('form');
317 function message($msg)
319 $this->message_text = $msg;
323 function createNewUser()
325 if (!Event::handle('StartRegistrationTry', array($this))) {
329 if (common_config('site', 'closed')) {
330 // TRANS: Client error trying to register with registrations not allowed.
331 $this->clientError(_m('Registration not allowed.'));
337 if (common_config('site', 'inviteonly')) {
338 $code = $_SESSION['invitecode'];
340 // TRANS: Client error trying to register with registrations 'invite only'.
341 $this->clientError(_m('Registration not allowed.'));
345 $invite = Invitation::getKV($code);
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.'));
355 $nickname = Nickname::normalize($this->trimmed('newname'), true);
356 } catch (NicknameException $e) {
357 $this->showForm($e->getMessage());
362 'nickname' => $nickname,
363 'fullname' => $this->fbuser->name,
364 'homepage' => $this->fbuser->website,
365 'location' => $this->fbuser->location->name
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;
377 if (!empty($invite)) {
378 $args['code'] = $invite->code;
381 $user = User::register($args);
382 $result = $this->flinkUser($user->id, $this->fbuid);
385 // TRANS: Server error displayed when connecting to Facebook fails.
386 $this->serverError(_m('Error connecting user to Facebook.'));
390 // Add a Foreign_user record
391 Facebookclient::addFacebookUser($this->fbuser);
393 $this->setAvatar($user);
395 common_set_user($user);
396 common_real_login(true);
401 'Registered new user %s (%d) from Facebook user %s, (fbuid %d)',
410 Event::handle('EndRegistrationTry', array($this));
412 $this->goHome($user->nickname);
416 * Attempt to download the user's Facebook picture and create a
417 * StatusNet avatar for the new user.
419 function setAvatar($user)
423 'http://graph.facebook.com/%d/picture?type=large',
427 // fetch the picture from Facebook
428 $client = new HTTPClient();
430 // fetch the actual picture
431 $response = $client->get($picUrl);
433 if ($response->isOk()) {
435 // seems to always be jpeg, but not sure
436 $tmpname = "facebook-avatar-tmp-" . common_random_hexstr(4);
438 $ok = file_put_contents(
439 Avatar::path($tmpname),
444 common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__);
446 // save it as an avatar
448 $file = new ImageFile($user->id, Avatar::path($tmpname));
449 $filename = $file->resize(180); // size of the biggest img we get from Facebook
451 $profile = $user->getProfile();
453 if ($profile->setOriginal($filename)) {
457 'Saved avatar for %s (%d) from Facebook picture for '
458 . '%s (fbuid %d), filename = %s',
469 @unlink(Avatar::path($tmpname));
474 } catch (Exception $e) {
475 common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__);
476 // error isn't fatal, continue
480 function connectNewUser()
482 $nickname = $this->trimmed('nickname');
483 $password = $this->trimmed('password');
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.'));
491 $user = User::getKV('nickname', $nickname);
493 $this->tryLinkUser($user);
495 common_set_user($user);
496 common_real_login(true);
498 // clear out the stupid cookie
499 setcookie('fb_access_token', '', time() - 3600); // one hour ago
501 $this->goHome($user->nickname);
504 function connectUser()
506 $user = common_current_user();
507 $this->tryLinkUser($user);
509 // clear out the stupid cookie
510 setcookie('fb_access_token', '', time() - 3600); // one hour ago
511 common_redirect(common_local_url('facebookfinishlogin'), 303);
514 function tryLinkUser($user)
516 $result = $this->flinkUser($user->id, $this->fbuid);
518 if (empty($result)) {
519 // TRANS: Server error displayed when connecting to Facebook fails.
520 $this->serverError(_m('Error connecting user to Facebook.'));
527 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
529 if (!empty($flink)) {
530 $user = $flink->getUser();
537 'Logged in Facebook user %s as user %d (%s)',
545 common_set_user($user);
546 common_real_login(true);
548 // clear out the stupid cookie
549 setcookie('fb_access_token', '', time() - 3600); // one hour ago
551 $this->goHome($user->nickname);
555 $this->showForm(null, $this->bestNewNickname());
559 function goHome($nickname)
561 $url = common_get_returnto();
563 // We don't have to return to it again
564 common_set_returnto(null);
566 $url = common_local_url('all',
571 common_redirect($url, 303);
574 function flinkUser($user_id, $fbuid)
576 $flink = new Foreign_link();
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();
584 $flink_id = $flink->insert();
589 function bestNewNickname()
592 $nickname = Nickname::normalize($this->fbuser->username, true);
594 } catch (NicknameException $e) {
595 // Failed to normalize nickname, but let's try the full name
599 $nickname = Nickname::normalize($this->fbuser->name, true);
601 } catch (NicknameException $e) {
602 // Any more ideas? Nope.
609 * Do we already have a user record with this email?
610 * (emails have to be unique but they can change)
612 * @param string $email the email address to check
614 * @return boolean result
616 function isNewEmail($email)
618 // we shouldn't have to validate the format
619 $result = User::getKV('email', $email);
621 if (empty($result)) {