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 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 $facebook = null; // Facebook client
37 private $fbuid = null; // Facebook user ID
38 private $fbuser = null; // Facebook user object (JSON)
40 function prepare($args) {
41 parent::prepare($args);
43 $this->facebook = new Facebook(
45 'appId' => common_config('facebook', 'appid'),
46 'secret' => common_config('facebook', 'secret'),
51 // Check for a Facebook user session
53 $session = $this->facebook->getSession();
58 $this->fbuid = $this->facebook->getUser();
59 $this->fbuser = $this->facebook->api('/me');
60 } catch (FacebookApiException $e) {
61 common_log(LOG_ERROR, $e, __FILE__);
65 if (!empty($this->fbuser)) {
66 // OKAY, all is well... proceed to register
68 common_debug("Found a valid Facebook user.", __FILE__);
71 // This shouldn't happen in the regular course of things
73 list($proxy, $ip) = common_client_ip();
78 'Failed Facebook authentication attempt, proxy = %s, ip = %s.',
86 // TRANS: Client error displayed when trying to connect to Facebook while not logged in.
87 _m('You must be logged into Facebook to register a local account using Facebook.')
94 function handle($args)
96 parent::handle($args);
98 if (common_is_real_login()) {
100 // User is already logged in, are her accounts already linked?
102 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
104 if (!empty($flink)) {
106 // User already has a linked Facebook account and shouldn't be here!
110 'There\'s already a local user %d linked with Facebook user %s.',
117 // TRANS: Client error displayed when trying to connect to a Facebook account that is already linked
118 // TRANS: in the same StatusNet site.
119 _m('There is already a local account linked with that Facebook account.')
124 // Possibly reconnect an existing account
126 $this->connectUser();
129 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
136 function handlePost()
138 $token = $this->trimmed('token');
140 if (!$token || $token != common_session_token()) {
142 // TRANS: Client error displayed when the session token does not match or is not given.
143 _m('There was a problem with your session token. Try again, please.')
148 if ($this->arg('create')) {
150 if (!$this->boolean('license')) {
152 // TRANS: Form validation error displayed when user has not agreed to the license.
153 _m('You cannot register if you do not agree to the license.'),
154 $this->trimmed('newname')
159 // We has a valid Facebook session and the Facebook user has
160 // agreed to the SN license, so create a new user
161 $this->createNewUser();
163 } else if ($this->arg('connect')) {
165 $this->connectNewUser();
170 // TRANS: Form validation error displayed when an unhandled error occurs.
171 _m('An unknown error has occured.'),
172 $this->trimmed('newname')
177 function showPageNotice()
181 $this->element('div', array('class' => 'error'), $this->error);
186 'div', 'instructions',
188 // TRANS: Form instructions for connecting to Facebook.
189 // TRANS: %s is the site name.
190 _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.'),
191 common_config('site', 'name')
199 // TRANS: Page title.
200 return _m('Facebook Setup');
203 function showForm($error=null, $username=null)
205 $this->error = $error;
206 $this->username = $username;
217 * @todo FIXME: Much of this duplicates core code, which is very fragile.
218 * Should probably be replaced with an extensible mini version of
219 * the core registration form.
221 function showContent()
223 if (!empty($this->message_text)) {
224 $this->element('p', null, $this->message);
228 $this->elementStart('form', array('method' => 'post',
229 'id' => 'form_settings_facebook_connect',
230 'class' => 'form_settings',
231 'action' => common_local_url('facebookfinishlogin')));
232 $this->elementStart('fieldset', array('id' => 'settings_facebook_connect_options'));
233 // TRANS: Fieldset legend.
234 $this->element('legend', null, _m('Connection options'));
235 $this->elementStart('ul', 'form_data');
236 $this->elementStart('li');
237 $this->element('input', array('type' => 'checkbox',
239 'class' => 'checkbox',
242 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
243 // TRANS: %s is the name of the license used by the user for their status updates.
244 $message = _m('My text and files are available under %s ' .
245 'except this private data: password, ' .
246 'email address, IM address, and phone number.');
247 $link = '<a href="' .
248 htmlspecialchars(common_config('license', 'url')) .
250 htmlspecialchars(common_config('license', 'title')) .
252 $this->raw(sprintf(htmlspecialchars($message), $link));
253 $this->elementEnd('label');
254 $this->elementEnd('li');
255 $this->elementEnd('ul');
257 $this->elementStart('fieldset');
258 $this->hidden('token', common_session_token());
259 $this->element('legend', null,
260 // TRANS: Fieldset legend.
261 _m('Create new account'));
262 $this->element('p', null,
263 // TRANS: Form instructions.
264 _m('Create a new user with this nickname.'));
265 $this->elementStart('ul', 'form_data');
267 // Hook point for captcha etc
268 Event::handle('StartRegistrationFormData', array($this));
270 $this->elementStart('li');
271 // TRANS: Field label.
272 $this->input('newname', _m('New nickname'),
273 ($this->username) ? $this->username : '',
274 // TRANS: Field title.
275 _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
276 $this->elementEnd('li');
278 // Hook point for captcha etc
279 Event::handle('EndRegistrationFormData', array($this));
281 $this->elementEnd('ul');
282 // TRANS: Submit button to create a new account.
283 $this->submit('create', _m('BUTTON','Create'));
284 $this->elementEnd('fieldset');
286 $this->elementStart('fieldset');
287 $this->element('legend', null,
288 // TRANS: Fieldset legend.
289 _m('Connect existing account'));
290 $this->element('p', null,
291 // TRANS: Form instructions.
292 _m('If you already have an account, login with your username and password to connect it to your Facebook.'));
293 $this->elementStart('ul', 'form_data');
294 $this->elementStart('li');
295 // TRANS: Field label.
296 $this->input('nickname', _m('Existing nickname'));
297 $this->elementEnd('li');
298 $this->elementStart('li');
299 // TRANS: Field label.
300 $this->password('password', _m('Password'));
301 $this->elementEnd('li');
302 $this->elementEnd('ul');
303 // TRANS: Submit button to connect a Facebook account to an existing StatusNet account.
304 $this->submit('connect', _m('BUTTON','Connect'));
305 $this->elementEnd('fieldset');
307 $this->elementEnd('fieldset');
308 $this->elementEnd('form');
311 function message($msg)
313 $this->message_text = $msg;
317 function createNewUser()
319 if (!Event::handle('StartRegistrationTry', array($this))) {
323 if (common_config('site', 'closed')) {
324 // TRANS: Client error trying to register with registrations not allowed.
325 $this->clientError(_m('Registration not allowed.'));
331 if (common_config('site', 'inviteonly')) {
332 $code = $_SESSION['invitecode'];
334 // TRANS: Client error trying to register with registrations 'invite only'.
335 $this->clientError(_m('Registration not allowed.'));
339 $invite = Invitation::staticGet($code);
341 if (empty($invite)) {
342 // TRANS: Client error trying to register with an invalid invitation code.
343 $this->clientError(_m('Not a valid invitation code.'));
349 $nickname = Nickname::normalize($this->trimmed('newname'));
350 } catch (NicknameException $e) {
351 $this->showForm($e->getMessage());
355 if (!User::allowed_nickname($nickname)) {
356 // TRANS: Form validation error displayed when picking a nickname that is not allowed.
357 $this->showForm(_m('Nickname not allowed.'));
361 if (User::staticGet('nickname', $nickname)) {
362 // TRANS: Form validation error displayed when picking a nickname that is already in use.
363 $this->showForm(_m('Nickname already in use. Try another one.'));
368 'nickname' => $nickname,
369 'fullname' => $this->fbuser['first_name']
370 . ' ' . $this->fbuser['last_name'],
371 'homepage' => $this->fbuser['website'],
372 'bio' => $this->fbuser['about'],
373 'location' => $this->fbuser['location']['name']
376 // It's possible that the email address is already in our
377 // DB. It's a unique key, so we need to check
378 if ($this->isNewEmail($this->fbuser['email'])) {
379 $args['email'] = $this->fbuser['email'];
380 $args['email_confirmed'] = true;
383 if (!empty($invite)) {
384 $args['code'] = $invite->code;
387 $user = User::register($args);
388 $result = $this->flinkUser($user->id, $this->fbuid);
391 // TRANS: Server error displayed when connecting to Facebook fails.
392 $this->serverError(_m('Error connecting user to Facebook.'));
396 // Add a Foreign_user record
397 Facebookclient::addFacebookUser($this->fbuser);
399 $this->setAvatar($user);
401 common_set_user($user);
402 common_real_login(true);
407 'Registered new user %s (%d) from Facebook user %s, (fbuid %d)',
410 $this->fbuser['name'],
416 Event::handle('EndRegistrationTry', array($this));
418 $this->goHome($user->nickname);
422 * Attempt to download the user's Facebook picture and create a
423 * StatusNet avatar for the new user.
425 function setAvatar($user)
428 'http://graph.facebook.com/%s/picture?type=large',
432 // fetch the picture from Facebook
433 $client = new HTTPClient();
435 // fetch the actual picture
436 $response = $client->get($picUrl);
438 if ($response->isOk()) {
440 $finalUrl = $client->getUrl();
442 // Make sure the filename is unique becuase it's possible for a user
443 // to deauthorize our app, and then come back in as a new user but
444 // have the same Facebook picture (avatar URLs have a unique index
445 // and their URLs are based on the filenames).
446 $filename = 'facebook-' . common_good_rand(4) . '-'
447 . substr(strrchr($finalUrl, '/'), 1);
449 $ok = file_put_contents(
450 Avatar::path($filename),
458 'Couldn\'t save Facebook avatar %s',
466 // save it as an avatar
467 $profile = $user->getProfile();
469 if ($profile->setOriginal($filename)) {
473 'Saved avatar for %s (%d) from Facebook picture for '
474 . '%s (fbuid %d), filename = %s',
477 $this->fbuser['name'],
488 function connectNewUser()
490 $nickname = $this->trimmed('nickname');
491 $password = $this->trimmed('password');
493 if (!common_check_user($nickname, $password)) {
494 // TRANS: Form validation error displayed when username/password combination is incorrect.
495 $this->showForm(_m('Invalid username or password.'));
499 $user = User::staticGet('nickname', $nickname);
504 'Found a legit user to connect to Facebook: %s (%d)',
512 $this->tryLinkUser($user);
514 common_set_user($user);
515 common_real_login(true);
517 $this->goHome($user->nickname);
520 function connectUser()
522 $user = common_current_user();
523 $this->tryLinkUser($user);
524 common_redirect(common_local_url('facebookfinishlogin'), 303);
527 function tryLinkUser($user)
529 $result = $this->flinkUser($user->id, $this->fbuid);
531 if (empty($result)) {
532 // TRANS: Server error displayed when connecting to Facebook fails.
533 $this->serverError(_m('Error connecting user to Facebook.'));
539 'Connected Facebook user %s (fbuid %d) to local user %s (%d)',
540 $this->fbuser['name'],
553 'Trying login for Facebook user %s',
559 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
561 if (!empty($flink)) {
562 $user = $flink->getUser();
569 'Logged in Facebook user %s as user %d (%s)',
577 common_set_user($user);
578 common_real_login(true);
579 $this->goHome($user->nickname);
586 'No flink found for fbuid: %s - new user',
592 $this->showForm(null, $this->bestNewNickname());
596 function goHome($nickname)
598 $url = common_get_returnto();
600 // We don't have to return to it again
601 common_set_returnto(null);
603 $url = common_local_url('all',
608 common_redirect($url, 303);
611 function flinkUser($user_id, $fbuid)
613 $flink = new Foreign_link();
614 $flink->user_id = $user_id;
615 $flink->foreign_id = $fbuid;
616 $flink->service = FACEBOOK_SERVICE;
618 // Pull the access token from the Facebook cookies
619 $flink->credentials = $this->facebook->getAccessToken();
621 $flink->created = common_sql_now();
623 $flink_id = $flink->insert();
628 function bestNewNickname()
630 if (!empty($this->fbuser['name'])) {
631 $nickname = $this->nicknamize($this->fbuser['name']);
632 if ($this->isNewNickname($nickname)) {
639 $fullname = trim($this->fbuser['first_name'] .
640 ' ' . $this->fbuser['last_name']);
642 if (!empty($fullname)) {
643 $fullname = $this->nicknamize($fullname);
644 if ($this->isNewNickname($fullname)) {
653 * Given a string, try to make it work as a nickname
655 function nicknamize($str)
657 $str = preg_replace('/\W/', '', $str);
658 return strtolower($str);
662 * Is the desired nickname already taken?
664 * @return boolean result
666 function isNewNickname($str)
668 if (!Nickname::isValid($str)) {
672 if (!User::allowed_nickname($str)) {
676 if (User::staticGet('nickname', $str)) {
684 * Do we already have a user record with this email?
685 * (emails have to be unique but they can change)
687 * @param string $email the email address to check
689 * @return boolean result
691 function isNewEmail($email)
693 // we shouldn't have to validate the format
694 $result = User::staticGet('email', $email);
696 if (empty($result)) {
697 common_debug("XXXXXXXXXXXXXXXXXX We've never seen this email before!!!");
700 common_debug("XXXXXXXXXXXXXXXXXX dupe email address!!!!");