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)) {
58 $this->fbuid = $this->fbuser->id;
59 // OKAY, all is well... proceed to register
65 list($proxy, $ip) = common_client_ip();
70 'Failed Facebook authentication attempt, proxy = %s, ip = %s.',
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.')
86 function handle($args)
88 parent::handle($args);
90 if (common_is_real_login()) {
92 // This will throw a client exception if the user already
93 // has some sort of foreign_link to Facebook.
95 $this->checkForExistingLink();
97 // Possibly reconnect an existing account
101 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
108 function checkForExistingLink() {
110 // User is already logged in, are her accounts already linked?
112 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
114 if (!empty($flink)) {
116 // User already has a linked Facebook account and shouldn't be here!
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.')
127 $cur = common_current_user();
128 $flink = Foreign_link::getByUserID($cur->id, FACEBOOK_SERVICE);
130 if (!empty($flink)) {
132 // There's already a local user linked to this Facebook account.
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.')
144 function handlePost()
146 $token = $this->trimmed('token');
149 if (!$token || $token != common_session_token()) {
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.')
157 if ($this->arg('create')) {
159 if (!$this->boolean('license')) {
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')
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();
172 } else if ($this->arg('connect')) {
174 $this->connectNewUser();
179 // TRANS: Form validation error displayed when an unhandled error occurs.
180 _m('An unknown error has occured.'),
181 $this->trimmed('newname')
186 function showPageNotice()
190 $this->element('div', array('class' => 'error'), $this->error);
195 'div', 'instructions',
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')
208 // TRANS: Page title.
209 return _m('Facebook Setup');
212 function showForm($error=null, $username=null)
214 $this->error = $error;
215 $this->username = $username;
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.
230 function showContent()
232 if (!empty($this->message_text)) {
233 $this->element('p', null, $this->message);
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',
248 'class' => 'checkbox',
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')) .
259 htmlspecialchars(common_config('license', 'title')) .
261 $this->raw(sprintf(htmlspecialchars($message), $link));
262 $this->elementEnd('label');
263 $this->elementEnd('li');
264 $this->elementEnd('ul');
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');
276 // Hook point for captcha etc
277 Event::handle('StartRegistrationFormData', array($this));
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');
287 // Hook point for captcha etc
288 Event::handle('EndRegistrationFormData', array($this));
290 $this->elementEnd('ul');
291 // TRANS: Submit button to create a new account.
292 $this->submit('create', _m('BUTTON','Create'));
293 $this->elementEnd('fieldset');
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');
316 $this->elementEnd('fieldset');
317 $this->elementEnd('form');
320 function message($msg)
322 $this->message_text = $msg;
326 function createNewUser()
328 if (!Event::handle('StartRegistrationTry', array($this))) {
332 if (common_config('site', 'closed')) {
333 // TRANS: Client error trying to register with registrations not allowed.
334 $this->clientError(_m('Registration not allowed.'));
340 if (common_config('site', 'inviteonly')) {
341 $code = $_SESSION['invitecode'];
343 // TRANS: Client error trying to register with registrations 'invite only'.
344 $this->clientError(_m('Registration not allowed.'));
348 $invite = Invitation::staticGet($code);
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.'));
358 $nickname = Nickname::normalize($this->trimmed('newname'));
359 } catch (NicknameException $e) {
360 $this->showForm($e->getMessage());
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.'));
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.'));
377 'nickname' => $nickname,
378 'fullname' => $this->fbuser->name,
379 'homepage' => $this->fbuser->website,
380 'location' => $this->fbuser->location->name
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;
392 if (!empty($invite)) {
393 $args['code'] = $invite->code;
396 $user = User::register($args);
397 $result = $this->flinkUser($user->id, $this->fbuid);
400 // TRANS: Server error displayed when connecting to Facebook fails.
401 $this->serverError(_m('Error connecting user to Facebook.'));
405 // Add a Foreign_user record
406 Facebookclient::addFacebookUser($this->fbuser);
408 $this->setAvatar($user);
410 common_set_user($user);
411 common_real_login(true);
416 'Registered new user %s (%d) from Facebook user %s, (fbuid %d)',
425 Event::handle('EndRegistrationTry', array($this));
427 $this->goHome($user->nickname);
431 * Attempt to download the user's Facebook picture and create a
432 * StatusNet avatar for the new user.
434 function setAvatar($user)
438 'http://graph.facebook.com/%d/picture?type=large',
442 // fetch the picture from Facebook
443 $client = new HTTPClient();
445 // fetch the actual picture
446 $response = $client->get($picUrl);
448 if ($response->isOk()) {
450 // seems to always be jpeg, but not sure
451 $tmpname = "facebook-avatar-tmp-" . common_good_rand(4);
453 $ok = file_put_contents(
454 Avatar::path($tmpname),
459 common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__);
461 // save it as an avatar
463 $file = new ImageFile($user->id, Avatar::path($tmpname));
464 $filename = $file->resize(180); // size of the biggest img we get from Facebook
466 $profile = $user->getProfile();
468 if ($profile->setOriginal($filename)) {
472 'Saved avatar for %s (%d) from Facebook picture for '
473 . '%s (fbuid %d), filename = %s',
484 @unlink(Avatar::path($tmpname));
489 } catch (Exception $e) {
490 common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__);
491 // error isn't fatal, continue
495 function connectNewUser()
497 $nickname = $this->trimmed('nickname');
498 $password = $this->trimmed('password');
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.'));
506 $user = User::staticGet('nickname', $nickname);
508 $this->tryLinkUser($user);
510 common_set_user($user);
511 common_real_login(true);
513 // clear out the stupid cookie
514 setcookie('fb_access_token', '', time() - 3600); // one hour ago
516 $this->goHome($user->nickname);
519 function connectUser()
521 $user = common_current_user();
522 $this->tryLinkUser($user);
524 // clear out the stupid cookie
525 setcookie('fb_access_token', '', time() - 3600); // one hour ago
526 common_redirect(common_local_url('facebookfinishlogin'), 303);
529 function tryLinkUser($user)
531 $result = $this->flinkUser($user->id, $this->fbuid);
533 if (empty($result)) {
534 // TRANS: Server error displayed when connecting to Facebook fails.
535 $this->serverError(_m('Error connecting user to Facebook.'));
542 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
544 if (!empty($flink)) {
545 $user = $flink->getUser();
552 'Logged in Facebook user %s as user %d (%s)',
560 common_set_user($user);
561 common_real_login(true);
563 // clear out the stupid cookie
564 setcookie('fb_access_token', '', time() - 3600); // one hour ago
566 $this->goHome($user->nickname);
570 $this->showForm(null, $this->bestNewNickname());
574 function goHome($nickname)
576 $url = common_get_returnto();
578 // We don't have to return to it again
579 common_set_returnto(null);
581 $url = common_local_url('all',
586 common_redirect($url, 303);
589 function flinkUser($user_id, $fbuid)
591 $flink = new Foreign_link();
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();
599 $flink_id = $flink->insert();
604 function bestNewNickname()
606 if (!empty($this->fbuser->username)) {
607 $nickname = $this->nicknamize($this->fbuser->username);
608 if ($this->isNewNickname($nickname)) {
615 $fullname = $this->fbuser->name;
617 if (!empty($fullname)) {
618 $fullname = $this->nicknamize($fullname);
619 if ($this->isNewNickname($fullname)) {
628 * Given a string, try to make it work as a nickname
630 function nicknamize($str)
632 $str = preg_replace('/\W/', '', $str);
633 return strtolower($str);
637 * Is the desired nickname already taken?
639 * @return boolean result
641 function isNewNickname($str)
643 if (!Nickname::isValid($str)) {
647 if (!User::allowed_nickname($str)) {
651 if (User::staticGet('nickname', $str)) {
659 * Do we already have a user record with this email?
660 * (emails have to be unique but they can change)
662 * @param string $email the email address to check
664 * @return boolean result
666 function isNewEmail($email)
668 // we shouldn't have to validate the format
669 $result = User::staticGet('email', $email);
671 if (empty($result)) {