diff --git a/user_badges.admin.inc b/user_badges.admin.inc
index c8c044a..024f3c2 100644
--- a/user_badges.admin.inc
+++ b/user_badges.admin.inc
@@ -28,21 +28,45 @@ function user_badges_badgelist_form() {
     array('data' => t('Delete'))
   ));
 
-  $result = pager_query('SELECT bid, name, image, weight, href FROM {user_badges_badges} ubb '. tablesort_sql($form['header']['#value']), 50 );
+  $query = db_select('user_badges_badges', 'ubb')
+    ->extend('TableSort')->extend('PagerDefault')
+    ->fields('ubb,', array('bid', 'name', 'image', 'weight', 'href'))
+    ->orderByHeader($form['header']['#value'])
+    ->limit(50);
+
+  $results = $query->execute();
 
   // Build a table listing the appropriate badges.
-  while ($badge = db_fetch_object($result)) {
+  foreach ($results as $badge) {
+
     $badge->class = 'badge ' . _user_badges_class($badge);
-    $form['name'][$badge->bid] = array('#value' => check_plain($badge->name));
-    $form['badge'][$badge->bid] = array('#value' => theme('user_badge', $badge));
-    $form['weight'][$badge->bid] = array('#type' => 'textfield', '#size' => 4, '#maxlength' => 255, '#default_value' => $badge->weight );
-    $form['edit'][$badge->bid] = array('#value' => l(t('edit'), 'admin/user/user_badges/edit/'. $badge->bid));
-    $form['delete'][$badge->bid] = array('#value' => l(t('delete'), 'admin/user/user_badges/delete/'. $badge->bid));
+    $form['name'][$badge->bid] = array(
+      '#type' => 'markup',
+      '#markup' => check_plain($badge->name));
+
+    $form['badge'][$badge->bid] = array(
+      '#type' => 'markup',
+      '#markup' => theme('user_badge', array('badge' => $badge)));
+
+    $form['weight'][$badge->bid] = array(
+      '#type' => 'textfield',
+      '#size' => 4,
+      '#maxlength' => 255,
+      '#default_value' => $badge->weight );
+
+    $form['edit'][$badge->bid] = array(
+      '#type' => 'markup',
+      '#markup' => l(t('edit'), 'admin/user/user_badges/edit/' . $badge->bid));
+
+    $form['delete'][$badge->bid] = array(
+      '#type' => 'markup',
+      '#markup' => l(t('delete'),
+      'admin/user/user_badges/delete/' . $badge->bid));
   }
 
   $form['submit'] = array('#type' => 'submit', '#value' => t('Update'));
 
-  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
+  $form['pager'] = array('#value' => theme('pager'));
 
   return $form;
 }
@@ -70,10 +94,11 @@ function user_badges_badgelist_form_validate($form, &$form_state) {
 function user_badges_badgelist_form_submit($form, &$form_state) {
   if (isset($form['weight']) && is_array($form['weight'])) {
     foreach (element_children($form['weight']) as $bid) {
-      db_query("UPDATE {user_badges_badges} SET weight = %d WHERE bid = %d",
-      $form_state['values'][$bid],
-      $bid
-      );
+      db_update('user_badges_badges')
+        ->fields(array(
+          'weight' => $form_state['value'][$bid],
+          'bid' => $bid))
+        ->execute();
     }
     drupal_set_message(t('The badge weights have been updated.'));
   }
@@ -86,10 +111,12 @@ function user_badges_badgelist_form_submit($form, &$form_state) {
  *   An associative array containing the structure of the form.
  * @ingroup themeable
  */
-function theme_user_badges_badgelist_form($form) {
+function theme_user_badges_badgelist_form($forms) {
   $output = '';
 
-  // Loop through the array items in the name array to get all the bids for our listed badges.
+  $form = array_shift($forms);
+  // 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
@@ -108,16 +135,20 @@ function theme_user_badges_badgelist_form($form) {
     }
 
     // Add the submit button.
-    $rows[] = array(
-      array('data' => drupal_render($form['submit']), 'align' => 'center', 'colspan' => '20'),
-      );
-  }
-  else {
-    $rows[] = array(array('data' => t('No badges available.'), 'colspan' => '5'));
+    $rows[] = array(array(
+      'data' => drupal_render($form['submit']),
+      'align' => 'center',
+      'colspan' => '20'));
+  } else {
+    $rows[] = array(array(
+      'data' => t('No badges available.'),
+      'colspan' => '5'));
   }
 
   // Theme all that we have processed so far into a table.
-  $output .= theme('table', $form['header']['#value'], $rows);
+  $output .= theme('table', array(
+    'header' => $form['header']['#value'],
+    'rows' =>  $rows));
 
   // Create the table's pager.
   if ($form['pager']['#value']) {
@@ -125,7 +156,8 @@ function theme_user_badges_badgelist_form($form) {
   }
 
   // Render any remaining form elements.
-  $output .= drupal_render($form);
+  $output .= drupal_render($forms);
+
 
   return $output;
 }
@@ -133,10 +165,12 @@ function theme_user_badges_badgelist_form($form) {
 /**
  * Define the edit form for userbadges.
  */
-function user_badges_edit_form($form_state, $bid = NULL) {
-  // If we have been given an existing badge (bid) then get all the badge info into $edit.
+function user_badges_edit_form($form_id, &$form_state, $bid = NULL) {
+  // If we have been given an existing badge (bid) then get all the badge
+  // info into $edit.
+  $edit = NULL;
   if (is_numeric($bid)) {
-    $edit = db_fetch_object(db_query('SELECT * FROM {user_badges_badges} WHERE bid = %d', $bid));
+    $edit = user_badges_get_badge($bid);
     if (is_numeric($edit->bid)) {
       $form['bid'] = array(
         '#type' => 'value',
@@ -161,7 +195,9 @@ function user_badges_edit_form($form_state, $bid = NULL) {
     '#default_value' => isset($edit) ? $edit->name : '',
     '#size' => 40,
     '#maxlength' => 100,
-    '#description' => t('Name for the badge. Will be displayed as a tooltip when rolling over the badge.'),
+    '#description' => t(
+      'Name for the badge. Will be displayed as a tooltip when rolling ' .
+      'over the badge.'),
     '#required' => TRUE,
   );
   $form['imageurl'] = array(
@@ -170,7 +206,9 @@ function user_badges_edit_form($form_state, $bid = NULL) {
     '#default_value' => $imageurl,
     '#size' => 60,
     '#maxlength' => 255,
-    '#description' => t('The image URL for this badge. If you want to use an image from the user badges image library, select from the list below.'),
+    '#description' => t(
+      'The image URL for this badge. If you want to use an image from the ' .
+      'user badges image library, select from the list below.'),
   );
   $form['weight'] = array(
     '#type' => 'textfield',
@@ -178,7 +216,9 @@ function user_badges_edit_form($form_state, $bid = NULL) {
     '#size' => 4,
     '#maxlength' => 10,
     '#default_value' => isset($edit) ? $edit->weight : 0,
-    '#description' => t('Lighter weighted items float to the top of lists. Heavier items go to the bottom. You must enter a number (negative values are allowed).'),
+    '#description' => t(
+      'Lighter weighted items float to the top of lists. Heavier items go ' .
+      'to the bottom. You must enter a number (negative values are allowed).'),
     '#required' => TRUE,
   );
   $form['href'] = array(
@@ -186,14 +226,16 @@ function user_badges_edit_form($form_state, $bid = NULL) {
     '#title' => t('Description URL'),
     '#size' => 60,
     '#maxlength' => 255,
-    '#description' => t('You can specify here the link where your badge will redirect your user.
-      This is useful for explanation pages about the badge, for instance. If you do not wish
-      your badge to be clickable, please leave this field empty.') .'<br />'.
-      '<u>'. t('Tips:') .'</u>'.'<ul>'.
-        '<li>'. t('If you provide the full URL, it will be considered an external URL.') .'</li>'.
-        '<li>'. t('If you provide only the path (e.g. "admin/content/node"), it is considered an
+    '#description' => t(
+      'You can specify here the link where your badge will redirect your ' .
+      'user. This is useful for explanation pages about the badge, for ' .
+      'instance. If you do not wish your badge to be clickable, please ' .
+      'leave this field empty.') . '<br />' .
+      '<u>' . t('Tips:') . '</u>' . '<ul>' .
+        '<li>' . t('If you provide the full URL, it will be considered an external URL.') .'</li>'.
+        '<li>' . t('If you provide only the path (e.g. "admin/content/node"), it is considered an
           internal link.') .'</li>'.
-        '<li>'. t('Use %none to override a default link in the settings tab with no link for this badge.', array('%none' => '<none>')) .'</li>'.
+        '<li>' . t('Use %none to override a default link in the settings tab with no link for this badge.', array('%none' => '<none>')) .'</li>'.
       '</ul>',
     '#default_value' => $edit->href,
   );
@@ -320,20 +362,35 @@ function user_badges_edit_form_submit($form, &$form_state) {
 
   // If the badge already exists, delete it and re-insert it.
   if (isset($edit->bid) && preg_match("/^[0-9]+$/D", $edit->bid)) {
-    db_query('DELETE FROM {user_badges_badges} WHERE bid = %d', $edit->bid);
-    $result = db_query("
-      INSERT INTO {user_badges_badges} (bid, name, image, weight, href, unhideable, fixedweight, doesnotcounttolimit, tid)
-      VALUES (%d, '%s', '%s', %d, '%s', %d, %d, %d, %d)",
-      $edit->bid, trim($edit->name), $image, $edit->weight, trim($edit->href), $edit->unhideable, $edit->fixedweight, $edit->doesnotcounttolimit, $edit->tid
-    );
+    db_delete('user_badges_badges')->condition('bid', $edit->bid)->execute();
+    $result = db_insert('user_badges_badges')
+      ->fields(array(
+        'bid' => $edit->bid,
+        'name' => trim($edit->name),
+        'image' => $image,
+        'weight' => $edit->weight,
+        'href' => trim($edit->href),
+        'unhideable' => $edit->unhideable,
+        'fixedweight' => $edit->fixedweight,
+        'doesnotcounttolimit' => $edit->doesnotcounttolimit,
+        'tid' => $edit->tid,
+        ))
+      ->execute();
   }
   // If the badge does not already exist, create it anew.
   else {
-    $result = db_query("
-      INSERT INTO {user_badges_badges} (name, image, weight, href, unhideable, fixedweight, doesnotcounttolimit, tid)
-      VALUES ('%s', '%s', %d, '%s', %d, %d, %d, %d)",
-      trim($edit->name), $image, $edit->weight, trim($edit->href), $edit->unhideable, $edit->fixedweight, $edit->doesnotcounttolimit, $edit->tid
-    );
+    $result = db_insert('user_badges_badges')
+      ->fields(array(
+        'name' => trim($edit->name),
+        'image' => $image,
+        'weight' => $edit->weight,
+        'href' => trim($edit->href),
+        'unhideable' => $edit->unhideable,
+        'fixedweight' => $edit->fixedweight,
+        'doesnotcounttolimit' => $edit->doesnotcounttolimit,
+        'tid' => $edit->tid,
+        ))
+      ->execute();
   }
   if ($result) {
     drupal_set_message(t('Badge %badgename saved.', array('%badgename' => $edit->name)));
@@ -439,7 +496,8 @@ function user_badges_images_form_submit($form, &$form_state) {
   // Save uploaded files.
   if ($op == t('Upload')) {
     $file = $form_state['values']['file_image'];
-    file_set_status($file, FILE_STATUS_PERMANENT);
+    $file->status |= FILE_STATUS_PERMANENT;
+    $file = file_save($file);
   }
   elseif ($op == t('Delete')) {
     foreach ($form_state['values']['images'] as $path => $is_removed) {
@@ -500,7 +558,7 @@ function user_badges_roles_form() {
   foreach ($roles as $rid => $role) {
     $form['roles'][$rid] = array(
       '#type' => 'textfield',
-      '#title' => $role,
+      '#title' => check_plain($role),
       '#maxlength' => 255,
       '#autocomplete_path' => 'user_badges/autocomplete',
       '#default_value' => isset($badges[$rid]) ? $badges[$rid]->name . ' '
@@ -725,8 +783,11 @@ function user_badges_settings_form_submit($form, $form_state) {
  */
 function user_badges_image_selects() {
   $selects = array();
-  $dir = file_create_path('badges');
-  $files = file_scan_directory($dir, '.*\.(((J|j)(p|P)(g|G))|((p|P)(n|N)(g|G))|((g|G)(i|I)(f|F)))', array('.', '..', 'CVS'), 0, FALSE);
+  $dir = 'badges';
+  file_prepare_directory($path, FILE_CREATE_DIRECTORY);
+  $dir = drupal_realpath($dir);
+
+  $files = file_scan_directory($dir, '/.*\.(((J|j)(p|P)(g|G))|((p|P)(n|N)(g|G))|((g|G)(i|I)(f|F)))/', array('recurse' => FALSE));
   foreach ($files as $file) {
     $selects[$file->filename] = theme('image', $file->filename, $file->filename, $file->filename);
   }
diff --git a/user_badges.info b/user_badges.info
index 45cdbc2..2677deb 100644
--- a/user_badges.info
+++ b/user_badges.info
@@ -1,5 +1,10 @@
-
 name = User badges
 description = Enables assignment of graphical badges to users and roles.
-dependencies[] = upload
-core = 6.x
+core = 7.x
+files[] = user_badges.admin.inc
+files[] = user_badges.install
+files[] = user_badges.module
+files[] = user_badges.views.inc
+files[] = views_handler_field_user_badges_badges_badge.inc
+files[] = views_handler_field_user_badges_user_uid.inc
+files[] = views_handler_filter_user_badges_user_type.inc
diff --git a/user_badges.install b/user_badges.install
index e9799fd..0c25309 100644
--- a/user_badges.install
+++ b/user_badges.install
@@ -27,60 +27,60 @@ function user_badges_schema() {
     'description' => 'Defines the user badges themselves (image, weight etc.)',
     'fields' => array(
       'bid' => array(
-        'description' => t('Original badge ID'),
+        'description' => 'Original badge ID',
         'type' => 'serial',
         'unsigned' => TRUE,
         'not null' => TRUE,
         ),
       'name' => array(
-        'description' => t('Badge name'),
+        'description' => 'Badge name',
         'type' => 'varchar',
         'length' => 50,
         'not null' => TRUE,
         'default' => '',
         ),
       'image' => array(
-        'description' => t('Associated image. Can be a full URL, or a relative path for the image library.'),
+        'description' => 'Associated image. Can be a full URL, or a relative path for the image library.',
         'type' => 'varchar',
         'length' => 255,
         'not null' => TRUE,
         'default' => '',
         ),
       'weight' => array(
-        'description' => t('Order in list'),
+        'description' => 'Order in list',
         'type' => 'int',
         'not null' => TRUE,
         'default' => 0,
         ),
       'href' => array(
-        'description' => t('Badge description URL'),
+        'description' => 'Badge description URL',
         'type' => 'varchar',
         'length' => 255,
         'not null' => FALSE,
         'default' => '',
         ),
       'tid' => array(
-        'description' => t('Optional associated taxonomn term id'),
+        'description' => 'Optional associated taxonomn term id',
         'type' => 'int',
         'not null' => FALSE,
         'unsigned' => TRUE,
         ),
       'unhideable' => array(
-        'description' => t('If this is 1, the badge cannot be hidden by being moved down in weight. It will always show up.'),
+        'description' => 'If this is 1, the badge cannot be hidden by being moved down in weight. It will always show up.',
         'type' => 'int',
         'size' => 'tiny',
         'not null' => TRUE,
         'default' => 0,
         ),
       'fixedweight' => array(
-        'description' => t('If this is 1, the badge cannot have a user assigned weight, regardless of settings.'),
+        'description' => 'If this is 1, the badge cannot have a user assigned weight, regardless of settings.',
         'type' => 'int',
         'size' => 'tiny',
         'not null' => TRUE,
         'default' => 0,
         ),
       'doesnotcounttolimit' => array(
-        'description' => t('If this is 1, the badge does not count towards the limit for number of badges to display per user.'),
+        'description' => 'If this is 1, the badge does not count towards the limit for number of badges to display per user.',
         'type' => 'int',
         'size' => 'tiny',
         'not null' => TRUE,
@@ -99,13 +99,13 @@ function user_badges_schema() {
     'description' => 'Stores which roles grant which badges.',
     'fields' => array(
       'rid' => array(
-        'description' => t('Role ID'),
+        'description' => 'Role ID',
         'type' => 'int',
         'unsigned' => TRUE,
         'not null' => TRUE,
         ),
       'bid' => array(
-        'description' => t('Badge ID'),
+        'description' => 'Badge ID',
         'type' => 'int',
         'unsigned' => TRUE,
         'not null' => TRUE,
@@ -118,32 +118,33 @@ function user_badges_schema() {
     'description' => 'Stores which users have which badges.',
     'fields' => array(
       'uid' => array(
-        'description' => t('User ID'),
+        'description' => 'User ID',
         'type' => 'int',
         'unsigned' => TRUE,
         'not null' => TRUE,
         ),
       'bid' => array(
-        'description' => t('Badge ID'),
+        'description' => 'Badge ID',
         'type' => 'int',
         'unsigned' => TRUE,
         'not null' => TRUE,
         ),
       'type' => array(
-        'description' => t("Whether set as part of the role, or individually assigned ('user', 'role')"),
+        'description' => "Whether set as part of the role, or individually assigned ('user', 'role')",
         'type' => 'varchar',
         'length' => 20,
         'not null' => TRUE,
         'default' => '',
         ),
       'userweight' => array(
-        'description' => t('Order in list, as set by user.'),
+        'description' => 'Order in list, as set by user.',
         'type' => 'int',
         'not null' => FALSE,
         ),
       ),
     'primary key' => array('bid', 'uid', 'type'),
     'indexes' => array(
+      'uid' => array('uid'),
       'uid_bid' => array('uid', 'bid'),
       'uid_weight' => array('uid', 'userweight'),
       'type' => array('type'),
@@ -157,7 +158,7 @@ function user_badges_schema() {
  * Implements hook_install().
  */
 function user_badges_install() {
-  drupal_install_schema('user_badges');
+  //drupal_install_schema('user_badges');
 }
 
 
@@ -168,7 +169,7 @@ function user_badges_uninstall() {
   // Delete files.
   $dir = file_create_path('badges');
   if ($dir) {
-    $files = file_scan_directory($dir, '.*\.(gif|jpg|jpeg|png)', array('.', '..', 'CVS'), 0, FALSE);
+    $files = file_scan_directory($dir, '/.*\.(gif|jpg|jpeg|png)/', array('.', '..', 'CVS'), 0, FALSE);
     foreach ($files as $file) {
       file_delete($file->filename);
     }
@@ -179,7 +180,7 @@ function user_badges_uninstall() {
     rmdir($dir);
   }
 
-  drupal_uninstall_schema('user_badges');
+//  drupal_uninstall_schema('user_badges');
 
   variable_del('user_badges_showone');
   variable_del('user_badges_showblocked');
@@ -198,7 +199,9 @@ function user_badges_update_6001() {
   db_drop_primary_key($ret, 'user_badges_user');
   db_add_primary_key($ret, 'user_badges_user', array('bid', 'uid', 'type'));
   db_add_index($ret, 'user_badges_user', 'type', array('type'));
-  return $ret;
+
+//  return $ret;
+    return t('All tables updated');
 }
 
 
@@ -206,7 +209,9 @@ function user_badges_update_6100() {
   $ret = array();
   db_add_field($ret, 'user_badges_badges', 'href',
     array('type' => 'varchar', 'length' => 80, 'not null' => FALSE, 'default' => ''));
-  return $ret;
+
+//  return $ret;
+    return t('All tables updated');
 }
 
 function user_badges_update_6101() {
@@ -216,7 +221,9 @@ function user_badges_update_6101() {
   db_drop_index($ret, 'user_badges_roles', 'bid_nid');
   db_drop_index($ret, 'user_badges_roles', 'nid_bid');
   db_drop_index($ret, 'user_badges_user', 'bid_uid_type');
-  return $ret;
+
+//  return $ret;
+    return t('All tables updated');
 }
 
 function user_badges_update_6102() {
@@ -238,7 +245,8 @@ function user_badges_update_6102() {
   db_add_field($ret, 'user_badges_user', 'userweight', array('type' => 'int', 'not null' => FALSE));
   db_add_index($ret, 'user_badges_user', 'uid_weight', array('uid', 'userweight'));
 
-  return $ret;
+//  return $ret;
+    return t('All tables updated');
 }
 
 function user_badges_update_6103() {
@@ -248,7 +256,8 @@ function user_badges_update_6103() {
   db_add_field($ret, 'user_badges_badges', 'tid', array('type' => 'int', 'not null' => FALSE, 'unsigned' => TRUE));
   db_add_index($ret, 'user_badges_badges', 'tid_name', array('tid', 'name'));
 
-  return $ret;
+//  return $ret;
+    return t('All tables updated');
 }
 
 
@@ -266,6 +275,7 @@ function user_badges_update_6104() {
     'default' => "''",
     ));
 
-  return $ret;
+//  return $ret;
+    return t('All tables updated');
 }
 
diff --git a/user_badges.module b/user_badges.module
index 7ac8134..2d3cac1 100644
--- a/user_badges.module
+++ b/user_badges.module
@@ -12,6 +12,7 @@
  * @author Nuno Veloso (nunoveloso18), http://drupal.org/user/80656
  * @author Richard Skinner (Likeless), http://drupal.org/user/310635
  * @author Nancy Wichmann (NancyDru), http://drupal.org/user/101412
+ * @author Michael A Smith (mas5d2), http://drupal.org/user/1291584
  *
  */
 
@@ -55,11 +56,22 @@ function user_badges_help($path, $arg) {
 /**
  * Implements hook_perm().
  */
-function user_badges_perm() {
+function user_badges_permission() {
   return array(
-    'manage badges',
-    'change badge assignments',
-    'show badges in user profile'
+    'manage badges' => array(
+      'title' => t('Manage user badges'),
+      'description' => t(''),
+      ),
+
+    'change badge assignments' => array(
+      'title' => t('Change user badge assignments'),
+      'description' => t(''),
+      ),
+
+    'show badges in user profile' => array(
+      'title' => t('Show badge in profile'),
+      'description' => t('')
+     ),
   );
 }
 
@@ -133,7 +145,7 @@ function user_badges_menu() {
     'file' => 'user_badges.admin.inc',
     );
 
-  $items['admin/user/user_badges/delete/%'] = array(
+  $items['admin/user/user_badges/delete/%badge'] = array(
     'title' => 'Delete badge',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('user_badges_delete_form', 4),
@@ -179,24 +191,10 @@ function user_badges_menu() {
   return $items;
 }
 
-/**
- * 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($op, &$edit, &$account, $category = 'account') {
+function user_badges_user_load($users) {
   global $user;
-  static $badges = array();
-
-  switch ($op) {
-    case 'load':
-      // Have we loaded this user before?
-      if (isset($badges[$account->uid])) {
-        $account->badges = $badges[$account->uid];
-        break;
-      }
 
+  foreach ($users as $account) {
       $account->badges = array();
 
       if ($account->uid > 0) {
@@ -228,96 +226,106 @@ function user_badges_user($op, &$edit, &$account, $category = 'account') {
       }
 
       $badges[$account->uid] = $account->badges;
-      break;
+  }
 
-    case 'insert':
-      if (is_array($account->roles)) {
-        // Get the list of role badges.
-        $roles = user_badges_get_roles();
-        $badges = user_badges_get_badges('select');
-        $message = user_access('manage badges');
-        $rids = array_keys($account->roles);
-        foreach ($rids as $rid) {
-          // If this role has a badge...
-          if (key_exists($rid, $roles)) {
-            // and user doesn't already have this badge.
-            if (!key_exists($roles[$rid], $account->badges)) {
-              $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]])));
-              }
-            }
+}
+
+/**
+ * Implements hook_user_insert().
+ */
+function user_badges_user_insert(&$edit, &$account, $category = 'account') {
+  if (is_array($account->roles)) {
+    // Get the list of role badges.
+    $roles = user_badges_get_roles();
+    $badges = user_badges_get_badges('select');
+    $message = user_access('manage badges');
+    $rids = array_keys($account->roles);
+    foreach ($rids as $rid) {
+      // If this role has a badge...
+      if (key_exists($rid, $roles)) {
+        // and user doesn't already have this badge.
+        if (!key_exists($roles[$rid]->bid, $account->badges)) {
+          $success = user_badges_user_add_badge($account->uid, $roles[$rid]->bid, 'role');
+          if ($success && $message) {
+            drupal_set_message(t('User assigned %name badge.', array('%name' => $badges[$roles[$rid]->bid])));
           }
         }
       }
-      break;
+    }
+  }
+}
 
-    case 'update':
-      if (is_array($edit['roles'])) {
-        // 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 (key_exists($rid, $roles) && !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]])));
-            }
-          }
-        }
+function user_badges_user_delete($users) {
+  foreach ($users as $account)
+    db_delete('user_badges_user')->condition('uid', $account->uid, '=')->execute();
+}
 
-        // 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 (key_exists($rid, $roles) && key_exists($roles[$rid], $account->badges_all)) {
-            $success = user_badges_user_remove_badge($account->uid, $roles[$rid], 'role');
-            drupal_set_message(t('%name badge removed from user.', array('%name' => $badges[$roles[$rid]])));
+function user_badges_user_presave(&$edit, $account, $category = 'update') {
+
+  if (isset($edit['roles']) && is_array($edit['roles'])) {
+    // 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');
+
+    $added = array_diff(array_keys($new_roles), array_keys((array)$account->roles));
+    if (count($added) > 0) {
+      foreach ($added as $rid) {
+        if (key_exists($rid, $roles) && !key_exists($roles[$rid]->bid, $account->badges_all)) {
+          $success = user_badges_user_add_badge($account->uid, $roles[$rid]->bid, 'role');
+          if ($success && $message) {
+            drupal_set_message(t('User assigned %name badge.', array('%name' => $badges[$roles[$rid]->bid])));
           }
         }
-
-        //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));
       }
-      break;
-
-    case 'delete':
-      db_query('DELETE FROM {user_badges_user} WHERE uid = %d', $account->uid);
-      break;
+    }
 
-    case 'view':
-      if (is_array($account->badges) && count($account->badges)) {
-        $badgeimgs = array();
-        foreach ($account->badges as $badge) {
-          $badgeimgs[] = theme('user_badge', $badge, $account);
+    // What are the removed roles?
+    $removed = array_diff(array_keys((array)$account->roles), array_keys($new_roles));
+    if (count($removed) > 0) {
+      foreach ($removed as $rid) {
+        if (key_exists($rid, $roles) && key_exists($roles[$rid]->bid, $account->badges_all)) {
+          $success = user_badges_user_remove_badge($account->uid, $roles[$rid]->bid, 'role');
+          if ($success && $message) {
+            drupal_set_message(t('%name badge removed from user.', array('%name' => $badges[$roles[$rid]->bid])));
+          }
         }
-        $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', $badgeimgs),
-          '#attributes' => array('class' => 'badges'),
-        );
       }
+    }
+
+    //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));
   }
+
 }
 
+function user_badges_user_view($account, $view_mode, $langcode) {
+  if (is_array($account->badges) && count($account->badges)) {
+    $badgeimgs = array();
+    foreach ($account->badges as $badge) {
+      $badgeimgs[] = theme('user_badge', array(
+        'badge' => $badge,
+        'account' => $account));
+    }
+    $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',
+      '#markup' => theme('user_badge_group', $badgeimgs),
+      '#attributes' => array('class' => 'badges'),
+    );
+  }
+}
 /**
  * Helper function for building badge class names.
  * I was originally using form_clean_id, but it is not secure.
@@ -421,11 +429,13 @@ function user_badges_userweight_form($form_state, $account) {
 function user_badges_userweight_form_submit($form, &$form_state) {
   if (isset($form['weight']) && is_array($form['weight'])) {
     foreach (element_children($form['weight']) as $bid) {
-      db_query("UPDATE {user_badges_user} SET userweight = %d WHERE bid = %d AND uid = %d",
-      $form_state['values'][$bid],
-      $bid,
-      $form_state['values']['uid']
-      );
+      db_update('user_badges_user')
+        ->fields(array(
+          'userweight' => $form_state['values'][$bid],
+          ))
+        ->condition('bid', $bid, '=')
+        ->condition('uid', $form_state['values'], '=')
+        ->execute();
     }
     drupal_set_message(t('Your badge order has been updated.'));
   }
@@ -490,13 +500,20 @@ function user_badges_badge_autocomplete($string = '') {
 
   if (preg_match('/^[^(]+/', $string, $searchstring)) {
     $trimstring = trim($searchstring[0]);
-    $result = db_query_range("SELECT * FROM {user_badges_badges} WHERE name LIKE '%%%s%%'", $trimstring, 0, 10);
-    while ($badge = db_fetch_object($result)) {
-      $matches[$badge->name . ' (' . t('Badge ID') . ' ' . $badge->bid .')'] = check_plain($badge->name) . ' ' . theme('user_badge', $badge);
+    $result = db_select('user_badges_badges')
+                ->fields('user_badges_badges')
+                ->condition('name', "%%" . $trimstring . "%%", 'LIKE')
+                ->range(0, 10)
+                ->execute();
+
+    foreach ($result as $badge) {
+      $matches[$badge->name . ' (' . t('Badge ID') . ' ' . $badge->bid . ')'] =
+        check_plain($badge->name) . ' ' . theme('user_badge',
+          array('badge' => $badge));
     }
   }
 
-  drupal_json($matches);
+  drupal_json_output($matches);
 }
 
 /**
@@ -515,9 +532,14 @@ function user_badges_badge_autocomplete($string = '') {
  *   'nobid' for a correctly formatted string with an invalid badge ID
  */
 function user_badges_badge_autocomplete_validation($value) {
-  if (preg_match('/\('. t('Badge ID') .' (\d+)\)/', $value, $matches)) {
+  if (preg_match('/\(' . t('Badge ID') . ' (\d+)\)/', $value, $matches)) {
     //The format was correct, but we need to check the bid exists
-    if (db_result(db_query('SELECT COUNT(*) FROM {user_badges_badges} b WHERE b.bid=%d', $matches[1]))) {
+
+    $count = db_select('user_badges_badges')
+      ->condition('bid', $matches[1], '=')
+      ->countQuery()
+      ->execute()->fetchField();
+    if ($count) {
       //Result found
       return array($matches[1], 'valid');
     }
@@ -539,7 +561,7 @@ function user_badges_badge_autocomplete_validation($value) {
 function user_badges_page($uid) {
   $account = user_load($uid);
 
-  drupal_set_title(t('Edit badges for %user_name', array('%user_name' => $account->name)));
+  drupal_set_title(t('Edit badges for %user_name', array('%user_name' => $account->name)), PASS_THROUGH);
 
   return drupal_get_form('user_badges_change_form', $account);
 
@@ -551,7 +573,7 @@ function user_badges_page($uid) {
 function user_badges_userweight_page($uid) {
   $account = user_load($uid);
 
-  drupal_set_title(t('Badges for %user_name', array('%user_name' => $account->name)));
+  drupal_set_title(t('Badges for %user_name', array('%user_name' => $account->name)), 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')) ) {
@@ -563,10 +585,11 @@ function user_badges_userweight_page($uid) {
     $user_badges = user_badges_get_badges($account->uid, array('nolimit' => TRUE));
     $badges = array();
     foreach ((array)$user_badges as $badge) {
-      $badges[] = theme('user_badge', $badge, $account);
+      $badges[] = theme('user_badge', array('badge' => $badge, 'account' => $account));
     }
+
     if ($badges) {
-      $badges = array(theme('item_list', $badges));
+      $badges = array(theme('item_list', array('items' => array($badges))));
       return theme('user_badge_group', $badges);
     }
     else {
@@ -579,7 +602,7 @@ function user_badges_userweight_page($uid) {
 /**
  * Form to change badges of a user
  */
-function user_badges_change_form(&$form_state, $account) {
+function user_badges_change_form($form_state, $account) {
   $form = array();
 
   $form['uid'] = array(
@@ -594,9 +617,9 @@ function user_badges_change_form(&$form_state, $account) {
     '#collapsed' => FALSE,
   );
   for ($i = 1; $i <= 5; $i++) {
-    $form['add']['add'. $i] = array(
+    $form['add']['add' . $i] = array(
       '#type' => 'textfield',
-      '#title' => t('New Badge !number', array('!number' => $i)),
+      '#title' => check_plain(t('New Badge !number', array('!number' => $i))),
       '#size' => 40,
       '#maxlength' => 255,
       '#autocomplete_path' => 'user_badges/autocomplete',
@@ -634,14 +657,21 @@ function user_badges_change_form(&$form_state, $account) {
  */
 function user_badges_change_form_validate($form, &$form_state) {
   for ($i = 1; $i <= 5; $i++) {
-    if (!empty($form_state['values']['add'. $i])) {
-      $validation = user_badges_badge_autocomplete_validation($form_state['values']['add'. $i]);
+    if (!empty($form_state['values']['add' . $i])) {
+      $validation =
+        user_badges_badge_autocomplete_validation($form_state['values']['add' . $i]);
       switch ($validation[1]) {
         case 'nobid':
-          form_set_error('add'. $i, t('@value is not a valid badge ID. Try using the autocomplete function (requires javascript).', array('@value' => $validation[0])));
+          form_set_error('add' . $i,
+            t('@value is not a valid badge ID. Try using the autocomplete ' .
+              'function (requires javascript).',
+            array('@value' => $validation[0])));
           break;
         case 'string':
-          form_set_error('add'. $i, t('"@value" is not a valid badge. Try using the autocomplete function (requires javascript).', array('@value' => $form_state['values']['add'. $i])));
+          form_set_error('add' . $i,
+            t('"@value" is not a valid badge. Try using the autocomplete ' .
+              'function (requires javascript).',
+            array('@value' => $form_state['values']['add' . $i])));
           break;
       }
     }
@@ -658,8 +688,10 @@ function user_badges_change_form_submit($form, &$form_state) {
 
   //Add badges for non-empty fields
   for ($i = 1; $i <= 5; $i++) {
-    if (!empty($form_state['values']['add'. $i])) {
-      $validation = user_badges_badge_autocomplete_validation($form_state['values']['add'. $i]);
+    if (!empty($form_state['values']['add' . $i])) {
+      $validation =
+        user_badges_badge_autocomplete_validation(
+          $form_state['values']['add' . $i]);
       user_badges_user_add_badge($uid, $validation[0], 'user');
     }
   }
@@ -675,7 +707,9 @@ function user_badges_change_form_submit($form, &$form_state) {
     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' => check_plain(count($badges_to_go)))));
   }
 
 }
@@ -739,7 +773,14 @@ function user_badges_user_save($edit, $uid, $quiet = TRUE) {
  */
 function user_badges_user_add_badge($uid, $bid, $type = NULL) {
   user_badges_user_remove_badge($uid, $bid, $type);
-  return db_query('INSERT INTO {user_badges_user} (uid, bid, type) VALUES (%d, %d, \'%s\')', $uid, $bid, $type);
+  db_insert('user_badges_user')
+    ->fields(array(
+      'uid' =>  $uid,
+      'bid' => $bid,
+      'type' => $type,
+      ))
+    ->execute();
+  return true;
 }
 
 
@@ -753,12 +794,13 @@ function user_badges_user_add_badge($uid, $bid, $type = NULL) {
  * @return bool with query success
  */
 function user_badges_user_remove_badge($uid, $bid, $type = NULL) {
-  if (is_null($type)) {
-    return db_query('DELETE FROM {user_badges_user} WHERE uid=%d AND bid=%d', $uid, $bid);
-  }
-  else {
-    return db_query('DELETE FROM {user_badges_user} WHERE uid=%d AND bid=%d AND type=\'%s\'', $uid, $bid, $type);
-  }
+  $query = db_delete('user_badges_user')
+      ->condition('uid', $uid, '=')
+      ->condition('bid', $bid, '=');
+  if (!is_null($type))
+    $query->condition('type', $type, '=');
+
+  return $query->execute();
 }
 
 
@@ -785,42 +827,52 @@ function user_badges_get_badges($uid, $options = array()) {
 
   if (empty($past_uid) || $past_uid !== $uid || $past_options !== $options ) {
     $past_uid = $uid;
+
     if ($uid == 'all' || $uid == 'select') {
-      $sql = db_query('SELECT b.bid, b.weight, b.name, b.image, b.href,
+      $sql = 'SELECT b.bid, b.weight, b.name, b.image, b.href,
         b.unhideable, b.fixedweight, b.doesnotcounttolimit, b.tid
         FROM {user_badges_badges} b
-        ORDER BY b.weight, b.name');
+        ORDER BY b.weight, b.name';
     }
     else {
-      $usr = db_result(db_query('SELECT COUNT(uid) FROM {users} WHERE uid = %d AND status = 0', $uid));
-
+      $usr = db_select('users', 'u')
+        ->fields('u', array('uid'))
+        ->condition('uid', $uid , '=')
+        ->condition('status', 0, '=')
+        ->countQuery()
+        ->execute()
+        ->fetchField();
       if ($usr && variable_get('user_badges_showblocked', 0)) {
-        $sql = db_query('SELECT DISTINCT b.bid, b.weight, b.name, b.image, b.href,
+        $sql = '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
           FROM {user_badges_badges} b
             INNER JOIN {user_badges_user} u ON b.bid = u.bid
             INNER JOIN {user_badges_roles} r ON b.bid = r.bid
-          WHERE u.uid = %d AND r.rid = 0
-          ORDER BY coalescedweight, b.name',
-          $uid);
+          WHERE u.uid = :uid AND r.rid = 0
+          ORDER BY coalescedweight, b.name';
       }
       else {
-        $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
-          FROM {user_badges_badges} b
-            INNER JOIN {user_badges_user} u ON b.bid = u.bid
-          WHERE u.uid = %d
-          ORDER BY coalescedweight, b.name
-          ';
-        $sql = db_query($query, $uid);
-
+        $sql =
+          '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 ' .
+          'FROM user_badges_badges b ' .
+            'INNER JOIN user_badges_user u ON b.bid = u.bid ' .
+          'WHERE u.uid = :uid ORDER BY coalescedweight, b.name';
       }
     }
+    $query = db_query($sql, array(':uid' => $uid), array('fetch' => PDO::FETCH_ASSOC));
 
     // Should we limit the badges returned?
-    if (!$options['nolimit'] && variable_get('user_badges_showone', 0)) {
+    if (empty($options['nolimit']) && variable_get('user_badges_showone', 0)) {
       $limit = variable_get('user_badges_showone', 1);
     }
     else {
@@ -828,7 +880,8 @@ function user_badges_get_badges($uid, $options = array()) {
       $limit = -1;
     }
 
-    while ($badge = db_fetch_object($sql)) {
+    foreach ($query as $badge) {
+      $badge = (object) $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') {
@@ -855,15 +908,21 @@ function user_badges_get_badges($uid, $options = array()) {
  * 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 = %d', $bid));
+  $result = db_select('user_badges_badges')
+    ->fields('user_badges_badges')
+    ->condition('bid', $bid, '=')
+    ->range(0, 1)
+    ->execute();
+  foreach ($result as $res)
+    return $res;
 }
 
 
 
-function user_badges_delete_form($form_state, $bid) {
+function user_badges_delete_form($form_id, &$form_state, $bid) {
   if ($badge = user_badges_get_badge($bid)) {
     $form = array();
-    $form['badge'] = array('#value' => theme('user_badge_group', array(theme('user_badge', $badge))));
+    $form['badge'] = array('#value' => theme('user_badge', array('badge' => $badge)));
     $form['bid'] = array('#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');
   }
@@ -872,9 +931,11 @@ function user_badges_delete_form($form_state, $bid) {
 
 function user_badges_delete_form_submit($form, &$form_state) {
   $bid = $form_state['values']['bid'];
-  db_query("DELETE FROM {user_badges_badges} WHERE bid = %d", $bid);
-  db_query("DELETE FROM {user_badges_user} WHERE bid = %d", $bid);
-  db_query("DELETE FROM {user_badges_roles} WHERE bid = %d", $bid);
+
+  db_delete('user_badges_badges')->condition('bid', $bid)->execute();
+  db_delete('user_badges_user')->condition('bid', $bid)->execute();
+  db_delete('user_badges_roles')->condition('bid', $bid)->execute();
+
   drupal_set_message(t('Badge deleted.'));
   $form_state['redirect'] = 'admin/user/user_badges';
 }
@@ -892,16 +953,21 @@ function user_badges_delete_form_submit($form, &$form_state) {
  * @return a list of roles
  */
 function user_badges_get_roles($rid = NULL, $options = array()) {
+
   $roles = array();
   $options = array_merge(array('returnbadges' => 'FALSE'), $options);
 
-  if ($rid) {
-    $sql = db_query('SELECT ubr.rid, ubr.bid, ubb.name, ubb.image, ubb.weight, ubb.href, ubb.tid FROM {user_badges_roles} ubr INNER JOIN {user_badges_badges} ubb ON ubb.bid=ubr.bid WHERE ubr.rid = %d', $rid);
-  }
-  else {
-    $sql = db_query('SELECT ubr.rid, ubr.bid, ubb.name, ubb.image, ubb.weight, ubb.href, ubb.tid FROM {user_badges_roles} ubr INNER JOIN {user_badges_badges} ubb ON ubb.bid=ubr.bid', $rid);
-  }
-  while ($row = db_fetch_object($sql)) {
+  $query = db_select('user_badges_roles', 'ubr');
+  $query->join('user_badges_badges', 'ubb', 'ubb.bid=ubr.bid');
+  $query->fields('ubr', array('rid', 'bid'))
+        ->fields('ubb', array('name', 'image', 'weight', 'href', 'tid'));
+
+  if ($rid)
+    $query->condition('ubr.rid', $rid, '=');
+
+  $results = $query->execute();
+
+  foreach ($results as $row) {
     if ($options['returnbadges']) {
       $row->image = _user_badges_build_image($row);
       $roles[$row->rid] = $row;
@@ -923,8 +989,9 @@ function user_badges_save_roles($roles) {
   if (is_array($roles)) {
     // We have to clear out all badges first.
     $success = TRUE;
-    db_query('DELETE FROM {user_badges_roles}');
-    db_query("DELETE FROM {user_badges_user} WHERE type='role'");
+    db_delete('user_badges_roles')->condition('1', '1', '=')->execute();
+    db_delete('user_badges_user')->condition('type', 'role', '=')->execute();
+
 
     // Now we loop through the roles and their badges, and assign them to
     // each user accordingly.
@@ -932,7 +999,10 @@ function user_badges_save_roles($roles) {
       if ($bid) {
         // First of all, insert all the role and badge relationship
         // into user_badges_roles.
-        $success = $success && db_query('INSERT INTO {user_badges_roles} (rid, bid) VALUES (%d, %d)', $rid, $bid);
+        $result = db_query(
+          'INSERT INTO {user_badges_roles} (rid, bid) VALUES ' .
+          '(:rid, :bid)', array(':rid' => $rid, ':bid' => $bid));
+        $success = $success && $result;
 
         // For all of these queries, we LEFT JOIN user_badges_user to check
         // whether there are existing entries for that badge for that user
@@ -942,37 +1012,40 @@ function user_badges_save_roles($roles) {
         // The blocked user "role" (represented as rid 0) has no entry in
         // the users_role table, so it needs its own special query.
         if ($rid == 0) {
-          $success = $success && db_query("
-            INSERT INTO {user_badges_user} (uid, bid, type)
-            SELECT u.uid, %d, 'role'
-            FROM {users} u
-            LEFT JOIN {user_badges_user} ubu
-            ON ubu.uid=u.uid AND ubu.bid=%d AND ubu.type='role'
-            WHERE status = 0 AND ubu.uid IS NULL
-          ", $bid, $bid);
+          $result = db_query(
+            'INSERT INTO {user_badges_user} (uid, bid, type) ' .
+            'SELECT u.uid, :bid, \'role\' ' .
+            'FROM {users} u ' .
+            'LEFT JOIN {user_badges_user} ubu ' .
+            'ON ubu.uid=u.uid AND ubu.bid=:bid2 AND ubu.type=\'role\' ' .
+            'WHERE status = 0 AND ubu.uid IS NULL',
+            array(':bid' => $bid, ':bid2' => $bid));
+          $success = $success && $result;
         }
         // The authenticated user role (represented as rid 2) has no entry
         // in the users_role table, so it needs its own special query.
         elseif ($rid == 2) {
-          $success = $success && db_query("
-            INSERT INTO {user_badges_user} (uid, bid, type)
-            SELECT u.uid, %d, 'role'
-            FROM {users} u
-            LEFT JOIN {user_badges_user} ubu
-            ON ubu.uid=u.uid AND ubu.bid=%d AND ubu.type='role'
-            WHERE u.uid > 0 AND ubu.uid IS NULL
-          ", $bid, $bid);
+          $result = db_query(
+            'INSERT INTO {user_badges_user} (uid, bid, type) ' .
+            'SELECT u.uid, :bid, \'role\' ' .
+            'FROM {users} u ' .
+            'LEFT JOIN {user_badges_user} ubu ' .
+            'ON ubu.uid=u.uid AND ubu.bid=:bid2 AND ubu.type=\'role\' ' .
+            'WHERE u.uid >0 AND ubu.uid IS NULL',
+            array(':bid' => $bid, ':bid2' => $bid));
+          $success = $success && $result;
         }
         // For all the normal roles, we want to run this query.
         else {
-          $success = $success && db_query("
-            INSERT INTO {user_badges_user} (uid, bid, type)
-            SELECT ur.uid, %d, 'role'
-            FROM {users_roles} ur
-            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);
+          $result = db_query(
+            'INSERT INTO {user_badges_user} (uid, bid, type) ' .
+            'SELECT ur.uid, :bid, \'role\' ' .
+            'FROM {users_roles} ur ' .
+            'LEFT JOIN {user_badges_user} ubu ' .
+            'ON ubu.uid=ur.uid AND ubu.bid=:bid2 AND ubu.type=\'role\' ' .
+            'WHERE ur.rid = :rid AND ubu.uid IS NULL',
+            array(':bid' => $bid, ':bid2' => $bid, ':rid' => $rid));
+          $success = $success && $result;
         }
       }
     }
@@ -1049,7 +1122,7 @@ function user_badges_for_user($load, $list = FALSE) {
  */
 function theme_user_badge_group($badgeimages) {
   if (!empty($badgeimages)) {
-    return '<div class="user_badges">'. implode('', $badgeimages) .'</div>';
+    return '<div class="user_badges">' . implode('', $badgeimages) . '</div>';
   }
 }
 
@@ -1061,24 +1134,34 @@ function _user_badges_build_image($badge) {
     $badge->class = 'badge ' . _user_badges_class($badge);
   }
 
+  $image = '';
+
   if (variable_get('user_badges_imagecache', 0)) {
     $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).
-    $get_size = valid_url($badge->image, TRUE);
-    $image = theme('image', $badge->image, $badge->name, $badge->name, array('class' => $badge->class), !$get_size);
+
+    $image = theme('image', array('path' => $badge->image,
+                                  'alt' => $badge->name,
+                                  'title' => $badge->name,
+                                  'attributes' => array('class' => $badge->class)));
   }
 
   return $image;
+
 }
 
 /**
  * Return html representation of a badge image
  * (note: theme_image does the check_plaining)
  */
-function theme_user_badge($badge, $account = NULL) {
+function theme_user_badge(array $argv) {
+  $argv = array_merge(array('account' => NULL), $argv);
+  $badge = $argv['badge'];
+  $account = $argv['account'];
+
   //If we haven't been supplied with a user, use whoever is logged in
   global $user;
   if (is_null($account)) {
@@ -1101,18 +1184,23 @@ function theme_user_badge($badge, $account = NULL) {
     $href = $badge->href ? $badge->href : variable_get('user_badges_defaulthref', '') ;
 
     // Implement token replacement.
+    // TODO: Fix it.
+    /*
     if (module_exists('token')) {
       $href = token_replace($href, $type = 'userbadge', $object = $badge);
+      echo '2';
       $href = token_replace($href, $type = 'user', $object = $account);
-    }
+    }*/
 
     $pieces = parse_url($href);
-    $pieces['html'] = TRUE;
+
     if (isset($pieces['scheme'])) {
-      $pieces['path'] = $pieces['scheme'] . '://' . $pieces['host'] . $pieces['path'];
+      $host = (isset($pieces['host'])) ? $pieces['host'] : '';
+      $path = (isset($pieces['path'])) ? $pieces['path'] : '';
+      $pieces['path'] = $pieces['scheme'] . '://' . $host . $path;
     }
 
-    return l($image, $pieces['path'], $pieces);
+    return l($image, $pieces['path'], array('html' => true));
   }
 }
 
@@ -1284,25 +1372,36 @@ function user_badges_token_list($type = 'all') {
     return $tokens;
   }
 }
+
 /**
- * Implements hook_block();
+ * Implements hook_block_list_alter
  */
-function user_badges_block($op = 'list', $delta = 0, $edit = array()) {
-  switch ($op) {
-    case 'list':
-      return user_badges_block_list();
+function user_badges_list_alter(&$blocks) {
+  return user_badges_block_list();
+}
 
-    case 'view':
-      return user_badges_block_view($delta);
+/**
+ * Implements hook_block_view
+ */
+function user_badges_view($delta = '') {
+  return user_badges_block_view($delta);
+}
 
-    case 'configure':
-      return user_badges_block_configure($delta);
+/**
+ * Implements hook_block_configure
+ */
+function user_badges_configure($delta = '') {
+  return user_badges_block_configure($delta);
+}
 
-    case 'save':
-      return user_badges_block_save($delta, $edit);
-  }
+/**
+ * Implements hook_block_save
+ */
+function user_badges_save($delta = '', $edit = array()) {
+  return user_badges_block_save($delta, $edit);
 }
 
+
 /**
  * Function for user_badges_block(op = 'list').
  */
@@ -1325,7 +1424,7 @@ function user_badges_block_view($delta = 0) {
         $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(array('uid' => $node->uid));
+          $account = user_load($node->uid);
           $block['title'] = t("@name's Badges", array('@name' => $account->name));
           $block['content'] = $badges;
         }
@@ -1348,7 +1447,7 @@ function user_badges_block_configure($delta = 0) {
         '#type' => 'checkboxes',
         '#title' => t('Show on these content types'),
         '#default_value' => variable_get('user_badges_current_node_types', array()),
-        '#options' => node_get_types('names'),
+        '#options' => node_type_get_name(),
         '#attributes' => array('class' => 'container-inline'),
         );
       break;
@@ -1383,4 +1482,4 @@ function user_badges_block_save($delta = 0, $edit = array()) {
 //   }
 //
 //   user_badges_save_roles($roles);
-// }
+// }delete
