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) {
42 parent::prepare($args);
44 $this->facebook = new Facebook(
46 'appId' => common_config('facebook', 'appid'),
47 'secret' => common_config('facebook', 'secret'),
52 // Check for a Facebook user session
54 $session = $this->facebook->getSession();
59 $this->fbuid = $this->facebook->getUser();
60 $this->fbuser = $this->facebook->api('/me');
61 } catch (FacebookApiException $e) {
62 common_log(LOG_ERROR, $e, __FILE__);
66 if (!empty($this->fbuser)) {
68 // OKAY, all is well... proceed to register
70 common_debug("Found a valid Facebook user.", __FILE__);
73 // This shouldn't happen in the regular course of things
75 list($proxy, $ip) = common_client_ip();
80 'Failed Facebook authentication attempt, proxy = %s, ip = %s.',
88 _m('You must be logged into Facebook to register a local account using Facebook.')
95 function handle($args)
97 parent::handle($args);
99 if (common_is_real_login()) {
101 // User is already logged in, are her accounts already linked?
103 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
105 if (!empty($flink)) {
107 // User already has a linked Facebook account and shouldn't be here!
111 'There\'s already a local user %d linked with Facebook user %s.',
118 _m('There is already a local account linked with that Facebook account.')
123 // Possibly reconnect an existing account
125 $this->connectUser();
128 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
135 function handlePost()
137 $token = $this->trimmed('token');
139 if (!$token || $token != common_session_token()) {
141 _m('There was a problem with your session token. Try again, please.')
146 if ($this->arg('create')) {
148 if (!$this->boolean('license')) {
150 _m('You can\'t register if you don\'t agree to the license.'),
151 $this->trimmed('newname')
156 // We has a valid Facebook session and the Facebook user has
157 // agreed to the SN license, so create a new user
158 $this->createNewUser();
160 } else if ($this->arg('connect')) {
162 $this->connectNewUser();
167 _m('An unknown error has occured.'),
168 $this->trimmed('newname')
173 function showPageNotice()
177 $this->element('div', array('class' => 'error'), $this->error);
182 'div', 'instructions',
183 // TRANS: %s is the site name.
185 _m('This is the first time you\'ve 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.'),
186 common_config('site', 'name')
194 // TRANS: Page title.
195 return _m('Facebook Setup');
198 function showForm($error=null, $username=null)
200 $this->error = $error;
201 $this->username = $username;
212 * @fixme much of this duplicates core code, which is very fragile.
213 * Should probably be replaced with an extensible mini version of
214 * the core registration form.
216 function showContent()
218 if (!empty($this->message_text)) {
219 $this->element('p', null, $this->message);
223 $this->elementStart('form', array('method' => 'post',
224 'id' => 'form_settings_facebook_connect',
225 'class' => 'form_settings',
226 'action' => common_local_url('facebookfinishlogin')));
227 $this->elementStart('fieldset', array('id' => 'settings_facebook_connect_options'));
229 $this->element('legend', null, _m('Connection options'));
230 $this->elementStart('ul', 'form_data');
231 $this->elementStart('li');
232 $this->element('input', array('type' => 'checkbox',
234 'class' => 'checkbox',
237 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
238 // TRANS: %s is the name of the license used by the user for their status updates.
239 $message = _m('My text and files are available under %s ' .
240 'except this private data: password, ' .
241 'email address, IM address, and phone number.');
242 $link = '<a href="' .
243 htmlspecialchars(common_config('license', 'url')) .
245 htmlspecialchars(common_config('license', 'title')) .
247 $this->raw(sprintf(htmlspecialchars($message), $link));
248 $this->elementEnd('label');
249 $this->elementEnd('li');
250 $this->elementEnd('ul');
252 $this->elementStart('fieldset');
253 $this->hidden('token', common_session_token());
254 $this->element('legend', null,
256 _m('Create new account'));
257 $this->element('p', null,
258 _m('Create a new user with this nickname.'));
259 $this->elementStart('ul', 'form_data');
260 $this->elementStart('li');
261 // TRANS: Field label.
262 $this->input('newname', _m('New nickname'),
263 ($this->username) ? $this->username : '',
264 _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
265 $this->elementEnd('li');
266 $this->elementEnd('ul');
267 // TRANS: Submit button.
268 $this->submit('create', _m('BUTTON','Create'));
269 $this->elementEnd('fieldset');
271 $this->elementStart('fieldset');
273 $this->element('legend', null,
274 _m('Connect existing account'));
275 $this->element('p', null,
276 _m('If you already have an account, login with your username and password to connect it to your Facebook.'));
277 $this->elementStart('ul', 'form_data');
278 $this->elementStart('li');
279 // TRANS: Field label.
280 $this->input('nickname', _m('Existing nickname'));
281 $this->elementEnd('li');
282 $this->elementStart('li');
283 $this->password('password', _m('Password'));
284 $this->elementEnd('li');
285 $this->elementEnd('ul');
286 // TRANS: Submit button.
287 $this->submit('connect', _m('BUTTON','Connect'));
288 $this->elementEnd('fieldset');
290 $this->elementEnd('fieldset');
291 $this->elementEnd('form');
294 function message($msg)
296 $this->message_text = $msg;
300 function createNewUser()
302 if (common_config('site', 'closed')) {
303 // TRANS: Client error trying to register with registrations not allowed.
304 $this->clientError(_m('Registration not allowed.'));
310 if (common_config('site', 'inviteonly')) {
311 $code = $_SESSION['invitecode'];
313 // TRANS: Client error trying to register with registrations 'invite only'.
314 $this->clientError(_m('Registration not allowed.'));
318 $invite = Invitation::staticGet($code);
320 if (empty($invite)) {
321 // TRANS: Client error trying to register with an invalid invitation code.
322 $this->clientError(_m('Not a valid invitation code.'));
328 $nickname = Nickname::normalize($this->trimmed('newname'));
329 } catch (NicknameException $e) {
330 $this->showForm($e->getMessage());
334 if (!User::allowed_nickname($nickname)) {
335 $this->showForm(_m('Nickname not allowed.'));
339 if (User::staticGet('nickname', $nickname)) {
340 $this->showForm(_m('Nickname already in use. Try another one.'));
345 'nickname' => $nickname,
346 'fullname' => $this->fbuser['first_name']
347 . ' ' . $this->fbuser['last_name'],
348 'homepage' => $this->fbuser['website'],
349 'bio' => $this->fbuser['about'],
350 'location' => $this->fbuser['location']['name']
353 // It's possible that the email address is already in our
354 // DB. It's a unique key, so we need to check
355 if ($this->isNewEmail($this->fbuser['email'])) {
356 $args['email'] = $this->fbuser['email'];
357 $args['email_confirmed'] = true;
360 if (!empty($invite)) {
361 $args['code'] = $invite->code;
364 $user = User::register($args);
365 $result = $this->flinkUser($user->id, $this->fbuid);
368 $this->serverError(_m('Error connecting user to Facebook.'));
372 // Add a Foreign_user record
373 Facebookclient::addFacebookUser($this->fbuser);
375 $this->setAvatar($user);
377 common_set_user($user);
378 common_real_login(true);
383 'Registered new user %s (%d) from Facebook user %s, (fbuid %d)',
386 $this->fbuser['name'],
392 $this->goHome($user->nickname);
396 * Attempt to download the user's Facebook picture and create a
397 * StatusNet avatar for the new user.
399 function setAvatar($user)
402 'http://graph.facebook.com/%s/picture?type=large',
406 // fetch the picture from Facebook
407 $client = new HTTPClient();
409 // fetch the actual picture
410 $response = $client->get($picUrl);
412 if ($response->isOk()) {
414 $finalUrl = $client->getUrl();
416 // Make sure the filename is unique becuase it's possible for a user
417 // to deauthorize our app, and then come back in as a new user but
418 // have the same Facebook picture (avatar URLs have a unique index
419 // and their URLs are based on the filenames).
420 $filename = 'facebook-' . common_good_rand(4) . '-'
421 . substr(strrchr($finalUrl, '/'), 1);
423 $ok = file_put_contents(
424 Avatar::path($filename),
432 'Couldn\'t save Facebook avatar %s',
440 // save it as an avatar
441 $profile = $user->getProfile();
443 if ($profile->setOriginal($filename)) {
447 'Saved avatar for %s (%d) from Facebook picture for '
448 . '%s (fbuid %d), filename = %s',
451 $this->fbuser['name'],
462 function connectNewUser()
464 $nickname = $this->trimmed('nickname');
465 $password = $this->trimmed('password');
467 if (!common_check_user($nickname, $password)) {
468 $this->showForm(_m('Invalid username or password.'));
472 $user = User::staticGet('nickname', $nickname);
477 'Found a legit user to connect to Facebook: %s (%d)',
485 $this->tryLinkUser($user);
487 common_set_user($user);
488 common_real_login(true);
490 $this->goHome($user->nickname);
493 function connectUser()
495 $user = common_current_user();
496 $this->tryLinkUser($user);
497 common_redirect(common_local_url('facebookfinishlogin'), 303);
500 function tryLinkUser($user)
502 $result = $this->flinkUser($user->id, $this->fbuid);
504 if (empty($result)) {
505 $this->serverError(_m('Error connecting user to Facebook.'));
511 'Connected Facebook user %s (fbuid %d) to local user %s (%d)',
512 $this->fbuser['name'],
525 'Trying login for Facebook user %s',
531 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
533 if (!empty($flink)) {
534 $user = $flink->getUser();
541 'Logged in Facebook user %s as user %d (%s)',
549 common_set_user($user);
550 common_real_login(true);
551 $this->goHome($user->nickname);
558 'No flink found for fbuid: %s - new user',
564 $this->showForm(null, $this->bestNewNickname());
568 function goHome($nickname)
570 $url = common_get_returnto();
572 // We don't have to return to it again
573 common_set_returnto(null);
575 $url = common_local_url('all',
580 common_redirect($url, 303);
583 function flinkUser($user_id, $fbuid)
585 $flink = new Foreign_link();
586 $flink->user_id = $user_id;
587 $flink->foreign_id = $fbuid;
588 $flink->service = FACEBOOK_SERVICE;
590 // Pull the access token from the Facebook cookies
591 $flink->credentials = $this->facebook->getAccessToken();
593 $flink->created = common_sql_now();
595 $flink_id = $flink->insert();
600 function bestNewNickname()
602 if (!empty($this->fbuser['name'])) {
603 $nickname = $this->nicknamize($this->fbuser['name']);
604 if ($this->isNewNickname($nickname)) {
611 $fullname = trim($this->fbuser['first_name'] .
612 ' ' . $this->fbuser['last_name']);
614 if (!empty($fullname)) {
615 $fullname = $this->nicknamize($fullname);
616 if ($this->isNewNickname($fullname)) {
625 * Given a string, try to make it work as a nickname
627 function nicknamize($str)
629 $str = preg_replace('/\W/', '', $str);
630 return strtolower($str);
634 * Is the desired nickname already taken?
636 * @return boolean result
638 function isNewNickname($str)
640 if (!Nickname::isValid($str)) {
644 if (!User::allowed_nickname($str)) {
648 if (User::staticGet('nickname', $str)) {
656 * Do we already have a user record with this email?
657 * (emails have to be unique but they can change)
659 * @param string $email the email address to check
661 * @return boolean result
663 function isNewEmail($email)
665 // we shouldn't have to validate the format
666 $result = User::staticGet('email', $email);
668 if (empty($result)) {
669 common_debug("XXXXXXXXXXXXXXXXXX We've never seen this email before!!!");
672 common_debug("XXXXXXXXXXXXXXXXXX dupe email address!!!!");