function user_badges_user_presave in User Badges 7
Same name and namespace in other branches
- 8 user_badges.module \user_badges_user_presave()
Implements hook_user_presave().
File
- ./
user_badges.module, line 314 - @brief User Badges module file
Code
function user_badges_user_presave(&$edit, $account, $category) {
if (!empty($edit['roles']) && !empty($account->uid)) {
// Badges only get assigned or removed when a user's role assignments are changed.
// Add authenticated users (code below only cares about array keys) to prevent badge deletion
$new_roles = $edit['roles'];
$new_roles[2] = 2;
// Get the list of role badges.
$roles = user_badges_get_roles();
$badges = user_badges_get_badges('select');
$message = user_access('manage badges');
// What are the added roles?
$added = array_diff(array_keys($new_roles), array_keys((array) $account->roles));
foreach ($added as $rid) {
// if this role has a badge
if (array_key_exists($rid, $roles) && !array_key_exists($roles[$rid], $account->badges_all)) {
$success = user_badges_user_add_badge($account->uid, $roles[$rid], 'role');
if ($success && $message) {
drupal_set_message(t('User assigned %name badge.', array(
'%name' => $badges[$roles[$rid]],
)));
}
}
}
// What are the removed roles?
$removed = array_diff(array_keys((array) $account->roles), array_keys($new_roles));
foreach ($removed as $rid) {
// If this role has a badge and user has this badge..
if (array_key_exists($rid, $roles) && array_key_exists($roles[$rid], $account->badges_all)) {
user_badges_user_remove_badge($account->uid, $roles[$rid], 'role');
drupal_set_message(t('%name badge removed from user.', array(
'%name' => $badges[$roles[$rid]],
)));
}
}
//As we may have altered the badges, we need to refresh them in the $account object
$account->badges = user_badges_get_badges($account->uid);
$account->badges_all = user_badges_get_badges($account->uid, array(
'nolimit' => TRUE,
));
}
}