<?php
class Facebook{

    /**
     *
     * @author Shameer
     */
	
	private $_appID;
	private $_secret;
	public 	$cookie;
	public 	$accessToken;
	public 	$loggedIn =	false;
	public 	$userData;
	public 	$options;
    public  $redirectUrl = '';

    /**
     *  Constructor, sets the application ID, secret key and if already logged into facebook
     *  Sets logged in as true
     * @param $appID    The application ID, see @link http://www.facebook.com/developers/
     *                  for more details
     * @param $secret   Secret key of your appliation
     * @param $options  Additional options that you can pass to the class
     */
	public function __construct( $appID , $secret, &$options=null )
	{
		$this->_appID	=	$appID;
		$this->_secret	=	$secret;
		$this->options	=	$options;
		
		if(isset($options['redirect_url']))
            $this->redirectUrl  =   $options['redirect_url'];
		
		$cookie			=	$this->checkCookie();		
		$code	=	isset($cookie['code'])?$cookie['code']:'';		

		if($code) 
		{
			$this->loggedIn	= true;
			$this->setToken( $code );
		 
		}
		else 
		{
			$this->loggedIn	= false;
		}
        
	}

    /**
     *
     * @param bool $echo   Whether to echo the output or not
     * @return string      Facebook login or logout, depending on whether already
     *                     logged in or not
     */
	public function showButton( $echo = false )
	{
		if( $this->loggedIn ){
			$button = '<div id="fb-root"></div><fb:login-button scope="email,user_birthday" onlogin="window.location.reload(true);" autologoutlink="true">Logout</fb:login-button>';
		}
		else {
			$button = '<div id="fb-root"></div><fb:login-button scope="email,user_birthday" autologoutlink="true"></fb:login-button>';
		}
		if( $echo )
			echo $button;
		return $button;
	}

    /**
     *
     * @return array function to check the facebook cookie
     */
	public function checkCookie()
	{ 
		$args = array();
		if(isset($_COOKIE['fbsr_' . $this->_appID]))
		{
			$args	=	$this->parse_signed_request($_COOKIE['fbsr_' . $this->_appID], $this->_secret);		 
		}
		$this->cookie	=	$args;
		return $args;
	}
	function parse_signed_request($signed_request, $secret) 
	{
  		list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

		  // decode the data
		  $sig = $this->base64_url_decode($encoded_sig);
		  
		  $data = json_decode($this->base64_url_decode($payload), true);

		  // check sig
		  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
		  
		  if ($sig !== $expected_sig) {
			  
			error_log('Bad Signed JSON signature!');
			
			return null;
		  }

  		return $data;
	}

	function base64_url_decode($input) 
	{
			return base64_decode(strtr($input, '-_', '+/'));
	}


    /**
     *
     * @param mixed $token  Function to set the access token
     */
	public function setToken( $code )
	{
		$token_url = "https://graph.facebook.com/oauth/access_token?"
			   . "client_id=" .$this->_appID . "&redirect_uri=" . urlencode($this->redirectUrl)
			   . "&client_secret=" . $this->_secret . "&code=" . $code;
               
                 $response = @file_get_contents($token_url);
                 //$params = null;
		 //parse_str($response, $params);
                 //$this->accessToken	=	 $params['access_token'];
		 $obj = json_decode($response);
                 $this->accessToken  = $obj->{'access_token'};
                
	}

    /**
     *
     * @return mixed     Returns access token
     */
	public function getToken()
	{
		return $this->accessToken;
	}


	public function userData()
	{
	 
		if($this->accessToken){
			$userData = json_decode( @file_get_contents('https://graph.facebook.com/me?fields=id,first_name,last_name,email,gender,locale,picture&access_token='.$this->accessToken) );
			$this->userData	=	$this->objectToArray($userData);
		}
		return $this->userData;
	}

    /**
     * Function to convert object properties to  array
     * @param $object
     * @return array Containing object properties and its values
     */
	function objectToArray( $object )
    {
        if( !is_object( $object ) && !is_array( $object ) ){
            return $object;
        }
        if( is_object( $object ) ){
            $object = get_object_vars( $object );

        }
        return array_map( array($this,'objectToArray'), $object );
    }

    /**
     *
     * @param <type> $echo
     * @return string Facebook init script
     */
    public function fbInit( $echo = false )
    {
    	$script = '<script src="http://connect.facebook.net/en_US/all.js"></script>
					<script>
					FB.init({appId: '. $this->_appID .', status: true,
					cookie: true, xfbml: true,oauth      : true,
					channelUrl :  "/public/api/facebook/xd_receiver.htm"});
					FB.Event.subscribe(\'auth.login\', function(response) {';
        if($this->redirectUrl!=''){
            $script .= 'window.location.href="'.$this->redirectUrl.'"';
        }
        else {
            $script .= 	'window.location.reload();';
        }
		$script .= 	'});
            FB.Event.subscribe(\'auth.logout\', function(response) {
                 // do something with response
                 window.location.reload();
             });
					</script>';
		if($echo)
			echo $script;
		return $script;
    }
    public function unsetCookie()
    {
        if(isset ($_COOKIE['fbsr_' . $this->_appID] ) ){
            setcookie('fbsr_' . $this->_appID, '', time()-3600);
        }
    }
   
}