function fb_username_alter in Drupal for Facebook 7.4
Same name and namespace in other branches
- 6.3 fb.module \fb_username_alter()
- 6.2 fb.module \fb_username_alter()
- 7.3 fb.module \fb_username_alter()
Return a user's facebook name, instead of local username. Drupal invokes this hook A LOT! So caching is important.
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.
File
- ./
fb.module, line 426
Code
function fb_username_alter(&$name, $account) {
$enabled = variable_get(FB_VAR_ALTER_USERNAME, FB_ALTER_USERNAME_ALWAYS);
if ($enabled == FB_ALTER_USERNAME_NEVER) {
// Altering disabled.
return;
}
// Skip on admin pages.
if (arg(0) == 'admin') {
return;
}
// First we try the static cache.
$names_cache =& drupal_static(__FUNCTION__);
if (isset($names_cache[$account->uid])) {
if (!empty($names_cache[$account->uid])) {
$name = $names_cache[$account->uid];
}
return;
}
if ($pos = strpos($name, '@facebook')) {
// Only alter unique names created by fb_user.module.
if ($fbu = substr($name, 0, $pos)) {
// Querying names from facebook is expensive, so try local cache first.
$cache_key = 'fb_username_' . $fbu;
$cache = cache_get($cache_key);
if ($cache && $cache->data) {
$names_cache[$account->uid] = $cache->data;
}
else {
// Nothing cached so we have to query facebook.com.
try {
$data = fb_graph($fbu);
// TODO token
$names_cache[$account->uid] = $data['name'];
if ($names_cache[$account->uid]) {
//cache_set($cache_key, $names_cache[$account->uid]);
}
} catch (Exception $e) {
fb_log_exception($e, t('Failed to alter username for facebook user %fbu', array(
'%fbu' => $fbu,
)));
$names_cache[$account->uid] = FALSE;
}
}
if (!empty($names_cache[$account->uid])) {
$name = $names_cache[$account->uid];
}
}
}
else {
$names_cache[$account->uid] = FALSE;
}
}