Advertisement
plas71k

bsfcbk => decoded

Feb 27th, 2013
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 20.64 KB | None | 0 0
  1. <?php
  2. /*
  3. * @ Pirate-Sky Crew :: PHP Decoder v2
  4. * @ Author: pLa$71k
  5. * @ Web: http://pirate-sky.com
  6. * @ Pirate-Sky Crew © 2008 - 2013
  7. */
  8.  
  9. if (!function_exists('curl_init')) {
  10.     throw new Exception('Facebook needs the CURL PHP extension.');
  11. }
  12. if (!function_exists('json_decode')) {
  13.     throw new Exception('Facebook needs the JSON PHP extension.');
  14. }
  15. class FacebookApiException extends Exception
  16. {
  17.     protected $result;
  18.     public function __construct($result)
  19.     {
  20.         $this->result = $result;
  21.         $code         = isset($result['error_code']) ? $result['error_code'] : 0;
  22.         if (isset($result['error_description'])) {
  23.             $msg = $result['error_description'];
  24.         } else if (isset($result['error']) && is_array($result['error'])) {
  25.             $msg = $result['error']['message'];
  26.         } else if (isset($result['error_msg'])) {
  27.             $msg = $result['error_msg'];
  28.         } else {
  29.             $msg = 'Unknown Error. Check getResult()';
  30.         }
  31.         parent::__construct($msg, $code);
  32.     }
  33.     public function getResult()
  34.     {
  35.         return $this->result;
  36.     }
  37.     public function getType()
  38.     {
  39.         if (isset($this->result['error'])) {
  40.             $error = $this->result['error'];
  41.             if (is_string($error)) {
  42.                 return $error;
  43.             } else if (is_array($error)) {
  44.                 if (isset($error['type'])) {
  45.                     return $error['type'];
  46.                 }
  47.             }
  48.         }
  49.         return 'Exception';
  50.     }
  51.     public function __toString()
  52.     {
  53.         $str = $this->getType() . ': ';
  54.         if ($this->code != 0) {
  55.             $str .= $this->code . ': ';
  56.         }
  57.         return $str . $this->message;
  58.     }
  59. }
  60. abstract class BaseFacebook
  61. {
  62.     const VERSION = '3.1.1';
  63.     public static $CURL_OPTS = array(CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_USERAGENT => 'facebook-php-3.1');
  64.     protected static $DROP_QUERY_PARAMS = array('code', 'state', 'signed_request');
  65.     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/', 'www' => 'https://www.facebook.com/');
  66.     protected $appId;
  67.     protected $apiSecret;
  68.     protected $user;
  69.     protected $signedRequest;
  70.     protected $state;
  71.     protected $accessToken = null;
  72.     protected $fileUploadSupport = false;
  73.     public function __construct($config)
  74.     {
  75.         $this->setAppId($config['appId']);
  76.         $this->setApiSecret($config['secret']);
  77.         if (isset($config['fileUpload'])) {
  78.             $this->setFileUploadSupport($config['fileUpload']);
  79.         }
  80.         $state = $this->getPersistentData('state');
  81.         if (!empty($state)) {
  82.             $this->state = $this->getPersistentData('state');
  83.         }
  84.     }
  85.     public function setAppId($appId)
  86.     {
  87.         $this->appId = $appId;
  88.         return $this;
  89.     }
  90.     public function getAppId()
  91.     {
  92.         return $this->appId;
  93.     }
  94.     public function setApiSecret($apiSecret)
  95.     {
  96.         $this->apiSecret = $apiSecret;
  97.         return $this;
  98.     }
  99.     public function getApiSecret()
  100.     {
  101.         return $this->apiSecret;
  102.     }
  103.     public function setFileUploadSupport($fileUploadSupport)
  104.     {
  105.         $this->fileUploadSupport = $fileUploadSupport;
  106.         return $this;
  107.     }
  108.     public function useFileUploadSupport()
  109.     {
  110.         return $this->fileUploadSupport;
  111.     }
  112.     public function setAccessToken($access_token)
  113.     {
  114.         $this->accessToken = $access_token;
  115.         return $this;
  116.     }
  117.     public function getAccessToken()
  118.     {
  119.         if ($this->accessToken !== null) {
  120.             return $this->accessToken;
  121.         }
  122.         $this->setAccessToken($this->getApplicationAccessToken());
  123.         $user_access_token = $this->getUserAccessToken();
  124.         if ($user_access_token) {
  125.             $this->setAccessToken($user_access_token);
  126.         }
  127.         return $this->accessToken;
  128.     }
  129.     protected function getUserAccessToken()
  130.     {
  131.         $signed_request = $this->getSignedRequest();
  132.         if ($signed_request) {
  133.             if (array_key_exists('oauth_token', $signed_request)) {
  134.                 $access_token = $signed_request['oauth_token'];
  135.                 $this->setPersistentData('access_token', $access_token);
  136.                 return $access_token;
  137.             }
  138.             if (array_key_exists('code', $signed_request)) {
  139.                 $code         = $signed_request['code'];
  140.                 $access_token = $this->getAccessTokenFromCode($code, '');
  141.                 if ($access_token) {
  142.                     $this->setPersistentData('code', $code);
  143.                     $this->setPersistentData('access_token', $access_token);
  144.                     return $access_token;
  145.                 }
  146.             }
  147.             $this->clearAllPersistentData();
  148.             return false;
  149.         }
  150.         $code = $this->getCode();
  151.         if ($code && $code != $this->getPersistentData('code')) {
  152.             $access_token = $this->getAccessTokenFromCode($code);
  153.             if ($access_token) {
  154.                 $this->setPersistentData('code', $code);
  155.                 $this->setPersistentData('access_token', $access_token);
  156.                 return $access_token;
  157.             }
  158.             $this->clearAllPersistentData();
  159.             return false;
  160.         }
  161.         return $this->getPersistentData('access_token');
  162.     }
  163.     public function getSignedRequest()
  164.     {
  165.         if (!$this->signedRequest) {
  166.             if (isset($_REQUEST['signed_request'])) {
  167.                 $this->signedRequest = $this->parseSignedRequest($_REQUEST['signed_request']);
  168.             } else if (isset($_COOKIE[$this->getSignedRequestCookieName()])) {
  169.                 $this->signedRequest = $this->parseSignedRequest($_COOKIE[$this->getSignedRequestCookieName()]);
  170.             }
  171.         }
  172.         return $this->signedRequest;
  173.     }
  174.     public function getUser()
  175.     {
  176.         if ($this->user !== null) {
  177.             return $this->user;
  178.         }
  179.         return $this->user = $this->getUserFromAvailableData();
  180.     }
  181.     protected function getUserFromAvailableData()
  182.     {
  183.         $signed_request = $this->getSignedRequest();
  184.         if ($signed_request) {
  185.             if (array_key_exists('user_id', $signed_request)) {
  186.                 $user = $signed_request['user_id'];
  187.                 $this->setPersistentData('user_id', $signed_request['user_id']);
  188.                 return $user;
  189.             }
  190.             $this->clearAllPersistentData();
  191.             return 0;
  192.         }
  193.         $user                   = $this->getPersistentData('user_id', $default = 0);
  194.         $persisted_access_token = $this->getPersistentData('access_token');
  195.         $access_token           = $this->getAccessToken();
  196.         if ($access_token && $access_token != $this->getApplicationAccessToken() && !($user && $persisted_access_token == $access_token)) {
  197.             $user = $this->getUserFromAccessToken();
  198.             if ($user) {
  199.                 $this->setPersistentData('user_id', $user);
  200.             } else {
  201.                 $this->clearAllPersistentData();
  202.             }
  203.         }
  204.         return $user;
  205.     }
  206.     public function getLoginUrl($params = array())
  207.     {
  208.         $this->establishCSRFTokenState();
  209.         $currentUrl  = $this->getCurrentUrl();
  210.         $scopeParams = isset($params['scope']) ? $params['scope'] : null;
  211.         if ($scopeParams && is_array($scopeParams)) {
  212.             $params['scope'] = implode(',', $scopeParams);
  213.         }
  214.         return $this->getUrl('www', 'dialog/oauth', array_merge(array(
  215.             'client_id' => $this->getAppId(),
  216.             'redirect_uri' => $currentUrl,
  217.             'state' => $this->state
  218.         ), $params));
  219.     }
  220.     public function getLogoutUrl($params = array())
  221.     {
  222.         return $this->getUrl('www', 'logout.php', array_merge(array(
  223.             'next' => $this->getCurrentUrl(),
  224.             'access_token' => $this->getAccessToken()
  225.         ), $params));
  226.     }
  227.     public function getLoginStatusUrl($params = array())
  228.     {
  229.         return $this->getUrl('www', 'extern/login_status.php', array_merge(array(
  230.             'api_key' => $this->getAppId(),
  231.             'no_session' => $this->getCurrentUrl(),
  232.             'no_user' => $this->getCurrentUrl(),
  233.             'ok_session' => $this->getCurrentUrl(),
  234.             'session_version' => 3
  235.         ), $params));
  236.     }
  237.     public function api()
  238.     {
  239.         $args = func_get_args();
  240.         if (is_array($args[0])) {
  241.             return $this->_restserver($args[0]);
  242.         } else {
  243.             return call_user_func_array(array(
  244.                 $this,
  245.                 '_graph'
  246.             ), $args);
  247.         }
  248.     }
  249.     protected function getSignedRequestCookieName()
  250.     {
  251.         return 'fbsr_' . $this->getAppId();
  252.     }
  253.     protected function getCode()
  254.     {
  255.         if (isset($_REQUEST['code'])) {
  256.             if ($this->state !== null && isset($_REQUEST['state']) && $this->state === $_REQUEST['state']) {
  257.                 $this->state = null;
  258.                 $this->clearPersistentData('state');
  259.                 return $_REQUEST['code'];
  260.             } else {
  261.                 self::errorLog('CSRF state token does not match one provided.');
  262.                 return false;
  263.             }
  264.         }
  265.         return false;
  266.     }
  267.     protected function getUserFromAccessToken()
  268.     {
  269.         try {
  270.             $user_info = $this->api('/me');
  271.             return $user_info['id'];
  272.         }
  273.         catch (FacebookApiException $e) {
  274.             return 0;
  275.         }
  276.     }
  277.     protected function getApplicationAccessToken()
  278.     {
  279.         return $this->appId . '|' . $this->apiSecret;
  280.     }
  281.     protected function establishCSRFTokenState()
  282.     {
  283.         if ($this->state === null) {
  284.             $this->state = md5(uniqid(mt_rand(), true));
  285.             $this->setPersistentData('state', $this->state);
  286.         }
  287.     }
  288.     protected function getAccessTokenFromCode($code, $redirect_uri = null)
  289.     {
  290.         if (empty($code)) {
  291.             return false;
  292.         }
  293.         if ($redirect_uri === null) {
  294.             $redirect_uri = $this->getCurrentUrl();
  295.         }
  296.         try {
  297.             $access_token_response = $this->_oauthRequest($this->getUrl('graph', '/oauth/access_token'), $params = array(
  298.                 'client_id' => $this->getAppId(),
  299.                 'client_secret' => $this->getApiSecret(),
  300.                 'redirect_uri' => $redirect_uri,
  301.                 'code' => $code
  302.             ));
  303.         }
  304.         catch (FacebookApiException $e) {
  305.             return false;
  306.         }
  307.         if (empty($access_token_response)) {
  308.             return false;
  309.         }
  310.         $response_params = array();
  311.         parse_str($access_token_response, $response_params);
  312.         if (!isset($response_params['access_token'])) {
  313.             return false;
  314.         }
  315.         return $response_params['access_token'];
  316.     }
  317.     protected function _restserver($params)
  318.     {
  319.         $params['api_key'] = $this->getAppId();
  320.         $params['format']  = 'json-strings';
  321.         $result            = json_decode($this->_oauthRequest($this->getApiUrl($params['method']), $params), true);
  322.         if (is_array($result) && isset($result['error_code'])) {
  323.             $this->throwAPIException($result);
  324.         }
  325.         if ($params['method'] === 'auth.expireSession' || $params['method'] === 'auth.revokeAuthorization') {
  326.             $this->destroySession();
  327.         }
  328.         return $result;
  329.     }
  330.     protected function _graph($path, $method = 'GET', $params = array())
  331.     {
  332.         if (is_array($method) && empty($params)) {
  333.             $params = $method;
  334.             $method = 'GET';
  335.         }
  336.         $params['method'] = $method;
  337.         $result           = json_decode($this->_oauthRequest($this->getUrl('graph', $path), $params), true);
  338.         if (is_array($result) && isset($result['error'])) {
  339.             $this->throwAPIException($result);
  340.         }
  341.         return $result;
  342.     }
  343.     protected function _oauthRequest($url, $params)
  344.     {
  345.         if (!isset($params['access_token'])) {
  346.             $params['access_token'] = $this->getAccessToken();
  347.         }
  348.         foreach ($params as $key => $value) {
  349.             if (!is_string($value)) {
  350.                 $params[$key] = json_encode($value);
  351.             }
  352.         }
  353.         return $this->makeRequest($url, $params);
  354.     }
  355.     protected function makeRequest($url, $params, $ch = null)
  356.     {
  357.         if (!$ch) {
  358.             $ch = curl_init();
  359.         }
  360.         $opts = self::$CURL_OPTS;
  361.         if ($this->useFileUploadSupport()) {
  362.             $opts[CURLOPT_POSTFIELDS] = $params;
  363.         } else {
  364.             $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
  365.         }
  366.         $opts[CURLOPT_URL] = $url;
  367.         if (isset($opts[CURLOPT_HTTPHEADER])) {
  368.             $existing_headers         = $opts[CURLOPT_HTTPHEADER];
  369.             $existing_headers[]       = 'Expect:';
  370.             $opts[CURLOPT_HTTPHEADER] = $existing_headers;
  371.         } else {
  372.             $opts[CURLOPT_HTTPHEADER] = array(
  373.                 'Expect:'
  374.             );
  375.         }
  376.         curl_setopt_array($ch, $opts);
  377.         $result = curl_exec($ch);
  378.         if (curl_errno($ch) == 60) {
  379.             self::errorLog('Invalid or no certificate authority found, ' . 'using bundled information');
  380.             curl_setopt($ch, CURLOPT_CAINFO, dirname('1a4d7f76cb_copy.php') . '/fb_ca_chain_bundle.crt');
  381.             $result = curl_exec($ch);
  382.         }
  383.         if ($result === false) {
  384.             $e = new FacebookApiException(array(
  385.                 'error_code' => curl_errno($ch),
  386.                 'error' => array(
  387.                     'message' => curl_error($ch),
  388.                     'type' => 'CurlException'
  389.                 )
  390.             ));
  391.             curl_close($ch);
  392.             throw $e;
  393.         }
  394.         curl_close($ch);
  395.         return $result;
  396.     }
  397.     protected function parseSignedRequest($signed_request)
  398.     {
  399.         list($encoded_sig, $payload) = explode('.', $signed_request, 2);
  400.         $sig  = self::base64UrlDecode($encoded_sig);
  401.         $data = json_decode(self::base64UrlDecode($payload), true);
  402.         if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
  403.             self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
  404.             return null;
  405.         }
  406.         $expected_sig = hash_hmac('sha256', $payload, $this->getApiSecret(), $raw = true);
  407.         if ($sig !== $expected_sig) {
  408.             self::errorLog('Bad Signed JSON signature!');
  409.             return null;
  410.         }
  411.         return $data;
  412.     }
  413.     protected function getApiUrl($method)
  414.     {
  415.         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);
  416.         $name = 'api';
  417.         if (isset($READ_ONLY_CALLS[strtolower($method)])) {
  418.             $name = 'api_read';
  419.         } else if (strtolower($method) == 'video.upload') {
  420.             $name = 'api_video';
  421.         }
  422.         return self::getUrl($name, 'restserver.php');
  423.     }
  424.     protected function getUrl($name, $path = '', $params = array())
  425.     {
  426.         $url = self::$DOMAIN_MAP[$name];
  427.         if ($path) {
  428.             if ($path[0] === '/') {
  429.                 $path = substr($path, 1);
  430.             }
  431.             $url .= $path;
  432.         }
  433.         if ($params) {
  434.             $url .= '?' . http_build_query($params, null, '&');
  435.         }
  436.         return $url;
  437.     }
  438.     protected function getCurrentUrl()
  439.     {
  440.         if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  441.             $protocol = 'https://';
  442.         } else {
  443.             $protocol = 'http://';
  444.         }
  445.         $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  446.         $parts      = parse_url($currentUrl);
  447.         $query      = '';
  448.         if (!empty($parts['query'])) {
  449.             $params          = explode('&', $parts['query']);
  450.             $retained_params = array();
  451.             foreach ($params as $param) {
  452.                 if ($this->shouldRetainParam($param)) {
  453.                     $retained_params[] = $param;
  454.                 }
  455.             }
  456.             if (!empty($retained_params)) {
  457.                 $query = '?' . implode($retained_params, '&');
  458.             }
  459.         }
  460.         $port = isset($parts['port']) && (($protocol === 'http://' && $parts['port'] !== 80) || ($protocol === 'https://' && $parts['port'] !== 443)) ? ':' . $parts['port'] : '';
  461.         return $protocol . $parts['host'] . $port . $parts['path'] . $query;
  462.     }
  463.     protected function shouldRetainParam($param)
  464.     {
  465.         foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
  466.             if (strpos($param, $drop_query_param . '=') === 0) {
  467.                 return false;
  468.             }
  469.         }
  470.         return true;
  471.     }
  472.     protected function throwAPIException($result)
  473.     {
  474.         $e = new FacebookApiException($result);
  475.         switch ($e->getType()) {
  476.             case 'OAuthException':
  477.             case 'invalid_token':
  478.             case 'Exception':
  479.                 $message = $e->getMessage();
  480.                 if ((strpos($message, 'Error validating access token') !== false) || (strpos($message, 'Invalid OAuth access token') !== false)) {
  481.                     $this->setAccessToken(null);
  482.                     $this->user = 0;
  483.                     $this->clearAllPersistentData();
  484.                 }
  485.         }
  486.         throw $e;
  487.     }
  488.     protected static function errorLog($msg)
  489.     {
  490.         if (php_sapi_name() != 'cli') {
  491.             error_log($msg);
  492.         }
  493.     }
  494.     protected static function base64UrlDecode($input)
  495.     {
  496.         return base64_decode(strtr($input, '-_', '+/'));
  497.     }
  498.     public function destroySession()
  499.     {
  500.         $this->setAccessToken(null);
  501.         $this->user = 0;
  502.         $this->clearAllPersistentData();
  503.     }
  504.     abstract protected function setPersistentData($key, $value);
  505.     abstract protected function getPersistentData($key, $default = false);
  506.     abstract protected function clearPersistentData($key);
  507.     abstract protected function clearAllPersistentData();
  508.     public function getExtendedAccessToken()
  509.     {
  510.         try {
  511.             $access_token_response = $this->_oauthRequest($this->getUrl('graph', '/oauth/access_token'), $params = array(
  512.                 'client_id' => $this->getAppId(),
  513.                 'client_secret' => $this->getApiSecret(),
  514.                 'grant_type' => 'fb_exchange_token',
  515.                 'fb_exchange_token' => $this->getAccessToken()
  516.             ));
  517.         }
  518.         catch (FacebookApiException $e) {
  519.             return false;
  520.         }
  521.         if (empty($access_token_response)) {
  522.             return false;
  523.         }
  524.         $response_params = array();
  525.         parse_str($access_token_response, $response_params);
  526.         if (!isset($response_params['access_token'])) {
  527.             return false;
  528.         }
  529.         return $response_params['access_token'];
  530.     }
  531. }
  532. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement