Skip to content

Instantly share code, notes, and snippets.

@jonathonbyrdziak
Created September 26, 2012 19:02
Show Gist options
  • Save jonathonbyrdziak/3789887 to your computer and use it in GitHub Desktop.
Save jonathonbyrdziak/3789887 to your computer and use it in GitHub Desktop.
FINALLY! A facebook connect mu-plugin that freakin works.
<?php
/**
* @Author Jonathon Byrd
* @link http://www.redrokk.com
* @Package Wordpress
* @SubPackage Red Rokk Library
*
* @version 0.1
*/
defined('ABSPATH') or die('You\'re not supposed to be here.');
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
/**
* Facebook Connect
*
* I am so freaking tired of all these so called facebook connect plugins that
* don't work worth a damn.
*
*/
if (!class_exists('redrokk_facebook_connect')):
class redrokk_facebook_connect
{
/**
* The facebook application keys
*
*/
var $_appid = null;
var $_appsecret = null;
/**
* The Facebook Permissions
*
* @var csv string
*/
var $scope = 'email,status_update,publish_stream,user_photos,user_videos';
/**
* The url to redirect the user to after login
*
* @var string
*/
var $redirect;
/**
* Constructor.
*
*/
function __construct( $options )
{
// Initializing
$o = get_option('sfc_options');
$options = wp_parse_args($options, array(
'_appid' => @$o['appid'],
'_appsecret'=> @$o['app_secret'],
'redirect' => site_url()
));
$this->setProperties($options);
if (!$this->_fb) {
$this->_fb = new Facebook(array(
'appId' => $this->_appid,
'secret' => $this->_appsecret,
));
}
// Hooks
add_action( 'init' , array($this, 'force_logout') );
add_action( 'init', array($this, 'login') );
add_action( 'init', array($this, 'init_js') );
add_action( 'wp_footer', array($this, 'button') );
add_action( 'wp_head', array($this, 'head') );
add_action( 'wp', array($this, 'channel') );
add_action( 'wp_ajax_nopriv_redrokk_facebook_connect', array($this, 'redrokk_facebook_connect') );
add_action( 'wp_ajax_redrokk_facebook_connect', array($this, 'redrokk_facebook_connect') );
}
/**
*
*/
function force_logout()
{
if (!array_key_exists('facebook_logout', $_GET)) return false;
wp_logout();
$redirect_to = !empty( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : $this->redirect;
wp_safe_redirect( $redirect_to );
exit();
}
/**
*
*/
function init_js()
{
wp_enqueue_script('jquery');
}
/**
* Method is designed to log the user in
*
*/
function login()
{
$fbuser = $this->getUser();
if ($fbuser && isset($fbuser->email))
{
//logged into fb and website
//then link accounts
if (is_user_logged_in())
{
update_user_meta(get_current_user_id(), 'fbuid', $fbuser->id);
}
//logged into fb and not website
//if account does not exist create it and log them in
elseif ( is_email($fbuser->email) && !$this->getUserByFacebookID($fbuser->id) )
{
$user_pass = wp_generate_password( 12, false);
$user_id = wp_insert_user(array(
'user_login' => isset($fbuser->username)?$fbuser->username:$fbuser->first_name.' '.$fbuser->last_name,
'user_email' => $fbuser->email,
'first_name' => $fbuser->first_name,
'last_name' => $fbuser->last_name,
'user_pass' => $user_pass,
));
if (!is_wp_error($user_id))
{
update_user_option( $user_id, 'default_password_nag', true, true );
wp_new_user_notification( $user_id, $user_pass );
update_usermeta($user_id, 'fbuid', $fbuser->id);
wp_signon(array(
'user_login' => isset($fbuser->username)?$fbuser->username:$fbuser->email,
'user_password' => $user_pass
));
}
$redirect = isset($_REQUEST['redirect']) && $_REQUEST['redirect']
? $_REQUEST['redirect']
: site_url();
wp_redirect( $redirect );
exit;
}
//logged into fb and not website
//website account already exists
else
{
//what do we do when this person already has a wordpress account
//the are not logged in with wordpress
//but they are logged in with facebook
//I think that the cookie is already set..
//ask them to login regularily
}
}
if (!is_user_logged_in() && $fbuser && isset($fbuser->email) && is_email($fbuser->email))
{
//$user_info = get_user_by_email($fbuser->email);
$user_info = $this->getUserByFacebookID($fbuser->id);
if (!$user_info)
{
}
$this->forceLogin( $user_info->ID );
update_usermeta($user_info->ID, 'fbuid', $fbuser->id);
if (is_user_logged_in()) {
$redirect = isset($_REQUEST['redirect']) && $_REQUEST['redirect']
? $_REQUEST['redirect']
: site_url();
wp_redirect( $redirect );
exit;
}
}
}
function forceLogin( $ID )
{
$user_info = get_userdata( $ID );
$credentials = array();
$credentials['user_login'] = $user_info->user_login;
$secure_cookie = apply_filters('secure_signon_cookie', is_ssl(), $credentials);
wp_set_auth_cookie($user_info->ID, true, $secure_cookie);
}
function getUserByFacebookID( $Id )
{
global $wpdb;
$sql = "SELECT users.ID
FROM $wpdb->users users, $wpdb->usermeta usermeta
WHERE users.ID = usermeta.user_id
AND usermeta.meta_key = 'fbuid'
AND usermeta.meta_value = '$Id'";
$users = $wpdb->get_results($sql);
if (count($users) >= 1) {
foreach ($users as $user) {
return get_userdata( $user->ID );
}
}
return false;
}
function getUser()
{
if (!$this->fbuser)
{
try {
// $fbuid = get_usermeta($this->id, 'fbuid', false);
// $this->fbuser = (object)$this->_fb->api("/$fbuid");
$this->fbuser = (object)$this->_fb->api("/me");
}
catch (FacebookApiException $e) {
error_log($e);
$this->fbuser = null;
}
}
return $this->fbuser;
}
function is_facebook_user()
{
//get wp user
$user = get_userdata(get_current_user_ID());
if (!is_user_logged_in()) return false;
if (!$this->getUser()) return false;
$fbuid = get_user_meta(get_current_user_id(), 'fbuid', true);
//get fb user
if (isset($this->getUser()->username)
&& sanitize_title($this->getUser()->username) == $user->user_nicename
){
return true;
}
// does email match?
/*
elseif (isset($this->getUser()->email)
&& $this->getUser()->email == $user->user_email
){
return true;
}
*/
// does fbuid match?
elseif (isset($this->getUser()->id)
&& $this->getUser()->id == $fbuid
){
return true;
}
return false;
}
/**
* Method refreshes the users cookie so that we can log them in on reload
*
*/
function redrokk_facebook_connect()
{
?>
<script type="text/javascript">
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
window.location.replace("<?php echo $_REQUEST['redirect']; ?>");
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
</script>
<?php
die();
}
/**
* Method outputs the js needed to operate the connect
*
*/
function js()
{
ob_start();
?>
var FacebookConnect;
;;(function(j){
/**
* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*
* http://ejohn.org/blog/simple-javascript-inheritance/
* Inspired by base2 and Prototype
*
*/
(function(){function h(b){function a(){for(var b=[].slice.call(arguments,0),a=0,g,a=0;c.before[a];a+=1)g=c.before[a],g.apply(this,b);for(var f=d.apply(this,arguments),a=0;c.after[a];a++)g=c.after[a],g.apply(this,b);return f}var d=b,c={before:[],after:[]};a.addHook=function(a,b){if(c[a]instanceof Array)c[a].push(b);else throw function(){var b=Error("Invalid hook type");b.expected=Object.keys(c);b.got=a;return b}();};return a}var f=!1,i=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.Class=function(){this.loadjs=
function(b,a){var d=document.createElement("script");d.type="text/javascript";d.readyState?d.onreadystatechange=function(){if("loaded"==d.readyState||"complete"==d.readyState)d.onreadystatechange=null,a&&a()}:d.onload=function(){a&&a()};d.src=b;document.getElementsByTagName("head")[0].appendChild(d)};this.setOptions=function(b){return this.bind(this.defaults,b)};this.bind=function(b,a){var d={},c;for(c in b)d[c]=b[c];for(c in a)d[c]=a[c];return d}};Class.extend=function(b){function a(){!f&&this.init&&
this.init.apply(this,arguments)}var d=this.prototype;f=!0;var c=new this;f=!1;for(var e in b)c[e]="function"==typeof b[e]&&"function"==typeof d[e]&&i.test(b[e])?function(a,b){return function(){var c=this._super;this._super=d[a];var e=b.apply(this,arguments);this._super=c;return e}}(e,b[e]):"function"==typeof b[e]?h(b[e]):b[e];a.prototype=c;a.constructor=a;a.extend=arguments.callee;return a}})();
/**
* Facebook Connect from Red Rokk
* By Jonathon http://redrokk.com
* MIT LICENSED
*
*/
FacebookConnect = Class.extend({
defaults : {
container : null,
appID : 0,
scope : '<?php echo $this->scope ?>'
},
// Initializing
init: function(options)
{
api = this;
this.o = this.setOptions(options);
this.addListeners();
},
addListeners : function()
{
api.o.container.bind('click', this.onclick.bind(this));
},
onclick : function( evt )
{
evt.stopPropagation();
FB.login(function(response) {
if (response.session) {
if (response.perms) {
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
api.ajax_login();
} else {
// user is logged in, but did not grant any permissions
api.ajax_login();
}
} else {
// user is not logged in
api.ajax_login();
}
}, {scope:api.o.scope});
return false;
},
ajax_login : function()
{
j('#facebookloader').css('display', 'inline');
j.ajax({
url : '<?php echo admin_url('/admin-ajax.php') ?>',
dataType : 'html',
cache : false,
data : {
action : 'redrokk_facebook_connect',
redirect : '<?php echo get_permalink(get_queried_object_id()) ?>'
},
success : function(r) {
api.o.container.append(r);
}
});
}
});
j.fn.FacebookConnect = function(o){
var o = o || {'container':''};
return this.each(function(){
o.container = j(this);
var api = new FacebookConnect(o);
});
};
})(jQuery);
window.fbAsyncInit = function() {
FB.init({
"appId" : "<?php echo $this->_appid ?>",
"channelUrl": "<?php echo add_query_arg('facebook_channel', '', site_url()) ?>",
"status" : true,
"cookie" : true,
"xfbml" : true,
"oauth" : true
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
jQuery(function(){
jQuery('#facebooklink').FacebookConnect();
});
<?php
return ob_get_clean();
}
/**
*
*/
function channel()
{
if (!array_key_exists('facebook_channel', $_GET))
return false;
echo '<script src="//connect.facebook.net/en_US/all.js"></script>';
die();
}
/**
*
*/
function head()
{
echo '<script type="application/javascript">', $this->js(), '</script>';
}
/**
* Method outputs the connect link for facebook
*
*/
function button()
{
if (!is_user_logged_in()):
?>
<div id="fb-root"></div>
<div id="facebooklogin">
<a href="#" id="facebooklink">
<img id="facebookimage" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALsAAAAfCAIAAAAwfyvFAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVU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gNwlxcVA3eOfVRqh2IBOudcn15vq2/2yE9CmNMnkEECrdIonF1uycP/AMV6AxufFoVLTxzd4+tnGyBS7m0PP8bB/76csWAZF0I+YohdU9EesSlCJIEKsgqV6VA3jVxMM3vqILhcE/lWCBk0S+lSSunhExFXycDovpWrvsXx28zr7aPO8kKBXc8XPSUzEmxiuM027aYYVavFySoew1PAJz0cnhX2VVHIDXfFR6T+EEBY1VrM5hAXaVskun1meS9SkSqQVYpPFd9tqrcrjEzSbwLkMxDAH1eZSGaH3eiFik93zbNV0onX05hYJyT4luVfYuHA9KA3ZNiif2CWlLK7pxHqjYoYKi8ESNiIJLVWgx6VSDT7YyIc1FuZAKYPWP84baBeKpeokJwl+Gagh7cMR14GKSqeo9cCxMi4Z6EuKBKB2qSqqlpJ2MAd8XAZfGEdCV+mkkPcZiOkbKZpE2FJaYIhjngIebVq0H0nSAjP9Aq6OJQyhRBMJLTESlFxkyPNRhpBZdMitjRSi+4YZ47c38TefYmKlR92w5Zii56csU8lLJkUU+Y758xdZyTwbv2in9AsSs31Gnblnvy5OIUeTlTIuZ+wcXmhLQ27vEeU86HAXKQhsDEaYQoGicnGcicGT1klHMJKGQOHhLj3sEYiIM7T5kzqUOzKEoHF6eo4iuekkswmNuMca6mNQG3DdxlOvNyIq6uSAwLgMn74o6YyMUvpvOTOc24SpuwHxE/yQYunRw+JhMkr5hklMs0EAecRTEQI7nFFTzxsrRwE5jMPS52+S9ndKIYZluV/FCXne+8bPmZTgZvR/PRgcH8C6/sPPZxx1C24Hv70F9ZrpR5+95posCbYIH7Xl2Xk2YY+ZVHrZ7c7TjSu4beS6vkf2nS/8YrU02nyqvgf+81Tf1NDsaCb0FqVdLVnnvRpTZd1bc/9Un9rzZ6fkRbrI9mCrwQ7n+qFMXpy3dYnUzGpk5qWLViSW1N4uqlC9gn/7fDJ5//1+d/BwCkpg71LtpU5wAAAABJRU5ErkJggg==" />
</a>
<img id="facebookloader" style="margin:8px;display:none;" src='data:image/gif;base64,R0lG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YMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA=='/>
</div>
<?php else: ?>
<div id="fb-root"></div>
<div class="facebooklogin">
<a href="<?php $this->logout_url() ?>">
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFkAAAAXCAIAAADvO3TkAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABWtJREFUeNrkWH1MW1UUp6UP2vLRFloKbRl1pXyU0QGLIOwPJwyYykSmom4s2T/6zzaXGLO4+EGURWeyhDCXmWyJyZKRmOCMExNlRIKyaRj7YMCAAoUWCi30A+gnH33vedZXXhto4dFNInpyaQ/n/c559/7uuffcWxqO4+eu/P7bn2rX4nLYJkUu5Q9rTGHbXFiRSEmR7MN3nqedrPvJMu/KUYii2RGbCnHtxoOaytyw7S9251J3/1Qch8XoHtS/Vp5tMFlHJ8whBOpR6bc7F5wY5rPK5OstvQwMw8PptDnrQmiBcHzb5wWMXZzAAR4Y8A+K4aCFFihkx3+VoJ5RMDzjgRGFygX+X+ACCPBygaLY/z0v0BUu3ChOEBNQ2EykskSRpxDxeVHj+rnW2yO37mtWMbq+SMW8N8qzu/p07XdGt2Bg8DpBXFRXr466CzAAn3QyL4K1t17eXbZXDkQAckcS1+Fawvz2l3UcyQYFXJGa4JybME6pqeCfpEEPa4+XcNh0y8w4dS9fXqDYemuEz2UTSsddjWnWMaab9QdTWSPEnrLksi8vLQK+Yl/GLrkQOO3s0d3pmSAw+crk4oKdYGzrHH1GzAP7jMXhH2StV5ZcSCJJfV/+TngkEzGLn0u7O+SkvHdi3rxwoxhspMEaOdZvvutsaumbNtsJO7kDb9gIvuADglW/mP3mS8q+gRH7vPFkTaFCygJApiwB9EgkTKUagPMfABiYxeW0kxECeqWIeCSS1FOSYuFdErEwjhNh1KupdA+aG/XjIpgcKs0SeFYHCOjQ4rks4hG5X2wouJdPPFHAPfhC5s+tXXVf1tc1XJ8ymI9W5s8axwuU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_url( $redirect = null )
{
if ($redirect === null) {
$redirect = $this->redirect;
}
$logout = add_query_arg(array('redirect_to' => $redirect, 'facebook_logout' =>''), site_url());
echo $this->_fb->getLogoutUrl( array('next' => $logout) );
}
/**
* Method to bind an associative array or object to the JTable instance.This
* method only binds properties that are publicly accessible and optionally
* takes an array of properties to ignore when binding.
*
* @param mixed $src An associative array or object to bind to the JTable instance.
* @param mixed $ignore An optional array or space separated list of properties to ignore while binding.
*
* @return boolean True on success.
*
* @link http://docs.joomla.org/JTable/bind
* @since 11.1
*/
public function bind($src, $ignore = array())
{
// If the source value is not an array or object return false.
if (!is_object($src) && !is_array($src))
{
trigger_error('Bind failed as the provided source is not an array.');
return $this;
}
// If the source value is an object, get its accessible properties.
if (is_object($src))
{
$src = get_object_vars($src);
}
// If the ignore value is a string, explode it over spaces.
if (!is_array($ignore))
{
$ignore = explode(' ', $ignore);
}
// Bind the source value, excluding the ignored fields.
foreach ($this->getProperties() as $k => $v)
{
// Only process fields not in the ignore array.
if (!in_array($k, $ignore))
{
if (isset($src[$k]))
{
$this->$k = $src[$k];
}
}
}
return $this;
}
/**
* Set the object properties based on a named array/hash.
*
* @param mixed $properties Either an associative array or another object.
*
* @return boolean
*
* @since 11.1
*
* @see set()
*/
public function setProperties($properties)
{
if (is_array($properties) || is_object($properties))
{
foreach ((array) $properties as $k => $v)
{
// Use the set function which might be overridden.
$this->set($k, $v);
}
}
return $this;
}
/**
* Modifies a property of the object, creating it if it does not already exist.
*
* @param string $property The name of the property.
* @param mixed $value The value of the property to set.
*
* @return mixed Previous value of the property.
*
* @since 11.1
*/
public function set($property, $value = null)
{
$_property = 'set'.str_replace(' ', '', ucwords(str_replace('_', ' ', $property)));
if (method_exists($this, $_property)) {
return $this->$_property($value);
}
$previous = isset($this->$property) ? $this->$property : null;
$this->$property = $value;
return $this;
}
/**
* Returns an associative array of object properties.
*
* @param boolean $public If true, returns only the public properties.
*
* @return array
*
* @see get()
*/
public function getProperties($public = true)
{
$vars = get_object_vars($this);
if ($public)
{
foreach ($vars as $key => $value)
{
if ('_' == substr($key, 0, 1))
{
unset($vars[$key]);
}
}
}
return $vars;
}
/**
* Method returns the called class
*
*/
public static function get_called_class()
{
if (function_exists('get_called_class')) {
return get_called_class();
}
$called_class = false;
$objects = array();
$traces = debug_backtrace();
foreach ($traces as $trace)
{
if (isset($trace['object'])) {
if (is_object($trace['object'])) {
$objects[] = $trace['object'];
}
}
}
if (count($objects)) {
$called_class = get_class($objects[0]);
}
return $called_class;
}
/**
*
* contains the current instance of this class
* @var object
*/
static $_instance = null;
/**
* Method is called when we need to instantiate this class
*
* @param array $id
* @param array $options
*/
public static function getInstance( $options = array() )
{
if (!isset(self::$_instance))
{
$class = self::get_called_class();
self::$_instance =& new $class($options);
}
return self::$_instance;
}
}
endif;
/**
* Copyright 2011 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
if (!function_exists('curl_init')) {
throw new Exception('Facebook needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
throw new Exception('Facebook needs the JSON PHP extension.');
}
/**
* Thrown when an API call returns an exception.
*
* @author Naitik Shah <[email protected]>
*/
class FacebookApiException extends Exception
{
/**
* The result from the API server that represents the exception information.
*/
protected $result;
/**
* Make a new API Exception with the given result.
*
* @param array $result The result from the API server
*/
public function __construct($result) {
$this->result = $result;
$code = isset($result['error_code']) ? $result['error_code'] : 0;
if (isset($result['error_description'])) {
// OAuth 2.0 Draft 10 style
$msg = $result['error_description'];
} else if (isset($result['error']) && is_array($result['error'])) {
// OAuth 2.0 Draft 00 style
$msg = $result['error']['message'];
} else if (isset($result['error_msg'])) {
// Rest server style
$msg = $result['error_msg'];
} else {
$msg = 'Unknown Error. Check getResult()';
}
parent::__construct($msg, $code);
}
/**
* Return the associated result object returned by the API server.
*
* @return array The result from the API server
*/
public function getResult() {
return $this->result;
}
/**
* Returns the associated type for the error. This will default to
* 'Exception' when a type is not available.
*
* @return string
*/
public function getType() {
if (isset($this->result['error'])) {
$error = $this->result['error'];
if (is_string($error)) {
// OAuth 2.0 Draft 10 style
return $error;
} else if (is_array($error)) {
// OAuth 2.0 Draft 00 style
if (isset($error['type'])) {
return $error['type'];
}
}
}
return 'Exception';
}
/**
* To make debugging easier.
*
* @return string The string representation of the error
*/
public function __toString() {
$str = $this->getType() . ': ';
if ($this->code != 0) {
$str .= $this->code . ': ';
}
return $str . $this->message;
}
}
/**
* Provides access to the Facebook Platform. This class provides
* a majority of the functionality needed, but the class is abstract
* because it is designed to be sub-classed. The subclass must
* implement the four abstract methods listed at the bottom of
* the file.
*
* @author Naitik Shah <[email protected]>
*/
abstract class BaseFacebook
{
/**
* Version.
*/
const VERSION = '3.2.0';
/**
* Signed Request Algorithm.
*/
const SIGNED_REQUEST_ALGORITHM = 'HMAC-SHA256';
/**
* Default options for curl.
*/
public static $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_USERAGENT => 'facebook-php-3.2',
);
/**
* List of query parameters that get automatically dropped when rebuilding
* the current URL.
*/
protected static $DROP_QUERY_PARAMS = array(
'code',
'state',
'signed_request',
);
/**
* Maps aliases to Facebook domains.
*/
public static $DOMAIN_MAP = array(
'api' => 'https://api.facebook.com/',
'api_video' => 'https://api-video.facebook.com/',
'api_read' => 'https://api-read.facebook.com/',
'graph' => 'https://graph.facebook.com/',
'graph_video' => 'https://graph-video.facebook.com/',
'www' => 'https://www.facebook.com/',
);
/**
* The Application ID.
*
* @var string
*/
protected $appId;
/**
* The Application App Secret.
*
* @var string
*/
protected $appSecret;
/**
* The ID of the Facebook user, or 0 if the user is logged out.
*
* @var integer
*/
protected $user;
/**
* The data from the signed_request token.
*/
protected $signedRequest;
/**
* A CSRF state variable to assist in the defense against CSRF attacks.
*/
protected $state;
/**
* The OAuth access token received in exchange for a valid authorization
* code. null means the access token has yet to be determined.
*
* @var string
*/
protected $accessToken = null;
/**
* Indicates if the CURL based @ syntax for file uploads is enabled.
*
* @var boolean
*/
protected $fileUploadSupport = false;
/**
* Indicates if we trust HTTP_X_FORWARDED_* headers.
*
* @var boolean
*/
protected $trustForwarded = false;
/**
* Initialize a Facebook Application.
*
* The configuration:
* - appId: the application ID
* - secret: the application secret
* - fileUpload: (optional) boolean indicating if file uploads are enabled
*
* @param array $config The application configuration
*/
public function __construct($config) {
$this->setAppId($config['appId']);
$this->setAppSecret($config['secret']);
if (isset($config['fileUpload'])) {
$this->setFileUploadSupport($config['fileUpload']);
}
if (isset($config['trustForwarded']) && $config['trustForwarded']) {
$this->trustForwarded = true;
}
$state = $this->getPersistentData('state');
if (!empty($state)) {
$this->state = $state;
}
}
/**
* Set the Application ID.
*
* @param string $appId The Application ID
* @return BaseFacebook
*/
public function setAppId($appId) {
$this->appId = $appId;
return $this;
}
/**
* Get the Application ID.
*
* @return string the Application ID
*/
public function getAppId() {
return $this->appId;
}
/**
* Set the App Secret.
*
* @param string $apiSecret The App Secret
* @return BaseFacebook
* @deprecated
*/
public function setApiSecret($apiSecret) {
$this->setAppSecret($apiSecret);
return $this;
}
/**
* Set the App Secret.
*
* @param string $appSecret The App Secret
* @return BaseFacebook
*/
public function setAppSecret($appSecret) {
$this->appSecret = $appSecret;
return $this;
}
/**
* Get the App Secret.
*
* @return string the App Secret
* @deprecated
*/
public function getApiSecret() {
return $this->getAppSecret();
}
/**
* Get the App Secret.
*
* @return string the App Secret
*/
public function getAppSecret() {
return $this->appSecret;
}
/**
* Set the file upload support status.
*
* @param boolean $fileUploadSupport The file upload support status.
* @return BaseFacebook
*/
public function setFileUploadSupport($fileUploadSupport) {
$this->fileUploadSupport = $fileUploadSupport;
return $this;
}
/**
* Get the file upload support status.
*
* @return boolean true if and only if the server supports file upload.
*/
public function getFileUploadSupport() {
return $this->fileUploadSupport;
}
/**
* DEPRECATED! Please use getFileUploadSupport instead.
*
* Get the file upload support status.
*
* @return boolean true if and only if the server supports file upload.
*/
public function useFileUploadSupport() {
return $this->getFileUploadSupport();
}
/**
* Sets the access token for api calls. Use this if you get
* your access token by other means and just want the SDK
* to use it.
*
* @param string $access_token an access token.
* @return BaseFacebook
*/
public function setAccessToken($access_token) {
$this->accessToken = $access_token;
return $this;
}
/**
* Extend an access token, while removing the short-lived token that might
* have been generated via client-side flow. Thanks to http://bit.ly/b0Pt0H
* for the workaround.
*/
public function setExtendedAccessToken() {
try {
// need to circumvent json_decode by calling _oauthRequest
// directly, since response isn't JSON format.
$access_token_response = $this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $this->getAccessToken(),
)
);
}
catch (FacebookApiException $e) {
// most likely that user very recently revoked authorization.
// In any event, we don't have an access token, so say so.
return false;
}
if (empty($access_token_response)) {
return false;
}
$response_params = array();
parse_str($access_token_response, $response_params);
if (!isset($response_params['access_token'])) {
return false;
}
$this->destroySession();
$this->setPersistentData(
'access_token', $response_params['access_token']
);
}
/**
* Determines the access token that should be used for API calls.
* The first time this is called, $this->accessToken is set equal
* to either a valid user access token, or it's set to the application
* access token if a valid user access token wasn't available. Subsequent
* calls return whatever the first call returned.
*
* @return string The access token
*/
public function getAccessToken() {
if ($this->accessToken !== null) {
// we've done this already and cached it. Just return.
return $this->accessToken;
}
// first establish access token to be the application
// access token, in case we navigate to the /oauth/access_token
// endpoint, where SOME access token is required.
$this->setAccessToken($this->getApplicationAccessToken());
$user_access_token = $this->getUserAccessToken();
if ($user_access_token) {
$this->setAccessToken($user_access_token);
}
return $this->accessToken;
}
/**
* Determines and returns the user access token, first using
* the signed request if present, and then falling back on
* the authorization code if present. The intent is to
* return a valid user access token, or false if one is determined
* to not be available.
*
* @return string A valid user access token, or false if one
* could not be determined.
*/
protected function getUserAccessToken() {
// first, consider a signed request if it's supplied.
// if there is a signed request, then it alone determines
// the access token.
$signed_request = $this->getSignedRequest();
if ($signed_request) {
// apps.facebook.com hands the access_token in the signed_request
if (array_key_exists('oauth_token', $signed_request)) {
$access_token = $signed_request['oauth_token'];
$this->setPersistentData('access_token', $access_token);
return $access_token;
}
// the JS SDK puts a code in with the redirect_uri of ''
if (array_key_exists('code', $signed_request)) {
$code = $signed_request['code'];
$access_token = $this->getAccessTokenFromCode($code, '');
if ($access_token) {
$this->setPersistentData('code', $code);
$this->setPersistentData('access_token', $access_token);
return $access_token;
}
}
// signed request states there's no access token, so anything
// stored should be cleared.
$this->clearAllPersistentData();
return false; // respect the signed request's data, even
// if there's an authorization code or something else
}
$code = $this->getCode();
if ($code && $code != $this->getPersistentData('code')) {
$access_token = $this->getAccessTokenFromCode($code);
if ($access_token) {
$this->setPersistentData('code', $code);
$this->setPersistentData('access_token', $access_token);
return $access_token;
}
// code was bogus, so everything based on it should be invalidated.
$this->clearAllPersistentData();
return false;
}
// as a fallback, just return whatever is in the persistent
// store, knowing nothing explicit (signed request, authorization
// code, etc.) was present to shadow it (or we saw a code in $_REQUEST,
// but it's the same as what's in the persistent store)
return $this->getPersistentData('access_token');
}
/**
* Retrieve the signed request, either from a request parameter or,
* if not present, from a cookie.
*
* @return string the signed request, if available, or null otherwise.
*/
public function getSignedRequest() {
if (!$this->signedRequest) {
if (isset($_REQUEST['signed_request'])) {
$this->signedRequest = $this->parseSignedRequest(
$_REQUEST['signed_request']);
} else if (isset($_COOKIE[$this->getSignedRequestCookieName()])) {
$this->signedRequest = $this->parseSignedRequest(
$_COOKIE[$this->getSignedRequestCookieName()]);
}
}
return $this->signedRequest;
}
/**
* Get the UID of the connected user, or 0
* if the Facebook user is not connected.
*
* @return string the UID if available.
*/
public function getUser() {
if ($this->user !== null) {
// we've already determined this and cached the value.
return $this->user;
}
return $this->user = $this->getUserFromAvailableData();
}
/**
* Determines the connected user by first examining any signed
* requests, then considering an authorization code, and then
* falling back to any persistent store storing the user.
*
* @return integer The id of the connected Facebook user,
* or 0 if no such user exists.
*/
protected function getUserFromAvailableData() {
// if a signed request is supplied, then it solely determines
// who the user is.
$signed_request = $this->getSignedRequest();
if ($signed_request) {
if (array_key_exists('user_id', $signed_request)) {
$user = $signed_request['user_id'];
$this->setPersistentData('user_id', $signed_request['user_id']);
return $user;
}
// if the signed request didn't present a user id, then invalidate
// all entries in any persistent store.
$this->clearAllPersistentData();
return 0;
}
$user = $this->getPersistentData('user_id', $default = 0);
$persisted_access_token = $this->getPersistentData('access_token');
// use access_token to fetch user id if we have a user access_token, or if
// the cached access token has changed.
$access_token = $this->getAccessToken();
if ($access_token &&
$access_token != $this->getApplicationAccessToken() &&
!($user && $persisted_access_token == $access_token)) {
$user = $this->getUserFromAccessToken();
if ($user) {
$this->setPersistentData('user_id', $user);
} else {
$this->clearAllPersistentData();
}
}
return $user;
}
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*
* @param array $params Provide custom parameters
* @return string The URL for the login flow
*/
public function getLoginUrl($params=array()) {
$this->establishCSRFTokenState();
$currentUrl = $this->getCurrentUrl();
// if 'scope' is passed as an array, convert to comma separated list
$scopeParams = isset($params['scope']) ? $params['scope'] : null;
if ($scopeParams && is_array($scopeParams)) {
$params['scope'] = implode(',', $scopeParams);
}
return $this->getUrl(
'www',
'dialog/oauth',
array_merge(array(
'client_id' => $this->getAppId(),
'redirect_uri' => $currentUrl, // possibly overwritten
'state' => $this->state),
$params));
}
/**
* Get a Logout URL suitable for use with redirects.
*
* The parameters:
* - next: the url to go to after a successful logout
*
* @param array $params Provide custom parameters
* @return string The URL for the logout flow
*/
public function getLogoutUrl($params=array()) {
return $this->getUrl(
'www',
'logout.php',
array_merge(array(
'next' => $this->getCurrentUrl(),
'access_token' => $this->getUserAccessToken(),
), $params)
);
}
/**
* Get a login status URL to fetch the status from Facebook.
*
* The parameters:
* - ok_session: the URL to go to if a session is found
* - no_session: the URL to go to if the user is not connected
* - no_user: the URL to go to if the user is not signed into facebook
*
* @param array $params Provide custom parameters
* @return string The URL for the logout flow
*/
public function getLoginStatusUrl($params=array()) {
return $this->getUrl(
'www',
'extern/login_status.php',
array_merge(array(
'api_key' => $this->getAppId(),
'no_session' => $this->getCurrentUrl(),
'no_user' => $this->getCurrentUrl(),
'ok_session' => $this->getCurrentUrl(),
'session_version' => 3,
), $params)
);
}
/**
* Make an API call.
*
* @return mixed The decoded response
*/
public function api(/* polymorphic */) {
$args = func_get_args();
if (is_array($args[0])) {
return $this->_restserver($args[0]);
} else {
return call_user_func_array(array($this, '_graph'), $args);
}
}
/**
* Constructs and returns the name of the cookie that
* potentially houses the signed request for the app user.
* The cookie is not set by the BaseFacebook class, but
* it may be set by the JavaScript SDK.
*
* @return string the name of the cookie that would house
* the signed request value.
*/
protected function getSignedRequestCookieName() {
return 'fbsr_'.$this->getAppId();
}
/**
* Constructs and returns the name of the coookie that potentially contain
* metadata. The cookie is not set by the BaseFacebook class, but it may be
* set by the JavaScript SDK.
*
* @return string the name of the cookie that would house metadata.
*/
protected function getMetadataCookieName() {
return 'fbm_'.$this->getAppId();
}
/**
* Get the authorization code from the query parameters, if it exists,
* and otherwise return false to signal no authorization code was
* discoverable.
*
* @return mixed The authorization code, or false if the authorization
* code could not be determined.
*/
protected function getCode() {
if (isset($_REQUEST['code'])) {
if ($this->state !== null &&
isset($_REQUEST['state']) &&
$this->state === $_REQUEST['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $_REQUEST['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
/**
* Retrieves the UID with the understanding that
* $this->accessToken has already been set and is
* seemingly legitimate. It relies on Facebook's Graph API
* to retrieve user information and then extract
* the user ID.
*
* @return integer Returns the UID of the Facebook user, or 0
* if the Facebook user could not be determined.
*/
protected function getUserFromAccessToken() {
try {
$user_info = $this->api('/me');
return $user_info['id'];
} catch (FacebookApiException $e) {
return 0;
}
}
/**
* Returns the access token that should be used for logged out
* users when no authorization code is available.
*
* @return string The application access token, useful for gathering
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
/**
* Lays down a CSRF state token for this process.
*
* @return void
*/
protected function establishCSRFTokenState() {
if ($this->state === null) {
$this->state = md5(uniqid(mt_rand(), true));
$this->setPersistentData('state', $this->state);
}
}
/**
* Retrieves an access token for the given authorization code
* (previously generated from www.facebook.com on behalf of
* a specific user). The authorization code is sent to graph.facebook.com
* and a legitimate access token is generated provided the access token
* and the user for which it was generated all match, and the user is
* either logged in to Facebook or has granted an offline access permission.
*
* @param string $code An authorization code.
* @return mixed An access token exchanged for the authorization code, or
* false if an access token could not be generated.
*/
protected function getAccessTokenFromCode($code, $redirect_uri = null) {
if (empty($code)) {
return false;
}
if ($redirect_uri === null) {
$redirect_uri = $this->getCurrentUrl();
}
try {
// need to circumvent json_decode by calling _oauthRequest
// directly, since response isn't JSON format.
$access_token_response =
$this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array('client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'redirect_uri' => $redirect_uri,
'code' => $code));
} catch (FacebookApiException $e) {
// most likely that user very recently revoked authorization.
// In any event, we don't have an access token, so say so.
return false;
}
if (empty($access_token_response)) {
return false;
}
$response_params = array();
parse_str($access_token_response, $response_params);
if (!isset($response_params['access_token'])) {
return false;
}
return $response_params['access_token'];
}
/**
* Invoke the old restserver.php endpoint.
*
* @param array $params Method call object
*
* @return mixed The decoded response object
* @throws FacebookApiException
*/
protected function _restserver($params) {
// generic application level parameters
$params['api_key'] = $this->getAppId();
$params['format'] = 'json-strings';
$result = json_decode($this->_oauthRequest(
$this->getApiUrl($params['method']),
$params
), true);
// results are returned, errors are thrown
if (is_array($result) && isset($result['error_code'])) {
$this->throwAPIException($result);
// @codeCoverageIgnoreStart
}
// @codeCoverageIgnoreEnd
$method = strtolower($params['method']);
if ($method === 'auth.expiresession' ||
$method === 'auth.revokeauthorization') {
$this->destroySession();
}
return $result;
}
/**
* Return true if this is video post.
*
* @param string $path The path
* @param string $method The http method (default 'GET')
*
* @return boolean true if this is video post
*/
protected function isVideoPost($path, $method = 'GET') {
if ($method == 'POST' && preg_match("/^(\/)(.+)(\/)(videos)$/", $path)) {
return true;
}
return false;
}
/**
* Invoke the Graph API.
*
* @param string $path The path (required)
* @param string $method The http method (default 'GET')
* @param array $params The query/post data
*
* @return mixed The decoded response object
* @throws FacebookApiException
*/
protected function _graph($path, $method = 'GET', $params = array()) {
if (is_array($method) && empty($params)) {
$params = $method;
$method = 'GET';
}
$params['method'] = $method; // method override as we always do a POST
if ($this->isVideoPost($path, $method)) {
$domainKey = 'graph_video';
} else {
$domainKey = 'graph';
}
$result = json_decode($this->_oauthRequest(
$this->getUrl($domainKey, $path),
$params
), true);
// results are returned, errors are thrown
if (is_array($result) && isset($result['error'])) {
$this->throwAPIException($result);
// @codeCoverageIgnoreStart
}
// @codeCoverageIgnoreEnd
return $result;
}
/**
* Make a OAuth Request.
*
* @param string $url The path (required)
* @param array $params The query/post data
*
* @return string The decoded response object
* @throws FacebookApiException
*/
protected function _oauthRequest($url, $params) {
if (!isset($params['access_token'])) {
$params['access_token'] = $this->getAccessToken();
}
// json_encode all params values that are not strings
foreach ($params as $key => $value) {
if (!is_string($value)) {
$params[$key] = json_encode($value);
}
}
return $this->makeRequest($url, $params);
}
/**
* Makes an HTTP request. This method can be overridden by subclasses if
* developers want to do fancier things or use something other than curl to
* make the request.
*
* @param string $url The URL to make the request to
* @param array $params The parameters to use for the POST body
* @param CurlHandler $ch Initialized curl handle
*
* @return string The response text
*/
protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->getFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
self::errorLog('Invalid or no certificate authority found, '.
'using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
$result = curl_exec($ch);
}
// With dual stacked DNS responses, it's possible for a server to
// have IPv6 enabled but not have IPv6 connectivity. If this is
// the case, curl will try IPv4 first and if that fails, then it will
// fall back to IPv6 and the error EHOSTUNREACH is returned by the
// operating system.
if ($result === false && empty($opts[CURLOPT_IPRESOLVE])) {
$matches = array();
$regex = '/Failed to connect to ([^:].*): Network is unreachable/';
if (preg_match($regex, curl_error($ch), $matches)) {
if (strlen(@inet_pton($matches[1])) === 16) {
self::errorLog('Invalid IPv6 configuration on server, '.
'Please disable or get native IPv6 on your server.');
self::$CURL_OPTS[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$result = curl_exec($ch);
}
}
}
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
/**
* Parses a signed_request and validates the signature.
*
* @param string $signed_request A signed token
* @return array The payload inside it or null if the sig is wrong
*/
protected function parseSignedRequest($signed_request) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = self::base64UrlDecode($encoded_sig);
$data = json_decode(self::base64UrlDecode($payload), true);
if (strtoupper($data['algorithm']) !== self::SIGNED_REQUEST_ALGORITHM) {
self::errorLog(
'Unknown algorithm. Expected ' . self::SIGNED_REQUEST_ALGORITHM);
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload,
$this->getAppSecret(), $raw = true);
if ($sig !== $expected_sig) {
self::errorLog('Bad Signed JSON signature!');
return null;
}
return $data;
}
/**
* Makes a signed_request blob using the given data.
*
* @param array The data array.
* @return string The signed request.
*/
protected function makeSignedRequest($data) {
if (!is_array($data)) {
throw new InvalidArgumentException(
'makeSignedRequest expects an array. Got: ' . print_r($data, true));
}
$data['algorithm'] = self::SIGNED_REQUEST_ALGORITHM;
$data['issued_at'] = time();
$json = json_encode($data);
$b64 = self::base64UrlEncode($json);
$raw_sig = hash_hmac('sha256', $b64, $this->getAppSecret(), $raw = true);
$sig = self::base64UrlEncode($raw_sig);
return $sig.'.'.$b64;
}
/**
* Build the URL for api given parameters.
*
* @param $method String the method name.
* @return string The URL for the given parameters
*/
protected function getApiUrl($method) {
static $READ_ONLY_CALLS =
array('admin.getallocation' => 1,
'admin.getappproperties' => 1,
'admin.getbannedusers' => 1,
'admin.getlivestreamvialink' => 1,
'admin.getmetrics' => 1,
'admin.getrestrictioninfo' => 1,
'application.getpublicinfo' => 1,
'auth.getapppublickey' => 1,
'auth.getsession' => 1,
'auth.getsignedpublicsessiondata' => 1,
'comments.get' => 1,
'connect.getunconnectedfriendscount' => 1,
'dashboard.getactivity' => 1,
'dashboard.getcount' => 1,
'dashboard.getglobalnews' => 1,
'dashboard.getnews' => 1,
'dashboard.multigetcount' => 1,
'dashboard.multigetnews' => 1,
'data.getcookies' => 1,
'events.get' => 1,
'events.getmembers' => 1,
'fbml.getcustomtags' => 1,
'feed.getappfriendstories' => 1,
'feed.getregisteredtemplatebundlebyid' => 1,
'feed.getregisteredtemplatebundles' => 1,
'fql.multiquery' => 1,
'fql.query' => 1,
'friends.arefriends' => 1,
'friends.get' => 1,
'friends.getappusers' => 1,
'friends.getlists' => 1,
'friends.getmutualfriends' => 1,
'gifts.get' => 1,
'groups.get' => 1,
'groups.getmembers' => 1,
'intl.gettranslations' => 1,
'links.get' => 1,
'notes.get' => 1,
'notifications.get' => 1,
'pages.getinfo' => 1,
'pages.isadmin' => 1,
'pages.isappadded' => 1,
'pages.isfan' => 1,
'permissions.checkavailableapiaccess' => 1,
'permissions.checkgrantedapiaccess' => 1,
'photos.get' => 1,
'photos.getalbums' => 1,
'photos.gettags' => 1,
'profile.getinfo' => 1,
'profile.getinfooptions' => 1,
'stream.get' => 1,
'stream.getcomments' => 1,
'stream.getfilters' => 1,
'users.getinfo' => 1,
'users.getloggedinuser' => 1,
'users.getstandardinfo' => 1,
'users.hasapppermission' => 1,
'users.isappuser' => 1,
'users.isverified' => 1,
'video.getuploadlimits' => 1);
$name = 'api';
if (isset($READ_ONLY_CALLS[strtolower($method)])) {
$name = 'api_read';
} else if (strtolower($method) == 'video.upload') {
$name = 'api_video';
}
return self::getUrl($name, 'restserver.php');
}
/**
* Build the URL for given domain alias, path and parameters.
*
* @param $name string The name of the domain
* @param $path string Optional path (without a leading slash)
* @param $params array Optional query parameters
*
* @return string The URL for the given parameters
*/
protected function getUrl($name, $path='', $params=array()) {
$url = self::$DOMAIN_MAP[$name];
if ($path) {
if ($path[0] === '/') {
$path = substr($path, 1);
}
$url .= $path;
}
if ($params) {
$url .= '?' . http_build_query($params, null, '&');
}
return $url;
}
protected function getHttpHost() {
if ($this->trustForwarded && isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
return $_SERVER['HTTP_X_FORWARDED_HOST'];
}
return $_SERVER['HTTP_HOST'];
}
protected function getHttpProtocol() {
if ($this->trustForwarded && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
return 'https';
}
return 'http';
}
if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] == 1)) {
return 'https';
}
return 'http';
}
/**
* Get the base domain used for the cookie.
*/
protected function getBaseDomain() {
// The base domain is stored in the metadata cookie if not we fallback
// to the current hostname
$metadata = $this->getMetadataCookie();
if (array_key_exists('base_domain', $metadata) &&
!empty($metadata['base_domain'])) {
return trim($metadata['base_domain'], '.');
}
return $this->getHttpHost();
}
/**
/**
* Returns the Current URL, stripping it of known FB parameters that should
* not persist.
*
* @return string The current URL
*/
protected function getCurrentUrl() {
$protocol = $this->getHttpProtocol() . '://';
$host = $this->getHttpHost();
$currentUrl = $protocol.$host.$_SERVER['REQUEST_URI'];
$parts = parse_url($currentUrl);
$query = '';
if (!empty($parts['query'])) {
// drop known fb params
$params = explode('&', $parts['query']);
$retained_params = array();
foreach ($params as $param) {
if ($this->shouldRetainParam($param)) {
$retained_params[] = $param;
}
}
if (!empty($retained_params)) {
$query = '?'.implode($retained_params, '&');
}
}
// use port if non default
$port =
isset($parts['port']) &&
(($protocol === 'http://' && $parts['port'] !== 80) ||
($protocol === 'https://' && $parts['port'] !== 443))
? ':' . $parts['port'] : '';
// rebuild
return $protocol . $parts['host'] . $port . $parts['path'] . $query;
}
/**
* Returns true if and only if the key or key/value pair should
* be retained as part of the query string. This amounts to
* a brute-force search of the very small list of Facebook-specific
* params that should be stripped out.
*
* @param string $param A key or key/value pair within a URL's query (e.g.
* 'foo=a', 'foo=', or 'foo'.
*
* @return boolean
*/
protected function shouldRetainParam($param) {
foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
if (strpos($param, $drop_query_param.'=') === 0) {
return false;
}
}
return true;
}
/**
* Analyzes the supplied result to see if it was thrown
* because the access token is no longer valid. If that is
* the case, then we destroy the session.
*
* @param $result array A record storing the error message returned
* by a failed API call.
*/
protected function throwAPIException($result) {
$e = new FacebookApiException($result);
switch ($e->getType()) {
// OAuth 2.0 Draft 00 style
case 'OAuthException':
// OAuth 2.0 Draft 10 style
case 'invalid_token':
// REST server errors are just Exceptions
case 'Exception':
$message = $e->getMessage();
if ((strpos($message, 'Error validating access token') !== false) ||
(strpos($message, 'Invalid OAuth access token') !== false) ||
(strpos($message, 'An active access token must be used') !== false)
) {
$this->destroySession();
}
break;
}
throw $e;
}
/**
* Prints to the error log if you aren't in command line mode.
*
* @param string $msg Log message
*/
protected static function errorLog($msg) {
// disable error log if we are running in a CLI environment
// @codeCoverageIgnoreStart
if (php_sapi_name() != 'cli') {
error_log($msg);
}
// uncomment this if you want to see the errors on the page
// print 'error_log: '.$msg."\n";
// @codeCoverageIgnoreEnd
}
/**
* Base64 encoding that doesn't need to be urlencode()ed.
* Exactly the same as base64_encode except it uses
* - instead of +
* _ instead of /
* No padded =
*
* @param string $input base64UrlEncoded string
* @return string
*/
protected static function base64UrlDecode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
/**
* Base64 encoding that doesn't need to be urlencode()ed.
* Exactly the same as base64_encode except it uses
* - instead of +
* _ instead of /
*
* @param string $input string
* @return string base64Url encoded string
*/
protected static function base64UrlEncode($input) {
$str = strtr(base64_encode($input), '+/', '-_');
$str = str_replace('=', '', $str);
return $str;
}
/**
* Destroy the current session
*/
public function destroySession() {
$this->accessToken = null;
$this->signedRequest = null;
$this->user = null;
$this->clearAllPersistentData();
// Javascript sets a cookie that will be used in getSignedRequest that we
// need to clear if we can
$cookie_name = $this->getSignedRequestCookieName();
if (array_key_exists($cookie_name, $_COOKIE)) {
unset($_COOKIE[$cookie_name]);
if (!headers_sent()) {
$base_domain = $this->getBaseDomain();
setcookie($cookie_name, '', 1, '/', '.'.$base_domain);
} else {
// @codeCoverageIgnoreStart
self::errorLog(
'There exists a cookie that we wanted to clear that we couldn\'t '.
'clear because headers was already sent. Make sure to do the first '.
'API call before outputing anything.'
);
// @codeCoverageIgnoreEnd
}
}
}
/**
* Parses the metadata cookie that our Javascript API set
*
* @return an array mapping key to value
*/
protected function getMetadataCookie() {
$cookie_name = $this->getMetadataCookieName();
if (!array_key_exists($cookie_name, $_COOKIE)) {
return array();
}
// The cookie value can be wrapped in "-characters so remove them
$cookie_value = trim($_COOKIE[$cookie_name], '"');
if (empty($cookie_value)) {
return array();
}
$parts = explode('&', $cookie_value);
$metadata = array();
foreach ($parts as $part) {
$pair = explode('=', $part, 2);
if (!empty($pair[0])) {
$metadata[urldecode($pair[0])] =
(count($pair) > 1) ? urldecode($pair[1]) : '';
}
}
return $metadata;
}
protected static function isAllowedDomain($big, $small) {
if ($big === $small) {
return true;
}
return self::endsWith($big, '.'.$small);
}
protected static function endsWith($big, $small) {
$len = strlen($small);
if ($len === 0) {
return true;
}
return substr($big, -$len) === $small;
}
/**
* Each of the following four methods should be overridden in
* a concrete subclass, as they are in the provided Facebook class.
* The Facebook class uses PHP sessions to provide a primitive
* persistent store, but another subclass--one that you implement--
* might use a database, memcache, or an in-memory cache.
*
* @see Facebook
*/
/**
* Stores the given ($key, $value) pair, so that future calls to
* getPersistentData($key) return $value. This call may be in another request.
*
* @param string $key
* @param array $value
*
* @return void
*/
abstract protected function setPersistentData($key, $value);
/**
* Get the data for $key, persisted by BaseFacebook::setPersistentData()
*
* @param string $key The key of the data to retrieve
* @param boolean $default The default value to return if $key is not found
*
* @return mixed
*/
abstract protected function getPersistentData($key, $default = false);
/**
* Clear the data with $key from the persistent storage
*
* @param string $key
* @return void
*/
abstract protected function clearPersistentData($key);
/**
* Clear all data from the persistent storage
*
* @return void
*/
abstract protected function clearAllPersistentData();
}
/**
* Copyright 2011 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/**
* Extends the BaseFacebook class with the intent of using
* PHP sessions to store user ids and access tokens.
*/
class Facebook extends BaseFacebook
{
const FBSS_COOKIE_NAME = 'fbss';
// We can set this to a high number because the main session
// expiration will trump this.
const FBSS_COOKIE_EXPIRE = 31556926; // 1 year
// Stores the shared session ID if one is set.
protected $sharedSessionID;
/**
* Identical to the parent constructor, except that
* we start a PHP session to store the user ID and
* access token if during the course of execution
* we discover them.
*
* @param Array $config the application configuration. Additionally
* accepts "sharedSession" as a boolean to turn on a secondary
* cookie for environments with a shared session (that is, your app
* shares the domain with other apps).
* @see BaseFacebook::__construct in facebook.php
*/
public function __construct($config) {
if (!session_id()) {
session_start();
}
parent::__construct($config);
if (!empty($config['sharedSession'])) {
$this->initSharedSession();
}
}
protected static $kSupportedKeys =
array('state', 'code', 'access_token', 'user_id');
protected function initSharedSession() {
$cookie_name = $this->getSharedSessionCookieName();
if (isset($_COOKIE[$cookie_name])) {
$data = $this->parseSignedRequest($_COOKIE[$cookie_name]);
if ($data && !empty($data['domain']) &&
self::isAllowedDomain($this->getHttpHost(), $data['domain'])) {
// good case
$this->sharedSessionID = $data['id'];
return;
}
// ignoring potentially unreachable data
}
// evil/corrupt/missing case
$base_domain = $this->getBaseDomain();
$this->sharedSessionID = md5(uniqid(mt_rand(), true));
$cookie_value = $this->makeSignedRequest(
array(
'domain' => $base_domain,
'id' => $this->sharedSessionID,
)
);
$_COOKIE[$cookie_name] = $cookie_value;
if (!headers_sent()) {
$expire = time() + self::FBSS_COOKIE_EXPIRE;
setcookie($cookie_name, $cookie_value, $expire, '/', '.'.$base_domain);
} else {
// @codeCoverageIgnoreStart
self::errorLog(
'Shared session ID cookie could not be set! You must ensure you '.
'create the Facebook instance before headers have been sent. This '.
'will cause authentication issues after the first request.'
);
// @codeCoverageIgnoreEnd
}
}
/**
* Provides the implementations of the inherited abstract
* methods. The implementation uses PHP sessions to maintain
* a store for authorization codes, user ids, CSRF states, and
* access tokens.
*/
protected function setPersistentData($key, $value) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to setPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
$_SESSION[$session_var_name] = $value;
}
protected function getPersistentData($key, $default = false) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to getPersistentData.');
return $default;
}
$session_var_name = $this->constructSessionVariableName($key);
return isset($_SESSION[$session_var_name]) ?
$_SESSION[$session_var_name] : $default;
}
protected function clearPersistentData($key) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to clearPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
unset($_SESSION[$session_var_name]);
}
protected function clearAllPersistentData() {
foreach (self::$kSupportedKeys as $key) {
$this->clearPersistentData($key);
}
if ($this->sharedSessionID) {
$this->deleteSharedSessionCookie();
}
}
protected function deleteSharedSessionCookie() {
$cookie_name = $this->getSharedSessionCookieName();
unset($_COOKIE[$cookie_name]);
$base_domain = $this->getBaseDomain();
setcookie($cookie_name, '', 1, '/', '.'.$base_domain);
}
protected function getSharedSessionCookieName() {
return self::FBSS_COOKIE_NAME . '_' . $this->getAppId();
}
protected function constructSessionVariableName($key) {
$parts = array('fb', $this->getAppId(), $key);
if ($this->sharedSessionID) {
array_unshift($parts, $this->sharedSessionID);
}
return implode('_', $parts);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment