You are here

function fb_get_friends in Drupal for Facebook 6.3

Same name and namespace in other branches
  1. 5.2 fb.module \fb_get_friends()
  2. 5 fb.module \fb_get_friends()
  3. 6.2 fb.module \fb_get_friends()
  4. 7.3 fb.module \fb_get_friends()

A convenience method for returning a list of facebook friends.

This should work efficiently in canvas pages for finding friends of the current user.

@TODO - also support users who have permitted offline access.

@return: an array of facebook ids

3 calls to fb_get_friends()
fb_user_get_local_friends in ./fb_user.module
Returns local uids of friends of a given user.
fb_views_handler_author_is_friend::query in fb_views/fb_views_handler_author_is_friend.inc
fb_views_handler_filter_friends::query in fb_views/fb_views_handler_filter_friends.inc

File

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

Code

function fb_get_friends($fbu, $fb_app = NULL) {
  static $cache = array();
  if (!$fb_app) {
    $fb_app = $GLOBALS['_fb_app'];
  }

  // Facebook only allows us to query the current user's friends, so let's try
  // to log in as that user.  It will only actually work if they are the
  // current user of a canvas page, or they've signed up for an infinite
  // session.
  $fb = fb_api_init($fb_app, $fbu);
  if (!$fb || !$fbu) {
    return;
  }
  $items = array();
  if (!isset($cache[$fbu])) {
    if ($fb === $GLOBALS['_fb'] && $fbu == fb_facebook_user($fb)) {
      try {
        $items = fb_call_method($fb, 'friends.get', array(
          'uid' => $fbu,
        ));
        $cache[$fbu] = $items;
      } catch (Exception $e) {
        fb_log_exception($e, t('Failed call to friends.get'), $fb);
      }
    }

    // friends_get does not work in cron call, so we double check. @TODO - still needed?
    if (!$items || !count($items)) {
      $logged_in = fb_facebook_user($fb);
      $query = "SELECT uid2 FROM friend WHERE uid1={$fbu}";

      // FQL, no {curly_brackets}!
      try {
        $result = fb_call_method($fb, 'fql.query', array(
          'query' => $query,
        ));

        //dpm($result, "FQL " . $query); // debug
        if (is_array($result)) {
          foreach ($result as $data) {
            $items[] = $data['uid2'];
          }
        }

        // Facebook's API has the annoying habit of returning an item even if user
        // has no friends.  We need to clean that up.
        if (!$items[0]) {
          unset($items[0]);
        }
        $cache[$fbu] = $items;
      } catch (Exception $e) {
        fb_log_exception($e, t('Failed call to fql.query: !query', array(
          '!query' => $query,
        )), $fb);
      }
    }
  }
  if (isset($cache[$fbu])) {
    return $cache[$fbu];
  }
}