? user_badges-D6.patch
Index: user_badges.info
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/user_badges/user_badges.info,v
retrieving revision 1.1.2.1
diff -u -p -r1.1.2.1 user_badges.info
--- user_badges.info	18 Jun 2007 23:07:11 -0000	1.1.2.1
+++ user_badges.info	16 Sep 2008 16:21:57 -0000
@@ -1,4 +1,6 @@
 ; $Id: user_badges.info,v 1.1.2.1 2007/06/18 23:07:11 dww Exp $
 name = User badges
 description = Enables assignment of graphical badges to users and roles.
-dependencies = upload
+dependencies[] = upload
+core = 6.x
+
Index: user_badges.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/user_badges/user_badges.install,v
retrieving revision 1.1.4.3
diff -u -p -r1.1.4.3 user_badges.install
--- user_badges.install	14 Mar 2007 20:15:41 -0000	1.1.4.3
+++ user_badges.install	16 Sep 2008 16:21:57 -0000
@@ -1,65 +1,126 @@
 <?php
 // $Id: user_badges.install,v 1.1.4.3 2007/03/14 20:15:41 heine Exp $
 
-function user_badges_install() {
-  switch ($GLOBALS['db_type']) {
-    case 'mysql':
-    case 'mysqli':
-      db_query("CREATE TABLE {user_badges_badges} (
-        bid int(10) NOT NULL default '0',
-        name varchar(50) NOT NULL default '',
-        image varchar(80) NOT NULL default '',
-        weight int(2) NOT NULL default '0'
-      )");
-
-      db_query("CREATE TABLE {user_badges_product} (
-        bid int(10) NOT NULL default '0',
-        nid int(10) NOT NULL default '0'
-      )");
-
-      db_query("CREATE TABLE {user_badges_roles} (
-        rid int(10) NOT NULL default '0',
-        bid int(10) NOT NULL default '0'
-      )");
-
-      db_query("CREATE TABLE {user_badges_user} (
-        uid int(10) NOT NULL default '0',
-        bid int(10) NOT NULL default '0',
-        type varchar(20) NOT NULL default ''
-      )");
-
-      break;
-    case 'pgsql':
-      db_query("CREATE TABLE {user_badges_badges} (
-        bid int NOT NULL default '0',
-        name varchar(50) NOT NULL default '',
-        image varchar(80) NOT NULL default '',
-        weight int NOT NULL default '0',
-        PRIMARY KEY (bid)
-      ); ");
-
-      db_query("CREATE SEQUENCE {user_badges_badges}_seq");
-
-      db_query("CREATE TABLE {user_badges_product} (
-        bid int NOT NULL default '0',
-        nid int NOT NULL default '0'
-      ); ");
-
-      db_query("CREATE TABLE {user_badges_roles} (
-        rid int NOT NULL default '0',
-        bid int NOT NULL default '0'
-      ); ");
-
-      db_query("CREATE TABLE {user_badges_user} (
-        uid int NOT NULL default '0',
-        bid int NOT NULL default '0',
-        type varchar(20) NOT NULL default ''
-      ); ");
+function user_badges_schema() {
+  $schema = array();
+  $schema['user_badges_badges'] = array(
+    'description' => 'Holds the user badge images',
+    'fields' => array(
+      'bid' => array(
+        'description' => t('Original badge ID'),
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'name' => array(
+        'description' => t('Badge name'),
+        'type' => 'varchar',
+        'length' => 50,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'image' => array(
+        'description' => t('Associated image'),
+        'type' => 'varchar',
+        'length' => 80,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'weight' => array(
+        'description' => t('Order in list'),
+        'type' => 'int',
+        'not null' => TRUE,
+        'default' => 0
+      ),
+    ),
+    'primary key' => array('bid'),
+    'indexes' => array(
+      'bid_weight_name' => array('bid', 'weight', 'name'),
+      'weight_name' => array('weight', 'name'),
+    )
+  );
+  $schema['user_badges_product'] = array(
+    'description' => 'Holds the user badge images',
+    'fields' => array(
+      'bid' => array(
+        'description' => t('Original badge ID'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0
+      ),
+      'nid' => array(
+        'description' => t('Node ID'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+    ),
+    'primary key' => array('bid', 'nid'),
+    'indexes' => array(
+      'bid_nid' => array('bid', 'nid'),
+      'nid_bid' => array('nid', 'bid'),
+    ),
+  );
+  $schema['user_badges_roles'] = array(
+    'description' => 'Holds the user badge images',
+    'fields' => array(
+      'rid' => array(
+        'description' => t('Original role ID'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'bid' => array(
+        'description' => t('Original badge ID'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+    ),
+    'primary key' => array('bid', 'rid'),
+    'indexes' => array(
+      'bid_nid' => array('bid', 'rid'),
+      'nid_bid' => array('rid', 'bid'),
+    ),
+  );
+  $schema['user_badges_user'] = array(
+    'description' => 'Holds the user badge images',
+    'fields' => array(
+      'uid' => array(
+        'description' => t('Original user ID'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'bid' => array(
+        'description' => t('Original badge ID'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'type' => array(
+        'description' => t('Badge Type'),
+        'type' => 'varchar',
+        'length' => 20,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+    ),
+    'primary key' => array('bid', 'uid', 'type'),
+    'indexes' => array(
+      'bid_uid_type' => array('bid', 'uid', 'type'),
+      'uid_bid' => array('uid', 'bid'),
+      'type' => array('type'),
+    ),
+  );
+  
+  return $schema;
+}
 
-      break;
-    default:
-      break;
-  }
+function user_badges_install() {
+  drupal_install_schema('user_badges');
 }
 
 function user_badges_uninstall() {
@@ -72,14 +133,17 @@ function user_badges_uninstall() {
     }
   }
   
-  // Delete the badges directory.  
+  // Delete the badges directory.
   if (file_exists($dir)) {
     rmdir($dir);
   }
+  drupal_uninstall_schema('user_badges');
+}
 
-  // Remove database tables.
-  db_query("DROP TABLE {user_badges_badges}");
-  db_query("DROP TABLE {user_badges_roles}");
-  db_query("DROP TABLE {user_badges_user}");
-  db_query("DROP TABLE {user_badges_product}");
+function user_badges_update_6001() {
+  $ret = array();
+  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;
 }
\ No newline at end of file
Index: user_badges.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/user_badges/user_badges.module,v
retrieving revision 1.14.2.5
diff -u -p -r1.14.2.5 user_badges.module
--- user_badges.module	16 Mar 2007 13:00:28 -0000	1.14.2.5
+++ user_badges.module	16 Sep 2008 16:21:58 -0000
@@ -1,130 +1,115 @@
 <?php
 /* $Id: user_badges.module,v 1.14.2.5 2007/03/16 13:00:28 heine Exp $ */
 
-# Todo: convert to 5, make it work with private files.
+// TODO: make it work with private files.
 
-function user_badges_help($section) {
-  switch ($section) {
+/**
+ * Implementation of hook_help().
+ */
+function user_badges_help($path, $arg) {
+  switch ($path) {
     case 'admin/modules#description':
       // This description is shown in the listing at admin/modules.
       return t('Merit badges that administrators can assign to users.');
+      
     case 'admin/settings/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).");
+      
     case 'admin/settings/user_badges/roles':
       return t("Select the badge that you'd like to associate with each role.");
+      
     case 'admin/settings/user_badges/images':
       return t("Upload images to display as a user badge. These 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/settings/user_badges/products':
-      return t("For each ecommerce product listed below, select the badge that will be assigned to users upon payment completion.");
   }
 }
 
+/**
+ * Implementation of hook_perm().
+ */
 function user_badges_perm() {
   return array('manage badges');
 }
 
-
-function user_badges_menu($may_cache) {
-  $access = user_access('manage badges');
-  if ($may_cache) {
-    $items[] = array(
-      'path' => 'admin/user/user_badges',
-      'title' => t('Badges'),
-      'callback' => 'user_badges_settings_page',
-      'access' => $access,
-    );
-  }
-  else {
-    $items[] = array(
-      'path' => 'admin/user/user_badges/list',
-      'title' => t('Edit user badges'),
-      'access' => $access,
-      'type' => MENU_DEFAULT_LOCAL_TASK,
-      'weight' => -10
-    );
-    $items[] = array(
-      'path' => 'admin/user/user_badges/images',
-      'title' => t('Images'),
-      'callback' => 'drupal_get_form',
-      'callback arguments' => array('user_badges_images_form'),
-      'access' => $access,
-      'type' => MENU_LOCAL_TASK
-    );
-    $items[] = array(
-      'path' => 'admin/user/user_badges/roles',
-      'title' => t('Roles'),
-      'callback' => 'drupal_get_form',
-      'callback arguments' => array('user_badges_roles_form'),
-      'access' => $access,
-      'type' => MENU_LOCAL_TASK
-    );
-    if (module_exists('product')) {
-      $items[] = array(
-        'path' => 'admin/user/user_badges/products',
-        'title' => t('Products'),
-        'callback' => 'user_badges_products_page',
-        'weight' => 8,
-        'access' => $access,
-        'type' => MENU_LOCAL_TASK
-      );
-    }
-    $items[] = array(
-      'path' => 'admin/user/user_badges/delete',
-      'title' => t('Delete badge'),
-      'callback' => 'drupal_get_form',
-      'callback arguments' => array('user_badges_delete_form'),
-      'access' => $access,
-      'type' => MENU_CALLBACK,
-    );
-    if (arg(0) == 'user') {
-      if ($access) {
-        $uid = arg(1);
-      }
-      if (is_numeric($uid)) {
-        $items[] = array(
-          'path' => "user/$uid/badges",
-          'title' => t('Badges'),
-          'callback' => 'user_badges_page',
-          'access' => $access,
-          'type' => MENU_LOCAL_TASK,
-          'weight' => 5,
-        );
-      }
-    }
-  }
+/**
+ * Implementation of hook_menu().
+ */
+function user_badges_menu() {
+  $items = array();
+  $access = user_badges_perm();
+  $items['admin/user/user_badges'] = array(
+    'title' => 'Badges',
+    'page callback' => 'user_badges_settings_page',
+    'access arguments' => $access,
+  );
+  
+  $items['admin/user/user_badges/list'] = array(
+    'title' => 'Edit user badges',
+    'access arguments' => $access,
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+    'weight' => -10,
+  );
+  $items['admin/user/user_badges/images'] = array(
+    'title' => 'Images',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('user_badges_images_form'),
+    'access arguments' => $access,
+    'type' => MENU_LOCAL_TASK,
+  );
+  $items['admin/user/user_badges/roles'] = array(
+    'title' => 'Roles',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('user_badges_roles_form'),
+    'access arguments' => $access,
+    'type' => MENU_LOCAL_TASK,
+  );
+  $items['admin/user/user_badges/delete'] = array(
+    'title' => 'Delete badge',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('user_badges_delete_form'),
+    'access arguments' => $access,
+    'type' => MENU_CALLBACK,
+  );
+  $items['user/%user/badges'] = array(
+    'title' => 'Badges',
+    'page callback' => 'user_badges_page',
+    'page arguments' => array(1),
+    'access arguments' => $access,
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 5,
+  );
+  
   return $items;
 }
 
-
 /**
- * Implementation of hook_user()
- * This handles assignment of badges based on role.
- * When role is assigned or removed, appropriate badges are added or removed.
+ * Implementation of 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, &$user, $category = 'account') {
+function user_badges_user($op, &$edit, &$account, $category = 'account') {
   switch ($op) {
 
     case 'load':
-      if ($user->uid > 0) {
-        $user->badges = user_badges_get_badges($user->uid);
+      if ($account->uid > 0) {
+        $account->badges = user_badges_get_badges($account->uid);
       }
       break;
 
     case 'insert':
-      if (is_array($user->roles)){
-        // get the list of role badges
+      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($user->roles);
-        foreach($rids as $rid){
+        $rids = array_keys($account->roles);
+        foreach ($rids as $rid) {
           // if this role has a badge
-          if (key_exists($rid, $roles)){
+          if (key_exists($rid, $roles)) {
             // and user doesn't already have this badge
-            if (!key_exists($roles[$rid], $user->badges)){
-              $success = user_badges_user_add_badge($user->uid, $roles[$rid], 'role');
-              if($success && $message){
+            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]])));
               }
             }
@@ -134,7 +119,7 @@ function user_badges_user($op, &$edit, &
       break;
 
     case 'update':
-      if (is_array($edit['roles'])){
+      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
@@ -147,23 +132,23 @@ function user_badges_user($op, &$edit, &
         $message = user_access('manage badges');
 
         // What are the added roles?
-        $added = array_diff(array_keys($new_roles), array_keys((array)$user->roles));
-        foreach($added as $rid){
+        $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], $user->badges)){
-            $success = user_badges_user_add_badge($user->uid, $roles[$rid], 'role');
-            if($success && $message){
+          if (key_exists($rid, $roles) && !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]])));
             }
           }
         }
 
         // What are the removed roles?
-        $removed = array_diff(array_keys((array)$user->roles), array_keys($new_roles));
-        foreach($removed as $rid){
+        $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], $user->badges)) {
-            $success = user_badges_user_remove_badge($user->uid, $roles[$rid], 'role');
+          if (key_exists($rid, $roles) && key_exists($roles[$rid], $account->badges)) {
+            $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]])));
           }
         }
@@ -171,31 +156,50 @@ function user_badges_user($op, &$edit, &
       break;
 
     case 'delete':
-      db_query('DELETE FROM {user_badges_user} WHERE uid = %d', $user->uid);
+      db_query('DELETE FROM {user_badges_user} WHERE uid = %d', $account->uid);
       break;
 
     case 'view':
-      foreach($user->badges as $badge) {
+      $badgeimgs = array();
+      foreach ($account->badges as $badge) {
         $badgeimgs[] = theme('user_badge', $badge);
       }
-      if ($badgeimgs) {
-      	$badge_group[] = array(
-          'title' => '',
-          'value' => theme('user_badge_group', $badgeimgs),
-          'class' => '',
+      if (!empty($badgeimgs)) {
+        $account->content['user_badges'] = array(
+          '#type' => 'user_profile_category',
+          '#title' => t('Badges'),
+          '#weight' => 10,
+        );
+        $account->content['user_badges']['badges'] = array(
+          '#type' => 'user_profile_item',
+          '#value' => theme('user_badge_group', $badgeimgs),
         );
-        return array(t('Badges') => $badge_group);
       }
   }
 }
 
 /**
- * Define the page on user/uid/badges.
+ * Implementation of hook_theme().
  */
-function user_badges_page() {
-  $uid = arg(1);
-  $account = user_load(array('uid' => $uid));
+function user_badges_theme() {
+  $themes = array();
+  $themes['user_badge'] = array(
+    'arguments' => array(
+      'badge' => NULL,
+    ),
+  );
+  $themes['user_badge_group'] = array(
+    'arguments' => array(
+      'badgeimages' => array(),
+    ),
+  );
+  return $themes;
+}
 
+/**
+ * Define the page on user/uid/badges.
+ */
+function user_badges_page($account) {
   drupal_set_title(t('Edit badges for %user_name', array('%user_name' => $account->name)));
 
   return drupal_get_form('user_badges_page_form', $account);
@@ -204,7 +208,7 @@ function user_badges_page() {
 /**
  * Form to assign badges to users.
  */
-function user_badges_page_form($account) {
+function user_badges_page_form(&$form_state, $account) {
   $form = array();
 
   $form['uid'] = array('#type' => 'value', '#value' => $account->uid);
@@ -228,25 +232,27 @@ function user_badges_page_form($account)
   return $form;
 }
 
-function user_badges_page_form_submit($form_id, $form_values) {
-  user_badges_user_save($form_values['badges'], $form_values['uid'], FALSE);
+function user_badges_page_form_submit($form, &$form_state) {
+  $badges = $form_state['values']['badges'];
+  $uid = $form_state['values']['uid'];
+  user_badges_user_save($badges, $uid, FALSE);
 }
 
 /**
-  * Assign user badges to a user
-  *
-  * $edit is an array containing badges array
-  * $uid is the user id
-  * $quiet suppresses message display
-  */
+ * Assign user badges to a user
+ *
+ * $edit is an array containing badges array
+ * $uid is the user id
+ * $quiet suppresses message display
+ */
 function user_badges_user_save($edit, $uid, $quiet = TRUE) {
   $badges = user_badges_get_badges($uid);
 
   if (is_array($edit)) {
     // an array of just the checked boxes please
     $newbadges = array();
-    foreach($edit as $bid => $is_selected){
-      if ($is_selected){
+    foreach ($edit as $bid => $is_selected) {
+      if ($is_selected) {
         $newbadges[] = $bid;
       }
     }
@@ -256,8 +262,8 @@ function user_badges_user_save($edit, $u
     // what are the added badges?
     $added = array_diff($newbadges, array_keys($badges));
 
-    foreach($added as $bid){
-      if (!key_exists($bid, $badges)){
+    foreach ($added as $bid) {
+      if (!key_exists($bid, $badges)) {
         $success = (boolean) user_badges_user_add_badge($uid, $bid);
       }
     }
@@ -265,9 +271,9 @@ function user_badges_user_save($edit, $u
     // what are the removed badges?
     $removed = array_diff(array_keys($badges), $newbadges);
 
-    foreach($removed as $bid){
+    foreach ($removed as $bid) {
       // and user has this badge
-      if (key_exists($bid, $badges)){
+      if (key_exists($bid, $badges)) {
         $success = $success && (boolean) user_badges_user_remove_badge($uid, $bid);
       }
     }
@@ -275,7 +281,7 @@ function user_badges_user_save($edit, $u
       drupal_set_message(t('Badges saved.'));
     }
     elseif (!$quiet) {
-      drupal_set_message(t('There was a problem saving badges to the database.'));
+      drupal_set_message(t('There was a problem saving badges to the database.'), 'error');
     }
   }
 }
@@ -292,12 +298,12 @@ function user_badges_user_save($edit, $u
  *
  * @return unknown
  */
-function user_badges_user_add_badge($uid, $bid, $type = NULL){
+function user_badges_user_add_badge($uid, $bid, $type = NULL) {
   return db_query('INSERT INTO {user_badges_user} (uid, bid, type) VALUES (%d, %d, \'%s\')', $uid, $bid, $type);
 }
 
-function user_badges_user_remove_badge($uid, $bid, $type = NULL){
-  if (is_null($type)){
+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 {
@@ -306,18 +312,19 @@ function user_badges_user_remove_badge($
 }
 
 function user_badges_settings_page($op = NULL, $bid = NULL) {
-
   switch ($op) {
     case 'edit':
       if (is_numeric($bid)) {
         $output = drupal_get_form('user_badges_edit_form', $bid);
-        break;
       }
+      break;
+      
     case 'delete' :
       if (is_numeric($bid)) {
         $output = user_badges_delete($bid);
-        break;
       }
+      break;
+      
     default:
       $badges = user_badges_get_badges('all');
       $header = array(t('Name'), t('Image'), t('Operations'));
@@ -325,30 +332,31 @@ function user_badges_settings_page($op =
         foreach ($badges as $badge) {
           $tablerow[$badge->bid]['name'] = $badge->name;
           $tablerow[$badge->bid]['image'] = theme('image', $badge->image, $badge->image, $badge->image);
-          $tablerow[$badge->bid]['ops'] = l(t('edit'), 'admin/user/user_badges/edit/'.$badge->bid).' '.l(t('delete'), 'admin/user/user_badges/delete/'.$badge->bid);
+          $tablerow[$badge->bid]['ops'] = l(t('edit'), 'admin/user/user_badges/edit/'. $badge->bid) .' '. l(t('delete'), 'admin/user/user_badges/delete/'. $badge->bid);
         }
       }
-      $output = theme('table', $header, $tablerow, array('style'=>'width:100%'));
+      $output = theme('table', $header, $tablerow, array('style' => 'width:100%'));
       $output .= "<br/><br/>";
       $form[] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Add another'),
-    );
-    //$output .= user_badges_edit_form();
-    $output .= drupal_get_form('user_badges_edit_form');
-
+        '#type' => 'fieldset',
+        '#title' => t('Add another'),
+      );
+      //$output .= user_badges_edit_form();
+      $output .= drupal_get_form('user_badges_edit_form');
+      break;
   }
+  
   return $output;
 }
 
-function user_badges_edit_form_submit($form_id, $form_values) {
-  user_badges_save_badge($form_values);
+function user_badges_edit_form_submit($form, &$form_state) {
+  $form_state['redirect'] = user_badges_save_badge($form_state['values']);
 }
 
 /**
  * Define a form to upload the badge images.
  */
-function user_badges_images_form() {
+function user_badges_images_form($form_state) {
   $form = array('#skip_duplicate_check' => TRUE);
   if (module_exists('upload')) {
     $form['new']['upload'] = array('#type' => 'file', '#title' => t('Upload image'), '#size' => 40);
@@ -362,7 +370,7 @@ function user_badges_images_form() {
 
   $selects = user_badges_image_selects();
   if (count($selects)) {
-  	$form['images'] = array('#tree' => TRUE);
+    $form['images'] = array('#tree' => TRUE);
     foreach ($selects as $imagepath => $imageimg) {
       $form['images'][$imagepath] = array(
         '#type' => 'checkbox',
@@ -388,40 +396,54 @@ function user_badges_images_form() {
  * OR
  * Upload has been chosen AND the file upload form is not empty.
  */
-function user_badges_images_form_validate($form_id, $form_values) {
-  if ($form_values['op'] == t('Upload') && file_check_upload('upload') === FALSE ) {
-    form_set_error('upload', t('Please enter the filename of an image to upload.'));
+function user_badges_images_form_validate($form, &$form_state) {
+  $op = $form_state['clicked_button']['#value'];
+  if ($op == t('Upload')) {
+    $dir = file_create_path('badges');
+    $is_writable = file_check_directory($dir, 1);
+    if ($is_writable) {
+      if ($file = file_save_upload('upload', array(), $dir)) {
+        if (!image_get_info($file->filepath)) {
+          file_delete($file->filepath);
+          form_set_error('upload', t('Uploaded image file does not appear to be a valid image file.  Please try again'));
+        }
+        else {
+          user_badges_hold_temporary_file($file);
+          $form_state['values']['file_image'] = $file;
+        }
+      }
+      else {
+        form_set_error('upload', t('Cannot save image.  Enter the path to an image and try again.'));
+      }
+    }
+    else {
+      form_set_error('upload', t('Cannot save image - directory not writable'));
+    }
   }
-  else if ($form_values['op'] == t('Delete')) {
-    if (count(array_filter($form_values['images'])) == 0) {
+  else if ($op == t('Delete')) {
+    if (count(array_filter($form_state['values']['images'])) == 0) {
       form_set_error('images', t('Please select images to delete.'));
     }
   }
 }
 
-function user_badges_images_form_submit($form_id, $form_values) {
-  $op = $form_values['op'];
+function user_badges_hold_temporary_file($file = NULL) {
+  static $static_file;
+  if (isset($file)) {
+    $static_file = $file;
+  }
+  return $file;
+}
+
+function user_badges_images_form_submit($form, &$form_state) {
+  $op = $form_state['clicked_button']['#value'];
   // Save uploaded files
   if ($op == t('Upload')) {
-    $dir = file_create_path('badges');
-    $is_writable = file_check_directory($dir, 1);
-    if ($is_writable) {
-      if( $source = file_check_upload('upload')) {
-        // Security measure to prevent exploit of file.php.png
-        $source->filename = upload_munge_filename($source->filename);
-        if ($file = file_save_upload($source, $dir)) {
-          if (image_get_info($file->filepath)) {
-            drupal_set_message(t('New image saved.'));
-          } else {
-            file_delete($file->filepath);
-            drupal_set_message('Uploaded file does not appear to be a valid image file. Please try again.');
-          }
-        }
-      }
-    }
+    $file = $form_state['values']['file_image'];
+    file_set_status($file, FILE_STATUS_PERMANENT);
   }
   else if ($op == t('Delete')) {
-    foreach ($form_values['images'] as $path => $is_removed) {
+    foreach ($form_state['values']['images'] as $path => $is_removed) {
       if ($is_removed) {
         $to_delete[] = $path;
       }
@@ -445,12 +467,12 @@ function user_badges_roles_form() {
   $badges = user_badges_get_roles();
   $selects = array('' => 'inactive') + user_badges_get_badges('select');
   $form['roles'] = array('#tree' => TRUE);
-  foreach($roles as $rid => $role) {
+  foreach ($roles as $rid => $role) {
     if ($rid != 1) { // no badges for the anonymous role
       $form['roles'][$rid] = array(
         '#type' => 'select',
         '#title' => $role,
-        '#default_value' => $badges[$rid],
+        '#default_value' => isset($badges[$rid]) ? $badges[$rid] : '',
         '#options' => $selects,
       );
     }
@@ -462,122 +484,123 @@ function user_badges_roles_form() {
   return $form;
 }
 
-function user_badges_roles_form_submit($form_id, $form_values) {
-	user_badges_save_roles($form_values['roles']);
+function user_badges_roles_form_submit($form, &$form_state) {
+  user_badges_save_roles($form_state['values']['roles']);
 }
 
 /**
-  * Return array of user badges where keys are badge ids (bid)
-  *   and values are object containing badge info
-  * if $uid is a user id, returns badges for that user
-  * if $uid is 'all', returns all badges
-  * if $uid is 'select', returns badges for form_select options
-  *   returned values for 'select' are just badge names
-  *
-  */
+ * Return array of user badges where keys are badge ids (bid)
+ *   and values are object containing badge info
+ * if $uid is a user id, returns badges for that user
+ * if $uid is 'all', returns all badges
+ * if $uid is 'select', returns badges for form_select options
+ *   returned values for 'select' are just badge names
+ */
 function user_badges_get_badges($uid) {
-  $badges = array();
-  if ($uid == 'all' || $uid == 'select') {
-    $sql = db_query('SELECT b.bid, b.weight, b.name, b.image FROM {user_badges_badges} b ORDER BY b.weight, b.name');
-  }
-  else {
-    $sql = db_query('SELECT DISTINCT b.bid, b.weight, b.name, b.image FROM {user_badges_badges} b INNER JOIN {user_badges_user} u ON b.bid = u.bid WHERE u.uid = %d ORDER BY b.weight, b.name', $uid);
-  }
-  while ($badge = db_fetch_object($sql)) {
-    if ($uid == 'select') {
-      $badges[$badge->bid] = $badge->name;
+  static $badges, $past_uid;
+  if (empty($past_uid) || $past_uid !== $uid) {
+    $past_uid = $uid;
+    $badges = array();
+    if ($uid == 'all' || $uid == 'select') {
+      $sql = db_query('SELECT b.bid, b.weight, b.name, b.image FROM {user_badges_badges} b ORDER BY b.weight, b.name');
     }
     else {
-      $badges[$badge->bid] = $badge;
+      $sql = db_query('SELECT DISTINCT b.bid, b.weight, b.name, b.image FROM {user_badges_badges} b INNER JOIN {user_badges_user} u ON b.bid = u.bid WHERE u.uid = %d ORDER BY b.weight, b.name', $uid);
+    }
+    while ($badge = db_fetch_object($sql)) {
+      if ($uid == 'select') {
+        $badges[$badge->bid] = $badge->name;
+      }
+      else {
+        $badges[$badge->bid] = $badge;
+      }
     }
   }
+  
   return $badges;
 }
 
-
 /**
-  * Return badge object for given badge id
-  */
+ * 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));
 }
 
 /**
  * Define the edit form for userbadges.
- *
  */
-function user_badges_edit_form($bid = NULL) {
+function user_badges_edit_form($form_state, $bid = NULL) {
   if (is_numeric($bid)) {
     $edit = db_fetch_object(db_query('SELECT * FROM {user_badges_badges} WHERE bid = %d', $bid));
     if (is_numeric($edit->bid)) {
       $form['bid'] = array(
-    '#type' => 'hidden',
-    '#value' => $edit->bid,
-    );
+        '#type' => 'hidden',
+        '#value' => $edit->bid,
+      );
     }
   }
   $form['name'] = array(
-  '#type' => 'textfield',
-  '#title' => t('Name'),
-  '#default_value' => $edit->name,
-  '#size' => 40,
-  '#maxlength' => 100,
-  '#description' => t('Name for the badge. Will be displayed as tooltip when rolling over badge image.'),
-  '#attributes' => NULL,
-  '#required' => TRUE,
+    '#type' => 'textfield',
+    '#title' => t('Name'),
+    '#default_value' => isset($edit) ? $edit->name : '',
+    '#size' => 40,
+    '#maxlength' => 100,
+    '#description' => t('Name for the badge. Will be displayed as tooltip when rolling over badge image.'),
+    '#attributes' => NULL,
+    '#required' => TRUE,
   );
   $selects = user_badges_image_selects();
   if (count($selects)) {
-  $form['image'] = array(
-    '#type' => 'radios',
-    '#title' => t('Image'),
-    '#default_value' => $edit->image,
-    '#options' => $selects,
-    '#description' => t('Select an image to associate with this badge. You can upload additional images on the <a href="@url">Images page</a>.', array('@url' => url("admin/user/user_badges/images"))),
-  );
+    $form['image'] = array(
+      '#type' => 'radios',
+      '#title' => t('Image'),
+      '#default_value' => isset($edit) ? $edit->image : '',
+      '#options' => $selects,
+      '#description' => t('Select an image to associate with this badge. You can upload additional images on the <a href="@url">Images page</a>.', array('@url' => url("admin/user/user_badges/images"))),
+    );
   }
   else {
-    drupal_set_message('<strong>' . t('You have to <a href="@upload_link">upload badge images</a> first.', array('@upload_link' => url("admin/user/user_badges/images"))). '</strong>', 'error');
+    drupal_set_message('<strong>'. t('You have to <a href="@upload_link">upload badge images</a> first.', array('@upload_link' => url("admin/user/user_badges/images"))) .'</strong>', 'error');
   }
   $form['weight'] = array(
     '#type' => 'weight',
     '#title' => t('Weight'),
-    '#default_value' => $edit->weight,
+    '#default_value' => isset($edit) ? $edit->weight : '',
     '#delta' => 10,
     '#description' => t('Lighter weighted items float to the top of lists. Heavier items go to the bottom.'),
   );
-  $form[] = array(
-  '#type' => 'submit',
-  '#value' => 'Submit',
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Submit'),
   );
   return $form;
 }
 
 /**
-  * Saves information about a badge into the database
-  *
-  */
+ * Saves information about a badge into the database
+ */
 function user_badges_save_badge($edit) {
   $edit = (object)$edit;
-  if (is_numeric($edit->bid)) {
+  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) VALUES (%d, '%s', '%s', %d)", $edit->bid, $edit->name, $edit->image, $edit->weight);
+    drupal_set_message('Edited image');
   }
   else {
-    $edit->bid = db_next_id('user_badges_badges');
+    $result = db_query("INSERT INTO {user_badges_badges} (name, image, weight) VALUES ('%s', '%s', %d)", $edit->name, $edit->image, $edit->weight);
+    drupal_set_message('Inserted new image');
   }
-  $result = db_query("INSERT INTO {user_badges_badges} (bid, name, image, weight) VALUES (%d, '%s', '%s', %d)", $edit->bid, $edit->name, $edit->image, $edit->weight);
   if ($result) {
     drupal_set_message(t('Badge %badgename saved.', array('%badgename' => $edit->name)));
   }
   else {
     drupal_set_message(t('There was a problem saving the badge information into the database.'));
   }
-  drupal_goto('admin/user/user_badges');
-  return $result;
+  return 'admin/user/user_badges';
 }
 
-
-function user_badges_delete_form($bid) {
+function user_badges_delete_form($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))));
@@ -587,12 +610,13 @@ function user_badges_delete_form($bid) {
   form_set_error('', t('This badge does not exist.'));
 }
 
-function user_badges_delete_form_submit($form_id, $form_values) {
-  db_query("DELETE FROM {user_badges_badges} WHERE bid = %d", $form_values['bid']);
-  db_query("DELETE FROM {user_badges_user} WHERE bid = %d", $form_values['bid']);
-  db_query("DELETE FROM {user_badges_roles} WHERE bid = %d", $form_values['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);
   drupal_set_message(t('Badge deleted.'));
-  return 'admin/user/user_badges';
+  $form_state['redirect'] = 'admin/user/user_badges';
 }
 
 function user_badges_image_selects() {
@@ -602,22 +626,21 @@ function user_badges_image_selects() {
   foreach ($files as $file) {
     $selects[$file->filename] = theme('image', $file->filename, $file->filename, $file->filename);
   }
+  
   return $selects;
 }
 
 /**
-  * Returns an array where keys are role ids (rid) and values are badge ids (bid)
-  * These values are assigned on admin/user/user_badges/roles
-  *
-  * @param
-  * $rid - if set, return only value for this role
-  *
-  * @return
-  * a list of roles
-  *
-  */
-
-function user_badges_get_roles($rid = NULL){
+ * Returns an array where keys are role ids (rid) and values are badge ids (bid)
+ * These values are assigned on admin/user/user_badges/roles
+ *
+ * @param
+ * $rid - if set, return only value for this role
+ *
+ * @return
+ * a list of roles
+ */
+function user_badges_get_roles($rid = NULL) {
   $roles = array();
   if ($rid) {
     $sql = db_query('SELECT * FROM {user_badges_roles} WHERE rid = %d', $rid);
@@ -628,13 +651,13 @@ function user_badges_get_roles($rid = NU
   while ($row = db_fetch_object($sql)) {
     $roles[$row->rid] = $row->bid;
   }
+  
   return $roles;
 }
 
 /**
-  * Save information about roles for user_badges (in settings)
-  *
-  */
+ * Save information about roles for user_badges (in settings)
+ */
 function user_badges_save_roles($roles) {
   if (is_array($roles)) {
     $success = TRUE;
@@ -644,11 +667,11 @@ function user_badges_save_roles($roles) 
       if ($bid) {
         $success = $success && db_query('INSERT INTO {user_badges_roles} (rid, bid) VALUES (%d, %d)', $rid, $bid);
         // Authenticated user, rid 2 has no entry in the users_role table
-        if($rid == 2) {
-          $success = $success && db_query("INSERT INTO {user_badges_user} (uid, bid, type) SELECT uid, %d, 'role' FROM {users} WHERE uid > 0", $bid);
+        if ($rid == 2) {
+          $success = $success && db_query("INSERT INTO {user_badges_user} (uid, bid, type) (SELECT uid, %d, 'role' FROM {users} WHERE uid > 0)", $bid);
         }
         else {
-          $success = $success && db_query("INSERT INTO {user_badges_user} (uid, bid, type) SELECT uid, %d, 'role' FROM {users_roles} WHERE rid=%d", $bid, $rid);
+          $success = $success && db_query("INSERT INTO {user_badges_user} (uid, bid, type) (SELECT uid, %d, 'role' FROM {users_roles} WHERE rid=%d)", $bid, $rid);
         }
       }
     }
@@ -661,7 +684,6 @@ function user_badges_save_roles($roles) 
   }
 }
 
-
 /**
  * Returns HTML representation of user badges for given uid
  *   @param $uid
@@ -670,36 +692,33 @@ function user_badges_save_roles($roles) 
  *     when TRUE, refreshes the cache for $uid
  *   @return string
  *     html representation of userbadges
- *
  */
 function user_badges_for_uid($uid, $refresh = FALSE) {
   static $cache;
-  if($uid) {
-    if(isset($cache[$uid]) && !$refresh) {
+  if ($uid) {
+    if (isset($cache[$uid]) && !$refresh) {
       return $cache[$uid];
     }
     else {
       $user_badges = user_badges_get_badges($uid);
-	    foreach((array)$user_badges as $badge) {
+        foreach ((array)$user_badges as $badge) {
         $badges[] = theme('user_badge', $badge);
       }
       $cache[$uid] = isset($badges) ? theme('user_badge_group', $badges) : '';
       return $cache[$uid];
     }
   }
-
 }
 
 /**
-  * Returns HTML representation of user badges for given user
-  * $array is array defining criteria for user_load()
-  * most common use will be:
-  *   user_badges_for_user(array('uid'=>123));
-  *
-  */
+ * Returns HTML representation of user badges for given user
+ * $array is array defining criteria for user_load()
+ * most common use will be:
+ *   user_badges_for_user(array('uid'=>123));
+ */
 function user_badges_for_user($array) {
   $account = user_load($array);
-  foreach((array)$account->badges as $badge) {
+  foreach ((array)$account->badges as $badge) {
     $badges[] = theme('user_badge', $badge);
   }
   if ($badges) {
@@ -708,115 +727,19 @@ function user_badges_for_user($array) {
 }
 
 /**
-  * Return html representation of a group of badges
-  * $badgeimages is an array of badge image tags from theme_user_badge()
-  *
-  */
-
+ * Return html representation of a group of badges
+ * $badgeimages is an array of badge image tags from theme_user_badge()
+ */
 function theme_user_badge_group($badgeimages) {
-   if (!empty($badgeimages)) {
-    return '<div class="user_badges">'.implode('', $badgeimages)."</div>";
-   }
+  if (!empty($badgeimages)) {
+    return '<div class="user_badges">'. implode('', $badgeimages) .'</div>';
+  }
 }
 
 /**
-  * Return html representation of a badge image
-  * (note: theme_image does the check_plaining)
-  */
+ * Return html representation of a badge image
+ * (note: theme_image does the check_plaining)
+ */
 function theme_user_badge($badge) {
   return theme('image', $badge->image, $badge->name, $badge->name);
 }
-
-
-
-function user_badges_products_page() {
-  $products = user_badges_get_product_list();
-  $badges = user_badges_get_products();
-  $selects = array(''=>'inactive') + user_badges_get_badges('select');
-  $form['products'] = array('#tree' => TRUE);
-  foreach($products as $key => $val) {
-      $form['products'][$key] = array(
-        '#type' => 'select',
-        '#title' => $val->title,
-        '#default_value' => $badges[$key],
-        '#options' => $selects,
-        '#description' => check_plain($val->sku),
-      );
-  }
-  $form[] = array(
-    '#type' => 'submit',
-    '#value' => 'Save',
-  );
-  $output = drupal_get_form('user_badges_products_page', $form);
-
-  return $output;
-}
-
-function user_badges_products_page_submit($form_id, $form_values) {
-  user_badges_save_products($form_values['products']);
-}
-
-function user_badges_save_products($edit) {
-  if (is_array($edit)) {
-    $success = TRUE;
-    db_query('DELETE FROM {user_badges_product}');
-    foreach ($edit as $nid => $bid) {
-      if ($bid) {
-        $success = $success && db_query('INSERT INTO {user_badges_product} (nid, bid) VALUES (%d, %d)', $nid, $bid);
-      }
-    }
-    if ($success) {
-      drupal_set_message(t('Products saved.'));
-    }
-    else {
-      drupal_set_message(t('There was a problem saving product information to the database'));
-    }
-  }
-}
-
-
-function user_badges_ecommerceapi($t, $op) {
-  switch ($op) {
-    case 'on payment completion':
-      $productbadges = user_badges_get_products();
-      foreach ($t['items'] as $item) {
-        if (array_key_exists($item->nid, $productbadges)) {
-          // no duplicates please...
-          db_query("DELETE FROM {user_badges_user} WHERE uid=%d AND bid=%d", $t['uid'], $productbadges[$item->nid]);
-          db_query("INSERT INTO {user_badges_user} (uid, bid, type) VALUES (%d, %d, 'product')", $t['uid'], $productbadges[$item->nid]);
-        }
-      }
-  }
-}
-
-function user_badges_get_sku($nid) {
-  return db_result(db_query('SELECT sku FROM {ec_product} WHERE nid = %d', $nid));
-}
-
-/**
-  * Get list of all ecommerce products
-  */
-
-function user_badges_get_product_list() {
-  $products = array();
-  $sql = db_query('SELECT p.*, n.title FROM {ec_product} p INNER JOIN {node} n ON p.nid = n.nid ORDER BY sku');
-  while ($row = db_fetch_object($sql)) {
-    $products[$row->nid] = $row;
-  }
-  return $products;
-}
-
-/**
-  * Get list of products that have badges
-  * keys are node ids (nid)
-  * values are badge ids (bid)
-  */
-
-function user_badges_get_products() {
-  $products = array();
-  $sql = db_query('SELECT * FROM {user_badges_product}');
-  while ($row = db_fetch_object($sql)) {
-    $products[$row->nid] = $row->bid;
-  }
-  return $products;
-}
