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'];
47 if (empty($this->accessToken)) {
48 $this->clientError(_m("Unable to authenticate you with Facebook."));
53 $graphUrl = 'https://graph.facebook.com/me?access_token=' . urlencode($this->accessToken);
54 $this->fbuser = json_decode(file_get_contents($graphUrl));
56 if (!empty($this->fbuser)) {
57 $this->fbuid = $this->fbuser->id;
58 // OKAY, all is well... proceed to register
64 list($proxy, $ip) = common_client_ip();
69 'Failed Facebook authentication attempt, proxy = %s, ip = %s.',
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.')
85 function handle($args)
87 parent::handle($args);
89 if (common_is_real_login()) {
91 // This will throw a client exception if the user already
92 // has some sort of foreign_link to Facebook.
94 $this->checkForExistingLink();
96 // Possibly reconnect an existing account
100 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
107 function checkForExistingLink() {
109 // User is already logged in, are her accounts already linked?
111 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
113 if (!empty($flink)) {
115 // User already has a linked Facebook account and shouldn't be here!
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.')
126 $cur = common_current_user();
127 $flink = Foreign_link::getByUserID($cur->id, FACEBOOK_SERVICE);
129 if (!empty($flink)) {
131 // There's already a local user linked to this Facebook account.
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.')
143 function handlePost()
145 $token = $this->trimmed('token');
148 if (!$token || $token != common_session_token()) {
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.')
156 if ($this->arg('create')) {
158 if (!$this->boolean('license')) {
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')
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();
171 } else if ($this->arg('connect')) {
173 $this->connectNewUser();
178 // TRANS: Form validation error displayed when an unhandled error occurs.
179 _m('An unknown error has occured.'),
180 $this->trimmed('newname')
185 function showPageNotice()
189 $this->element('div', array('class' => 'error'), $this->error);
194 'div', 'instructions',
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')
207 // TRANS: Page title.
208 return _m('Facebook Setup');
211 function showForm($error=null, $username=null)
213 $this->error = $error;
214 $this->username = $username;
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.
229 function showContent()
231 if (!empty($this->message_text)) {
232 $this->element('p', null, $this->message);
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',
247 'class' => 'checkbox',
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')) .
258 htmlspecialchars(common_config('license', 'title')) .
260 $this->raw(sprintf(htmlspecialchars($message), $link));
261 $this->elementEnd('label');
262 $this->elementEnd('li');
263 $this->elementEnd('ul');
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');
275 // Hook point for captcha etc
276 Event::handle('StartRegistrationFormData', array($this));
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');
286 // Hook point for captcha etc
287 Event::handle('EndRegistrationFormData', array($this));
289 $this->elementEnd('ul');
290 // TRANS: Submit button to create a new account.
291 $this->submit('create', _m('BUTTON','Create'));
292 $this->elementEnd('fieldset');
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');
315 $this->elementEnd('fieldset');
316 $this->elementEnd('form');
319 function message($msg)
321 $this->message_text = $msg;
325 function createNewUser()
327 if (!Event::handle('StartRegistrationTry', array($this))) {
331 if (common_config('site', 'closed')) {
332 // TRANS: Client error trying to register with registrations not allowed.
333 $this->clientError(_m('Registration not allowed.'));
339 if (common_config('site', 'inviteonly')) {
340 $code = $_SESSION['invitecode'];
342 // TRANS: Client error trying to register with registrations 'invite only'.
343 $this->clientError(_m('Registration not allowed.'));
347 $invite = Invitation::staticGet($code);
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.'));
357 $nickname = Nickname::normalize($this->trimmed('newname'));
358 } catch (NicknameException $e) {
359 $this->showForm($e->getMessage());
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.'));
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.'));
376 'nickname' => $nickname,
377 'fullname' => $this->fbuser->name,
378 'homepage' => $this->fbuser->website,
379 'location' => $this->fbuser->location->name
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;
391 if (!empty($invite)) {
392 $args['code'] = $invite->code;
395 $user = User::register($args);
396 $result = $this->flinkUser($user->id, $this->fbuid);
399 // TRANS: Server error displayed when connecting to Facebook fails.
400 $this->serverError(_m('Error connecting user to Facebook.'));
404 // Add a Foreign_user record
405 Facebookclient::addFacebookUser($this->fbuser);
407 $this->setAvatar($user);
409 common_set_user($user);
410 common_real_login(true);
415 'Registered new user %s (%d) from Facebook user %s, (fbuid %d)',
424 Event::handle('EndRegistrationTry', array($this));
426 $this->goHome($user->nickname);
430 * Attempt to download the user's Facebook picture and create a
431 * StatusNet avatar for the new user.
433 function setAvatar($user)
437 'http://graph.facebook.com/%d/picture?type=large',
441 // fetch the picture from Facebook
442 $client = new HTTPClient();
444 // fetch the actual picture
445 $response = $client->get($picUrl);
447 if ($response->isOk()) {
449 // seems to always be jpeg, but not sure
450 $tmpname = "facebook-avatar-tmp-" . common_good_rand(4);
452 $ok = file_put_contents(
453 Avatar::path($tmpname),
458 common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__);
460 // save it as an avatar
462 $file = new ImageFile($user->id, Avatar::path($tmpname));
463 $filename = $file->resize(180); // size of the biggest img we get from Facebook
465 $profile = $user->getProfile();
467 if ($profile->setOriginal($filename)) {
471 'Saved avatar for %s (%d) from Facebook picture for '
472 . '%s (fbuid %d), filename = %s',
483 @unlink(Avatar::path($tmpname));
488 } catch (Exception $e) {
489 common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__);
490 // error isn't fatal, continue
494 function connectNewUser()
496 $nickname = $this->trimmed('nickname');
497 $password = $this->trimmed('password');
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.'));
505 $user = User::staticGet('nickname', $nickname);
507 $this->tryLinkUser($user);
509 common_set_user($user);
510 common_real_login(true);
512 // clear out the stupid cookie
513 setcookie('fb_access_token', '', time() - 3600); // one hour ago
515 $this->goHome($user->nickname);
518 function connectUser()
520 $user = common_current_user();
521 $this->tryLinkUser($user);
523 // clear out the stupid cookie
524 setcookie('fb_access_token', '', time() - 3600); // one hour ago
525 common_redirect(common_local_url('facebookfinishlogin'), 303);
528 function tryLinkUser($user)
530 $result = $this->flinkUser($user->id, $this->fbuid);
532 if (empty($result)) {
533 // TRANS: Server error displayed when connecting to Facebook fails.
534 $this->serverError(_m('Error connecting user to Facebook.'));
541 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
543 if (!empty($flink)) {
544 $user = $flink->getUser();
551 'Logged in Facebook user %s as user %d (%s)',
559 common_set_user($user);
560 common_real_login(true);
562 // clear out the stupid cookie
563 setcookie('fb_access_token', '', time() - 3600); // one hour ago
565 $this->goHome($user->nickname);
569 $this->showForm(null, $this->bestNewNickname());
573 function goHome($nickname)
575 $url = common_get_returnto();
577 // We don't have to return to it again
578 common_set_returnto(null);
580 $url = common_local_url('all',
585 common_redirect($url, 303);
588 function flinkUser($user_id, $fbuid)
590 $flink = new Foreign_link();
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();
598 $flink_id = $flink->insert();
603 function bestNewNickname()
605 if (!empty($this->fbuser->username)) {
606 $nickname = $this->nicknamize($this->fbuser->username);
607 if ($this->isNewNickname($nickname)) {
614 $fullname = $this->fbuser->name;
616 if (!empty($fullname)) {
617 $fullname = $this->nicknamize($fullname);
618 if ($this->isNewNickname($fullname)) {
627 * Given a string, try to make it work as a nickname
629 function nicknamize($str)
631 $str = preg_replace('/\W/', '', $str);
632 return strtolower($str);
636 * Is the desired nickname already taken?
638 * @return boolean result
640 function isNewNickname($str)
642 if (!Nickname::isValid($str)) {
646 if (!User::allowed_nickname($str)) {
650 if (User::staticGet('nickname', $str)) {
658 * Do we already have a user record with this email?
659 * (emails have to be unique but they can change)
661 * @param string $email the email address to check
663 * @return boolean result
665 function isNewEmail($email)
667 // we shouldn't have to validate the format
668 $result = User::staticGet('email', $email);
670 if (empty($result)) {