You are here

function fb_get_token in Drupal for Facebook 6.3

Same name and namespace in other branches
  1. 7.3 fb.module \fb_get_token()

Helper to get the tokens needed to accss facebook's API.

You would think that facebook's SDK would provide basic functions like this.

Parameters

$fb: Get the token for this API instance. If NULL, use the global $_fb.

$fbu: Get the user-specific token. If NULL, get the application token.

20 calls to fb_get_token()
fb_admin_app_page in ./fb.admin.inc
fb_admin_get_app_info in ./fb.admin.inc
fb_admin_set_properties_form_submit in ./fb.admin.inc
Confirm form submit function. We don't use fb_app_set_app_properties, because fb_app.module may not be enabled.
fb_app_fb_admin in ./fb_app.admin.inc
Implementation of hook_fb_admin().
fb_app_set_app_properties in ./fb_app.admin.inc
Sets callback URLs and other properties of a facebook app. Calls the facebook

... See full list

File

./fb.module, line 561
This is the core required module of Drupal for Facebook.

Code

function fb_get_token($fb = NULL, $fbu = NULL) {
  static $cache;
  if (!isset($cache)) {
    $cache = array();
  }
  if (!$fb) {
    $fb = $GLOBALS['_fb'];
  }
  if (!$fb) {
    return;
  }
  $app_id = $fb
    ->getAppId();
  $cache_key = "fb_token_{$app_id}";
  if (!$fbu) {

    // Get the application token.
    if (empty($cache[$cache_key])) {

      // try Drupal cache
      $cache_obj = cache_get($cache_key);
      if ($cache_obj && $cache_obj->data) {
        $cache[$cache_key] = $cache_obj->data;
      }
    }
    if (empty($cache[$cache_key])) {

      // Query facebook for token.
      // http://developers.facebook.com/docs/authentication/applications/
      $path = "https://graph.facebook.com/oauth/access_token?client_id=" . $app_id . "&client_secret=" . $fb
        ->getApiSecret() . "&grant_type=client_credentials";
      $http = drupal_http_request($path);
      if ($http->code == 200 && isset($http->data)) {
        $data = explode('=', $http->data);
        $token = $data[1];
        if ($token) {
          $cache[$cache_key] = $token;
          $result = cache_set($cache_key, $token, 'cache', CACHE_TEMPORARY);
        }
      }
      if (!$token) {
        watchdog('fb', 'Failed to get application (%app_id) access token.', array(
          '%app_id' => $app_id,
        ), WATCHDOG_ERROR);
      }
    }
  }
  else {
    $cache_key .= '_' . $fbu;

    // Get the user access token.
    if ($fbu == 'me' || $fbu == fb_facebook_user($fb)) {
      $cache[$cache_key] = $fb
        ->getAccessToken();
    }
    else {
      $session_data = fb_invoke(FB_OP_GET_USER_SESSION, array(
        'fb' => $fb,
        'fb_app' => fb_get_app(array(
          'id' => $app_id,
        )),
        'fbu' => $fbu,
      ), array());
      if (count($session_data)) {
        $cache[$cache_key] = $session_data['access_token'];
      }
    }
  }
  return isset($cache[$cache_key]) ? $cache[$cache_key] : NULL;
}