Index: drupalvb.admin-pages.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/drupalvb/drupalvb.admin-pages.inc,v
retrieving revision 1.10
diff -u -p -r1.10 drupalvb.admin-pages.inc
--- drupalvb.admin-pages.inc	15 Oct 2008 01:43:45 -0000	1.10
+++ drupalvb.admin-pages.inc	15 Oct 2008 01:47:39 -0000
@@ -126,7 +126,7 @@ function drupalvb_settings_database() {
   return $form;
 }
 
-function drupalvb_settings_database_submit($form_id, $form_values) {
+function drupalvb_settings_database_submit($form, &$form_state) {
   $initial_import = FALSE;
   // If there is no database configuration yet, we want to execute an initial
   // user import later.
@@ -134,10 +134,10 @@ function drupalvb_settings_database_subm
     $initial_import = TRUE;
   }
 
-  $url = $form_values['scheme'] .'://'. $form_values['user'] .':'. $form_values['pass'] .'@'. $form_values['host'] .'/'. $form_values['path'];
+  $url = $form_state['values']['scheme'] .'://'. $form_state['values']['user'] .':'. $form_state['values']['pass'] .'@'. $form_state['values']['host'] .'/'. $form_state['values']['path'];
   variable_set('drupalvb_db', $url);
   variable_set('drupalvb_db_is_default', (is_array($GLOBALS['db_url']) ? $GLOBALS['db_url']['default'] == $url : $GLOBALS['db_url'] == $url));
-  variable_set('drupalvb_db_prefix', $form_values['db_prefix']);
+  variable_set('drupalvb_db_prefix', $form_state['values']['db_prefix']);
 
   if ($initial_import) {
     // First time setup; initialize DrupalvB's user mapping.
@@ -180,8 +180,8 @@ function drupalvb_settings_actions() {
 /**
  * Form submit callback for action form.
  */
-function drupalvb_settings_actions_submit($form_id, $form_values) {
-  switch ($form_values['action']) {
+function drupalvb_settings_actions_submit($form, &$form_state) {
+  switch ($form_state['values']['action']) {
     case 'export':
       drupalvb_export_drupal_users();
       drupal_set_message(t('Drupal users have been exported to vBulletin.'));
Index: drupalvb.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/drupalvb/drupalvb.inc,v
retrieving revision 1.14
diff -u -p -r1.14 drupalvb.inc
--- drupalvb.inc	15 Oct 2008 02:31:03 -0000	1.14
+++ drupalvb.inc	15 Oct 2008 02:53:53 -0000
@@ -163,6 +163,32 @@ function drupalvb_db_query($query) {
 }
 
 /**
+ * Query remote system database with range.
+ *
+  * @see db_query_range
+ */
+function drupalvb_db_query_range($query) {
+  drupalvb_db_connect();
+  
+  $args = func_get_args();
+  $count = array_pop($args);
+  $from = array_pop($args);
+  array_shift($args);
+
+  $query = db_prefix_tables($query);
+  if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
+    $args = $args[0];
+  }
+  _db_query_callback($args, TRUE);
+  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
+  $query .= ' LIMIT '. (int)$count .' OFFSET '. (int)$from;
+  $result = _db_query($query);
+  
+  drupalvb_db_disconnect();
+  return $result;
+}
+
+/**
  * Return the last insert id.
  *
  * Borrowed from Drupal 6.
@@ -188,7 +214,8 @@ function _drupalvb_init_user_map() {
   }
   // Fetch all users in vBulletin.
   $result = drupalvb_db_query("SELECT userid, username FROM {user}");
-  // Insert all vB users with corresponding Drupal username into mapping table.
+  // Insert all vB users who already exist in Drupal with corresponding username
+  // into our mapping table.
   while ($vbuser = db_fetch_array($result)) {
     if (isset($users[$vbuser['username']])) {
       db_query("INSERT INTO {drupalvb_users} (uid, userid) VALUES (%d, %d)", $users[$vbuser['username']], $vbuser['userid']);
Index: drupalvb.inc.php
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/drupalvb/drupalvb.inc.php,v
retrieving revision 1.31
diff -u -p -r1.31 drupalvb.inc.php
--- drupalvb.inc.php	15 Oct 2008 02:31:03 -0000	1.31
+++ drupalvb.inc.php	16 Oct 2008 23:18:41 -0000
@@ -30,10 +30,17 @@ function drupalvb_set_login_cookies($use
 
   $cookie_prefix = (isset($vb_config['Misc']['cookieprefix']) ? $vb_config['Misc']['cookieprefix'] : 'bb');
   $cookie_path = $vb_options['cookiepath'];
-  $cookie_domain = (!empty($vb_options['cookiedomain']) ? $vb_options['cookiedomain'] : $GLOBALS['cookie_domain']);
+  $vb_cookie_domain = (!empty($vb_options['cookiedomain']) ? $vb_options['cookiedomain'] : $GLOBALS['cookie_domain']);
   $now = time();
   $expire = $now + (@ini_get('session.cookie_lifetime') ? ini_get('session.cookie_lifetime') : 60 * 60 * 24 * 365);
 
+  // Per RFC 2109, cookie domains must contain at least one dot other than the
+  // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
+  // @see conf_init()
+  if (!(count(explode('.', $vb_cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $vb_cookie_domain)))) {
+    $vb_cookie_domain = '';
+  }
+
   // Clear out old session (if available).
   if (!empty($_COOKIE[$cookie_prefix .'sessionhash'])) {
     drupalvb_db_query("DELETE FROM {session} WHERE sessionhash = '%s'", $_COOKIE[$cookie_prefix .'sessionhash']);
@@ -47,11 +54,11 @@ function drupalvb_set_login_cookies($use
   drupalvb_db_query("REPLACE INTO {session} (sessionhash, userid, host, idhash, lastactivity, location, useragent, loggedin) VALUES ('%s', %d, '%s', '%s', %d, '%s', '%s', %d)", $sessionhash, $vbuser['userid'], substr($_SERVER['REMOTE_ADDR'], 0, 15), $idhash, $now, '/forum/', $_SERVER['HTTP_USER_AGENT'], 2);
 
   // Setup cookies.
-  setcookie($cookie_prefix .'sessionhash', $sessionhash, $expire, $cookie_path, $cookie_domain);
-  setcookie($cookie_prefix .'lastvisit', $now, $expire, $cookie_path, $cookie_domain);
-  setcookie($cookie_prefix .'lastactivity', $now, $expire, $cookie_path, $cookie_domain);
-  setcookie($cookie_prefix .'userid', $vbuser['userid'], $expire, $cookie_path, $cookie_domain);
-  setcookie($cookie_prefix .'password', md5($vbuser['password'] . variable_get('drupalvb_license', '')), $expire, $cookie_path, $cookie_domain);
+  setcookie($cookie_prefix .'sessionhash', $sessionhash, $expire, $cookie_path, $vb_cookie_domain);
+  setcookie($cookie_prefix .'lastvisit', $now, $expire, $cookie_path, $vb_cookie_domain);
+  setcookie($cookie_prefix .'lastactivity', $now, $expire, $cookie_path, $vb_cookie_domain);
+  setcookie($cookie_prefix .'userid', $vbuser['userid'], $expire, $cookie_path, $vb_cookie_domain);
+  setcookie($cookie_prefix .'password', md5($vbuser['password'] . variable_get('drupalvb_license', '')), $expire, $cookie_path, $vb_cookie_domain);
   return TRUE;
 }
 
Index: drupalvb.info
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/drupalvb/drupalvb.info,v
retrieving revision 1.3
diff -u -p -r1.3 drupalvb.info
--- drupalvb.info	30 Apr 2008 01:19:57 -0000	1.3
+++ drupalvb.info	15 Oct 2008 02:35:05 -0000
@@ -1,3 +1,4 @@
 ; $Id: drupalvb.info,v 1.3 2008/04/30 01:19:57 sun Exp $
 name = Drupal vB
 description = Integrate your Drupal site with vBulletin forums.
+core = 6.x
Index: drupalvb.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/drupalvb/drupalvb.install,v
retrieving revision 1.9
diff -u -p -r1.9 drupalvb.install
--- drupalvb.install	15 Oct 2008 01:33:35 -0000	1.9
+++ drupalvb.install	15 Oct 2008 01:52:36 -0000
@@ -2,27 +2,35 @@
 // $Id: drupalvb.install,v 1.9 2008/10/15 01:33:35 sun Exp $
 
 /**
+ * Implementation of hook_schema().
+ */
+function drupalvb_schema() {
+  $schema['drupalvb_users'] = array(
+    'fields' => array(
+      'uid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
+      'userid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
+    ),
+    'primary key' => array('uid'),
+    'unique keys' => array(
+      'userid' => array('userid'),
+    ),
+  );
+
+  return $schema;
+}
+
+/**
  * Implementation of hook_install().
  */
 function drupalvb_install() {
-  switch ($GLOBALS['db_type']) {
-    case 'mysql':
-    case 'mysqli':
-      db_query("CREATE TABLE {drupalvb_users} (
-          uid int(10) unsigned NOT NULL default '0',
-          userid int(10) unsigned NOT NULL default '0',
-          PRIMARY KEY (uid),
-          UNIQUE userid (userid)
-        ) /*!40100 DEFAULT CHARACTER SET utf8 */;");
-      break;
-  }
+  drupal_install_schema('drupalvb');
 }
 
 /**
  * Implementation of hook_uninstall().
  */
 function drupalvb_uninstall() {
-  db_query("DROP TABLE {drupalvb_users}");
+  drupal_uninstall_schema('drupalvb');
   db_query("DELETE FROM {variable} WHERE name LIKE 'drupalvb_%%'");
 }
 
@@ -45,79 +53,3 @@ function drupalvb_update_5100() {
   return $ret;
 }
 
-/**
- * Install user id mapping table.
- */
-function drupalvb_update_5200() {
-  $ret = array();
-  switch ($GLOBALS['db_type']) {
-    case 'mysql':
-    case 'mysqli':
-      $ret[] = update_sql("CREATE TABLE {drupalvb_users} (
-          uid int(10) unsigned NOT NULL default '0',
-          userid int(10) unsigned NOT NULL default '0',
-          PRIMARY KEY (uid),
-          KEY userid (userid)
-        ) /*!40100 DEFAULT CHARACTER SET utf8 */;");
-
-      require_once drupal_get_path('module', 'drupalvb') .'/drupalvb.inc';
-      _drupalvb_init_user_map();
-      break;
-  }
-  return $ret;
-}
-
-/**
- * Update block configuration variables.
- */
-function drupalvb_update_5201() {
-  $ret = array();
-  // Recent threads/posts.
-  variable_set('drupalvb_block_recent_type', variable_get('drupalvb_block_0_type', 'threads'));
-  variable_del('drupalvb_block_0_type');
-  variable_set('drupalvb_block_recent_count', variable_get('drupalvb_block_0', 5));
-  variable_del('drupalvb_block_0');
-  variable_set('drupalvb_block_recent_limit', variable_get('drupalvb_block_0_limit', 7));
-  variable_del('drupalvb_block_0_limit');
-  $authors = (variable_get('drupalvb_block_0_name', 'no') == 'no' ? 0 : 1);
-  variable_set('drupalvb_block_recent_authors', $authors);
-  variable_del('drupalvb_block_0_name');
-  $ret[] = update_sql("UPDATE {blocks} SET delta = 'recent' WHERE module = 'drupalvb' AND delta = 0");
-  $ret[] = update_sql("UPDATE {blocks_roles} SET delta = 'recent' WHERE module = 'drupalvb' AND delta = 0");
-  // User info.
-  variable_set('drupalvb_block_user', variable_get('drupalvb_block_1', array('newposts' => 'newposts', 'recent' => 'recent', 'online' => 'online', 'pms' => 'pms')));
-  variable_del('drupalvb_block_1');
-  $ret[] = update_sql("UPDATE {blocks} SET delta = 'user' WHERE module = 'drupalvb' AND delta = 1");
-  $ret[] = update_sql("UPDATE {blocks_roles} SET delta = 'user' WHERE module = 'drupalvb' AND delta = 1");
-  // Overall statistics.
-  variable_set('drupalvb_block_stats', variable_get('drupalvb_block_2', array('threads' => 'threads', 'posts' => 'posts', 'tmembers' => 'tmembers', 'amembers' => 'amembers')));
-  variable_del('drupalvb_block_2');
-  $ret[] = update_sql("UPDATE {blocks} SET delta = 'stats' WHERE module = 'drupalvb' AND delta = 2");
-  $ret[] = update_sql("UPDATE {blocks_roles} SET delta = 'stats' WHERE module = 'drupalvb' AND delta = 2");
-  
-  return $ret;
-}
-
-/**
- * Change index type for vB userids.
- */
-function drupalvb_update_5202() {
-  $ret = array();
-  switch ($GLOBALS['db_type']) {
-    case 'mysql':
-    case 'mysqli':
-      $ret[] = update_sql("ALTER TABLE {drupalvb_users} DROP INDEX userid, ADD UNIQUE userid (userid)");
-      break;
-  }
-  return $ret;
-}
-
-/**
- * Delete obsolete drupalvb_default_timezone variable.
- */
-function drupalvb_update_5203() {
-  $ret = array();
-  variable_del('drupalvb_default_timezone');
-  return $ret;
-}
-
Index: drupalvb.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/drupalvb/drupalvb.module,v
retrieving revision 1.32
diff -u -p -r1.32 drupalvb.module
--- drupalvb.module	15 Oct 2008 02:31:03 -0000	1.32
+++ drupalvb.module	15 Oct 2008 03:43:52 -0000
@@ -11,10 +11,33 @@
 require_once drupal_get_path('module', 'drupalvb') .'/drupalvb.inc.php';
 
 /**
+ * Implementation of hook_theme().
+ */
+function drupalvb_theme() {
+  return array(
+    'drupalvb_block_recent' => array(
+      'arguments' => array('recent' => NULL, 'vb_options' => NULL),
+    ),
+    'drupalvb_block_recent_user' => array(
+      'arguments' => array('recent' => NULL, 'vb_options' => NULL),
+    ),
+    'drupalvb_block_top_posters' => array(
+      'arguments' => array('items' => array()),
+    ),
+    'drupalvb_username' => array(
+      'arguments' => array('object' => NULL, 'class' => NULL),
+    ),
+    'drupalvb_settings_variables' => array(
+      'arguments' => array('form' => array()),
+    ),
+  );
+}
+
+/**
  * Implementation of hook_help().
  */
-function drupalvb_help($section) {
-  switch ($section) {
+function drupalvb_help($path, $arg) {
+  switch ($path) {
     case 'admin/settings#description':
       return t('Allows basic integration of Drupal with a vBulletin forum.');
 
@@ -40,82 +63,76 @@ function drupalvb_help($section) {
 /**
  * Implementation of menu_hook().
  */
-function drupalvb_menu($may_cache) {
+function drupalvb_menu() {
   $items = array();
 
-  if ($may_cache) {
-    $access = user_access('administer drupalvb');
-
-    $items[] = array(
-      'path' => 'admin/settings/drupalvb',
-      'title' => t('Drupal vB integration'),
-      'callback' => 'drupalvb_settings',
-      'callback arguments' => array('integration'),
-      'description' => t('Configure integration of Drupal with vBulletin forum.'),
-      'access' => $access,
-    );
-    $items[] = array(
-      'path' => 'admin/settings/drupalvb/integration',
-      'title' => t('Integration'),
-      'type' => MENU_DEFAULT_LOCAL_TASK,
-      'weight' => -10,
-    );
-    $items[] = array(
-      'path' => 'admin/settings/drupalvb/database',
-      'title' => t('Database'),
-      'callback' => 'drupalvb_settings',
-      'callback arguments' => array('database'),
-      'access' => $access,
-      'type' => MENU_LOCAL_TASK,
-    );
-    $items[] = array(
-      'path' => 'admin/settings/drupalvb/actions',
-      'title' => t('Actions'),
-      'callback' => 'drupalvb_settings',
-      'callback arguments' => array('actions'),
-      'access' => $access,
-      'type' => MENU_LOCAL_TASK,
-      'weight' => 10,
-    );
-    $items[] = array(
-      'path' => 'admin/settings/drupalvb/variables',
-      'title' => t('Variables'),
-      'callback' => 'drupalvb_settings',
-      'callback arguments' => array('variables'),
-      'access' => user_access('access devel information'),
-      'type' => MENU_LOCAL_TASK,
-      'weight' => 88,
-    );
-    $items[] = array(
-      'path' => 'drupalvb/pms',
-      'callback' => 'drupalvb_private_messages',
-      'access' => user_access('access content'),
-      'type' => MENU_CALLBACK,
-    );
-    $items[] = array(
-      'path' => 'drupalvb',
-      'callback' => 'drupalvb_redirect',
-      'access' => variable_get('drupalvb_acct_generation', TRUE),
-      'type' => MENU_CALLBACK,
-    );
-    $items[] = array(
-      'path' => 'drupalvb/login',
-      'callback' => 'drupalvb_login',
-      'access' => TRUE,
-      'type' => MENU_CALLBACK,
-    );
-    $items[] = array(
-      'path' => 'drupalvb/logout',
-      'callback' => 'drupalvb_logout',
-      'access' => TRUE,
-      'type' => MENU_CALLBACK,
-    );
-  }
+  $items['admin/settings/drupalvb'] = array(
+    'title' => 'Drupal vB integration',
+    'page callback' => 'drupalvb_settings',
+    'page arguments' => array('integration'),
+    'description' => 'Configure integration of Drupal with vBulletin forum.',
+    'access arguments' => array('administer drupalvb'),
+  );
+  $items['admin/settings/drupalvb/integration'] = array(
+    'title' => 'Integration',
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+    'weight' => -10,
+  );
+  $items['admin/settings/drupalvb/database'] = array(
+    'title' => 'Database',
+    'page callback' => 'drupalvb_settings',
+    'page arguments' => array('database'),
+    'access arguments' => array('administer drupalvb'),
+    'type' => MENU_LOCAL_TASK,
+  );
+  $items['admin/settings/drupalvb/actions'] = array(
+    'title' => 'Actions',
+    'page callback' => 'drupalvb_settings',
+    'page arguments' => array('actions'),
+    'access arguments' => array('administer drupalvb'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 10,
+  );
+  $items['admin/settings/drupalvb/variables'] = array(
+    'title' => 'Variables',
+    'page callback' => 'drupalvb_settings',
+    'page arguments' => array('variables'),
+    'access arguments' => array('access devel information'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 88,
+  );
+  $items['drupalvb/pms'] = array(
+    'page callback' => 'drupalvb_private_messages',
+    'access arguments' => array('access content'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['drupalvb'] = array(
+    'page callback' => 'drupalvb_redirect',
+    'access callback' => 'drupalvb_acct_generation_access', 
+    'type' => MENU_CALLBACK,
+  );
+  $items['drupalvb/login'] = array(
+    'page callback' => 'drupalvb_login',
+    'access callback' => TRUE, 
+    'type' => MENU_CALLBACK,
+  );
+  $items['drupalvb/logout'] = array(
+    'page callback' => 'drupalvb_logout',
+    'access callback' => TRUE, 
+    'type' => MENU_CALLBACK,
+  );
 
   return $items;
 }
 
 /**
+ * Menu access callback; determine whether /drupalvb redirects are allowed.
+ */
+function drupalvb_acct_generation_access() {
+  return variable_get('drupalvb_acct_generation', TRUE);
+}
+
+/**
  * Implementation of hook_perm().
  */
 function drupalvb_perm() {
@@ -133,44 +150,68 @@ function drupalvb_settings($form = 'inte
 }
 
 /**
- * Implementation of hook_info().
- */
-function drupalvb_info($field = 0) {
-  $info['name'] = 'vBulletin';
-  $info['protocol'] = 'DB';
-
-  if ($field) {
-    return $info[$field];
-  }
-  else {
-    return $info;
-  }
-}
-
-/**
  * Implementation of hook_form_alter().
  *
+ * Validate the submitted values of user login forms before Drupal core invokes
+ * its regular form validation callback.
+ *
  * Add a validation handler to the password recovery form to import a user from
  * vB, should one exist there.
  *
  * @see drupalvb_user_pass_validate()
  */
-function drupalvb_form_alter($form_id, &$form) {
-  if ($form_id == 'user_pass') {
+function drupalvb_form_alter(&$form, $form_state, $form_id) {
+  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
+    require_once drupal_get_path('module', 'drupalvb') .'/drupalvb.inc';
+
+    // Splice in our validate handler for authentication if user is performing
+    // a vBulletin login.
+    if (!empty($form_state['post']['name']) && drupalvb_db_is_valid()) {
+      $username = $form_state['post']['name'];
+      if ($vbuser = db_fetch_array(drupalvb_db_query("SELECT userid, password, salt, email FROM {user} WHERE username = '%s'", drupalvb_htmlspecialchars($username)))) {
+        $key = array_search('user_login_final_validate', $form['#validate']);
+        if ($key !== FALSE) {
+          array_splice($form['#validate'], $key, 0, 'drupalvb_login_validate');
+        }
+        else {
+          // Another module altered the validation sequence before us, not sure
+          // how to properly handle this case...
+          $form['#validate'] = array('drupalvb_login_validate') + $form['#validate'];
+        }
+      }
+    }
+  }
+  else if ($form_id == 'user_pass') {
     $form['#validate'] = array_merge(array('drupalvb_user_pass_validate' => array()), $form['#validate']);
   }
 }
 
 /**
- * Implementation of hook_auth().
+ * Validate login against vBulletin user database.
  */
-function drupalvb_auth($username, $password, $server = NULL) {
+function drupalvb_login_validate($form, &$form_state) {
+  global $user;
+
   if (!variable_get('drupalvb_dual_login', TRUE)) {
     return;
   }
+  if ($user->uid) {
+    return;
+  }
+
+  $username = $form_state['values']['name'];
+  $password = trim($form_state['values']['pass']);
+
   if (empty($username) || empty($password)) {
     return;
   }
+
+  // If this user already exists in Drupal, no further validation required.
+  $finduser = user_load(array('name' => $username));
+  if ($finduser && $finduser->uid) {
+    return TRUE;
+  }
+
   require_once drupal_get_path('module', 'drupalvb') .'/drupalvb.inc';
   if (!drupalvb_db_is_valid()) {
     return;
@@ -300,7 +341,7 @@ function drupalvb_user($op, &$edit, &$ac
  * @see drupalvb_user()
  */
 function drupalvb_user_login($account) {
-  $vbuser = db_fetch_array(drupalvb_db_query("SELECT u.userid, ub.liftdate FROM {user} u LEFT JOIN {userban} ub ON ub.userid = u.userid WHERE u.username = '%s'", drupalvb_htmlspecialchars($account->name)));
+  $vbuser = db_fetch_array(drupalvb_db_query_range("SELECT u.userid, ub.liftdate FROM {user} u LEFT JOIN {userban} ub ON ub.userid = u.userid WHERE u.username = '%s'", drupalvb_htmlspecialchars($account->name), 0, 1));
 
   // Create account in vB if user does not exist.
   if (!$vbuser) {
@@ -335,7 +376,7 @@ function drupalvb_user_login($account) {
  * @see drupalvb_user()
  */
 function drupalvb_user_logout($account) {
-  $vbuser = db_fetch_array(drupalvb_db_query("SELECT userid, username FROM {user} WHERE username = '%s'", drupalvb_htmlspecialchars($account->name)));
+  $vbuser = db_fetch_array(drupalvb_db_query_range("SELECT userid, username FROM {user} WHERE username = '%s'", drupalvb_htmlspecialchars($account->name), 0, 1));
   if ($vbuser) {
     // Remove all vB cookies for current user.
     drupalvb_clear_cookies($vbuser['userid']);
@@ -350,13 +391,13 @@ function drupalvb_user_validate($uid, &$
   $userid = db_result(db_query("SELECT userid FROM {drupalvb_users} WHERE uid = %d", $uid));
   // Validate the username.
   if (arg(1) == 'register' || user_access('change own username') || user_access('administer users')) {
-    if (db_result(drupalvb_db_query("SELECT userid FROM {user} WHERE userid <> %d AND LOWER(username) = LOWER('%s')", $userid, drupalvb_htmlspecialchars($edit['name']))) > 0) {
+    if (db_result(drupalvb_db_query_range("SELECT userid FROM {user} WHERE userid <> %d AND LOWER(username) = LOWER('%s')", $userid, drupalvb_htmlspecialchars($edit['name']), 0, 1))) {
       form_set_error('name', t('The name %name is already taken.', array('%name' => $edit['name'])));
     }
   }
 
   // Validate the e-mail address.
-  if (db_result(drupalvb_db_query("SELECT userid FROM {user} WHERE userid != %d AND LOWER(email) = LOWER('%s')", $userid, drupalvb_htmlspecialchars($edit['mail']))) > 0) {
+  if (db_result(drupalvb_db_query_range("SELECT userid FROM {user} WHERE userid <> %d AND LOWER(email) = LOWER('%s')", $userid, drupalvb_htmlspecialchars($edit['mail']), 0, 1)) > 0) {
     form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $edit['mail'], '@password' => url('user/password'))));
   }
 }
@@ -386,7 +427,7 @@ function drupalvb_user_update($account, 
   global $user;
 
   // Update data if user exists.
-  if ($vbuser = db_fetch_array(drupalvb_db_query("SELECT userid, salt FROM {user} WHERE username = '%s'", drupalvb_htmlspecialchars($account->name)))) {
+  if ($vbuser = db_fetch_array(drupalvb_db_query_range("SELECT userid, salt FROM {user} WHERE username = '%s'", drupalvb_htmlspecialchars($account->name), 0, 1))) {
     // Merge current username, salt, and finally edited values into one array,
     // so usernames may be altered (if allowed).
     drupalvb_update_user($account, array_merge(array('name' => $account->name), $vbuser, $edit));
@@ -694,7 +735,7 @@ function theme_drupalvb_block_recent($re
   $items = array();
   $display_authors = variable_get('drupalvb_block_recent_authors', 0);
   foreach ($recent as $item) {
-    $link = l($item['title'], $item['url'], array(), $item['query'], $item['fragment']);
+    $link = l($item['title'], $item['url'], array('query' => $item['query'], 'fragment' => $item['fragment']));
     $items[] = ($display_authors ? t('!title <span>by !name</span>', array('!title' => $link, '!name' => theme('drupalvb_username', (object)$item))) : $link);
   }
   $output = theme('item_list', $items);
@@ -736,8 +777,8 @@ function drupalvb_block_recent_user($acc
 function theme_drupalvb_block_recent_user($recent, $vb_options) {
   $items = array();
   foreach ($recent as $item) {
-    $link_post = l($item['title'], $item['url'], array(), $item['query'], $item['fragment']);
-    $link_thread = l($item['threadtitle'], $item['url'], array(), $item['query']);
+    $link_post = l($item['title'], $item['url'], array('query' => $item['query'], 'fragment' => $item['fragment']));
+    $link_thread = l($item['threadtitle'], $item['url'], array('query' => $item['query']));
     $items[] = t('<span class="drupalvb-post">!title</span> <span class="drupalvb-thread">Thread: !thread</span>', array('!title' => $link_post, '!thread' => $link_thread));
   }
   return theme('item_list', $items);
@@ -749,7 +790,7 @@ function theme_drupalvb_block_recent_use
 function drupalvb_block_top_posters() {
   $items = array();
   $num_items = variable_get('drupalvb_block_recent_count', 5);
-  $result = drupalvb_db_query("SELECT posts AS count, userid, username AS name FROM {user} ORDER BY posts DESC LIMIT %d", $num_items);
+  $result = drupalvb_db_query_range("SELECT posts AS count, userid, username AS name FROM {user} ORDER BY posts DESC", 0, $num_items);
   while ($data = db_fetch_array($result)) {
     $items[$data['userid']] = $data;
   }
@@ -859,11 +900,11 @@ function drupalvb_block_stats() {
  *   A class name for User Display API.
  */
 function theme_drupalvb_username($object, $class = NULL) {
-  if ($object->uid && $object->name) {
+  if ($object && !empty($object->uid) && $object->name) {
     // Drupal account exists: fall back on default theming.
     $output = theme('username', $object, $class);
   }
-  else if ($object->userid && $object->name) {
+  else if ($object && !empty($object->userid) && $object->name) {
     // Remove any html entities injected by vBulletin.
     $object->name = decode_entities($object->name);
     // Drupal account doesn't exists yet. Link to it using our redirector,
@@ -1045,7 +1086,7 @@ function drupalvb_privatemsg($message, $
     case 'sent':
       // Verify that recipient exists in vB.
       $recipient = user_load(array('uid' => $message->recipient));
-      if (!$userid = db_result(drupalvb_db_query("SELECT userid FROM {user} WHERE username = '%s'", drupalvb_htmlspecialchars($recipient->name)))) {
+      if (!$userid = db_result(drupalvb_db_query_range("SELECT userid FROM {user} WHERE username = '%s'", drupalvb_htmlspecialchars($recipient->name), 0, 1))) {
         if (!$userid = drupalvb_create_user($recipient, (array)$recipient)) {
           // Indicates duplicate username (should not happen).
           return;
