private $fbuser = null; // Facebook user object (JSON)
private $accessToken = null; // Access token provided by Facebook JS API
- function prepare($args) {
+ function prepare(array $args=array()) {
parent::prepare($args);
// Check cookie for a valid access_token
- $cookie = $this->get_facebook_cookie(
- common_config('facebook', 'appid'),
- common_config('facebook', 'secret')
- );
-
- $this->accessToken = $cookie['access_token'];
-
- common_debug("cookie = " . var_export($cookie, true));
-
- $this->fbuser = json_decode(
- file_get_contents(
- 'https://graph.facebook.com/me?access_token='
- . $this->accessToken
- )
- );
-
- if (!empty($this->fbuser)) {
-
- $this->fbuid = $this->fbuser->id;
- common_debug("fbuser = " . var_export($this->fbuser, true));
- common_debug("fbuid = " . $this->fbuid);
-
- // OKAY, all is well... proceed to register
-
- common_debug("Found a valid Facebook user.", __FILE__);
+ if (isset($_COOKIE['fb_access_token'])) {
+ $this->accessToken = $_COOKIE['fb_access_token'];
+ }
- return true;
+ if (empty($this->accessToken)) {
+ $this->clientError(_m("Unable to authenticate you with Facebook."));
+ }
- } else {
+ $graphUrl = 'https://graph.facebook.com/me?access_token=' . urlencode($this->accessToken);
+ $this->fbuser = json_decode(file_get_contents($graphUrl));
- // This shouldn't happen in the regular course of things
+ if (empty($this->fbuser)) {
+ // log badness
list($proxy, $ip) = common_client_ip();
);
}
- return false;
- }
-
- function get_facebook_cookie($app_id, $app_secret) {
- $args = array();
-
- parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
-
- ksort($args);
- $payload = '';
-
- foreach ($args as $key => $value) {
- if ($key != 'sig') {
- $payload .= $key . '=' . $value;
- }
- }
-
- if (md5($payload . $app_secret) != $args['sig']) {
- return null;
- }
-
- return $args;
+ $this->fbuid = $this->fbuser->id;
+ // OKAY, all is well... proceed to register
+ return true;
}
- function handle($args)
+ function handle(array $args=array())
{
parent::handle($args);
// User already has a linked Facebook account and shouldn't be here!
- common_debug(
- sprintf(
- 'There\'s already a local user %d linked with Facebook user %s.',
- $flink->user_id,
- $this->fbuid
- )
- );
-
$this->clientError(
// TRANS: Client error displayed when trying to connect to a Facebook account that is already linked
// TRANS: in the same StatusNet site.
_m('There is already a local account linked with that Facebook account.')
);
-
- return;
}
$cur = common_current_user();
// There's already a local user linked to this Facebook account.
- common_debug(
- sprintf(
- 'There\'s already a local user %d linked with Facebook user %s.',
- $cur->id,
- $this->fbuid
- )
- );
-
$this->clientError(
// TRANS: Client error displayed when trying to connect to a Facebook account that is already linked
// TRANS: in the same StatusNet site.
_m('There is already a local account linked with that Facebook account.')
);
-
- return;
}
}
{
$token = $this->trimmed('token');
+ // CSRF protection
if (!$token || $token != common_session_token()) {
$this->showForm(
// TRANS: Client error displayed when the session token does not match or is not given.
if (common_config('site', 'closed')) {
// TRANS: Client error trying to register with registrations not allowed.
$this->clientError(_m('Registration not allowed.'));
- return;
}
$invite = null;
if (empty($code)) {
// TRANS: Client error trying to register with registrations 'invite only'.
$this->clientError(_m('Registration not allowed.'));
- return;
}
- $invite = Invitation::staticGet($code);
+ $invite = Invitation::getKV($code);
if (empty($invite)) {
// TRANS: Client error trying to register with an invalid invitation code.
$this->clientError(_m('Not a valid invitation code.'));
- return;
}
}
try {
- $nickname = Nickname::normalize($this->trimmed('newname'));
+ $nickname = Nickname::normalize($this->trimmed('newname'), true);
} catch (NicknameException $e) {
$this->showForm($e->getMessage());
return;
}
- if (!User::allowed_nickname($nickname)) {
- // TRANS: Form validation error displayed when picking a nickname that is not allowed.
- $this->showForm(_m('Nickname not allowed.'));
- return;
- }
-
- if (User::staticGet('nickname', $nickname)) {
- // TRANS: Form validation error displayed when picking a nickname that is already in use.
- $this->showForm(_m('Nickname already in use. Try another one.'));
- return;
- }
-
$args = array(
'nickname' => $nickname,
'fullname' => $this->fbuser->name,
if (!$result) {
// TRANS: Server error displayed when connecting to Facebook fails.
$this->serverError(_m('Error connecting user to Facebook.'));
- return;
}
// Add a Foreign_user record
*/
function setAvatar($user)
{
- $picUrl = sprintf(
- 'http://graph.facebook.com/%s/picture?type=large',
- $this->fbuid
- );
-
- // fetch the picture from Facebook
- $client = new HTTPClient();
-
- // fetch the actual picture
- $response = $client->get($picUrl);
+ try {
+ $picUrl = sprintf(
+ 'http://graph.facebook.com/%d/picture?type=large',
+ $this->fbuser->id
+ );
- if ($response->isOk()) {
+ // fetch the picture from Facebook
+ $client = new HTTPClient();
- $finalUrl = $client->getUrl();
+ // fetch the actual picture
+ $response = $client->get($picUrl);
- // Make sure the filename is unique becuase it's possible for a user
- // to deauthorize our app, and then come back in as a new user but
- // have the same Facebook picture (avatar URLs have a unique index
- // and their URLs are based on the filenames).
- $filename = 'facebook-' . common_good_rand(4) . '-'
- . substr(strrchr($finalUrl, '/'), 1);
+ if ($response->isOk()) {
- $ok = file_put_contents(
- Avatar::path($filename),
- $response->getBody()
- );
+ // seems to always be jpeg, but not sure
+ $tmpname = "facebook-avatar-tmp-" . common_random_hexstr(4);
- if (!$ok) {
- common_log(
- LOG_WARNING,
- sprintf(
- 'Couldn\'t save Facebook avatar %s',
- $tmp
- ),
- __FILE__
+ $ok = file_put_contents(
+ Avatar::path($tmpname),
+ $response->getBody()
);
- } else {
-
- // save it as an avatar
- $profile = $user->getProfile();
-
- if ($profile->setOriginal($filename)) {
- common_log(
- LOG_INFO,
- sprintf(
- 'Saved avatar for %s (%d) from Facebook picture for '
- . '%s (fbuid %d), filename = %s',
- $user->nickname,
- $user->id,
- $this->fbuser->name,
- $this->fbuid,
- $filename
- ),
- __FILE__
- );
+ if (!$ok) {
+ common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__);
+ } else {
+ // save it as an avatar
+
+ $imagefile = new ImageFile(null, Avatar::path($tmpname));
+ $filename = Avatar::filename($user->id, image_type_to_extension($imagefile->preferredType()),
+ 180, common_timestamp());
+ // Previous docs said 180 is the "biggest img we get from Facebook"
+ $imagefile->resizeTo(Avatar::path($filename, array('width'=>180, 'height'=>180)));
+
+ // No need to keep the temporary file around...
+ @unlink(Avatar::path($tmpname));
+
+ $profile = $user->getProfile();
+
+ if ($profile->setOriginal($filename)) {
+ common_log(
+ LOG_INFO,
+ sprintf(
+ 'Saved avatar for %s (%d) from Facebook picture for '
+ . '%s (fbuid %d), filename = %s',
+ $user->nickname,
+ $user->id,
+ $this->fbuser->name,
+ $this->fbuid,
+ $filename
+ ),
+ __FILE__
+ );
+
+ // clean up tmp file
+ }
+
}
}
+ } catch (Exception $e) {
+ common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__);
+ // error isn't fatal, continue
}
}
return;
}
- $user = User::staticGet('nickname', $nickname);
-
- if (!empty($user)) {
- common_debug(
- sprintf(
- 'Found a legit user to connect to Facebook: %s (%d)',
- $user->nickname,
- $user->id
- ),
- __FILE__
- );
- }
+ $user = User::getKV('nickname', $nickname);
$this->tryLinkUser($user);
common_set_user($user);
common_real_login(true);
+ // clear out the stupid cookie
+ setcookie('fb_access_token', '', time() - 3600); // one hour ago
+
$this->goHome($user->nickname);
}
{
$user = common_current_user();
$this->tryLinkUser($user);
+
+ // clear out the stupid cookie
+ setcookie('fb_access_token', '', time() - 3600); // one hour ago
common_redirect(common_local_url('facebookfinishlogin'), 303);
}
if (empty($result)) {
// TRANS: Server error displayed when connecting to Facebook fails.
$this->serverError(_m('Error connecting user to Facebook.'));
- return;
}
-
- common_debug(
- sprintf(
- 'Connected Facebook user %s (fbuid %d) to local user %s (%d)',
- $this->fbuser->name,
- $this->fbuid,
- $user->nickname,
- $user->id
- ),
- __FILE__
- );
}
function tryLogin()
{
- common_debug(
- sprintf(
- 'Trying login for Facebook user %s',
- $this->fbuid
- ),
- __FILE__
- );
-
- $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
-
- if (!empty($flink)) {
+ try {
+ $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
$user = $flink->getUser();
- if (!empty($user)) {
-
- common_log(
- LOG_INFO,
- sprintf(
- 'Logged in Facebook user %s as user %d (%s)',
- $this->fbuid,
- $user->nickname,
- $user->id
- ),
- __FILE__
- );
-
- common_set_user($user);
- common_real_login(true);
- $this->goHome($user->nickname);
- }
-
- } else {
-
- common_debug(
+ common_log(
+ LOG_INFO,
sprintf(
- 'No flink found for fbuid: %s - new user',
- $this->fbuid
+ 'Logged in Facebook user %s as user %d (%s)',
+ $this->fbuid,
+ $user->nickname,
+ $user->id
),
__FILE__
);
+ common_set_user($user);
+ common_real_login(true);
+
+ // clear out the stupid cookie
+ setcookie('fb_access_token', '', time() - 3600); // one hour ago
+
+ $this->goHome($user->nickname);
+
+ } catch (NoResultException $e) {
$this->showForm(null, $this->bestNewNickname());
}
}
function flinkUser($user_id, $fbuid)
{
$flink = new Foreign_link();
- $flink->user_id = $user_id;
- $flink->foreign_id = $fbuid;
- $flink->service = FACEBOOK_SERVICE;
- // Pull the access token from the Facebook cookies
+ $flink->user_id = $user_id;
+ $flink->foreign_id = $fbuid;
+ $flink->service = FACEBOOK_SERVICE;
$flink->credentials = $this->accessToken;
-
- $flink->created = common_sql_now();
+ $flink->created = common_sql_now();
$flink_id = $flink->insert();
function bestNewNickname()
{
- if (!empty($this->fbuser->username)) {
- $nickname = $this->nicknamize($this->fbuser->username);
- if ($this->isNewNickname($nickname)) {
- return $nickname;
- }
+ try {
+ $nickname = Nickname::normalize($this->fbuser->username, true);
+ return $nickname;
+ } catch (NicknameException $e) {
+ // Failed to normalize nickname, but let's try the full name
}
- // Try the full name
-
- $fullname = $this->fbuser->name;
-
- if (!empty($fullname)) {
- $fullname = $this->nicknamize($fullname);
- if ($this->isNewNickname($fullname)) {
- return $fullname;
- }
+ try {
+ $nickname = Nickname::normalize($this->fbuser->name, true);
+ return $nickname;
+ } catch (NicknameException $e) {
+ // Any more ideas? Nope.
}
return null;
}
- /**
- * Given a string, try to make it work as a nickname
- */
- function nicknamize($str)
- {
- $str = preg_replace('/\W/', '', $str);
- return strtolower($str);
- }
-
- /*
- * Is the desired nickname already taken?
- *
- * @return boolean result
- */
- function isNewNickname($str)
- {
- if (!Nickname::isValid($str)) {
- return false;
- }
-
- if (!User::allowed_nickname($str)) {
- return false;
- }
-
- if (User::staticGet('nickname', $str)) {
- return false;
- }
-
- return true;
- }
-
/*
* Do we already have a user record with this email?
* (emails have to be unique but they can change)
function isNewEmail($email)
{
// we shouldn't have to validate the format
- $result = User::staticGet('email', $email);
+ $result = User::getKV('email', $email);
if (empty($result)) {
return true;