Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

base_facebook.php

By: a guest on May 2nd, 2012  |  syntax: PHP  |  size: 34.32 KB  |  views: 6  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2. /**
  3.  * Copyright 2011 Facebook, Inc.
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License"); you may
  6.  * not use this file except in compliance with the License. You may obtain
  7.  * a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13.  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14.  * License for the specific language governing permissions and limitations
  15.  * under the License.
  16.  */
  17.  
  18. if (!function_exists('curl_init')) {
  19.   throw new Exception('Facebook needs the CURL PHP extension.');
  20. }
  21. if (!function_exists('json_decode')) {
  22.   throw new Exception('Facebook needs the JSON PHP extension.');
  23. }
  24.  
  25. /**
  26.  * Thrown when an API call returns an exception.
  27.  *
  28.  * @author Naitik Shah <naitik@facebook.com>
  29.  */
  30. class FacebookApiException extends Exception
  31. {
  32.   /**
  33.    * The result from the API server that represents the exception information.
  34.    */
  35.   protected $result;
  36.  
  37.   /**
  38.    * Make a new API Exception with the given result.
  39.    *
  40.    * @param array $result The result from the API server
  41.    */
  42.   public function __construct($result) {
  43.     $this->result = $result;
  44.  
  45.     $code = isset($result['error_code']) ? $result['error_code'] : 0;
  46.  
  47.     if (isset($result['error_description'])) {
  48.       // OAuth 2.0 Draft 10 style
  49.       $msg = $result['error_description'];
  50.     } else if (isset($result['error']) && is_array($result['error'])) {
  51.       // OAuth 2.0 Draft 00 style
  52.       $msg = $result['error']['message'];
  53.     } else if (isset($result['error_msg'])) {
  54.       // Rest server style
  55.       $msg = $result['error_msg'];
  56.     } else {
  57.       $msg = 'Unknown Error. Check getResult()';
  58.     }
  59.  
  60.     parent::__construct($msg, $code);
  61.   }
  62.  
  63.   /**
  64.    * Return the associated result object returned by the API server.
  65.    *
  66.    * @return array The result from the API server
  67.    */
  68.   public function getResult() {
  69.     return $this->result;
  70.   }
  71.  
  72.   /**
  73.    * Returns the associated type for the error. This will default to
  74.    * 'Exception' when a type is not available.
  75.    *
  76.    * @return string
  77.    */
  78.   public function getType() {
  79.     if (isset($this->result['error'])) {
  80.       $error = $this->result['error'];
  81.       if (is_string($error)) {
  82.         // OAuth 2.0 Draft 10 style
  83.         return $error;
  84.       } else if (is_array($error)) {
  85.         // OAuth 2.0 Draft 00 style
  86.         if (isset($error['type'])) {
  87.           return $error['type'];
  88.         }
  89.       }
  90.     }
  91.  
  92.     return 'Exception';
  93.   }
  94.  
  95.   /**
  96.    * To make debugging easier.
  97.    *
  98.    * @return string The string representation of the error
  99.    */
  100.   public function __toString() {
  101.     $str = $this->getType() . ': ';
  102.     if ($this->code != 0) {
  103.       $str .= $this->code . ': ';
  104.     }
  105.     return $str . $this->message;
  106.   }
  107. }
  108.  
  109. /**
  110.  * Provides access to the Facebook Platform.  This class provides
  111.  * a majority of the functionality needed, but the class is abstract
  112.  * because it is designed to be sub-classed.  The subclass must
  113.  * implement the four abstract methods listed at the bottom of
  114.  * the file.
  115.  *
  116.  * @author Naitik Shah <naitik@facebook.com>
  117.  */
  118. abstract class BaseFacebook
  119. {
  120.   /**
  121.    * Version.
  122.    */
  123.   const VERSION = '3.1.1';
  124.  
  125.   /**
  126.    * Default options for curl.
  127.    */
  128.   public static $CURL_OPTS = array(
  129.     CURLOPT_CONNECTTIMEOUT => 10,
  130.     CURLOPT_RETURNTRANSFER => true,
  131.     CURLOPT_TIMEOUT        => 60,
  132.     CURLOPT_USERAGENT      => 'facebook-php-3.1',
  133.   );
  134.  
  135.   /**
  136.    * List of query parameters that get automatically dropped when rebuilding
  137.    * the current URL.
  138.    */
  139.   protected static $DROP_QUERY_PARAMS = array(
  140.     'code',
  141.     'state',
  142.     'signed_request',
  143.   );
  144.  
  145.   /**
  146.    * Maps aliases to Facebook domains.
  147.    */
  148.   public static $DOMAIN_MAP = array(
  149.     'api'       => 'https://api.facebook.com/',
  150.     'api_video' => 'https://api-video.facebook.com/',
  151.     'api_read'  => 'https://api-read.facebook.com/',
  152.     'graph'     => 'https://graph.facebook.com/',
  153.     'www'       => 'https://www.facebook.com/',
  154.   );
  155.  
  156.   /**
  157.    * The Application ID.
  158.    *
  159.    * @var string
  160.    */
  161.   protected $appId;
  162.  
  163.   /**
  164.    * The Application API Secret.
  165.    *
  166.    * @var string
  167.    */
  168.   protected $apiSecret;
  169.  
  170.   /**
  171.    * The ID of the Facebook user, or 0 if the user is logged out.
  172.    *
  173.    * @var integer
  174.    */
  175.   protected $user;
  176.  
  177.   /**
  178.    * The data from the signed_request token.
  179.    */
  180.   protected $signedRequest;
  181.  
  182.   /**
  183.    * A CSRF state variable to assist in the defense against CSRF attacks.
  184.    */
  185.   protected $state;
  186.  
  187.   /**
  188.    * The OAuth access token received in exchange for a valid authorization
  189.    * code.  null means the access token has yet to be determined.
  190.    *
  191.    * @var string
  192.    */
  193.   protected $accessToken = null;
  194.  
  195.   /**
  196.    * Indicates if the CURL based @ syntax for file uploads is enabled.
  197.    *
  198.    * @var boolean
  199.    */
  200.   protected $fileUploadSupport = false;
  201.  
  202.   /**
  203.    * Initialize a Facebook Application.
  204.    *
  205.    * The configuration:
  206.    * - appId: the application ID
  207.    * - secret: the application secret
  208.    * - fileUpload: (optional) boolean indicating if file uploads are enabled
  209.    *
  210.    * @param array $config The application configuration
  211.    */
  212.   public function __construct($config) {
  213.     $this->setAppId($config['appId']);
  214.     $this->setApiSecret($config['secret']);
  215.     if (isset($config['fileUpload'])) {
  216.       $this->setFileUploadSupport($config['fileUpload']);
  217.     }
  218.  
  219.     $state = $this->getPersistentData('state');
  220.     if (!empty($state)) {
  221.       $this->state = $this->getPersistentData('state');
  222.     }
  223.   }
  224.  
  225.   /**
  226.    * Set the Application ID.
  227.    *
  228.    * @param string $appId The Application ID
  229.    * @return BaseFacebook
  230.    */
  231.   public function setAppId($appId) {
  232.     $this->appId = $appId;
  233.     return $this;
  234.   }
  235.  
  236.   /**
  237.    * Get the Application ID.
  238.    *
  239.    * @return string the Application ID
  240.    */
  241.   public function getAppId() {
  242.     return $this->appId;
  243.   }
  244.  
  245.   /**
  246.    * Set the API Secret.
  247.    *
  248.    * @param string $apiSecret The API Secret
  249.    * @return BaseFacebook
  250.    */
  251.   public function setApiSecret($apiSecret) {
  252.     $this->apiSecret = $apiSecret;
  253.     return $this;
  254.   }
  255.  
  256.   /**
  257.    * Get the API Secret.
  258.    *
  259.    * @return string the API Secret
  260.    */
  261.   public function getApiSecret() {
  262.     return $this->apiSecret;
  263.   }
  264.  
  265.   /**
  266.    * Set the file upload support status.
  267.    *
  268.    * @param boolean $fileUploadSupport The file upload support status.
  269.    * @return BaseFacebook
  270.    */
  271.   public function setFileUploadSupport($fileUploadSupport) {
  272.     $this->fileUploadSupport = $fileUploadSupport;
  273.     return $this;
  274.   }
  275.  
  276.   /**
  277.    * Get the file upload support status.
  278.    *
  279.    * @return boolean true if and only if the server supports file upload.
  280.    */
  281.   public function useFileUploadSupport() {
  282.     return $this->fileUploadSupport;
  283.   }
  284.  
  285.   /**
  286.    * Sets the access token for api calls.  Use this if you get
  287.    * your access token by other means and just want the SDK
  288.    * to use it.
  289.    *
  290.    * @param string $access_token an access token.
  291.    * @return BaseFacebook
  292.    */
  293.   public function setAccessToken($access_token) {
  294.     $this->accessToken = $access_token;
  295.     return $this;
  296.   }
  297.  
  298.   /**
  299.    * Determines the access token that should be used for API calls.
  300.    * The first time this is called, $this->accessToken is set equal
  301.    * to either a valid user access token, or it's set to the application
  302.    * access token if a valid user access token wasn't available.  Subsequent
  303.    * calls return whatever the first call returned.
  304.    *
  305.    * @return string The access token
  306.    */
  307.   public function getAccessToken() {
  308.     if ($this->accessToken !== null) {
  309.       // we've done this already and cached it.  Just return.
  310.       return $this->accessToken;
  311.     }
  312.  
  313.     // first establish access token to be the application
  314.     // access token, in case we navigate to the /oauth/access_token
  315.     // endpoint, where SOME access token is required.
  316.     $this->setAccessToken($this->getApplicationAccessToken());
  317.     $user_access_token = $this->getUserAccessToken();
  318.     if ($user_access_token) {
  319.       $this->setAccessToken($user_access_token);
  320.     }
  321.  
  322.     return $this->accessToken;
  323.   }
  324.  
  325.   /**
  326.    * Determines and returns the user access token, first using
  327.    * the signed request if present, and then falling back on
  328.    * the authorization code if present.  The intent is to
  329.    * return a valid user access token, or false if one is determined
  330.    * to not be available.
  331.    *
  332.    * @return string A valid user access token, or false if one
  333.    *                could not be determined.
  334.    */
  335.   protected function getUserAccessToken() {
  336.     // first, consider a signed request if it's supplied.
  337.     // if there is a signed request, then it alone determines
  338.     // the access token.
  339.     $signed_request = $this->getSignedRequest();
  340.     if ($signed_request) {
  341.       // apps.facebook.com hands the access_token in the signed_request
  342.       if (array_key_exists('oauth_token', $signed_request)) {
  343.         $access_token = $signed_request['oauth_token'];
  344.         $this->setPersistentData('access_token', $access_token);
  345.         return $access_token;
  346.       }
  347.  
  348.       // the JS SDK puts a code in with the redirect_uri of ''
  349.       if (array_key_exists('code', $signed_request)) {
  350.         $code = $signed_request['code'];
  351.         $access_token = $this->getAccessTokenFromCode($code, '');
  352.         if ($access_token) {
  353.           $this->setPersistentData('code', $code);
  354.           $this->setPersistentData('access_token', $access_token);
  355.           return $access_token;
  356.         }
  357.       }
  358.  
  359.       // signed request states there's no access token, so anything
  360.       // stored should be cleared.
  361.       $this->clearAllPersistentData();
  362.       return false; // respect the signed request's data, even
  363.                     // if there's an authorization code or something else
  364.     }
  365.  
  366.     $code = $this->getCode();
  367.     if ($code && $code != $this->getPersistentData('code')) {
  368.       $access_token = $this->getAccessTokenFromCode($code);
  369.       if ($access_token) {
  370.         $this->setPersistentData('code', $code);
  371.         $this->setPersistentData('access_token', $access_token);
  372.         return $access_token;
  373.       }
  374.  
  375.       // code was bogus, so everything based on it should be invalidated.
  376.       $this->clearAllPersistentData();
  377.       return false;
  378.     }
  379.  
  380.     // as a fallback, just return whatever is in the persistent
  381.     // store, knowing nothing explicit (signed request, authorization
  382.     // code, etc.) was present to shadow it (or we saw a code in $_REQUEST,
  383.     // but it's the same as what's in the persistent store)
  384.     return $this->getPersistentData('access_token');
  385.   }
  386.  
  387.   /**
  388.    * Retrieve the signed request, either from a request parameter or,
  389.    * if not present, from a cookie.
  390.    *
  391.    * @return string the signed request, if available, or null otherwise.
  392.    */
  393.   public function getSignedRequest() {
  394.     if (!$this->signedRequest) {
  395.       if (isset($_REQUEST['signed_request'])) {
  396.         $this->signedRequest = $this->parseSignedRequest(
  397.           $_REQUEST['signed_request']);
  398.       } else if (isset($_COOKIE[$this->getSignedRequestCookieName()])) {
  399.         $this->signedRequest = $this->parseSignedRequest(
  400.           $_COOKIE[$this->getSignedRequestCookieName()]);
  401.       }
  402.     }
  403.     return $this->signedRequest;
  404.   }
  405.  
  406.   /**
  407.    * Get the UID of the connected user, or 0
  408.    * if the Facebook user is not connected.
  409.    *
  410.    * @return string the UID if available.
  411.    */
  412.   public function getUser() {
  413.     if ($this->user !== null) {
  414.       // we've already determined this and cached the value.
  415.       return $this->user;
  416.     }
  417.  
  418.     return $this->user = $this->getUserFromAvailableData();
  419.   }
  420.  
  421.   /**
  422.    * Determines the connected user by first examining any signed
  423.    * requests, then considering an authorization code, and then
  424.    * falling back to any persistent store storing the user.
  425.    *
  426.    * @return integer The id of the connected Facebook user,
  427.    *                 or 0 if no such user exists.
  428.    */
  429.   protected function getUserFromAvailableData() {
  430.     // if a signed request is supplied, then it solely determines
  431.     // who the user is.
  432.     $signed_request = $this->getSignedRequest();
  433.     if ($signed_request) {
  434.       if (array_key_exists('user_id', $signed_request)) {
  435.         $user = $signed_request['user_id'];
  436.         $this->setPersistentData('user_id', $signed_request['user_id']);
  437.         return $user;
  438.       }
  439.  
  440.       // if the signed request didn't present a user id, then invalidate
  441.       // all entries in any persistent store.
  442.       $this->clearAllPersistentData();
  443.       return 0;
  444.     }
  445.  
  446.     $user = $this->getPersistentData('user_id', $default = 0);
  447.     $persisted_access_token = $this->getPersistentData('access_token');
  448.  
  449.     // use access_token to fetch user id if we have a user access_token, or if
  450.     // the cached access token has changed.
  451.     $access_token = $this->getAccessToken();
  452.     if ($access_token &&
  453.         $access_token != $this->getApplicationAccessToken() &&
  454.         !($user && $persisted_access_token == $access_token)) {
  455.       $user = $this->getUserFromAccessToken();
  456.       if ($user) {
  457.         $this->setPersistentData('user_id', $user);
  458.       } else {
  459.         $this->clearAllPersistentData();
  460.       }
  461.     }
  462.  
  463.     return $user;
  464.   }
  465.  
  466.   /**
  467.    * Get a Login URL for use with redirects. By default, full page redirect is
  468.    * assumed. If you are using the generated URL with a window.open() call in
  469.    * JavaScript, you can pass in display=popup as part of the $params.
  470.    *
  471.    * The parameters:
  472.    * - redirect_uri: the url to go to after a successful login
  473.    * - scope: comma separated list of requested extended perms
  474.    *
  475.    * @param array $params Provide custom parameters
  476.    * @return string The URL for the login flow
  477.    */
  478.   public function getLoginUrl($params=array()) {
  479.     $this->establishCSRFTokenState();
  480.     $currentUrl = $this->getCurrentUrl();
  481.  
  482.     // if 'scope' is passed as an array, convert to comma separated list
  483.     $scopeParams = isset($params['scope']) ? $params['scope'] : null;
  484.     if ($scopeParams && is_array($scopeParams)) {
  485.       $params['scope'] = implode(',', $scopeParams);
  486.     }
  487.  
  488.     return $this->getUrl(
  489.       'www',
  490.       'dialog/oauth',
  491.       array_merge(array(
  492.                     'client_id' => $this->getAppId(),
  493.                     'redirect_uri' => $currentUrl, // possibly overwritten
  494.                     'state' => $this->state),
  495.                   $params));
  496.   }
  497.  
  498.   /**
  499.    * Get a Logout URL suitable for use with redirects.
  500.    *
  501.    * The parameters:
  502.    * - next: the url to go to after a successful logout
  503.    *
  504.    * @param array $params Provide custom parameters
  505.    * @return string The URL for the logout flow
  506.    */
  507.   public function getLogoutUrl($params=array()) {
  508.     return $this->getUrl(
  509.       'www',
  510.       'logout.php',
  511.       array_merge(array(
  512.         'next' => $this->getCurrentUrl(),
  513.         'access_token' => $this->getAccessToken(),
  514.       ), $params)
  515.     );
  516.   }
  517.  
  518.   /**
  519.    * Get a login status URL to fetch the status from Facebook.
  520.    *
  521.    * The parameters:
  522.    * - ok_session: the URL to go to if a session is found
  523.    * - no_session: the URL to go to if the user is not connected
  524.    * - no_user: the URL to go to if the user is not signed into facebook
  525.    *
  526.    * @param array $params Provide custom parameters
  527.    * @return string The URL for the logout flow
  528.    */
  529.   public function getLoginStatusUrl($params=array()) {
  530.     return $this->getUrl(
  531.       'www',
  532.       'extern/login_status.php',
  533.       array_merge(array(
  534.         'api_key' => $this->getAppId(),
  535.         'no_session' => $this->getCurrentUrl(),
  536.         'no_user' => $this->getCurrentUrl(),
  537.         'ok_session' => $this->getCurrentUrl(),
  538.         'session_version' => 3,
  539.       ), $params)
  540.     );
  541.   }
  542.  
  543.   /**
  544.    * Make an API call.
  545.    *
  546.    * @return mixed The decoded response
  547.    */
  548.   public function api(/* polymorphic */) {
  549.     $args = func_get_args();
  550.     if (is_array($args[0])) {
  551.       return $this->_restserver($args[0]);
  552.     } else {
  553.       return call_user_func_array(array($this, '_graph'), $args);
  554.     }
  555.   }
  556.  
  557.   /**
  558.    * Constructs and returns the name of the cookie that
  559.    * potentially houses the signed request for the app user.
  560.    * The cookie is not set by the BaseFacebook class, but
  561.    * it may be set by the JavaScript SDK.
  562.    *
  563.    * @return string the name of the cookie that would house
  564.    *         the signed request value.
  565.    */
  566.   protected function getSignedRequestCookieName() {
  567.     return 'fbsr_'.$this->getAppId();
  568.   }
  569.  
  570.   /**
  571.    * Get the authorization code from the query parameters, if it exists,
  572.    * and otherwise return false to signal no authorization code was
  573.    * discoverable.
  574.    *
  575.    * @return mixed The authorization code, or false if the authorization
  576.    *               code could not be determined.
  577.    */
  578.   protected function getCode() {
  579.     if (isset($_REQUEST['code'])) {
  580.       if ($this->state !== null &&
  581.           isset($_REQUEST['state']) &&
  582.           $this->state === $_REQUEST['state']) {
  583.  
  584.         // CSRF state has done its job, so clear it
  585.         $this->state = null;
  586.         $this->clearPersistentData('state');
  587.         return $_REQUEST['code'];
  588.       } else {
  589.         self::errorLog('CSRF state token does not match one provided.');
  590.         return false;
  591.       }
  592.     }
  593.  
  594.     return false;
  595.   }
  596.  
  597.   /**
  598.    * Retrieves the UID with the understanding that
  599.    * $this->accessToken has already been set and is
  600.    * seemingly legitimate.  It relies on Facebook's Graph API
  601.    * to retrieve user information and then extract
  602.    * the user ID.
  603.    *
  604.    * @return integer Returns the UID of the Facebook user, or 0
  605.    *                 if the Facebook user could not be determined.
  606.    */
  607.   protected function getUserFromAccessToken() {
  608.     try {
  609.       $user_info = $this->api('/me');
  610.       return $user_info['id'];
  611.     } catch (FacebookApiException $e) {
  612.       return 0;
  613.     }
  614.   }
  615.  
  616.   /**
  617.    * Returns the access token that should be used for logged out
  618.    * users when no authorization code is available.
  619.    *
  620.    * @return string The application access token, useful for gathering
  621.    *                public information about users and applications.
  622.    */
  623.   protected function getApplicationAccessToken() {
  624.     return $this->appId.'|'.$this->apiSecret;
  625.   }
  626.  
  627.   /**
  628.    * Lays down a CSRF state token for this process.
  629.    *
  630.    * @return void
  631.    */
  632.   protected function establishCSRFTokenState() {
  633.     if ($this->state === null) {
  634.       $this->state = md5(uniqid(mt_rand(), true));
  635.       $this->setPersistentData('state', $this->state);
  636.     }
  637.   }
  638.  
  639.   /**
  640.    * Retrieves an access token for the given authorization code
  641.    * (previously generated from www.facebook.com on behalf of
  642.    * a specific user).  The authorization code is sent to graph.facebook.com
  643.    * and a legitimate access token is generated provided the access token
  644.    * and the user for which it was generated all match, and the user is
  645.    * either logged in to Facebook or has granted an offline access permission.
  646.    *
  647.    * @param string $code An authorization code.
  648.    * @return mixed An access token exchanged for the authorization code, or
  649.    *               false if an access token could not be generated.
  650.    */
  651.   protected function getAccessTokenFromCode($code, $redirect_uri = null) {
  652.     if (empty($code)) {
  653.       return false;
  654.     }
  655.  
  656.     if ($redirect_uri === null) {
  657.       $redirect_uri = $this->getCurrentUrl();
  658.     }
  659.  
  660.     try {
  661.       // need to circumvent json_decode by calling _oauthRequest
  662.       // directly, since response isn't JSON format.
  663.       $access_token_response =
  664.         $this->_oauthRequest(
  665.           $this->getUrl('graph', '/oauth/access_token'),
  666.           $params = array('client_id' => $this->getAppId(),
  667.                           'client_secret' => $this->getApiSecret(),
  668.                           'redirect_uri' => $redirect_uri,
  669.                           'code' => $code));
  670.     } catch (FacebookApiException $e) {
  671.       // most likely that user very recently revoked authorization.
  672.       // In any event, we don't have an access token, so say so.
  673.       return false;
  674.     }
  675.  
  676.     if (empty($access_token_response)) {
  677.       return false;
  678.     }
  679.  
  680.     $response_params = array();
  681.     parse_str($access_token_response, $response_params);
  682.     if (!isset($response_params['access_token'])) {
  683.       return false;
  684.     }
  685.  
  686.     return $response_params['access_token'];
  687.   }
  688.  
  689.   /**
  690.    * Invoke the old restserver.php endpoint.
  691.    *
  692.    * @param array $params Method call object
  693.    *
  694.    * @return mixed The decoded response object
  695.    * @throws FacebookApiException
  696.    */
  697.   protected function _restserver($params) {
  698.     // generic application level parameters
  699.     $params['api_key'] = $this->getAppId();
  700.     $params['format'] = 'json-strings';
  701.  
  702.     $result = json_decode($this->_oauthRequest(
  703.       $this->getApiUrl($params['method']),
  704.       $params
  705.     ), true);
  706.  
  707.     // results are returned, errors are thrown
  708.     if (is_array($result) && isset($result['error_code'])) {
  709.       $this->throwAPIException($result);
  710.     }
  711.  
  712.     if ($params['method'] === 'auth.expireSession' ||
  713.         $params['method'] === 'auth.revokeAuthorization') {
  714.       $this->destroySession();
  715.     }
  716.  
  717.     return $result;
  718.   }
  719.  
  720.   /**
  721.    * Invoke the Graph API.
  722.    *
  723.    * @param string $path The path (required)
  724.    * @param string $method The http method (default 'GET')
  725.    * @param array $params The query/post data
  726.    *
  727.    * @return mixed The decoded response object
  728.    * @throws FacebookApiException
  729.    */
  730.   protected function _graph($path, $method = 'GET', $params = array()) {
  731.     if (is_array($method) && empty($params)) {
  732.       $params = $method;
  733.       $method = 'GET';
  734.     }
  735.     $params['method'] = $method; // method override as we always do a POST
  736.  
  737.     $result = json_decode($this->_oauthRequest(
  738.       $this->getUrl('graph', $path),
  739.       $params
  740.     ), true);
  741.  
  742.     // results are returned, errors are thrown
  743.     if (is_array($result) && isset($result['error'])) {
  744.       $this->throwAPIException($result);
  745.     }
  746.  
  747.     return $result;
  748.   }
  749.  
  750.   /**
  751.    * Make a OAuth Request.
  752.    *
  753.    * @param string $url The path (required)
  754.    * @param array $params The query/post data
  755.    *
  756.    * @return string The decoded response object
  757.    * @throws FacebookApiException
  758.    */
  759.   protected function _oauthRequest($url, $params) {
  760.     if (!isset($params['access_token'])) {
  761.       $params['access_token'] = $this->getAccessToken();
  762.     }
  763.  
  764.     // json_encode all params values that are not strings
  765.     foreach ($params as $key => $value) {
  766.       if (!is_string($value)) {
  767.         $params[$key] = json_encode($value);
  768.       }
  769.     }
  770.  
  771.     return $this->makeRequest($url, $params);
  772.   }
  773.  
  774.   /**
  775.    * Makes an HTTP request. This method can be overridden by subclasses if
  776.    * developers want to do fancier things or use something other than curl to
  777.    * make the request.
  778.    *
  779.    * @param string $url The URL to make the request to
  780.    * @param array $params The parameters to use for the POST body
  781.    * @param CurlHandler $ch Initialized curl handle
  782.    *
  783.    * @return string The response text
  784.    */
  785.   protected function makeRequest($url, $params, $ch=null) {
  786.     if (!$ch) {
  787.       $ch = curl_init();
  788.     }
  789.  
  790.     $opts = self::$CURL_OPTS;
  791.     if ($this->useFileUploadSupport()) {
  792.       $opts[CURLOPT_POSTFIELDS] = $params;
  793.     } else {
  794.       $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
  795.     }
  796.     $opts[CURLOPT_URL] = $url;
  797.  
  798.     // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
  799.     // for 2 seconds if the server does not support this header.
  800.     if (isset($opts[CURLOPT_HTTPHEADER])) {
  801.       $existing_headers = $opts[CURLOPT_HTTPHEADER];
  802.       $existing_headers[] = 'Expect:';
  803.       $opts[CURLOPT_HTTPHEADER] = $existing_headers;
  804.     } else {
  805.       $opts[CURLOPT_HTTPHEADER] = array('Expect:');
  806.     }
  807.  
  808.     curl_setopt_array($ch, $opts);
  809.     $result = curl_exec($ch);
  810.  
  811.     if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
  812.       self::errorLog('Invalid or no certificate authority found, '.
  813.                      'using bundled information');
  814.       curl_setopt($ch, CURLOPT_CAINFO,
  815.                   dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
  816.       $result = curl_exec($ch);
  817.     }
  818.  
  819.     if ($result === false) {
  820.       $e = new FacebookApiException(array(
  821.         'error_code' => curl_errno($ch),
  822.         'error' => array(
  823.         'message' => curl_error($ch),
  824.         'type' => 'CurlException',
  825.         ),
  826.       ));
  827.       curl_close($ch);
  828.       throw $e;
  829.     }
  830.     curl_close($ch);
  831.     return $result;
  832.   }
  833.  
  834.   /**
  835.    * Parses a signed_request and validates the signature.
  836.    *
  837.    * @param string $signed_request A signed token
  838.    * @return array The payload inside it or null if the sig is wrong
  839.    */
  840.   protected function parseSignedRequest($signed_request) {
  841.     list($encoded_sig, $payload) = explode('.', $signed_request, 2);
  842.  
  843.     // decode the data
  844.     $sig = self::base64UrlDecode($encoded_sig);
  845.     $data = json_decode(self::base64UrlDecode($payload), true);
  846.  
  847.     if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
  848.       self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
  849.       return null;
  850.     }
  851.  
  852.     // check sig
  853.     $expected_sig = hash_hmac('sha256', $payload,
  854.                               $this->getApiSecret(), $raw = true);
  855.     if ($sig !== $expected_sig) {
  856.       self::errorLog('Bad Signed JSON signature!');
  857.       return null;
  858.     }
  859.  
  860.     return $data;
  861.   }
  862.  
  863.   /**
  864.    * Build the URL for api given parameters.
  865.    *
  866.    * @param $method String the method name.
  867.    * @return string The URL for the given parameters
  868.    */
  869.   protected function getApiUrl($method) {
  870.     static $READ_ONLY_CALLS =
  871.       array('admin.getallocation' => 1,
  872.             'admin.getappproperties' => 1,
  873.             'admin.getbannedusers' => 1,
  874.             'admin.getlivestreamvialink' => 1,
  875.             'admin.getmetrics' => 1,
  876.             'admin.getrestrictioninfo' => 1,
  877.             'application.getpublicinfo' => 1,
  878.             'auth.getapppublickey' => 1,
  879.             'auth.getsession' => 1,
  880.             'auth.getsignedpublicsessiondata' => 1,
  881.             'comments.get' => 1,
  882.             'connect.getunconnectedfriendscount' => 1,
  883.             'dashboard.getactivity' => 1,
  884.             'dashboard.getcount' => 1,
  885.             'dashboard.getglobalnews' => 1,
  886.             'dashboard.getnews' => 1,
  887.             'dashboard.multigetcount' => 1,
  888.             'dashboard.multigetnews' => 1,
  889.             'data.getcookies' => 1,
  890.             'events.get' => 1,
  891.             'events.getmembers' => 1,
  892.             'fbml.getcustomtags' => 1,
  893.             'feed.getappfriendstories' => 1,
  894.             'feed.getregisteredtemplatebundlebyid' => 1,
  895.             'feed.getregisteredtemplatebundles' => 1,
  896.             'fql.multiquery' => 1,
  897.             'fql.query' => 1,
  898.             'friends.arefriends' => 1,
  899.             'friends.get' => 1,
  900.             'friends.getappusers' => 1,
  901.             'friends.getlists' => 1,
  902.             'friends.getmutualfriends' => 1,
  903.             'gifts.get' => 1,
  904.             'groups.get' => 1,
  905.             'groups.getmembers' => 1,
  906.             'intl.gettranslations' => 1,
  907.             'links.get' => 1,
  908.             'notes.get' => 1,
  909.             'notifications.get' => 1,
  910.             'pages.getinfo' => 1,
  911.             'pages.isadmin' => 1,
  912.             'pages.isappadded' => 1,
  913.             'pages.isfan' => 1,
  914.             'permissions.checkavailableapiaccess' => 1,
  915.             'permissions.checkgrantedapiaccess' => 1,
  916.             'photos.get' => 1,
  917.             'photos.getalbums' => 1,
  918.             'photos.gettags' => 1,
  919.             'profile.getinfo' => 1,
  920.             'profile.getinfooptions' => 1,
  921.             'stream.get' => 1,
  922.             'stream.getcomments' => 1,
  923.             'stream.getfilters' => 1,
  924.             'users.getinfo' => 1,
  925.             'users.getloggedinuser' => 1,
  926.             'users.getstandardinfo' => 1,
  927.             'users.hasapppermission' => 1,
  928.             'users.isappuser' => 1,
  929.             'users.isverified' => 1,
  930.             'video.getuploadlimits' => 1);
  931.     $name = 'api';
  932.     if (isset($READ_ONLY_CALLS[strtolower($method)])) {
  933.       $name = 'api_read';
  934.     } else if (strtolower($method) == 'video.upload') {
  935.       $name = 'api_video';
  936.     }
  937.     return self::getUrl($name, 'restserver.php');
  938.   }
  939.  
  940.   /**
  941.    * Build the URL for given domain alias, path and parameters.
  942.    *
  943.    * @param $name string The name of the domain
  944.    * @param $path string Optional path (without a leading slash)
  945.    * @param $params array Optional query parameters
  946.    *
  947.    * @return string The URL for the given parameters
  948.    */
  949.   protected function getUrl($name, $path='', $params=array()) {
  950.     $url = self::$DOMAIN_MAP[$name];
  951.     if ($path) {
  952.       if ($path[0] === '/') {
  953.         $path = substr($path, 1);
  954.       }
  955.       $url .= $path;
  956.     }
  957.     if ($params) {
  958.       $url .= '?' . http_build_query($params, null, '&');
  959.     }
  960.  
  961.     return $url;
  962.   }
  963.  
  964.   /**
  965.    * Returns the Current URL, stripping it of known FB parameters that should
  966.    * not persist.
  967.    *
  968.    * @return string The current URL
  969.    */
  970.   protected function getCurrentUrl() {
  971.     if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1)
  972.       || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
  973.     ) {
  974.       $protocol = 'https://';
  975.     }
  976.     else {
  977.       $protocol = 'http://';
  978.     }
  979.     $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  980.     $parts = parse_url($currentUrl);
  981.  
  982.     $query = '';
  983.     if (!empty($parts['query'])) {
  984.       // drop known fb params
  985.       $params = explode('&', $parts['query']);
  986.       $retained_params = array();
  987.       foreach ($params as $param) {
  988.         if ($this->shouldRetainParam($param)) {
  989.           $retained_params[] = $param;
  990.         }
  991.       }
  992.  
  993.       if (!empty($retained_params)) {
  994.         $query = '?'.implode($retained_params, '&');
  995.       }
  996.     }
  997.  
  998.     // use port if non default
  999.     $port =
  1000.       isset($parts['port']) &&
  1001.       (($protocol === 'http://' && $parts['port'] !== 80) ||
  1002.        ($protocol === 'https://' && $parts['port'] !== 443))
  1003.       ? ':' . $parts['port'] : '';
  1004.  
  1005.     // rebuild
  1006.     return $protocol . $parts['host'] . $port . $parts['path'] . $query;
  1007.   }
  1008.  
  1009.   /**
  1010.    * Returns true if and only if the key or key/value pair should
  1011.    * be retained as part of the query string.  This amounts to
  1012.    * a brute-force search of the very small list of Facebook-specific
  1013.    * params that should be stripped out.
  1014.    *
  1015.    * @param string $param A key or key/value pair within a URL's query (e.g.
  1016.    *                     'foo=a', 'foo=', or 'foo'.
  1017.    *
  1018.    * @return boolean
  1019.    */
  1020.   protected function shouldRetainParam($param) {
  1021.     foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
  1022.       if (strpos($param, $drop_query_param.'=') === 0) {
  1023.         return false;
  1024.       }
  1025.     }
  1026.  
  1027.     return true;
  1028.   }
  1029.  
  1030.   /**
  1031.    * Analyzes the supplied result to see if it was thrown
  1032.    * because the access token is no longer valid.  If that is
  1033.    * the case, then the persistent store is cleared.
  1034.    *
  1035.    * @param $result array A record storing the error message returned
  1036.    *                      by a failed API call.
  1037.    */
  1038.   protected function throwAPIException($result) {
  1039.     $e = new FacebookApiException($result);
  1040.     switch ($e->getType()) {
  1041.       // OAuth 2.0 Draft 00 style
  1042.       case 'OAuthException':
  1043.         // OAuth 2.0 Draft 10 style
  1044.       case 'invalid_token':
  1045.         // REST server errors are just Exceptions
  1046.       case 'Exception':
  1047.         $message = $e->getMessage();
  1048.       if ((strpos($message, 'Error validating access token') !== false) ||
  1049.           (strpos($message, 'Invalid OAuth access token') !== false)) {
  1050.         $this->setAccessToken(null);
  1051.         $this->user = 0;
  1052.         $this->clearAllPersistentData();
  1053.       }
  1054.     }
  1055.  
  1056.     throw $e;
  1057.   }
  1058.  
  1059.  
  1060.   /**
  1061.    * Prints to the error log if you aren't in command line mode.
  1062.    *
  1063.    * @param string $msg Log message
  1064.    */
  1065.   protected static function errorLog($msg) {
  1066.     // disable error log if we are running in a CLI environment
  1067.     // @codeCoverageIgnoreStart
  1068.     if (php_sapi_name() != 'cli') {
  1069.       error_log($msg);
  1070.     }
  1071.     // uncomment this if you want to see the errors on the page
  1072.     // print 'error_log: '.$msg."\n";
  1073.     // @codeCoverageIgnoreEnd
  1074.   }
  1075.  
  1076.   /**
  1077.    * Base64 encoding that doesn't need to be urlencode()ed.
  1078.    * Exactly the same as base64_encode except it uses
  1079.    *   - instead of +
  1080.    *   _ instead of /
  1081.    *
  1082.    * @param string $input base64UrlEncoded string
  1083.    * @return string
  1084.    */
  1085.   protected static function base64UrlDecode($input) {
  1086.     return base64_decode(strtr($input, '-_', '+/'));
  1087.   }
  1088.  
  1089.   /**
  1090.    * Destroy the current session
  1091.    */
  1092.   public function destroySession() {
  1093.     $this->setAccessToken(null);
  1094.     $this->user = 0;
  1095.     $this->clearAllPersistentData();
  1096.   }
  1097.  
  1098.   /**
  1099.    * Each of the following four methods should be overridden in
  1100.    * a concrete subclass, as they are in the provided Facebook class.
  1101.    * The Facebook class uses PHP sessions to provide a primitive
  1102.    * persistent store, but another subclass--one that you implement--
  1103.    * might use a database, memcache, or an in-memory cache.
  1104.    *
  1105.    * @see Facebook
  1106.    */
  1107.  
  1108.   /**
  1109.    * Stores the given ($key, $value) pair, so that future calls to
  1110.    * getPersistentData($key) return $value. This call may be in another request.
  1111.    *
  1112.    * @param string $key
  1113.    * @param array $value
  1114.    *
  1115.    * @return void
  1116.    */
  1117.   abstract protected function setPersistentData($key, $value);
  1118.  
  1119.   /**
  1120.    * Get the data for $key, persisted by BaseFacebook::setPersistentData()
  1121.    *
  1122.    * @param string $key The key of the data to retrieve
  1123.    * @param boolean $default The default value to return if $key is not found
  1124.    *
  1125.    * @return mixed
  1126.    */
  1127.   abstract protected function getPersistentData($key, $default = false);
  1128.  
  1129.   /**
  1130.    * Clear the data with $key from the persistent storage
  1131.    *
  1132.    * @param string $key
  1133.    * @return void
  1134.    */
  1135.   abstract protected function clearPersistentData($key);
  1136.  
  1137.   /**
  1138.    * Clear all data from the persistent storage
  1139.    *
  1140.    * @return void
  1141.    */
  1142.   abstract protected function clearAllPersistentData();
  1143. }