--- old\user_badges.module	2011-09-13 16:52:48.000000000 -0400
+++ new\user_badges.module	2011-10-25 00:15:07.406250000 -0400
@@ -16,21 +16,37 @@
  */
 
 /**
+ * Open code.
+ * Include code that is only needed if other modules are present.
+ */
+if (module_exists('token')) {
+  include_once(drupal_get_path('module', 'user_badges') . '/user_badges.tokens.inc');
+}
+
+// Add any other module that can initiate actions.
+if (module_exists('trigger') || module_exists('rules')) {
+  include_once(drupal_get_path('module', 'user_badges') . '/user_badges.actions.inc');
+}
+
+if (module_exists('autoassignrole')) {
+  include_once(drupal_get_path('module', 'user_badges') . '/user_badges.autoassignrole.inc');
+}
+
+/**
  * Implements hook_help().
  */
 function user_badges_help($path, $arg) {
   global $user;
   switch ($path) {
     case 'admin/modules#description':
+    case 'admin/people/user_badges':
+      return t('User badges are iconic images which can be assigned to users. They can represent accomplishments, status, or anything you\'d like. These badges will show up in the user\'s profile, and could also be used by a theme to appear with user postings on forums, comments, or nodes. Badges can be assigned manually by an administrator by visiting a user\'s profile. They also can be assigned automatically by role or ecommerce purchase (if ecommerce modules are installed). The excellent !link module can also be used to automatically set and unset badges on a wide variety of conditions.', array('!link' => l('Rules', 'http://drupal.org/project/rules', array('absolute' => TRUE))));
 
-    case 'admin/user/user_badges':
-      return t('User badges are iconic images which can be assigned to users. They can represent accomplishments, status, or anything you\'d like. These badges will show up in the user\'s profile, and could also be used by a theme to appear with user postings on forums, comments, or nodes. Badges can be assigned manually by an administrator by visiting a user\'s profile. They also can be assigned automatically by role or ecommerce purchase (if ecommerce modules are installed). The excellent !link module can also be used to set and unset badges on a wide variety of conditions.', array('!link' => l('Rules', 'http://drupal.org/project/rules', array('absolute' => TRUE))));
-
-    case 'admin/user/user_badges/roles':
+    case 'admin/people/user_badges/roles':
       return t("Select the badge that you'd like to associate with each role.");
 
-    case 'admin/user/user_badges/images':
-      return t("This is the user badges image library. Note that this area is not functional if you have private download active. Here you can upload images to display as a user badge, but you can also enter image URLs directly in the badge form, so this area is optional. The images can be anything you like, but it is recommended that you maintain a uniform icon size for all of your badges. Keep in mind that a user may have many badges displayed so you'll probably want to keep them as small as possible (like 16x16 pixels or smaller).");
+    case 'admin/people/user_badges/images':
+      return t("This is the user badges image library. Note that this area is not functional if you have private download active. Here you can upload images to display as a user badge, but you can also enter image URLs directly in the badge form, so this area is optional. The images can be anything you like, but it is recommended that you maintain a uniform image size (or use image styling) for all of your badges. Keep in mind that a user may have many badges displayed so you'll probably want to keep them as small as possible.");
 
     case 'user/%/badges':
     case 'user/%/badges/list':
@@ -38,7 +54,7 @@ function user_badges_help($path, $arg) {
       if (variable_get('user_badges_userweight', 0) && ($user->uid == $arg[1] || user_access('change badge assignments')) ) {
         // Help messages for users who can reorder.
         if ($showone) {
-          return t("You can reorder badges here. Some badges may not appear on the list; these badges cannot be reordered. Only the top !number badges will be shown publicly.", array('!number' => $showone));
+          return t("You can reorder badges here. Only the top !number badges will be shown publicly.", array('!number' => (int) $showone));
         }
         else {
           return t("You can reorder your badges here. Some badges may not appear on the list; these badges cannot be reordered.");
@@ -48,7 +64,6 @@ function user_badges_help($path, $arg) {
         // Either we don't support reordering, or this user lacks the permission to do it.
 //        return t("These are all the badges owned by this user.");
       }
-
   }
 }
 
@@ -57,19 +72,27 @@ function user_badges_help($path, $arg) {
  */
 function user_badges_permission() {
   return array(
+    'access user badges' => array(
+      'title' => t('access user badges'),
+      'description' => t('Display user badges to the user.'),
+      ),
     'manage badges' => array(
       'title' => t('manage badges'),
-      'description' => t('TODO Add a description for \'manage badges\''),
-    ),
+      'description' => t('Access the User Badges administration pages.'),
+      ),
     'change badge assignments' => array(
       'title' => t('change badge assignments'),
-      'description' => t('TODO Add a description for \'change badge assignments\''),
-    ),
-    'show badges in user profile' => array(
-      'title' => t('show badges in user profile'),
-      'description' => t('TODO Add a description for \'show badges in user profile\''),
-    ),
-  );
+      'description' => t('Access the "Badges" tab in user profiles.'),
+      ),
+    'change own badge assignments' => array(
+      'title' => t('change own badge assignments'),
+      'description' => t('Access the "Badges" tab in their own user profile.'),
+      ),
+    'suppress badges in user profile' => array(
+      'title' => t('Don\'t show badges in user profile'),
+      'description' => t('Don\'t show badges when viewing a user profile.'),
+      ),
+    );
 }
 
 /**
@@ -77,97 +100,105 @@ function user_badges_permission() {
  */
 function user_badges_menu() {
   $items = array();
-  $access = array('manage badges');
 
-  $items['admin/user/user_badges'] = array(
+  $items['admin/people/user_badges'] = array(
     'title' => 'Badges',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('user_badges_badgelist_form'),
-    'access arguments' => $access,
+    'access arguments' => array('manage badges'),
     'file' => 'user_badges.admin.inc',
-  );
+    );
 
-  $items['admin/user/user_badges/list'] = array(
+  $items['admin/people/user_badges/list'] = array(
     'title' => 'List',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('user_badges_badgelist_form'),
-    'access arguments' => $access,
+    'access arguments' => array('manage badges'),
     'type' => MENU_DEFAULT_LOCAL_TASK,
     'weight' => -10,
     'file' => 'user_badges.admin.inc',
-  );
+    );
 
-  $items['admin/user/user_badges/add'] = array(
+  $items['admin/people/user_badges/add'] = array(
     'title' => 'Add',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('user_badges_edit_form'),
-    'access arguments' => $access,
+    'access arguments' => array('manage badges'),
     'type' => MENU_LOCAL_TASK,
     'file' => 'user_badges.admin.inc',
-  );
+    );
 
-  $items['admin/user/user_badges/images'] = array(
+  $items['admin/people/user_badges/images'] = array(
     'title' => 'Images',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('user_badges_images_form'),
-    'access arguments' => $access,
+    'access arguments' => array('manage badges'),
     'type' => MENU_LOCAL_TASK,
     'file' => 'user_badges.admin.inc',
-  );
+    );
 
-  $items['admin/user/user_badges/roles'] = array(
+  $items['admin/people/user_badges/roles'] = array(
     'title' => 'Roles',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('user_badges_roles_form'),
-    'access arguments' => $access,
+    'access arguments' => array('manage badges'),
     'type' => MENU_LOCAL_TASK,
     'file' => 'user_badges.admin.inc',
-  );
+    );
 
-  $items['admin/user/user_badges/settings'] = array(
+  $items['admin/people/user_badges/settings'] = array(
     'title' => 'Settings',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('user_badges_settings_form'),
-    'access arguments' => $access,
+    'access arguments' => array('manage badges'),
     'type' => MENU_LOCAL_TASK,
     'file' => 'user_badges.admin.inc',
-  );
+    );
 
-  $items['admin/user/user_badges/edit/%'] = array(
+  $items['admin/people/user_badges/edit/%'] = array(
     'title' => 'Edit badge',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('user_badges_edit_form', 4),
-    'access arguments' => $access,
+    'access arguments' => array('manage badges'),
     'type' => MENU_CALLBACK,
     'file' => 'user_badges.admin.inc',
-  );
+    );
 
-  $items['admin/user/user_badges/delete/%'] = array(
+  $items['admin/people/user_badges/delete/%'] = array(
     'title' => 'Delete badge',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('user_badges_delete_form', 4),
-    'access arguments' => $access,
+    'access arguments' => array('manage badges'),
     'type' => MENU_CALLBACK,
     'file' => 'user_badges.admin.inc',
-  );
+    );
 
   $items['user/%/badges'] = array(
     'title' => 'Badges',
     'page callback' => 'user_badges_userweight_page',
     'page arguments' => array(1),
-    'access arguments' => array('show badges in user profile'),
+    'access arguments' => array('change badge assignments'),
     'type' => MENU_LOCAL_TASK,
     'weight' => 4,
-  );
+    );
 
   $items['user/%/badges/list'] = array(
     'title' => 'List',
     'page callback' => 'user_badges_userweight_page',
     'page arguments' => array(1),
-    'access arguments' => array('show badges in user profile'),
+    'access arguments' => array('change badge assignments'),
     'type' => MENU_DEFAULT_LOCAL_TASK,
     'weight' => -10,
-  );
+    );
+
+  $items['user/%/badges/whoelse'] = array(
+    'title' => 'Who Else',
+    'page callback' => 'user_badges_userweight_page',
+    'page arguments' => array(1),
+    'access arguments' => array('change badge assignments'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 0,
+    );
 
   $items['user/%/badges/edit'] = array(
     'title' => 'Edit',
@@ -176,61 +207,74 @@ function user_badges_menu() {
     'access arguments' => array('change badge assignments'),
     'type' => MENU_LOCAL_TASK,
     'weight' => 5,
-  );
+    );
+
+  // Menu item to allow a user to change their own badge assignments.
+  $items['user/%user/edit/badges'] = array(
+    'title' => 'Badges',
+    'page callback' => 'user_badges_page',
+    'page arguments' => array(1),
+    'access arguments' => array('change own badge assignments'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 5,
+    );
 
   $items['user_badges/autocomplete'] = array(
     'title' => 'User Badges Badge Name Autocomplete',
     'page callback' => 'user_badges_badge_autocomplete',
     'access callback' => TRUE,
     'type' => MENU_CALLBACK,
-  );
+    );
 
   return $items;
 }
 
 /**
  * Implements hook_user_load().
+ * Gets all badges for the user and the limited badges.
  */
 function user_badges_user_load($users) {
-  global $user;
-  
-  // Have we loaded this user before?
-  if (isset($badges[$user->uid])) {
-    $user->badges = $badges[$user->uid];
-    break;
-  }
-
-  $user->badges = array();
-
-  if ($user->uid > 0) {
-    // Get all user badges for this user, regardless of whether we filter the ones we show.
-    $user->badges_all = user_badges_get_badges($user->uid, array('nolimit' => TRUE));
-
-    // Now make the array of badges we will show.
-    $user->badges = $user->badges_all;
-    if ($limit = variable_get('user_badges_showone', 0)) {
-//  dsm("Limit: $limit, account->badges: ".print_r($account->badges, true));
-      // Loop through all potential badges and get the ones we can show.
-//          if ($account->badges_all) {
-      foreach ($user->badges_all as $bid => $badge) {
-        $badge->class = 'badge ' . _user_badges_class($badge);
-        // Display the badge if there's no limit or if the badge is unhideable or if we are within our limit.
-        if ($limit > 0 || $badge->unhideable == 1) {
-          $user->badges[$bid] = $badge;
-          // Count down our limit, unless the badge doesn't count towards it.
-          if (!$badge->doesnotcounttolimit) {
-            $limit--;
+  static $badges = array();
+
+  foreach ($users as $uid => $account) {
+    // Only handle authenticated users.
+    if ($uid > 0) {
+      // Have we loaded this user before?
+      if (isset($badges[$uid])) {
+        $users[$uid]->badges = $badges[$uid];
+      }
+
+      // Get all user badges for this user, regardless of
+      // whether we filter the ones we show.
+      // @TODO: Is this the right function to use? Certainly nolimit is wrong.
+      // @TODO: This also doesn't get role badges.
+      $badges_all = user_badges_get_badges($uid, array('nolimit' => TRUE));;
+      $users[$uid]->badges_all = $badges_all;
+      $users[$uid]->badges_count = count($badges_all);
+      $badges[$uid] = array();
+
+      // Display the badge if there's no limit
+      // or if the badge is unhideable
+      // or if we are within our limit.
+      if ($limit = variable_get('user_badges_showone', 0)) {
+        // Loop through all potential badges and get the ones we can show.
+        foreach ($badges_all as $bid => $badge) {
+          $badge->class = "badge  badge-$bid " . _user_badges_class($badge);
+          if ($limit > 0 || $badge->unhideable == 1) {
+            $badges[$uid][$bid] = $badge;
+            // Count down our limit, unless the badge doesn't count towards it.
+            if (!$badge->doesnotcounttolimit) {
+              $limit--;
+            }
           }
         }
+        $users[$uid]->badges = $badges[$uid];
+      }
+      else {
+        $users[$uid]->badges = $badges_all;
       }
-//          }
     }
-//        else {
-//          $account->badges = $account->badges_all;
-//        }
   }
-
-  $badges[$user->uid] = $user->badges;
 }
 
 /**
@@ -248,6 +292,7 @@ function user_badges_user_insert(&$edit,
       if (key_exists($rid, $roles)) {
         // and user doesn't already have this badge.
         if (!key_exists($roles[$rid], $account->badges)) {
+     // @TODO: Stop this nonsense and user role badges separately.
           $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]])));
@@ -305,47 +350,45 @@ function user_badges_user_presave(&$edit
 /**
  * Implements hook_user_cancel().
  */
+// @TODO: hook_user_delete - let them keep the badges until then.
 function user_badges_user_cancel($edit, $account, $method) {
-  // TODO Please review the conversion of this statement to the D7 database API syntax.
-  /* db_query('DELETE FROM {user_badges_user} WHERE uid = %d', $account->uid) */
   db_delete('user_badges_user')
-  ->condition('uid', $account->uid)
-  ->execute();
+    ->condition('uid', $account->uid)
+    ->execute();
 }
 
 /**
  * Implements hook_user_view().
  */
 function user_badges_user_view($account, $view_mode) {
-  if (isset($account->badges) && is_array($account->badges) && count($account->badges)) {
+  // Check if the user's badges are to be shown.
+  if ($account->uid > 1 && user_access('suppress badges in user profile', $account)) {
+    return;
+  }
+
+  if (isset($account->badges) && count($account->badges)) {
     $badgeimgs = array();
     foreach ($account->badges as $badge) {
       $badgeimgs[] = theme('user_badge', array('badge' => $badge, 'account' => $account));
     }
+
+    // @TODO: Show role badges separately?
     $account->content['user_badges'] = array(
-      '#type' => 'user_profile_category',
       '#title' => t('Badges'),
-      '#weight' => 10,
-      '#attributes' => array('class' => 'user-badges'),
-    );
-    $account->content['user_badges']['badges'] = array(
       '#type' => 'user_profile_item',
-      '#value' => theme('user_badge_group', array('badgeimages' => $badgeimgs)),
-      '#attributes' => array('class' => 'badges'),
-    );
+      '#markup' => theme('user_badge_group', array('badgeimages' => $badgeimgs)),
+      '#attributes' => array('class' => array('badges')),
+      );
+  }
+  else {
+    // They don't have any badges, so show the "no badges" message.
+    $account->content['user_badges'] = array(
+      '#title' => t('Badges'),
+      '#type' => 'user_profile_item',
+      '#markup' => variable_get('user_badges_nobadges', ''),
+      '#attributes' => array('class' => array('badges')),
+      );
   }
-}
-
-/**
- * Implements hook_user().
- *
- * This handles assignment of badges based on role.
- * When a role is assigned or removed, appropriate badges are added or removed.
- */
-function user_badges_user_OLD($op, &$edit, &$account, $category = 'account') {
-  // TODO Remaining code in this function needs to be moved to the appropriate new hook function.
-  global $user;
-  static $badges = array();
 }
 
 /**
@@ -358,12 +401,15 @@ function user_badges_user_OLD($op, &$edi
 function _user_badges_class($badge) {
   // Doing separate lines makes changing the algorithm easier.
   $class = $badge->name;
+  // Make it 'safe.'
   $class = strip_tags($class, '');
+  // Lower case.
   $class = drupal_strtolower($class);
+  // Remove quotes.
   $class = str_replace(array('"', "'"), '', $class);
+  // Change underscores and spaces to dashes.
   $class = str_replace(array('_', ' '), '-', $class);
 
-//  dsm("_user_badges_class: badge->name = $badge->name becomes $class.");
   return $class;
 }
 
@@ -388,7 +434,7 @@ function user_badges_theme() {
 }
 
 /**
- * form for users to weight their own badges
+ * Form for users to weight their own badges.
  */
 function user_badges_userweight_form($form, $form_state, $account) {
   $allbadges = $account->badges_all;
@@ -405,6 +451,7 @@ function user_badges_userweight_form($fo
 
   // We need to know what the weight delta will be, which depends on the number
   // of badges we will list.
+  $delta = 1;
   foreach ($allbadges as $badge) {
     if (!$badge->fixedweight) {
       $delta++;
@@ -412,6 +459,7 @@ function user_badges_userweight_form($fo
   }
 
   // Build a table listing the appropriate badges.
+  $vars = array('account' => $account);
   foreach ($allbadges as $badge) {
     // We cannot include fixed weight badges.
     if ($badge->fixedweight) {
@@ -424,14 +472,16 @@ function user_badges_userweight_form($fo
       $weight = $badge->userweight;
     }
 
-    $form['name'][$badge->bid] = array('#value' => check_plain($badge->name));
-    $form['badge'][$badge->bid] = array('#value' => theme('user_badge', array('badge' => $badge, 'account' => $account)));
+    $form['name'][$badge->bid] = array('#markup' => check_plain($badge->name));
+    $vars['badge'] = $badge;
+    $form['badge'][$badge->bid] = array('#markup' => theme('user_badge', $vars));
 
     $form['weight'][$badge->bid] = array(
       '#type' => 'weight',
       '#default_value' => $weight,
       '#delta' => $delta,
-      '#attributes' => array('class' => 'user_badges_userweight_element'),
+      '#tree' => TRUE,
+      '#attributes' => array('class' => array('user_badges_userweight_element')),
     );
   }
 
@@ -442,7 +492,7 @@ function user_badges_userweight_form($fo
 
   $form['submit'] = array(
     '#type' => 'submit',
-    '#value' => t('Submit'),
+    '#value' => t('Save configuration'),
   );
 
 
@@ -478,7 +528,7 @@ function theme_user_badges_userweight_fo
   $form = $variables['form'];
   $output = '';
 
-  //Loop through the array items in the name array to get all the bids for our listed badges
+  // Loop through the array items in the name array to get all the bids for our listed badges.
   if (isset($form['name']) && is_array($form['name'])) {
     foreach (element_children($form['name']) as $key) {
       //We only want bids as values of $key
@@ -486,7 +536,7 @@ function theme_user_badges_userweight_fo
         continue;
       }
 
-      //Create the rows array for the table theme
+      // Create the rows array for the table theme.
       $row = array();
       $row[] = drupal_render($form['name'][$key]);
       $row[] = drupal_render($form['badge'][$key]);
@@ -494,15 +544,15 @@ function theme_user_badges_userweight_fo
       //Add the draggable class to this row
       $rows[] = array(
         'data' => $row,
-        'class' => 'draggable',
+        'class' => array('draggable'),
         '#weight' => $form['weight'][$key]['#value'],
       );
     }
 
-    //Sort the rows by their weights
+    // Sort the rows by their weights.
     usort($rows, 'element_sort');
 
-    //Add the submit button
+    // Add the submit button.
     $row = array();
     $row[] = '';
     $row[] = drupal_render($form['submit']);
@@ -517,13 +567,18 @@ function theme_user_badges_userweight_fo
       ));
   }
 
-  //This makes the table draggable
+  // This makes the table draggable.
   drupal_add_tabledrag('user_badges_userweight', 'order', 'sibling', 'user_badges_userweight_element');
 
-  //Theme all that we have processed so far into a table
-  $output .= theme('table', array('header' => $form['header']['#value'], 'rows' => $rows, 'attributes' => array('id' => 'user_badges_userweight')));
+  // Theme all that we have processed so far into a table.
+  $output .= theme('table',
+    array('header' => $form['header']['#value'],
+      'rows' => $rows,
+      'attributes' => array('id' => 'user_badges_userweight'),
+      )
+    );
 
-  //Render any remaining form elements
+  // Render any remaining form elements.
   $output .= drupal_render_children($form);
 
   return $output;
@@ -538,16 +593,18 @@ function user_badges_badge_autocomplete(
 
   if (preg_match('/^[^(]+/', $string, $searchstring)) {
     $trimstring = trim($searchstring[0]);
-    
+
     $result = db_select('user_badges_badges', 'ubb')
-      -> fields('ubb')
+      -> fields('ubb', array('bid', 'name'))
       -> condition('name', '%' . db_like($trimstring) . '%', 'LIKE')
+      -> orderBy(array('weight', 'name'))
       -> extend('PagerDefault')
       -> limit(5)
       -> execute();
 
-    foreach ($result as $badge) {          
-      $matches[$badge->name . ' (' . t('Badge ID') . ' ' . $badge->bid . ')'] = check_plain($badge->name) . ' ' . theme('user_badge', array('badge' => $badge));
+    foreach ($result as $badge) {
+      $matches[$badge->name . ' (' . t('Badge ID') . ' ' . $badge->bid . ')'] =
+        check_plain($badge->name) . ' ' . theme('user_badge', array('badge' => $badge));
     }
   }
 
@@ -571,7 +628,7 @@ function user_badges_badge_autocomplete(
  */
 function user_badges_badge_autocomplete_validation($value) {
   if (preg_match('/\(' . t('Badge ID') . ' (\d+)\)/', $value, $matches)) {
-    //The format was correct, but we need to check the bid exists    
+    //The format was correct, but we need to check the bid exists
     $bid = $matches[1];
     $records = db_select('user_badges_badges', 'ubb')
       -> fields('ubb')
@@ -593,15 +650,20 @@ function user_badges_badge_autocomplete_
   }
 }
 
-
 /**
- * Define the page on user/uid/badges/edit.
+ * Define the page on user/uid/badges/edit
+ * and user/%user/edit/badges.
+ *
+ * Note: menu system passes user/% as integer,
+ * but user/%user as an object (with badges).
  */
 function user_badges_page($uid) {
-  // TODO Convert "user_load" to "user_load_multiple" if "$uid" is other than a uid.
-  // To return a single user object, wrap "user_load_multiple" with "array_shift" or equivalent.
-  // Example: array_shift(user_load_multiple(array(), $uid))
-  $account = user_load($uid);
+  if (is_object($uid)) {
+    $account = $uid;
+  }
+  else {
+    $account = array_shift(user_load_multiple(array($uid)));
+  }
 
   drupal_set_title(t('Edit badges for %user_name', array('%user_name' => $account->name)), PASS_THROUGH);
 
@@ -613,12 +675,10 @@ function user_badges_page($uid) {
  * Define the page on user/uid/badges.
  */
 function user_badges_userweight_page($uid) {
-  // TODO Convert "user_load" to "user_load_multiple" if "$uid" is other than a uid.
-  // To return a single user object, wrap "user_load_multiple" with "array_shift" or equivalent.
-  // Example: array_shift(user_load_multiple(array(), $uid))
-  $account = user_load($uid);
+  global $user;
+  $account = array_shift(user_load_multiple(array($uid)));
 
-  drupal_set_title(t('Badges for %user_name', array('%user_name' => $account->name)), PASS_THROUGH);
+  drupal_set_title(t('Badges for %user_name', array('%user_name' => format_username($account))), PASS_THROUGH);
 
   // Do we have the right to rearrange badges?
   if (variable_get('user_badges_userweight', 0) && ($account->uid == $user->uid || user_access('change badge assignments')) ) {
@@ -626,21 +686,43 @@ function user_badges_userweight_page($ui
     return drupal_get_form('user_badges_userweight_form', $account);
   }
   else {
+    $whoelse = arg(3) == 'whoelse';
     // Otherwise, just list the badges on the page.
     $user_badges = user_badges_get_badges($account->uid, array('nolimit' => TRUE));
     $badges = array();
-    foreach ((array) $user_badges as $badge) {
-      $badges[] = theme('user_badge', array('badge' => $badge, 'account' => $account));
+
+    foreach ($user_badges as $badge) {
+      $item = array(theme('user_badge', array('badge' => $badge, 'account' => $account)),
+        array('data' => check_plain($badge->name), 'class' => 'user-badge-name'));
+      if ($whoelse) {
+        $query = db_select('user_badges_user', 'ubu')
+          ->condition('ubu.bid', $badge->bid, '=')
+          ->condition('ubu.uid', $account->uid, '<>')
+          ;
+        $u = $query->join('users', 'u', 'u.uid=ubu.uid');
+        $query->fields($u);
+        $result = $query->execute();
+        $accts = array();
+        foreach ($result as $acct) {
+          // This allows other username functions to intercede.
+          $accts[] = format_username($acct);
+        }
+        if (!$accts) {
+          $accts[] = t('None');
+        }
+        $item[] = array('data' => theme('item_list', array('items' => $accts)), 'class' => 'user-badges-whoelse');
+      }
+      $badges[] = $item;
     }
+
     if ($badges) {
-      $badges = array(theme('item_list', array('items' => $badges)));
+      $badges = array(theme('table', array('rows' => $badges, 'attributes' => array('style' => 'width: auto;'))));
       return theme('user_badge_group', array('badgeimages' => $badges));
     }
     else {
       return t('This user is not currently assigned any badges.');
     }
   }
-
 }
 
 /**
@@ -653,6 +735,7 @@ function user_badges_change_form($form, 
     '#type' => 'value',
     '#value' => $account->uid,
   );
+
   $form['add'] = array(
     '#type' => 'fieldset',
     '#title' => t('Add Badges'),
@@ -660,15 +743,17 @@ function user_badges_change_form($form, 
     '#collapsible' => TRUE,
     '#collapsed' => FALSE,
   );
+
   for ($i = 1; $i <= 5; $i++) {
     $form['add']['add' . $i] = array(
       '#type' => 'textfield',
-      '#title' => t('New Badge !number', array('!number' => $i)),
+      '#title' => t('New Badge @number', array('@number' => $i)),
       '#size' => 40,
       '#maxlength' => 255,
       '#autocomplete_path' => 'user_badges/autocomplete',
     );
   }
+
   if (isset($account->badges_all) && count($account->badges_all)) {
     $form['remove'] = array(
       '#type' => 'fieldset',
@@ -677,6 +762,7 @@ function user_badges_change_form($form, 
       '#collapsible' => TRUE,
       '#collapsed' => FALSE,
     );
+
     foreach ($account->badges_all as $badge) {
       $form['remove'][$badge->bid] = array(
         '#type' => 'checkbox',
@@ -716,7 +802,7 @@ function user_badges_change_form_validat
 }
 
 /**
- * Process user_badges_remove_form form submissions.
+ * Process user_badges_change_form form submissions.
  *
  * Add the named badge. Remove the checked badges.
  */
@@ -742,9 +828,15 @@ function user_badges_change_form_submit(
     foreach ($badges_to_go as $bid) {
       user_badges_user_remove_badge($uid, $bid);
     }
-    drupal_set_message(t('!removalcount badge(s) removed.', array('!removalcount' => count($badges_to_go))));
+    drupal_set_message(t('@removalcount badge(s) removed.', array('@removalcount' => count($badges_to_go))));
   }
 
+  if (arg(2) == 'edit') {
+    $form_state['redirect'] = "user/$uid";  // My account.
+  }
+  else {
+    $form_state['redirect'] = "user/$uid/badges";  // Full admin UI.
+  }
 }
 
 /**
@@ -758,7 +850,7 @@ function user_badges_user_save($edit, $u
   $badges = user_badges_get_badges($uid);
 
   if (is_array($edit)) {
-    // an array of just the checked boxes please
+    // An array of just the checked boxes please.
     $newbadges = array();
     foreach ($edit as $bid => $is_selected) {
       if ($is_selected) {
@@ -768,7 +860,7 @@ function user_badges_user_save($edit, $u
 
     $success = TRUE;
 
-    // what are the added badges?
+    // What are the added badges?
     $added = array_diff($newbadges, array_keys($badges));
 
     foreach ($added as $bid) {
@@ -829,25 +921,20 @@ function user_badges_user_add_badge($uid
  */
 function user_badges_user_remove_badge($uid, $bid, $type = NULL) {
   if (is_null($type)) {
-    // TODO Please review the conversion of this statement to the D7 database API syntax.
-    /* db_query('DELETE FROM {user_badges_user} WHERE uid=%d AND bid=%d', $uid, $bid) */
     return db_delete('user_badges_user')
-  ->condition('uid', $uid)
-  ->condition('bid', $bid)
-  ->execute();
+      ->condition('uid', $uid)
+      ->condition('bid', $bid)
+      ->execute();
   }
   else {
-    // TODO Please review the conversion of this statement to the D7 database API syntax.
-    /* db_query('DELETE FROM {user_badges_user} WHERE uid=%d AND bid=%d AND type=\'%s\'', $uid, $bid, $type) */
     return db_delete('user_badges_user')
-  ->condition('uid', $uid)
-  ->condition('bid', $bid)
-  ->condition('type', $type)
-  ->execute();
+      ->condition('uid', $uid)
+      ->condition('bid', $bid)
+      ->condition('type', $type)
+      ->execute();
   }
 }
 
-
 /**
  * Return array of user badges where keys are badge ids (bid)
  *   and values are object containing badge info.
@@ -862,6 +949,9 @@ function user_badges_user_remove_badge($
 function user_badges_get_badges($uid, $options = array()) {
   static $badges = array(), $past_uid, $past_options;
 
+  $defaults = array('nolimit' => FALSE);
+  $options = array_merge($defaults, $options);
+
   if (isset($badges[$uid])) {
     return $badges[$uid];
   }
@@ -890,7 +980,7 @@ function user_badges_get_badges($uid, $o
           WHERE u.uid = :uid AND r.rid = :rid
           ORDER BY coalescedweight, b.name', array(':uid' => $uid, ':rid' => 0));
       }
-      else {        
+      else {
         $sql = db_query('SELECT DISTINCT b.bid, b.weight, b.name, b.image, b.href,
           b.unhideable, b.fixedweight, b.doesnotcounttolimit, u.userweight, b.tid,
           CASE WHEN b.fixedweight = 1 THEN b.weight ELSE COALESCE(u.userweight,b.weight) END coalescedweight
@@ -911,8 +1001,8 @@ function user_badges_get_badges($uid, $o
       // Set to -1 for no limit.
       $limit = -1;
     }
-  
-    foreach ($sql as $badge) {          
+
+    foreach ($sql as $badge) {
       // Display the badge if there's no limit or if the badge is unhideable or if we are within our limit.
       if ($limit != 0 || $badge->unhideable == 1) {
         if ($uid == 'select') {
@@ -934,19 +1024,18 @@ function user_badges_get_badges($uid, $o
   return $badges[$uid];
 }
 
-
 /**
  * Return badge object for given badge id
  */
 function user_badges_get_badge($bid) {
-  return db_fetch_object(db_query('SELECT * FROM {user_badges_badges} WHERE bid = :bid', array(':bid' => $bid)));
+  return db_select('user_badges_badges', 'ubb')
+    ->fields('ubb')
+    ->execute()
+    ->fetchObject();
 }
 
-
-
 /**
- * @todo Please document this function.
- * @see http://drupal.org/node/1354
+ * User badge deletion form.
  */
 function user_badges_delete_form($form, $form_state, $bid) {
   if ($badge = user_badges_get_badge($bid)) {
@@ -956,66 +1045,57 @@ function user_badges_delete_form($form, 
       '#type' => 'value',
       '#value' => $bid,
     );
-    return confirm_form($form, t('Are you sure you want to delete the badge %name?', array('%name' => $badge->name)), 'admin/user/user_badges');
+    return confirm_form($form, t('Are you sure you want to delete the badge %name?', array('%name' => $badge->name)), 'admin/people/user_badges');
   }
   form_set_error('', t('This badge does not exist.'));
 }
 
 /**
- * @todo Please document this function.
- * @see http://drupal.org/node/1354
+ * Submit handler for user badge deletion.
  */
 function user_badges_delete_form_submit($form, &$form_state) {
   $bid = $form_state['values']['bid'];
-  // TODO Please review the conversion of this statement to the D7 database API syntax.
-  /* db_query("DELETE FROM {user_badges_badges} WHERE bid = %d", $bid) */
+
   db_delete('user_badges_badges')
-  ->condition('bid', $bid)
-  ->execute();
-  // TODO Please review the conversion of this statement to the D7 database API syntax.
-  /* db_query("DELETE FROM {user_badges_user} WHERE bid = %d", $bid) */
+    ->condition('bid', $bid)
+    ->execute();
+
   db_delete('user_badges_user')
-  ->condition('bid', $bid)
-  ->execute();
-  // TODO Please review the conversion of this statement to the D7 database API syntax.
-  /* db_query("DELETE FROM {user_badges_roles} WHERE bid = %d", $bid) */
+    ->condition('bid', $bid)
+    ->execute();
+
   db_delete('user_badges_roles')
-  ->condition('bid', $bid)
-  ->execute();
+    ->condition('bid', $bid)
+    ->execute();
   drupal_set_message(t('Badge deleted.'));
-  $form_state['redirect'] = 'admin/user/user_badges';
+  $form_state['redirect'] = 'admin/people/user_badges';
 }
 
-
 /**
- * Returns an array where keys are role ids (rid) and values are the badge ids (bid) associated with that role
- * These values are assigned on admin/user/user_badges/roles
+ * Returns an array where keys are role ids (rid) and values are the
+ * badge ids (bid) associated with that role
+ * These values are assigned on admin/people/user_badges/roles
  *
  * @param $rid - if set, return only values for this role
  *
  * @param $options - array of options
  * $options['returnbadges'] - if TRUE, return badge objects, not just bids
  *
- * @return a list of roles
+ * @return a list of roles pt the whole badge object.
  */
 function user_badges_get_roles($rid = NULL, $options = array()) {
   $roles = array();
-  $options = array_merge(array('returnbadges' => 'FALSE'), $options);
+  $options = array_merge(array('returnbadges' => FALSE), $options);
 
-  $query = db_select('user_badges_roles', 'ubr')    
-    -> fields('ubr', array('rid', 'bid'))  
-    -> fields('ubb', array('name', 'image', 'weight', 'href', 'tid'));
-    
   if ($rid) {
-    $query -> condition('ubr.rid', $rid);
+    $records = db_query("SELECT ubr.rid, ubb.* FROM {user_badges_roles} ubr INNER JOIN {user_badges_badges} ubb ON ubb.bid = ubr.bid WHERE ubr.rid = :rid ", array(':rid' => $rid));
+  }
+  else {
+    $records = db_query("SELECT ubr.rid, ubb.* FROM {user_badges_roles} ubr INNER JOIN {user_badges_badges} ubb ON ubb.bid = ubr.bid ");
   }
-    
-  $alias = $query -> join('user_badges_badges', 'ubb', 'ubr.bid = ubb.bid');
-  $records = $query -> execute();
 
-  foreach ($records as $row) {      
+  foreach ($records as $row) {
     if ($options['returnbadges']) {
-      $row->image = _user_badges_build_image($row);
       $roles[$row->rid] = $row;
     }
     else {
@@ -1032,13 +1112,16 @@ function user_badges_get_roles($rid = NU
  *   An array in the format rid => bid for each role/badge relationship.
  */
 function user_badges_save_roles($roles) {
+  // @TODO: I (Nancy) think this is all wrong.
+  // user_badges_for_uid can easily pick stuff up by the user's roles.
+  // Otherwise, we can have stale data in the user table.
   if (is_array($roles)) {
     // We have to clear out all badges first.
     $success = TRUE;
 
     db_delete('user_badges_roles')
       ->execute();
-    
+
     db_delete('user_badges_user')
       ->condition('type', 'role')
       ->execute();
@@ -1048,22 +1131,46 @@ function user_badges_save_roles($roles) 
     foreach ($roles as $rid => $bid) {
       if ($bid) {
         // First of all, insert all the role and badge relationship
-        // into user_badges_roles.  
+        // into user_badges_roles.
         $id = db_insert('user_badges_roles')
           ->fields(array(
-              'rid' => $rid, 
-              'bid' => $bid,
+            'rid' => $rid,
+            'bid' => $bid,
             ))
           ->execute();
-        $success = $success && $id;
+        $success = $success && !empty($id);
 
         // For all of these queries, we LEFT JOIN user_badges_user to check
         // whether there are existing entries for that badge for that user
         // of the "role" type. Otherwise, we get database errors when
-        // multiple roles assign the same badge
+        // multiple roles assign the same badge.
+
+        // @TODO: rid>2 is a different query: user_roles vs users.
+        $query = db_select('users', 'u')
+          ->fields('u', array('uid'))
+          ->condition('u.status', 0)
+          ->condition('ubu.bid', $bid)
+          ->isNull('ubu.uid')
+          ;
+        if ($rid > 2) {
+          $query->condition();
+        }
+        $query->leftJoin('user_badges_user', 'ubu', "ubu.uid=u.uid AND ubu.type='role'");
+        $uid = $query->execute()->fetchCol();
+        /*
+        $uid = db_query("
+          SELECT u.uid
+            FROM {users} u
+            LEFT JOIN {user_badges_user} ubu
+            ON ubu.uid=u.uid AND ubu.bid=:bid AND ubu.type='role'
+            WHERE status = 0 AND ubu.uid IS NULL
+            ", array(':bid' => $bid))->fetchCol();  /* */
+//          dsm('user '.print_r($uid, true));
 
         // The blocked user "role" (represented as rid 0) has no entry in
         // the users_role table, so it needs its own special query.
+
+        // @TODO: fix these queries.
         if ($rid == 0) {
           $success = $success && db_query("
             INSERT INTO {user_badges_user} (uid, bid, type)
@@ -1088,6 +1195,10 @@ function user_badges_save_roles($roles) 
         }
         // For all the normal roles, we want to run this query.
         else {
+          $insert = db_insert('user_badges_user')
+            ->fields(array('uid' => $uid, 'bid' => $bid, 'rid' => $rid))
+            ->execute();
+/*
           $success = $success && db_query("
             INSERT INTO {user_badges_user} (uid, bid, type)
             SELECT ur.uid, %d, 'role'
@@ -1095,7 +1206,7 @@ function user_badges_save_roles($roles) 
             LEFT JOIN {user_badges_user} ubu
             ON ubu.uid=ur.uid AND ubu.bid=%d AND ubu.type='role'
             WHERE ur.rid=%d AND ubu.uid IS NULL
-          ", $bid, $bid, $rid);
+          ", $bid, $bid, $rid); /* */
         }
       }
     }
@@ -1122,12 +1233,19 @@ function user_badges_for_uid($uid, $refr
       return $cache[$uid];
     }
     else {
+      // TODO: User can also have role badges.
       $user_badges = user_badges_get_badges($uid);
-      foreach ((array) $user_badges as $badge) {
-        // TODO Convert "user_load" to "user_load_multiple" if "$uid" is other than a uid.
-        // To return a single user object, wrap "user_load_multiple" with "array_shift" or equivalent.
-        // Example: array_shift(user_load_multiple(array(), $uid))
-        $badges[] = theme('user_badge', array('badge' => $badge, 'account' => user_load($uid)));
+
+      $account = array_shift(user_load_multiple(array($uid)));
+
+      foreach ($account->roles as $rid => $role_name) {
+        $rb = user_badges_get_roles($rid, array('returnbadges' => TRUE));
+        foreach ($rb as $rid => $b) {
+          $user_badges[$b->bid] = $b;
+        }
+      }
+      foreach ($user_badges as $badge) {
+        $badges[] = theme('user_badge', array('badge' => $badge, 'account' => $account));
       }
       $cache[$uid] = isset($badges) ? theme('user_badge_group', array('badgeimages' => $badges)) : '';
       return $cache[$uid];
@@ -1137,39 +1255,48 @@ function user_badges_for_uid($uid, $refr
 
 /**
  * Get all user badges for a user.
- * @param $load is array defining criteria for user_load().
- *   The most common use will be:
- *   user_badges_for_user(array('uid'=>123));
+ * @param $uid is user id.
+ * @param $list - boolean to return an item_list (unordered).
+ *
  * @return string containing HTML representation of user badges for given user.
  */
-function user_badges_for_user($load, $list = FALSE) {
-  // @TODO: cache the results to minimize queries.
-  // TODO Convert "user_load" to "user_load_multiple" if "$load" is other than a uid.
-  // To return a single user object, wrap "user_load_multiple" with "array_shift" or equivalent.
-  // Example: array_shift(user_load_multiple(array(), $load))
-  $account = user_load($load);
+function user_badges_for_user($uid, $list = FALSE) {
+  static $save = array(0 => FALSE);
+
+  if (isset($save[$uid])) {
+    return $save[$uid];
+  }
 
-  foreach ((array) $account->badges as $badge) {
+  $account = array_shift(user_load_multiple(array($uid)));
+
+  $badges = array();
+  foreach ($account->badges as $badge) {
     $badges[] = theme('user_badge', array('badge' => $badge, 'account' => $account));
   }
 
   if ($list) {
     $badges = array(theme('item_list', array('items' => $badges)));
+    $save[$uid] = $badges;
+    return $badges;
   }
 
   if ($badges) {
-    return theme('user_badge_group', array('badgeimages' => $badges));
+    $save[$uid] = theme('user_badge_group', array('badgeimages' => $badges));
   }
   else {
     // Do we have a "no badges" message?
     if ($nobadges = variable_get('user_badges_nobadges', '')) {
-      $nobadges = '<div class="user_badges_no_badges">' . filter_xss_admin(t($nobadges)) . '</div>';
-      return theme('user_badge_group', array('badgeimages' => array($nobadges)));
+      $nobadges = array('<div class="user_badges_no_badges">'
+        . filter_xss_admin(t($nobadges))
+        . '</div>');
+      $save[$uid] = theme('user_badge_group', array('badgeimages' => $nobadges));
     }
     else {
-      return FALSE;
+      $save[$uid] = FALSE;
     }
   }
+
+  return $save[$uid];
 }
 
 /**
@@ -1187,24 +1314,22 @@ function theme_user_badge_group($variabl
  * Helper function to produce badge image.
  */
 function _user_badges_build_image($badge) {
+  $style_name = variable_get('user_badges_imagecache', '');
+  $alt = check_plain($badge->name);
+
   if (!isset($badge->class)) {
     $badge->class = 'badge ' . _user_badges_class($badge);
   }
 
-  if (variable_get('user_badges_imagecache', 0)) {
-    // TODO Please change this theme call to use an associative array for the $variables parameter.
-    $image = theme('imagecache', 'user-badges', $badge->image, $badge->name, $badge->name, array('class' => $badge->class));    
-  }
-  else {
-    // If we have a full image URL, don't require theme_image to get the size
-    // (it only breaks).
-    if ($get_size = valid_url($badge->image, TRUE)) {
-      $image = theme('image', array('path' => $badge->image, 'width' => $badge->name, 'height' => $badge->name, 'alt' => array('class' => $badge->class), 'title' => !$get_size));
-    }
-    else {
-      $image = theme('image', array('path' => 'public://badges/' . $badge->image, 'width' => $badge->name, 'height' => $badge->name, 'alt' => array('class' => $badge->class), 'title' => !$get_size)); 
-    }
-  }
+  $variables = array(
+    'style_name' => $style_name,
+    'path' => $badge->image,
+    'alt' => $alt,
+    'title' => $alt,
+    'attributes' => array('class' => $badge->class),
+    );
+  $theme = $style_name ? 'image_style' : 'image';
+  $image = theme($theme, $variables);
 
   return $image;
 }
@@ -1216,22 +1341,22 @@ function _user_badges_build_image($badge
 function theme_user_badge($variables) {
   $badge = $variables['badge'];
   $account = $variables['account'];
-  //If we haven't been supplied with a user, use whoever is logged in
+  // If we haven't been supplied with a user, use whoever is logged in
   global $user;
   if (is_null($account)) {
     $account = $user;
   }
 
   if (!isset($badge->class)) {
-    $badge->class = 'badge ' . _user_badges_class($badge);
+    $badge->class = "badge badge-$badge->bid " . _user_badges_class($badge);
   }
 
   $image = _user_badges_build_image($badge);
 
   // We don't link the badge if there is no link and no default,
   // or if the default is overridden.
-  if (($badge->href == "" && !variable_get('user_badges_defaulthref', ''))
-     || drupal_strtolower($badge->href) == '<none>') {
+  if (($badge->href == '' && !variable_get('user_badges_defaulthref', ''))
+    || drupal_strtolower($badge->href) == '<none>') {
     return $image;
   }
   else {
@@ -1239,7 +1364,7 @@ function theme_user_badge($variables) {
 
     // Implement token replacement.
     if (module_exists('token')) {
-      $href = token_replace($href, array('userbadge' => $badge, 'user' => $account));      
+//      $href = token_replace($href, array('userbadge' => $badge, 'user' => $account));
     }
 
     $pieces = parse_url($href);
@@ -1262,197 +1387,27 @@ function user_badges_views_api() {
 }
 
 /**
- * Implements hook_action_info().
+ * Implements hook_block_info().
  */
-function user_badges_action_info() {
+function user_badges_block_info() {
   return array(
-    'user_badges_add_badge_action' => array(
-      'label' => t('Add badge'),
-      'type' => 'user',
-      'configurable' => TRUE,
-      'triggers' => array('any' => TRUE),
-    ),
-    'user_badges_remove_badge_action' => array(
-      'label' => t('Remove badge'),
-      'type' => 'user',
-      'configurable' => TRUE,
-      'triggers' => array('any' => TRUE),
-    ),
-  );
-}
-
-/**
- * Implementsa Drupal action.
- * Adds a badge to the current user.
- */
-function user_badges_add_badge_action(&$account, $context = array()) {
-  if (isset($account->uid)) {
-    $uid = $account->uid;
-  }
-  elseif (isset($context['uid'])) {
-    $uid = $context['uid'];
-  }
-  else {
-    global $user;
-    $uid = $user->uid;
-  }
-  $success = TRUE;
-  $badges = user_badges_get_badges('all');
-
-  foreach ($context['badges'] as $bid) {
-    $success = (boolean) user_badges_user_add_badge($uid, $bid, 'uid');
-    if ($success) {
-      watchdog('action', 'Added user badge %badge to user %name.', array('%name' => check_plain($user->name), '%badge' => check_plain($badges[$bid]->name)));
-    }
-    else {
-      watchdog('action', 'Unable to add user badge %badge to user %name.', array('%name' => check_plain($user->name), '%badge' => check_plain($badges[$bid]->name)), WATCHDOG_WARNING);
-    }
-  }
-}
-
-/**
- * @todo Please document this function.
- * @see http://drupal.org/node/1354
- */
-function user_badges_add_badge_action_form($context) {
-  $form['badges'] = array('#tree' => TRUE);
-
-  $badges = user_badges_get_badges('all');
-  $context['badges'] = is_array($context['badges']) ? $context['badges'] : array();
-
-  foreach ($badges as $badge) {
-    $form['badges'][$badge->bid] = array(
-      '#type' => 'checkbox',
-      '#title' => theme('user_badge', array('badge' => $badge)),
-      '#return_value' => 1,
-      '#default_value' => $context['badges'][$badge->bid],
-      '#description' => check_plain($badge->name),
-    );
-  }
-
-  return $form;
-}
-
-/**
- * @todo Please document this function.
- * @see http://drupal.org/node/1354
- */
-function user_badges_add_badge_action_submit($form, $form_state) {
-  $badges = array();
-  foreach ($form_state['values']['badges'] as $badge => $set) {
-    if ($set) {
-      $badges[$badge] = $badge;
-    }
-  }
-  return array('badges' => $badges);
-}
-
-/**
- * Implementsa Drupal action.
- * Removes a badge to the current user.
- */
-function user_badges_remove_badge_action(&$account, $context = array()) {
-  if (isset($account->uid)) {
-    $uid = $account->uid;
-  }
-  elseif (isset($context['uid'])) {
-    $uid = $context['uid'];
-  }
-  else {
-    global $user;
-    $uid = $user->uid;
-  }
-  $success = TRUE;
-  $badges = user_badges_get_badges('all');
-
-  foreach ($context['badges'] as $bid) {
-    $success = (boolean) user_badges_user_remove_badge($uid, $bid, 'uid');
-    if ($success) {
-      watchdog('action', 'Removed user badge %badge to user %name.', array('%name' => check_plain($user->name), '%badge' => check_plain($badges[$bid]->name)));
-    }
-    else {
-      watchdog('action', 'Unable to remove user badge %badge to user %name.', array('%name' => check_plain($user->name), '%badge' => check_plain($badges[$bid]->name)), WATCHDOG_WARNING);
-    }
-  }
-}
-
-/**
- * @todo Please document this function.
- * @see http://drupal.org/node/1354
- */
-function user_badges_remove_badge_action_form($context) {
-  $form['badges'] = array('#tree' => TRUE);
-
-  $badges = user_badges_get_badges('all');
-  $context['badges'] = is_array($context['badges']) ? $context['badges'] : array();
-
-  foreach ($badges as $badge) {
-    $form['badges'][$badge->bid] = array(
-      '#type' => 'checkbox',
-      '#title' => theme('user_badge', array('badge' => $badge)),
-      '#return_value' => 1,
-      '#default_value' => $context['badges'][$badge->bid],
-      '#description' => check_plain($badge->name),
+    'current_node' => array(
+      'info' => t('User_Badges: Content Author'),
+      'cache' => DRUPAL_NO_CACHE,
+      ),
+    'my_badges' => array(
+      'info' => t('User_Badges: My Badges'),
+      'cache' => DRUPAL_CACHE_PER_USER,
+      ),
+    'all_badges' => array(
+      'info' => t('User_Badges: All Badges'),
+      'cache' => DRUPAL_CACHE_GLOBAL,
+      ),
     );
-  }
-
-  return $form;
-}
-
-/**
- * @todo Please document this function.
- * @see http://drupal.org/node/1354
- */
-function user_badges_remove_badge_action_submit($form, $form_state) {
-  $badges = array();
-  foreach ($form_state['values']['badges'] as $badge => $set) {
-    if ($set) {
-      $badges[$badge] = $badge;
-    }
-  }
-  return array('badges' => $badges);
 }
 
 /**
- * Implements hook_token_values().
- * @TODO: Add tokens for Submitted By module?
- */
-function user_badges_token_values($type, $object = NULL) {
-  if ($type == 'userbadge') {
-    $badge = $object;
-    $tokens['userbadge-name'] = $badge->name;
-    $tokens['userbadge-bid'] = $badge->bid;
-    return $tokens;
-  }
-}
-
-/**
- * Implements hook_token_list().
- */
-function user_badges_token_list($type = 'all') {
-  if ($type == 'userbadge' || $type == 'all') {
-    $tokens['userbadge']['userbadge-name'] = t("The badge name");
-    $tokens['userbadge']['userbadge-bid'] = t("The badge id number (bid)");
-    return $tokens;
-  }
-}
-
-/**
- * Implements hook_block();().
- */
-function user_badges_block_OLD($op = 'list', $delta = 0, $edit = array()) { }
-
-/**
- * Function for user_badges_block(op = 'list').
- */
-function user_badges_block_list() {
-  return array(
-    'current_node' => array('info' => t('User_Badges: Content Author'), 'cache' => BLOCK_NO_CACHE),
-  );
-}
-
-/**
- * Function for user_badges_block(op = 'view').
+ * Implements hook_block_view().
  */
 function user_badges_block_view($delta = 0) {
   $block = array();
@@ -1463,20 +1418,59 @@ function user_badges_block_view($delta =
       if (arg(0) == 'node' && is_numeric(arg(1)) && empty($arg2)) {
         $node = menu_get_object();
         if (in_array($node->type, variable_get('user_badges_current_node_types', array()))) {
-          $badges = user_badges_for_user(array('uid' => $node->uid));
-          $account = user_load($node->uid);
-          $block['title'] = t("@name's Badges", array('@name' => $account->name));
-          $block['content'] = $badges;
+          $account = array_shift(user_load_multiple(array($node->uid)));
+          $result = $account->badges;
+          $images = array();
+          foreach ($result as $badge) {
+            $images[] = theme('user_badge', array('badge' => $badge));
+          }
+          $block['subject'] = t("@name's Badges", array('@name' => $node->name));
+          $block['content'] = theme('user_badge_group', array('badgeimages' => $images));
         }
       }
       break;
+
+    case 'my_badges':
+      global $user;
+      if (!isset($user->badges_all)) {
+        $user = array_shift(user_load_multiple(array($user->uid)));
+      }
+      if (variable_get('user_badges_my_badges_limit', 1)) {
+        $result = $user->badges;
+      }
+      else {
+        $result = $user->badges_all;
+      }
+      $images = array();
+      foreach ($result as $badge) {
+        $images[] = theme('user_badge', array('badge' => $badge));
+      }
+      $block['subject'] = t('My Badges');
+      $block['content'] = theme('user_badge_group', array('badgeimages' => $images));
+      break;
+
+    case 'all_badges':
+      $result = db_select('user_badges_badges', 'ubb')
+        ->fields('ubb')
+        ->orderBy('ubb.weight', 'asc')
+        ->orderBy('ubb.name', 'asc')
+        ->execute();
+      $items = array();
+      foreach ($result as $badge) {
+        $items[] = theme('user_badge', array('badge' => $badge))
+          . ' <span class="all-badges-name">'
+          . check_plain($badge->name)
+          . '</span>';
+      }
+      $block['content'] = theme('item_list', array('items' => $items));
+      break;
   }
 
   return $block;
 }
 
 /**
- * Function for user_badges_block(op = 'configure').
+ * Implements hook_block_configure().
  */
 function user_badges_block_configure($delta = 0) {
   $form = array();
@@ -1488,8 +1482,21 @@ function user_badges_block_configure($de
         '#title' => t('Show on these content types'),
         '#default_value' => variable_get('user_badges_current_node_types', array()),
         '#options' => node_type_get_names(),
-        '#attributes' => array('class' => 'container-inline'),
-      );
+        '#attributes' => array('class' => array('container-inline')),
+        );
+      break;
+
+    case 'my_badges':
+      $form['limit'] = array(
+        '#type' => 'radios',
+        '#title' => t('Apply admin limit on this block?'),
+        '#default_value' => variable_get('user_badges_my_badges_limit', 1),
+        '#options' => array(t('No'), t('Yes')),
+        '#attributes' => array('class' => array('container-inline')),
+        '#description' => t('The current badge display limit is @limit.',
+          array('@limit' => (int) variable_get('user_badges_showone', 0))
+          ),
+        );
       break;
   }
 
@@ -1497,29 +1504,44 @@ function user_badges_block_configure($de
 }
 
 /**
- * Function for user_badges_block(op = 'save').
+ * Implements hook_block_save().
  */
 function user_badges_block_save($delta = 0, $edit = array()) {
   switch ($delta) {
     case 'current_node':
       variable_set('user_badges_current_node_types', array_filter($edit['types']));
+      drupal_set_message(t('Configuration saved.'));
       return;
+
+    case 'my_badges':
+      variable_set('user_badges_my_badges_limit', $edit['limit']);
+      drupal_set_message(t('Configuration saved.'));
+      return;
+  }
+}
+
+/**
+ * Implements hook_field_extra_fields().
+ */
+function user_badges_field_extra_fields_alter(&$info) {
+  foreach (node_type_get_types() as $node_type) {
+    if (!isset($info['node'][$node_type->type]['form']['badges'])) {
+      $info['node'][$node_type->type]['form']['badges'] = array(
+        'label' => t('User Badges'),
+        'description' => t('User badges display'),
+        'weight' => 30,
+      );
+    }
   }
 }
 
 /**
- * Implements hook_cron()
- * UNCOMMENT in order to get User Badges to work along with Auto Assign Role
- * notes: - this is a quite fast solution in order to solve Auto Assign Role issue
- *        - do not forget to set up your cron
- */
-// function user_badges_cron() {
-//   $result = db_query('SELECT * FROM {user_badges_roles}');
-//
-//   $roles = array();
-//   while ($o = db_fetch_object($result)) {
-//     $roles[$o->rid] = $o->bid;
-//   }
-//
-//   user_badges_save_roles($roles);
-// }
+ * Implements hook_preprocess_node().
+ */
+function user_badges_preprocess_node(&$variables, $hook) {
+  if (user_access('access user badges')) {
+    $uid = $variables['uid'];
+    $account = array_shift(user_load_multiple(array($uid)));
+    $variables['user_badges'] = user_badges_for_user($uid);
+  }
+}
