manchumahara

WPbook wordpress plugin-Multiple facebook library load issue

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