You are here

function fb_username_alter in Drupal for Facebook 7.3

Same name and namespace in other branches
  1. 6.3 fb.module \fb_username_alter()
  2. 6.2 fb.module \fb_username_alter()
  3. 7.4 fb.module \fb_username_alter()

hook_username_alter().

Return a user's facebook name, instead of local username.

File

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

Code

function fb_username_alter(&$name, $account) {

  // This function can be called very early in the bootstrap process, before
  // the modules are initialized, in which case we will fail to alter the
  // name.
  $is_theming_username =& drupal_static('fb_theming_username');
  $enabled = variable_get(FB_VAR_ALTER_USERNAME, FB_ALTER_USERNAME_NOT_THEMING);
  if ($enabled == FB_ALTER_USERNAME_NEVER || $enabled == FB_ALTER_USERNAME_NOT_THEMING && $is_theming_username) {

    // Altering disabled.
    return;
  }

  // Skip on admin pages.
  if (arg(0) == 'admin') {
    return;
  }
  if (!strpos($name, '@facebook')) {

    // Only alter unique names created by fb_user.module.
    return;
  }
  if ($fbu = fb_get_fbu($account)) {

    // Querying names from facebook is expensive, so some trickery here to optimize things.
    // First we try the static cache.
    $names =& drupal_static(__FUNCTION__);
    if (!isset($names[$fbu])) {

      // Next try database cache.
      $use_cache = variable_get(FB_VAR_ALTER_USERNAME_AND_CACHE, FB_ALTER_USERNAME_DONT_CACHE);
      if ($use_cache == FB_ALTER_USERNAME_AND_CACHE) {
        if ($cache = cache_get('fb_username_' . $fbu)) {
          $names[$fbu] = $cache->data;
        }
      }
    }
    if (!isset($names[$fbu]) && !empty($GLOBALS['_fb'])) {

      // Nothing from the previous attempts worked so we have to query facebook.com.
      try {

        // Use fql query instead of graph api, because it will succeed more often.
        $data = fb_fql_query($GLOBALS['_fb'], "SELECT name FROM user WHERE uid={$fbu}", array(
          'access_token' => fb_get_token($GLOBALS['_fb']),
        ));
        if (count($data) && isset($data[0]['name'])) {
          $names[$fbu] = $data[0]['name'];
          if ($use_cache == FB_ALTER_USERNAME_AND_CACHE) {
            cache_set('fb_username_' . $fbu, $names[$fbu]);
          }
        }
      } catch (Exception $e) {
        fb_log_exception($e, t('Failed to alter username for facebook user %fbu', array(
          '%fbu' => $fbu,
        )));
      }
    }
    if (!empty($names[$fbu])) {
      $name = $names[$fbu];
    }
  }
}