Index: troll.admin.inc
===================================================================
RCS file: troll.admin.inc
diff -N troll.admin.inc
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ troll.admin.inc	24 Sep 2008 14:22:16 -0000
@@ -0,0 +1,1022 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * Administrative forms and functions for troll module.
+ */
+
+/**
+ * Implementation of hook_settings().
+ *
+ * @return array
+ */
+function troll_admin_settings() {
+  $form['ip_settings'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'IP Address Banning'
+  );
+  $form['ip_settings']['troll_enable_ip_ban'] = array(
+    '#type' => 'radios',
+    '#title' => t('IP Address Banning'),
+    '#default_value' => variable_get('troll_enable_ip_ban', 1),
+    '#options' => array('1' => t('Enable banning by IP address'), '0' => t('Disable banning by IP address'))
+  );
+  $form['ip_settings']['troll_ip_ban_redirect'] = array(
+    '#type' => 'textfield',
+    '#title' => t('IP Ban Relocation Page'),
+    '#default_value' => variable_get('troll_ip_ban_redirect', ''),
+    '#description' => t("Page for relocating users banned based on their IP address or domain name.  If left blank, users will be redirected to blocked.html in the troll module's directory. Do not use a drupal path here! You will cause a loop since IP banning completely blocks all access to the site! Edit the blocked.html file, or redirect to http://localhost."),
+  );
+
+  $roles = user_roles();
+  array_unshift($roles, t(' -Select Role- '));
+  $form['role_settings'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('User Blocking')
+  );
+  $form['role_settings']['troll_block_role'] = array(
+    '#type' => 'select',
+    '#title' => t('Troll Block Role'),
+    '#default_value' => variable_get('troll_block_role', 0),
+    '#options' => $roles,
+    '#description' => t('Select the role to assign to users when blocking from the troll administration screens.'),
+  );
+
+  return system_settings_form($form);
+}
+
+/**
+ * Admin settings page validate handler.
+ * 
+ * @see troll_admin_settings
+ */
+function troll_admin_settings_validate($form, &$form_state) {
+  if ($form_state['values']['troll_block_role'] == '0') {
+    form_set_error('troll_block_role', t('You must choose a role to assign to users when blocking from the troll settings page.'));
+  }
+}
+
+/**
+ * Menu callback: user IP banning.
+ */
+function troll_ip_ban() {
+  $form['banfieldset'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Add IP Ban'),
+    '#weight' => -1,
+    '#collapsible' => true
+  );
+  $form['banfieldset']['banform'] = troll_ip_ban_form(array());
+  $form['#validate'] = array('troll_ip_ban_form_validate');
+  $form['ipdisplay'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Banned IPs'),
+    '#value' => troll_display_ip(),
+    '#weight' => 0,
+    '#collapsible' => true
+   );
+  return $form;
+}
+
+/**
+ * Submit handler for IP Ban form.
+ *
+ * @see troll_ip_ban
+ * @see troll_ip_ban_form
+ */
+function troll_ip_ban_submit($form, &$form_state) {
+  troll_insert_ip($form_state['values']);
+}
+
+/**
+ * Summary of how many IP blocks are filtered.
+ *
+ * @return string
+ */
+function troll_blacklist_summary() {
+  $count = db_result(db_query('SELECT COUNT(net) FROM {troll_blacklist}'));
+  return t('%d address blocks filtered.', array('%d' => $count));
+}
+
+/**
+ * Gives admins a choice of how to punish blacklisted visitors
+ *
+ * @return array
+ */
+function troll_blacklist_punishment_form() {
+  $form['stutter'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Randomly stutter output'),
+    '#default_value' => variable_get('troll_blacklist_stutter', 0),
+    '#description' => t('While outputting content, the troll module will cause Drupal to "sleep" for random intervals of 1-5 seconds to delay output.')
+  );
+  $form['mod_requests'] = array(
+    '#type' => 'radios',
+    '#title' => t('Page request modification'),
+    '#options' => array(t('none'), 'silent_post_drop' => 'Silently drop form post submission data', 'notice_post_drop' => 'Drop form post submission data and give a notice'),
+    '#default_value' => variable_get('troll_blacklist_mod_requests', '0'),
+    '#description' => t('Modifies data sent by visitors from blacklisted IPs before Drupal even has a chance to process it.')
+  );
+  $form['alt_page_output'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Alternate page output'
+  );
+  $form['alt_page_output']['alt_page'] = array(
+    '#type' => 'radios',
+    '#title' => 'Alternate pages',
+    '#options' => array(t('none'), 'blank' => t('Blank pages'), '404' => t('404 every page request'), 'redirect' => t('Redirect to alternate URL')),
+    '#default_value' => variable_get('troll_blacklist_alt_page', '0'),
+    '#description' => t('Sends alternate page output, whether the visitor hits a real URL or not.')
+  );
+  $form['alt_page_output']['alt_url'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Redirection URL'),
+    '#default_value' => variable_get('troll_blacklist_alt_url', ''),
+    '#description' => t('URL to redirect blacklisted visitors to if "Redirect to alternate URL" is selected. Start with the appropriate prefix (e.g. http://)')
+  );
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Update Blacklist Punishments'),
+    '#weight' => 1
+  );
+  return $form;
+}
+
+/**
+ * Submit handler for punishment form.
+ *
+ * @see troll_blacklist_punishment
+ */
+function troll_blacklist_punishment_form_submit($form, $form_state) {
+  variable_set('troll_blacklist_mod_requests', $form_state['values']['mod_requests']);
+  variable_set('troll_blacklist_stutter', $form_state['values']['stutter']);
+  variable_set('troll_blacklist_alt_page', $form_state['values']['alt_page']);
+  variable_set('troll_blacklist_alt_url', $form_state['values']['alt_url']);
+  drupal_set_message(t('The settings have been updated.'));  
+}
+
+/**
+ * Builds form array for admin to select how to import a new blacklist.
+ *
+ * @return array
+ */
+function troll_blacklist_import_form() {
+  $form['truncate_list'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Truncate/delete existing blacklist before import')
+    );
+  $options = array();
+  $options[0] = '';
+  if (function_exists('gzopen')) {
+    $options['S1gz'] = 'OpenBSD mirror: SPEWS.org Level 1 bzip archive';
+    $options['S2gz'] = 'OpenBSD mirror: SPEWS.org Level 2 bzip archive';
+    $options['OCgz'] = 'OpenBSD mirror: okean.com China bzip archive';
+    $options['OKgz'] = 'OpenBSD mirror: okean.com Korea bzip archive';
+  }
+  $options['S1tx'] = 'SPEWS.org Level 1 text file';
+  $options['S2tx'] = 'SPEWS.org Level 2 text file';
+  $options['OTtx'] = 'okean.com China and Korea text file';
+  $options['OCtx'] = 'okean.com China text file';
+  $options['OKtx'] = 'okean.com Korea text file';
+  $form['select_list'] = array(
+    '#type' => 'select',
+    '#title' => t('Download and import'),
+    '#options' => $options,
+    '#description' => t('Downloads supported blacklist from the internet. Please select a mirror when possible.'),
+    );
+  $form['custom_list'] = array(
+    '#type' => 'textfield',
+    '#title' => t('List URL'),
+    '#description' => t('URL of a list to import. List files should have one address per line in Classless Internet Domain Routing CIDR format (x.x.x.x/x). Individual IPs should still have /32.'),
+    );
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Import List'),
+    '#weight' => 1,
+  );
+  return $form;
+}
+
+/**
+ * Submit handler for blacklist import.
+ * 
+ * @see troll_blacklist_import
+ */
+function troll_blacklist_import_form_submit($form, &$form_state) {
+  if (!empty($form_state['values']['truncate_list'])) {
+    if (db_query('TRUNCATE TABLE {troll_blacklist}')) {
+      drupal_set_message(t('Blacklist table truncated.'));
+    }
+  }
+  if (!empty($form_state['values']['select_list'])) {
+    troll_blacklist_import_list($form_state['values']['select_list']);
+  }
+  if (!empty($form_state['values']['custom_list'])) {
+    troll_blacklist_import_url($form_state['values']['custom_list']);
+  }
+  $form_state['redirect'] = 'admin/settings/troll/ip_blacklist';
+}
+
+/**
+ * Decyphers what dropdown selection was chosen to send for parsing out IP blocks
+ *
+ * @see troll_blacklist_import_form()
+ * @see troll_blacklist_parse_save()
+ * @param array $edit
+ */
+function troll_blacklist_import_list($list) {
+  $files = array('S1gz' => array('gz' => 'http://www.openbsd.org/spamd/spews_list_level1.txt.gz'),
+    'S2gz' => array('gz' => 'http://www.openbsd.org/spamd/spews_list_level2.txt.gz'),
+    'OCgz' => array('gz' => 'http://www.openbsd.org/spamd/chinacidr.txt.gz'),
+    'OKgz' => array('gz' => 'http://www.openbsd.org/spamd/koreacidr.txt.gz'),
+    'S1tx' => array('txt' => 'http://www.spews.org/spews_list_level1.txt'),
+    'S2tx' => array('txt' => 'http://www.spews.org/spews_list_level2.txt'),
+    'OTtx' => array('txt' => 'http://www.okean.com/sinokoreacidr.txt'),
+    'OCtx' => array('txt' => 'http://www.okean.com/chinacidr.txt'),
+    'OKtx' => array('txt' => 'http://www.okean.com/koreacidr.txt'));
+
+  if (!isset($files[$list])) {
+    drupal_set_message(t('Form input not valid'));
+    return FALSE;
+  }
+
+  $file_type = array_keys($files[$list]);
+  troll_blacklist_parse_save($files[$list][$file_type[0]], $file_type[0]);
+}
+
+/**
+ * Parses a URL to send for parsing out IP blocks
+ *
+ * @see troll_blacklist_parse_save()
+ * @param array $edit
+ */
+function troll_blacklist_import_url($edit) {
+  $url_parts = parse_url($edit['custom_list']);
+  $file_parts = pathinfo($url_parts['path']);
+  troll_blacklist_parse_save($edit['custom_list'], $file_parts['extension']);
+}
+
+/**
+ * Parses input file, line by line, searching for IP blocks in CIDR
+ * format (x.x.x.x/x). Understands files in text, bzip, and bzip2 format,
+ * where the PHP installation supports it. Writes what it finds to the
+ * database as long integers.
+ *
+ * @todo should probably function_exists() the compression file functions
+ * @param $file_name string
+ * @param $file_type string
+ */
+function troll_blacklist_parse_save($file_name, $file_type) {
+  $netmasks = array(
+    0, -2147483648, -1073741824, -536870912, -268435456, -134217728,
+    -67108864, -33554432, -16777216, -8388608, -4194304, -2097152, -1048576,
+    -524288, -262144, -131072, -65536, -32768, -16384, -8192, -4096, -2048,
+    -1024, -512, -256, -128, -64, -32, -16, -8, -4, -2, -1);
+
+  switch ($file_type) {
+    case 'gz':
+      $fp = gzopen($file_name, 'r');
+      break;
+    default:
+      $fp = fopen($file_name, 'r');
+      break;
+  }
+
+  if (is_resource($fp)) {
+    $i = 0;
+    while (!feof($fp)) {
+      $buffer = fgets($fp);
+      if ($buffer{0} != '#' && ($buffer{0} != '/' && $buffer{1} != '/') && !empty($buffer)) {
+        preg_match("/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/([0-9]{1,2})/", $buffer, $matches);
+        // $matches array
+        // 0 = whole string
+        // 1 = i.i.i.i
+        // 2 = s
+        $longip = ip2long($matches[1]);
+        unset($buffer, $matches[0], $matches[1]);
+
+        if ($matches[2] == 32) {
+          $net = $bcast = $longip;
+        }
+        else {
+          $net = $longip & $netmasks[$matches[2]];
+          $bcast = $longip | ($netmasks[$matches[2]] ^ -1);
+        }
+        db_query('DELETE FROM {troll_blacklist} WHERE net = %d AND bcast = %d', $net, $bcast);
+        db_query('INSERT INTO {troll_blacklist} (net, bcast) VALUES (%d, %d)', $net, $bcast);
+        $i++;
+      }
+    }
+    switch ($file_type) {
+      case 'gz':
+        gzclose($fp);
+        break;
+      default:
+        fclose($fp);
+        break;
+    }
+    drupal_set_message(t('%i IP blocks imported', array('%i' => $i)));
+  }
+  else {
+    drupal_set_message(t('Import failed! File could not be read.'));
+  }
+}
+
+/**
+ * Form to search blacklist to see if an IP matches
+ *
+ * @return array
+ */
+function troll_blacklist_search_form($form_state) {
+  $form['ip_address'] = array(
+    '#type' => 'textfield',
+    '#title' => t('IP Address'),
+    '#size' => 15,
+    '#maxlength' => 15,
+    '#description' => t('Address to search for in the database of imported IP blocks.'),
+    );
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Search Blacklisted IPs'),
+    '#weight' => 1
+  );
+  // If a value has been entered, display search results.
+  if (!empty($form_state['values']['ip_address'])) {
+    $form['result'] = array(
+      '#value' => troll_blacklist_search($form_state['values']['ip_address']),
+    );
+  }
+  else {
+    $form['result'] = array(
+      '#value' => troll_blacklist_search(''),
+    );
+  }
+  return $form;
+}
+
+/**
+ * Submit handler for blacklist search form.
+ * 
+ * @see troll_blacklist_search_blacklist_form
+ */
+function troll_blacklist_search_form_submit($form, &$form_state) {
+  $form_state['rebuild'] = TRUE;
+}
+
+/**
+ * Perform search to see if an IP address matches a blacklisted IP block.
+ *
+ * @return string
+ */
+function troll_blacklist_search($ip_address) {
+  if ($ip_address == '') {
+    $sql = "SELECT net, bcast FROM {troll_blacklist}";
+  }
+  else {
+    $sql = "SELECT net, bcast FROM {troll_blacklist} WHERE net <= %d AND bcast >= %d";
+    $longip = _troll_longip($ip_address);
+  }
+  $headers = array(
+    array('data' => t('Network Address'), 'field' => 'net', 'sort' => 'asc'),
+    array('data' => t('Broadcast Address'), 'field' => 'bcast'),
+    array('data' => t('Actions'), 'field' => 'delete')
+  );
+
+  $sql .= tablesort_sql($headers);
+  $result = pager_query($sql, 25, 0, NULL, $longip, $longip);
+  while ($row = db_fetch_object($result)) {
+    $printnet = long2ip($row->net);
+    $printbcast = long2ip($row->bcast);
+    $action = l(t('remove'), "admin/settings/troll/ip_blacklist/deleteblack/{$row->net}/{$row->bcast}");
+    $rows[] = array($printnet, $printbcast, $action);
+  }
+  if ($rows) {
+    $pager = theme('pager', NULL, 25, 0);
+    if (!empty($pager)) {
+      $rows[] = array(array('data' => $pager, 'colspan' => 3));
+    }
+    return theme('table', $headers, $rows);
+  }
+  else {
+    drupal_set_message(t('No matches found.'));
+  }
+}
+
+/**
+ * Form builder function
+ *
+ * @param $net string Not used, here for later implementation of whitelist editing
+ * @param $bcast string Not used, here for later implementation of whitelist editing
+ * @see troll_whitelist_form()
+ * @return string
+ */
+function troll_whitelist($net = NULL, $bcast = NULL) {
+  $sql = 'SELECT net, bcast FROM {troll_whitelist}';
+
+  $headers = array(
+    array('data' => t('Start/Network Address'), 'field' => 'net', 'sort' => 'asc'),
+    array('data' => t('End/Broadcast Address'), 'field' => 'bcast'),
+    array('data' => t('Actions'), 'field' => 'delete')
+  );
+
+  $sql .= tablesort_sql($headers);
+  $result = pager_query($sql, 25);
+  while ($row = db_fetch_object($result)) {
+    $printnet = long2ip($row->net);
+    $printbcast = long2ip($row->bcast);
+    $action = l(t('remove'), "admin/settings/troll/ip_blacklist/deletewhite/{$row->net}/{$row->bcast}");
+    $rows[] = array($printnet, $printbcast, $action);
+  }
+
+  $pager = theme('pager', NULL, 25, 0);
+  if (!empty($pager)) {
+    $rows[] = array(array('data' => $pager, 'colspan' => 3));
+  }
+
+  return theme('table', $headers, $rows);
+}
+
+/**
+ * Display form for creating new whitelist block and table of current whitelisted IPs.
+ *
+ * @return array
+ */
+function troll_whitelist_form($form_state) {
+  $form['whitelist_addr1'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Starting IP Address'),
+    '#size' => 15,
+    '#maxlength' => 15,
+    '#default_value' => $net ? long2ip($net) : '',
+    '#description' => t('IP or start to range of IPs to whitelist.'),
+    '#required' => TRUE
+  );
+  $form['whitelist_addr2'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Ending IP Address'),
+    '#size' => 15,
+    '#maxlength' => 15,
+    '#default_value' => $bcast ? long2ip($bcast) : '',
+    '#description' => t('End of IP range to whitelist. If whitelisting a single IP, leave this blank.'),
+    '#required' => false
+  );
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Insert Whitelist IPs'),
+    '#weight' => 1
+  );
+  $form['whitelist'] = array(
+    '#value' => troll_whitelist(),
+  );
+  return $form;
+}
+
+/**
+ * Insert a new IP block into the whitelist
+ *
+ * @param array $edit
+ */
+function troll_whitelist_form_submit($form, &$form_state) {
+  $whitelist_addr1 = $form_state['values']['whitelist_addr1'];
+  $whitelist_addr2 = $form_state['values']['whitelist_addr2'];
+  $longip1 = _troll_longip($whitelist_addr1);
+  $longip2 = _troll_longip(empty($whitelist_addr2) ? $whitelist_addr1 : $whitelist_addr2);
+  if ($longip1 > $longip2) {
+    $temp = $longip1;
+    $longip1 = $longip2;
+    $longip2 = $temp;
+    unset($temp);
+  }
+  db_query("REPLACE INTO {troll_whitelist} (net, bcast) VALUES (%d, %d)", $longip1, $longip2);
+  drupal_set_message(t('IP range %ip1 to %ip2 whitelisted.', array('%ip1' => long2ip($longip1), '%ip2' => long2ip($longip2))));
+}
+
+/**
+ * Menu callback: block a user and redirect to search page.
+ *
+ * @param $uid
+ */
+function troll_confirm_block_user_form($form_state, $uid) {
+  $account = user_load(array('uid' => $uid));
+  if (!$account) {
+    drupal_goto('admin/settings/troll');
+  }
+  $form['uid'] = array(
+    '#type' => 'value',
+    '#value' => $uid,
+  );
+  return confirm_form($form, t('Block user %username?', array('%username' => $account->name)), 'admin/settings/troll', t('Are you sure you want to block this user?'));
+}
+
+function troll_confirm_block_user_form_submit($form, &$form_state) {
+  troll_block_user($form_state['values']['uid']);
+  $form_state['redirect'] = 'admin/settings/troll';
+}
+
+/**
+ * IP banning form.
+ *
+ * @param $iid int
+ * @return array
+ */
+function troll_ip_ban_form($form_state, $iid = NULL) {
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => (isset($iid)) ? t('Update Banned IP') : t('Ban IP'),
+    '#weight' => 1,
+  );
+
+  $ip = db_fetch_object(db_query('SELECT * FROM {troll_ip_ban} WHERE iid = %d', $iid));
+  $form['iid'] = array(
+    '#type' => 'value',
+    '#value' => $ip->iid,
+  );
+  $form['ip_address'] = array(
+    '#type' => 'textfield',
+    '#title' => t('IP Address'),
+    '#default_value' => $ip->ip_address,
+    '#description' => t('The IP address to ban.'),
+    '#required' => TRUE
+  );
+  $form['domain_name'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Domain Name'),
+    '#default_value' => ($ip->domain_name ? $ip->domain_name : ($ip->ip_address ? gethostbyaddr($ip->ip_address) : '')),
+    '#description' => t('The Domain Name of the IP address to ban - for reference only.')
+  );
+
+  $timestamp = ($ip->expires ? $ip->expires : time());
+
+  $date = getdate(gmmktime());
+  $curyear = $date['year'];
+  $i = 0;
+  while ($i < 10) {
+    $years[$curyear + $i] = $curyear + $i;
+    $i++;
+  }
+  $months = array(1 => t('January'), t('February'), t('March'), t('April'), t('May'), t('June'), t('July'), t('August'), t('September'), t('October'), t('November'), t('December'));
+  for ($i = 1; $i <= 31; $i++) {
+    $days[$i] = $i;
+  }
+
+  $form['timestamp'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Expires'),
+    '#prefix' => '<div class="container-inline"><div class="day">',
+    '#suffix' => '</div></div>',
+    '#description' => t('The ban will be removed after this day.')
+  );
+  $form['timestamp']['expires'] = array(
+    '#type' => 'checkbox',
+    '#default_value' => ($ip->expires ? TRUE : FALSE)
+  );
+  $form['timestamp']['month'] = array(
+    '#type' => 'select',
+    '#default_value' => date('n', $timestamp),
+    '#options' => $months
+  );
+  $form['timestamp']['day'] = array(
+    '#type' => 'select',
+    '#default_value' => date('j', $timestamp),
+    '#options' => $days
+  );
+  $form['timestamp']['year'] = array(
+    '#type' => 'select',
+    '#default_value' => date('Y', $timestamp),
+    '#options' => $years
+  );
+
+  //$form['#action'] = url('admin/settings/troll/ip_ban');
+  return $form;
+}
+
+/**
+ * troll_ip_ban form validate callback function.
+ *
+ * @see troll_ip_ban_form
+ */
+function troll_ip_ban_form_validate($form, &$form_state) {
+  if (!preg_match('([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})', $form_state['values']['ip_address'])) {
+    form_set_error('ip_address', t('Please include a valid IP address.'));
+  }
+}
+
+/**
+ * Submit handler for IP ban form.
+ *
+ * @see troll_ip_ban_form
+ */
+function troll_ip_ban_form_submit($form, &$form_state) {
+  troll_update_ip($form_state['values']);
+  $form_state['redirect'] = 'admin/settings/troll/ip_ban';
+}
+
+/**
+ * IP ban information form.
+ */
+function troll_display_ip() {
+
+  $sql = 'SELECT iid, ip_address, domain_name, expires, uid FROM {troll_ip_ban}';
+
+  $headers = array(
+    array('data' => t('IP Address'), 'field' => 'ip_address'),
+    array('data' => t('Domain Name'), 'field' => 'domain_name'),
+    array('data' => t('Expires'), 'field' => 'expires', 'sort' => 'desc'),
+    array('data' => t('Actions'), 'field' => 'delete')
+  );
+
+  $sql .= tablesort_sql($headers);
+  $result = pager_query($sql, 25);
+  while ($row = db_fetch_object($result)) {
+    $thisip = l($row->ip_address, 'admin/settings/troll/ip_ban/edit/'. $row->iid);
+    $thisdom = l(($row->domain_name ? $row->domain_name : gethostbyname($row->ip_address)), 'admin/settings/troll/ip_ban/edit/'. $row->iid);
+    $expires = ($row->expires ? date('M d, Y', $row->expires) : t('never'));
+    $action = l(t('remove'), 'admin/settings/troll/ip_ban/delete/'. $row->iid);
+    $rows[] = array($thisip, $thisdom, $expires, $action);
+  }
+
+  $pager = theme('pager', NULL, 25, 0);
+  if (!empty($pager)) {
+    $rows[] = array(array('data' => $pager, 'colspan' => 5));
+  }
+
+  return theme('table', $headers, $rows);
+}
+
+/**
+ * IP ban delete confirmation form.
+ */
+function troll_confirm_delete_ip_form($form_state, $iid) {
+  $ip = db_fetch_object(db_query('SELECT ip_address FROM {troll_ip_ban} WHERE iid = %d', $iid));
+  $form['iid'] = array(
+    '#type' => 'value',
+    '#value' => $iid,
+  );
+  return confirm_form($form, t('Remove Ban for IP %ip?', array('%ip' => $ip->ip_address)), 'admin/settings/troll/ip_ban', t('Are you sure you want to remove the ban on this IP?'));
+}
+
+/**
+ * Submit handler for delete confirmation form.
+ * 
+ * @see troll_confirm_delete_ip_form
+ */
+function troll_confirm_delete_ip_form_submit($form, &$form_state) {
+  troll_remove_ip($form_state['values']['iid']);
+  $form_state['redirect'] = 'admin/settings/troll/ip_ban';
+}
+
+/**
+ * IP ban confirmation form.
+ */
+function troll_confirm_ban_ip_form($form_state, $uid) {
+  $ip = db_fetch_object(db_query('SELECT ip_address FROM {troll_ip_track} WHERE uid = %d ORDER BY accessed DESC', $uid));
+  $form['ip_address'] = array(
+    '#type' => 'value',
+    '#value' => $ip->ip_address,
+  );
+  $form['domain_name'] = array(
+    '#type' => 'value',
+    '#value' => gethostbyaddr($ip->ip_address),
+  );
+  return confirm_form($form, t('Ban IP %ip?', array('%ip' => $ip->ip_address)), 'admin/settings/troll/ip_ban', t('Are you sure you want to ban this IP?'));
+}
+
+/**
+ * Submit handler for ban confirmation form.
+ * 
+ * @see troll_confirm_ban_ip_form
+ */
+function troll_confirm_ban_ip_form_submit($form, &$form_state) {
+  troll_insert_ip($form_state['values']);
+  $form_state['redirect'] = 'admin/settings/troll';
+}
+
+/**
+ * Confirmation form for deleting a blacklist IP block
+ *
+ * @param integer $net IP in long format
+ * @param integer $bcast IP in long format
+ */
+function troll_confirm_delete_black_block_form($form_state, $net, $bcast) {
+  $result = db_result(db_query('SELECT COUNT(net) FROM {troll_blacklist} WHERE net = %d AND bcast = %d', $net, $bcast));
+  if (empty($result)) {
+    drupal_set_message(t('No such IP range found in the database.'));
+    drupal_goto('admin/settings/troll/ip_blacklist/search');
+  }
+  $form['net'] = array(
+    '#type' => 'value',
+    '#value' => $net
+  );
+  $form['bcast'] = array(
+    '#type' => 'value',
+    '#value' => $bcast
+  );
+  return confirm_form(
+    $form,
+    t('Remove listing for IP block %ip1 to %ip2?', array('%ip1' => long2ip($net), '%ip2' => long2ip($bcast))),
+    'admin/settings/troll/ip_blacklist/search',
+    t('Are you sure you want to remove this IP block from the blacklist?'),
+    t('Confirm Blacklist Removal')
+  );
+}
+
+/**
+ * Submit handler for deletion of IP from blacklist.
+ * 
+ * @see troll_confirm_delete_black_block_form
+ */
+function troll_confirm_delete_black_block_form_submit($form, &$form_state) {
+  troll_remove_blacklist($form_state['values']['net'], $form_state['values']['bcast']);
+  $form_state['redirect'] = 'admin/settings/troll/ip_blacklist/search';
+}
+
+/**
+ * Confirmation form for deleting a whitelist IP block
+ *
+ * @param integer $net IP in long format
+ * @param integer $bcast IP in long format
+ */
+function troll_confirm_delete_white_block_form($form_state, $net, $bcast) {
+  $result = db_result(db_query('SELECT COUNT(net) FROM {troll_whitelist} WHERE net = %d AND bcast = %d', $net, $bcast));
+  if (empty($result)) {
+    drupal_set_message(t('No such IP range found in the database.'));
+    drupal_goto('admin/settings/troll/ip_blacklist/whitelist');
+  }
+  $form['net'] = array(
+    '#type' => 'value',
+    '#value' => $net
+  );
+  $form['bcast'] = array(
+    '#type' => 'value',
+    '#value' => $bcast
+  );
+
+  return confirm_form(
+    $form,
+    t('Remove listing for IP block %ip1 to %ip2?', array('%ip1' => long2ip($net), '%ip2' => long2ip($bcast))),
+    'admin/settings/troll/ip_blacklist/whitelist',
+    t('Are you sure you want to remove this IP block from the whitelist?'),
+    t('Confirm Whitelist Removal')
+  );
+}
+
+/**
+ * Submit handler for deletion of IP from whitelist.
+ * 
+ * @see troll_confirm_delete_white_block_form
+ */
+function troll_confirm_delete_white_block_form_submit($form, &$form_state) {
+  troll_remove_whitelist($form_state['values']['net'], $form_state['values']['bcast']);
+  $form_state['redirect'] = 'admin/settings/troll/ip_blacklist/whitelist';
+}
+
+/**
+ * User search form.
+ *
+ * @return array
+ */
+function troll_search_form($form_state) {
+  $form['search'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Search Users'),
+    '#collapsible' => TRUE
+  );
+  $form['search']['username'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Username'),
+    '#description' => t('You can use % for wildcard, so to get all usernames with \'A\' in them, use %A%')
+  );
+  $form['search']['mail'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Email')
+  );
+  $form['search']['ip_address'] = array(
+    '#type' => 'textfield',
+    '#title' => t('IP Address')
+  );
+  $form['search']['date_created'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Account Date Created'),
+    '#description' => t('Enter date in mm/dd/yyyy format. Returns all users created after the date entered.')
+  );
+  $form['search']['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Search Users')
+  );
+  $form['users'] = array(
+    '#value' => isset($form_state['values']) ? troll_list_users($form_state['values']) : troll_list_users(array()),
+  );
+
+  return $form;
+}
+
+function troll_search_form_submit($form, &$form_state) {
+  $form_state['rebuild'] = TRUE;
+}
+
+/**
+ * User list form.
+ *
+ * @param $edit array
+ */
+function troll_list_users($edit) {
+
+  $where[] = 'u.uid <> 0';
+
+  if (!empty($edit['username'])) {
+    $where[] = "LOWER(u.name) LIKE '%%%s%%' ";
+    $args[] = drupal_strtolower($edit['username']);
+  }
+  if (!empty($edit['mail'])) {
+    $where[] = "LOWER(u.mail) LIKE '%%%s%%' ";
+    $args[] = drupal_strtolower($edit['mail']);
+  }
+  if (!empty($edit['ip_address']) > 0) {
+    $where[] = "LOWER(t.ip_address) LIKE '%%%s%%' ";
+    $args[] = drupal_strtolower($edit['ip_address']);
+  }
+  if (!empty($edit['date_created']) > 0) {
+    $where[] = "u.created > %d ";
+    $args[] = drupal_strtotime($edit['date_created']);
+  }
+
+  $sql = "SELECT u.uid, u.name, u.mail, u.status, t.ip_address, MAX(t.accessed) AS recorded, u.created FROM {users} u LEFT JOIN {troll_ip_track} t ON u.uid = t.uid";
+
+  $sql .= ' WHERE '. implode(' AND ', $where);
+
+  $headers = array(
+    array('data' => t('Username'), 'field' => 'u.name'),
+    array('data' => t('Email'), 'field' => 'u.mail'),
+    array('data' => t('Status'), 'field' => 'u.status'),
+    array('data' => t('IP Address'), 'field' => 't.ip_address'),
+    array('data' => t('Last Access'), 'field' => 't.created'),
+    array('data' => t('Account Created'), 'field' => 'u.created'),
+    array('data' => t('Actions'), 'field' => 'actions')
+  );
+
+  $sql .= ' GROUP BY u.uid, u.name, u.mail, u.status, t.ip_address, u.created';
+  $sql .= tablesort_sql($headers);
+
+  $count = 'SELECT COUNT(*) FROM {users} u LEFT JOIN {troll_ip_track} t ON u.uid = t.uid WHERE '. implode(' AND ', $where) .' AND u.uid <> 0';
+  $result = pager_query($sql, 25, 0, $count, $args);
+
+  while($user = db_fetch_object($result)) {
+    $name = l($user->name, 'admin/settings/troll/search/view/'. $user->uid, array('title' => t('View detailed user information')));
+    $email = $user->mail;
+    $status = ($user->status ? t('Active') : t('Blocked'));
+    $ip = ($user->ip_address ? l($user->ip_address, 'admin/settings/troll/search/view/'. $user->uid, array('title' => t('View detailed user information'))) : t('none'));
+    $recorded = ($user->recorded ? date('M d, Y', $user->recorded) : t('none recorded'));
+    $created = date('M d, Y', $user->created);
+    $actions = array();
+
+    if (!$user->status) {
+      $actions[] = array('title' => t('Edit User'), 'href' => "user/{$user->uid}/edit");
+    }
+    else if (variable_get('troll_block_role', NULL)) {
+      $actions[] = array('title' => t('Block User'), 'href' => 'admin/settings/troll/search/block/'. $user->uid);
+    }
+    else {
+      $actions[] = array('title' => t('Set up Block Role'), 'href' => 'admin/settings/troll/settings');
+    }
+    if ($user->ip_address) {
+      $actions[] = array('title' => t('Ban IP'), 'href' => 'admin/settings/troll/ip_ban/user/'. $user->uid);
+    }
+    $action = theme('links', $actions);
+    $rows[] = array($name, $email, $status, $ip, $recorded, $created, $action);
+  }
+
+  $pager = theme('pager', NULL, 25);
+
+  if (!empty($pager)) {
+    $rows[] = array(array('data' => $pager, 'colspan' => 7));
+  }
+
+  return theme('table', $headers, $rows);
+}
+
+/**
+ * User detail form.
+ * 
+ * This is not an actual form; the form API is just being used for easy formatting.
+ *
+ * @param $uid int
+ * @return string
+ */
+function troll_search_user_detail($uid) {
+  $u = user_load(array('uid' => $uid));
+  $u->ip = db_fetch_object(db_query('SELECT t.ip_address FROM {troll_ip_track} t WHERE t.uid = %d GROUP BY t.uid, t.ip_address', $uid));
+
+  $form['details'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Account Details for %username', array('%username' => $u->name))
+  );
+
+  $form['details'][] = array(
+    '#type' => 'item',
+    '#title' => t('User Name'),
+    '#value' => theme('username', $u),
+  );
+  $form['details'][] = array(
+    '#type' => 'item',
+    '#title' => t('Email'),
+    '#value' => $u->mail
+  );
+  $form['details'][] = array(
+    '#type' => 'item',
+    '#title' => t('User ID'),
+    '#value' => $uid
+  );
+  $form['details'][] = array(
+    '#type' => 'item',
+    '#title' => t('Account Created'),
+    '#value' => format_date($u->created, 'long')
+  );
+  $form['details'][] = array(
+    '#type' => 'item',
+    '#title' => t('Last Access'),
+    '#value' => format_date($u->access, 'long')
+  );
+  $form['details'][] = array(
+    '#type' => 'item',
+    '#title' => t('Status'),
+    '#value' => ($u->status ? t('Active') : t('Blocked'))
+  );
+  $form['details'][] = array(
+    '#type' => 'item',
+    '#title' => t('User Roles'),
+    '#value' => implode(', ', $u->roles)
+  );
+  if ($u->status) {
+    $links[] = array('title' => t('Block User'), 'href' => "admin/settings/troll/search/block/$uid");
+  }
+  else {
+    $links[] = array('title' => t('Edit User'), 'href' => "user/$uid/edit");
+  }
+  if ($u->ip->ip_address) {
+    $links[] = array('title' => t('Ban IP'), 'href' => "admin/settings/troll/ip_ban/user/$uid");
+  }
+  $form['details'][] = array(
+    '#type' => 'item',
+    '#title' => t('Actions'),
+    '#value' => theme('links', $links)
+  );
+
+  $content = drupal_render($form);
+
+  // Get IP history.
+  $results = db_query('SELECT * FROM {troll_ip_track} WHERE uid = %d ORDER BY created DESC', $uid);
+  while ($ip = db_fetch_object($results)) {
+    $banned = db_fetch_object(db_query('SELECT * FROM {troll_ip_ban} WHERE ip_address = \'%s\'', $ip->ip_address));
+    if ($banned->ip_address) {
+      if ($banned->expires && $banned->expires < time()) {
+        $status = l(t('expired'), 'admin/settings/troll/ip_ban/edit/'. $banned->iid, array('title' => t('Edit IP ban information')));
+      }
+      else {
+        $status = l(t('banned'), 'admin/settings/troll/ip_ban/edit/'. $banned->iid, array('title' => t('Edit IP ban information')));
+      }
+    }
+    else {
+      $status = l(t('not banned'), 'admin/settings/troll/ip_ban/user/'. $uid, array('title' => t('Ban this IP')));
+    }
+    $rows[] = array($ip->ip_address, $status, format_date($ip->accessed, 'long'), format_date($ip->created, 'long'), exec('host '. $ip->ip_address));
+  }
+
+  if ($rows) {
+    $pheader = array(t('IP'), t('Status'), t('Last Access'), t('First Access'), t('Host Information'));
+    $posts = theme('table', $pheader, $rows);
+  }
+  $content .= theme('box', t('IP History'), ($posts ? $posts : t('No ip history')));
+
+  // Get recent posts.
+  $rdat = db_query_range("SELECT * FROM {node} WHERE uid = %d ORDER BY created DESC", $uid, 0, 5);
+  $posts = NULL;
+  $rows = array();
+  while ($node = db_fetch_object($rdat)) {
+    $rows[] = array(l($node->title, "node/$node->nid") .' '. theme('mark', node_mark($node->nid, $node->changed)), $node->type, date('M d, Y', $node->created), ($node->status ? t('published') : t('not published')));
+  }
+  if ($rows) {
+    $pheader = array(t('Title'), t('Type'), t('Created'), t('Status'));
+    $posts = theme('table', $pheader, $rows);
+  }
+
+  $content .= theme('box', t('Recent Posts'), ($posts ? $posts : t('No recent posts')));
+
+  // Get recent comments.
+  $cp = 'SELECT * FROM {comments} WHERE uid = %d ORDER BY timestamp DESC';
+  $cdat = db_query($cp, $uid);
+
+  $rows = array();
+  $posts = NULL;
+  while ($comment = db_fetch_object($cdat)) {
+    $rows[] = array(l($comment->subject, 'node/'. $comment->nid, array('fragment' => 'comment-'. $comment->cid)) .' '. theme('mark', node_mark($comment->nid, $comment->changed)), date('M d, Y', $comment->timestamp), ($comment->status ? t('not published') : t('published')));
+  }
+
+  if ($rows) {
+    $cheader = array(t('Subject'), t('Date Created'), t('Status'));
+    $posts = theme('table', $cheader, $rows);
+  }
+  $content .= theme('box', t('Recent Comments'), ($posts ? $posts : t('No recent comments')));
+
+  return $content;
+}
Index: troll.info
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/troll/troll.info,v
retrieving revision 1.2.2.2
diff -u -p -r1.2.2.2 troll.info
--- troll.info	8 Apr 2008 16:32:54 -0000	1.2.2.2
+++ troll.info	24 Sep 2008 14:22:16 -0000
@@ -1,4 +1,4 @@
 ; $Id $
 name = Troll
 description = Provides tools for community sites including users by IP address, banning IP addresses, advanced user searching, and blocking user by role.
-
+core = 6.x
Index: troll.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/troll/troll.install,v
retrieving revision 1.2.2.1
diff -u -p -r1.2.2.1 troll.install
--- troll.install	8 Apr 2008 16:32:54 -0000	1.2.2.1
+++ troll.install	24 Sep 2008 14:22:16 -0000
@@ -2,88 +2,18 @@
 // $Id: troll.install,v 1.2.2.1 2008/04/08 16:32:54 jaydub Exp $
 
 /**
+ * @file
+ * .install file for troll module.
+ */
+
+/**
  * Implementation of hook_install().
  */
 function troll_install() {
-  switch ($GLOBALS['db_type']) {
-    case 'mysql':
-    case 'mysqli':
-      db_query("CREATE TABLE {troll_blacklist} (
-          net int(11) NOT NULL,
-          bcast int(11) NOT NULL,
-          UNIQUE KEY net (net,bcast)
-        ) TYPE=MyISAM /*!40100 DEFAULT CHARACTER SET utf8 */"
-      );
-
-      db_query("CREATE TABLE {troll_ip_ban} (
-          iid int(11) NOT NULL auto_increment,
-          ip_address varchar(30) NOT NULL default '',
-          domain_name varchar(255) NOT NULL default '',
-          expires int(11) unsigned NOT NULL default '0',
-          created int(11) unsigned NOT NULL default '0',
-          uid int(10) unsigned NOT NULL default '0',
-          PRIMARY KEY (iid),
-          UNIQUE KEY ip (ip_address)
-        ) TYPE=MyISAM /*!40100 DEFAULT CHARACTER SET utf8 */"
-      );
-
-      db_query("CREATE TABLE {troll_ip_track} (
-          uid int(11) NOT NULL default '0',
-          accessed int(11) unsigned NOT NULL default '0',
-          ip_address varchar(20) NOT NULL default '',
-          created int(11) NOT NULL default '0',
-          KEY uid (uid)
-        ) TYPE=MyISAM /*!40100 DEFAULT CHARACTER SET utf8 */"
-      );
-
-      db_query("CREATE TABLE {troll_whitelist} (
-          net int(11) NOT NULL,
-          bcast int(11) NOT NULL,
-          UNIQUE KEY net (net,bcast)
-        ) TYPE=MyISAM /*!40100 DEFAULT CHARACTER SET utf8 */"
-      );
-
-      db_query("INSERT INTO {troll_whitelist} (net, bcast) VALUES (2130706433, 2130706433)");
-      break;
-
-    case 'pgsql':
-      db_query("CREATE TABLE {troll_blacklist} (
-          net integer NOT NULL default '0',
-          bcast integer NOT NULL default '0'
-        )"
-      );
-      db_query("CREATE UNIQUE INDEX {troll_blacklist}_net_bcast_idx ON {troll_blacklist} (net, bcast)");
-
-      db_query("CREATE TABLE {troll_ip_ban} (
-          iid serial,
-          ip_address varchar(30) NOT NULL default '',
-          domain_name varchar(255) NOT NULL default '',
-          expires integer NOT NULL default '0',
-          created integer NOT NULL default '0',
-          uid integer NOT NULL default '0',
-          PRIMARY KEY (iid)
-        )"
-      );
-      db_query("CREATE UNIQUE INDEX {troll_ip_ban}_ip_address_idx ON {troll_ip_ban} (ip_address)");
-
-      db_query("CREATE TABLE {troll_ip_track} (
-          uid integer NOT NULL default '0',
-          accessed integer NOT NULL default '0',
-          ip_address varchar(20) NOT NULL default '',
-          created integer NOT NULL default '0',
-          PRIMARY KEY (uid)
-        )"
-      );
-
-      db_query("CREATE TABLE {troll_whitelist} (
-          net integer NOT NULL default '0',
-          bcast integer NOT NULL default '0'
-        )"
-      );
-      db_query("CREATE UNIQUE INDEX {troll_whitelist}_net_bcast_idx ON {troll_whitelist} (net, bcast)");
-      db_query("INSERT INTO {troll_whitelist} (net, bcast) VALUES (2130706433, 2130706433)");
-      break;
-  }
+  drupal_install_schema('troll');
+ 
+  // Whitelist 127.0.0.1.
+  db_query("INSERT INTO {troll_whitelist} (net, bcast) VALUES (2130706433, 2130706433)");
 }
 
 /**
@@ -133,21 +63,24 @@ function troll_update_1() {
 }
 
 /**
+ * This update will not run properly under Drupal 6 because _system_update_utf8() does
+ * not exist in Drupal 6.
+ *
  * @see http://drupal.org/node/54614
  * @return array
+ * 
  */
+/*
 function troll_update_2() {
    return _system_update_utf8(array('troll_blacklist', 'troll_ip_ban', 'troll_ip_track', 'troll_whitelist'));
 }
+*/
 
 /**
  * Implmentation of hook_uninstall().
  */
 function troll_uninstall() {
-  db_query('DROP TABLE {troll_blacklist}');
-  db_query('DROP TABLE {troll_whitelist}');
-  db_query('DROP TABLE {troll_ip_ban}');
-  db_query('DROP TABLE {troll_ip_track}');
+  drupal_uninstall_schema('troll');
   variable_del('troll_block_role');
   variable_del('troll_blacklist_stutter');
   variable_del('troll_blacklist_mod_requests');
@@ -156,3 +89,46 @@ function troll_uninstall() {
   variable_del('troll_enable_ip_ban');
   variable_del('troll_ip_ban_redirect');
 }
+
+/**
+ * Implementation of hook_schema().
+ */
+function troll_schema() {
+  $schema['troll_whitelist'] = array(
+    'fields' => array(
+         'net' => array('type' => 'int', 'not null' => TRUE, 'disp-width' => '11'),
+         'bcast' => array('type' => 'int', 'not null' => TRUE, 'disp-width' => '11')),
+    'unique keys' => array(
+         'net' => array('net', 'bcast')),
+  );
+  $schema['troll_ip_track'] = array(
+    'fields' => array(
+         'uid' => array('type' => 'int', 'not null' => TRUE, 'default' => 0, 'disp-width' => '11'),
+         'accessed' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'disp-width' => '11'),
+         'ip_address' => array('type' => 'varchar', 'length' => '20', 'not null' => TRUE, 'default' => ''),
+         'created' => array('type' => 'int', 'not null' => TRUE, 'default' => 0, 'disp-width' => '11')),
+    'indexes' => array(
+         'uid' => array('uid')),
+  );
+  $schema['troll_ip_ban'] = array(
+    'fields' => array(
+         'iid' => array('type' => 'serial', 'not null' => TRUE, 'disp-width' => '11'),
+         'ip_address' => array('type' => 'varchar', 'length' => '30', 'not null' => TRUE, 'default' => ''),
+         'domain_name' => array('type' => 'varchar', 'length' => '255', 'not null' => TRUE, 'default' => ''),
+         'expires' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'disp-width' => '11'),
+         'created' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'disp-width' => '11'),
+         'uid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0, 'disp-width' => '10')),
+    'primary key' => array('iid'),
+    'unique keys' => array(
+         'ip' => array('ip_address')),
+  );
+  $schema['troll_blacklist'] = array(
+    'fields' => array(
+         'net' => array('type' => 'int', 'not null' => TRUE, 'disp-width' => '11'),
+         'bcast' => array('type' => 'int', 'not null' => TRUE, 'disp-width' => '11')),
+    'unique keys' => array(
+         'net' => array('net', 'bcast')),
+  );
+
+  return $schema;
+}
Index: troll.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/troll/troll.module,v
retrieving revision 1.26.2.11
diff -u -p -r1.26.2.11 troll.module
--- troll.module	21 Sep 2008 12:12:48 -0000	1.26.2.11
+++ troll.module	24 Sep 2008 14:22:16 -0000
@@ -13,9 +13,9 @@
  */
 
 /**
- * Implementation of hook_init.
+ * Implementation of hook_boot().
  */
-function troll_init() {
+function troll_boot() {
   if (troll_is_blacklisted()) {
     $alt_page = variable_get('troll_blacklist_alt_page', 0);
     if ($alt_page) {
@@ -27,11 +27,14 @@ function troll_init() {
           // drupal_not_found() can make a mess in admin logs with watchdog()
           drupal_set_header('HTTP/1.0 404 Not Found');
           drupal_set_title(t('Page not found'));
+          // $return seems to be undefined here.
           print theme('page', $return);
           exit;
           break;
         case 'redirect':
-          header('Location: '. variable_get('troll_blacklist_alt_url', ''));
+          // The default value of troll_blacklist_alt_url should not be an
+          // empty string because then we redirect to ourselves; so use 127.0.0.1.
+          header('Location: '. variable_get('troll_blacklist_alt_url', 'http://127.0.0.1'));
           exit;
           break;
       }
@@ -55,94 +58,51 @@ function troll_init() {
 
   if ($user->uid) {
     $track = db_fetch_object(db_query("SELECT * FROM {troll_ip_track} WHERE uid = %d AND ip_address = '%s'", $user->uid, $_SERVER['REMOTE_ADDR']));
-    if ($track->uid) {
-      // record for this IP exists, update accessed timestamp
+    if (!empty($track->uid)) {
+      // A record for this IP exists. Update accessed timestamp.
       db_query("UPDATE {troll_ip_track} SET accessed = %d WHERE uid = %d AND ip_address = '%s'", time(), $user->uid, $_SERVER['REMOTE_ADDR']);
     }
     else {
-      // insert new IP record for user
+      // Insert new IP record for user.
       db_query("INSERT INTO {troll_ip_track} (uid, ip_address, created, accessed) VALUES (%d, '%s', %d, %d)", $user->uid, $_SERVER['REMOTE_ADDR'], time(), time());
     }
   }
 
   if (variable_get('troll_enable_ip_ban', FALSE)) {
     $ban = db_fetch_object(db_query('SELECT * FROM {troll_ip_ban} WHERE (expires > %d OR expires = 0) AND ip_address = \'%s\'', time(), $_SERVER['REMOTE_ADDR']));
-    if ($ban->ip_address) {
+    if (!empty($ban->ip_address)) {
       global $base_url;
-      watchdog('troll', 'IP Ban: '. $_SERVER['REMOTE_ADDR'], WATCHDOG_NOTICE);
+      watchdog('troll', 'IP Ban: '. $_SERVER['REMOTE_ADDR'], array(), WATCHDOG_NOTICE);
       $troll_ip_ban_redirect = variable_get('troll_ip_ban_redirect', '');
-      $page = (empty($troll_ip_ban_redirect) ? drupal_get_path('module', 'troll') .'/blocked.html' : $troll_ip_ban_redirect);
-      header('location: '. $base_url .'/'. $page);
+      if (empty($troll_ip_ban_redirect)) {
+        include_once('includes/common.inc');
+        $page = drupal_get_path('module', 'troll') .'/blocked.html';
+      }
+      else {
+        $page = $troll_ip_ban_redirect;
+      }
+      header('Location: '. $base_url .'/'. $page);
       die();
     }
   }
 }
 
 /**
- * Implementation of hook_help.
+ * Implementation of hook_help().
  *
  * @param $section string
  */
-function troll_help($section = 'admin/help#legal') {
+function troll_help($section) {
   switch ($section) {
     case 'admin/settings/troll/ip_ban':
       if (!variable_get('troll_enable_ip_ban', FALSE)) {
-        return theme('error', t('IP banning is currently disabled, you can enable it in the !settings page', array('!settings' => l(t('settings'), 'admin/settings/troll/settings'))));
+        return "<div class='messages error'>". t('IP banning is currently disabled. You can enable it in the !settings page.', array('!settings' => l(t('settings'), 'admin/settings/troll/settings')));
       }
       break;
   }
 }
 
 /**
- * Implementation of hook_settings().
- *
- * @return array
- */
-function troll_admin_settings() {
-  $form['ip_settings'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'IP Address Banning'
-  );
-  $form['ip_settings']['troll_enable_ip_ban'] = array(
-    '#type' => 'radios',
-    '#title' => t('IP Address Banning'),
-    '#default_value' => variable_get('troll_enable_ip_ban', 1),
-    '#options' => array('1' => t('Enable banning by IP address'), '0' => t('Disable banning by IP address'))
-  );
-  $form['ip_settings']['troll_ip_ban_redirect'] = array(
-    '#type' => 'textfield',
-    '#title' => t('IP Ban Relocation Page'),
-    '#default_value' => variable_get('troll_ip_ban_redirect', ''),
-    '#description' => t("Page for relocating users banned based on their IP address or domain name.  If left blank, users will be redirected to blocked.html in the troll module's directory. Do not use a drupal path here! You will cause a loop since IP banning completely blocks all access to the site! Edit the blocked.html file, or redirect to http://localhost."),
-  );
-
-  $roles = user_roles();
-  array_unshift($roles, t(' -Select Role- '));
-  $form['role_settings'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('User Blocking')
-  );
-  $form['role_settings']['troll_block_role'] = array(
-    '#type' => 'select',
-    '#title' => t('Troll Block Role'),
-    '#default_value' => variable_get('troll_block_role', 0),
-    '#options' => $roles,
-    '#description' => t('Select the role to set users to when blocking from the troll adminstration screens'),
-  );
-
-  return system_settings_form($form);
-}
-
-/**
- * admin settings page validate handler
- */
-function troll_admin_settings_validate($form_id, $form_values) {
-  if ($form_values['troll_block_role'] == '0') {
-    form_set_error('troll_block_role', t('You must choose a role to set users to when blocking from the troll settings page.'));
-  }
-}
-
-/**
  * Implementation of hook_perm().
  */
 function troll_perm() {
@@ -154,606 +114,151 @@ function troll_perm() {
  *
  * @return array
  */
-function troll_menu($may_cache) {
-  $items = array();
-
-  $access = user_access('administer troll');
-  if ($may_cache) {
-    $items[] = array(
-      'path' => 'admin/settings/troll',
-      'title' => t('Troll'),
-      'description' => t('Manage visitor IP banning.'),
-      'callback' => 'troll_search_users',
-      'access' => $access,
-      'weight' => 0,
-    );
-    $items[] = array(
-      'path' => 'admin/settings/troll/search',
-      'title' => t('Search Users'),
-      'callback' => 'troll_search_users',
-      'type' => MENU_DEFAULT_LOCAL_TASK,
-      'access' => $access,
-      'weight' => 0
-    );
-    $items[] = array(
-      'path' => 'admin/settings/troll/ip_ban',
-      'title' => t('IP Banning'),
-      'callback' => 'troll_ip_ban',
-      'type' => MENU_LOCAL_TASK,
-      'access' => $access,
-      'weight' => 1
-    );
-    $items[] = array(
-      'path' => 'admin/settings/troll/ip_blacklist',
-      'title' => t('Blacklists'),
-      'callback' => 'troll_blacklist',
-      'type' => MENU_LOCAL_TASK,
-      'access' => $access,
-      'weight' => 2
-    );
-    $items[] = array(
-      'path' => 'admin/settings/troll/settings',
-      'title' => t('Settings'),
-      'callback' => 'drupal_get_form',
-      'callback arguments' => array('troll_admin_settings'),
-      'type' => MENU_LOCAL_TASK,
-      'access' => user_access('administer site configuration'), 
-      'weight' => 3
-    );
-    $items[] = array(
-      'path' => 'admin/settings/troll/ip_ban/edit',
-      'title' => t('IP Ban Form'),
-      'callback' => 'drupal_get_form',
-      'callback arguments' => 'troll_ip_ban_form',
-      'type' => MENU_CALLBACK,
-      'access' => $access
-    );
-  }
-  return $items;
-}
-
-/**
- *
- * MENU CALLBACKS
- *
-**/
-
-/**
- * User IP banning page callback function.
- */
-function troll_ip_ban($op = NULL, $iid = NULL) {
-  $op   = $_POST['op'] ? $_POST['op'] : $op;
-  $edit = $_POST ? $_POST : $edit;
-
-  switch ($op) {
-    case 'user':
-      $ip = db_fetch_object(db_query('SELECT ip_address FROM {troll_ip_track} WHERE uid = %d ORDER BY accessed DESC', $iid));
-      $edit['ip_address'] = $ip->ip_address;
-      troll_insert_ip($edit);
-      drupal_goto('admin/settings/troll/ip_ban');
-      break;
-    case t('Ban IP'):
-      troll_insert_ip($edit);
-      drupal_goto('admin/settings/troll/ip_ban');
-      break;
-    case t('Update Banned IP'):
-      troll_update_ip($edit);
-      drupal_goto('admin/settings/troll/ip_ban');
-      break;
-    case 'delete':
-      $output = troll_confirm_delete_ip($iid);
-      break;
-    case t('Confirm'):
-      troll_remove_ip($iid);
-      drupal_goto('admin/settings/troll/ip_ban');
-      break;
-    case t('Cancel'):
-      drupal_goto('admin/settings/troll/ip_ban');
-      break;
-    default:
-      $form['banform'] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Add IP Ban'),
-        '#value' => drupal_get_form('troll_ip_ban_form'),
-        '#weight' => -1,
-        '#collapsible' => true
-      );
-      $form['ipdisplay'] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Banned IPs'),
-        '#value' => troll_display_ip(),
-        '#weight' => 0,
-        '#collapsible' => true
-      );
-      $output = drupal_render($form);
-      break;
-  }
-  return $output;
-}
-
-/**
- * Central function to display Blacklists tab and fire
- * off functions for Blacklist-related form submissions
- *
- * @param string $op
- * @param array $edit
- * @return string
- */
-function troll_blacklist($op = NULL, $edit = NULL) {
-  $op = $_POST['op'] ? $_POST['op'] : $op;
-
-  switch ($op) {
-    case t('Update Blacklist Punishments'):
-      variable_set('troll_blacklist_mod_requests', $_POST['mod_requests']);
-      variable_set('troll_blacklist_stutter', $_POST['stutter']);
-      variable_set('troll_blacklist_alt_page', $_POST['alt_page']);
-      variable_set('troll_blacklist_alt_url', $_POST['alt_url']);
-      drupal_goto('admin/settings/troll/ip_blacklist');
-      break;
-    case t('Import List'):
-      if (!empty($_POST['truncate_list'])) {
-        if (db_query('TRUNCATE TABLE {troll_blacklist}')) {
-          drupal_set_message(t('Blacklist table truncated.'));
-        }
-      }
-      if (!empty($_POST['select_list'])) {
-        troll_blacklist_import_list($_POST['select_list']);
-      }
-      if (!empty($_POST['custom_list'])) {
-        troll_blacklist_import_url($_POST['custom_list']);
-      }
-      drupal_goto('admin/settings/troll/ip_blacklist');
-      break;
-    case t('Search Blacklisted IPs'):
-      return troll_blacklist_search($_POST['ip_address']);
-      break;
-    case t('Insert Whitelist IPs'):
-      troll_whitelist_insert_ips($_POST['whitelist_addr1'], $_POST['whitelist_addr2']);
-      drupal_goto('admin/settings/troll/ip_blacklist');
-      break;
-    case t('Update Whitelist IPs'):
-      troll_whitelist_insert_ips($_POST['whitelist_addr1'], $_POST['whitelist_addr2']);
-      drupal_goto('admin/settings/troll/ip_blacklist');
-      break;
-    case 'deletewhite':
-      $output = troll_confirm_delete_white_block(arg(5), arg(6));
-      break;
-    case t('Confirm Whitelist Removal'):
-      troll_remove_whitelist($_POST['net'], $_POST['bcast']);
-      drupal_goto('admin/settings/troll/ip_blacklist');
-      break;
-    case 'deleteblack':
-      $output = troll_confirm_delete_black_block(arg(5), arg(6));
-      break;
-    case t('Confirm Blacklist Removal'):
-      troll_remove_blacklist($_POST['net'], $_POST['bcast']);
-      drupal_goto('admin/settings/troll/ip_blacklist');
-      break;
-    default:
-      $form['blacklist_info'] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Blacklist Summary'),
-        '#value' => troll_blacklist_summary(),
-        '#weight' => -4,
-        '#collapsible' => true,
-        '#collapsed' => false
-      );
-      $form['blacklist_punishment'] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Blacklist Visitor Punishment'),
-        '#value' => troll_blacklist_punishment(),
-        '#weight' => -3,
-        '#collapsible' => true,
-        '#collapsed' => true
-      );
-      $form['blacklist_import'] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Import Blacklist'),
-        '#value' => troll_blacklist_import(),
-        '#weight' => -2,
-        '#collapsible' => true,
-        '#collapsed' => true
-      );
-      $form['search_blacklist'] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Search Blacklisted IPs'),
-        '#value' => troll_blacklist_search_blacklist(),
-        '#weight' => 0,
-        '#collapsible' => true,
-        '#collapsed' => true
-      );
-      $form['whitelist_form'] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Whitelist IPs'),
-        '#value' => troll_whitelist(),
-        '#description' => t('Whitelisted IPs override the blacklist. Does not apply to the IP Ban feature.'),
-        '#weight' => 1,
-        '#collapsible' => true,
-        '#collapsed' => true
-      );
-      $output = drupal_render($form);
-      break;
-  }
-  return $output;
-}
-
-/**
- * Summary of how many IP blocks are filtered
- *
- * @return string
- */
-function troll_blacklist_summary() {
-  $count = db_result(db_query('SELECT COUNT(net) FROM {troll_blacklist}'));
-  return t('%d address blocks filtered.', array('%d' => $count));
-}
-
-/**
- * Form builder function
- *
- * @uses troll_blacklist_punishment_form()
- * @return string
- */
-function troll_blacklist_punishment() {
-  return drupal_get_form('troll_blacklist_punishment_form');
-}
-
-/**
- * Gives admins a choice of how to punish blacklisted visitors
- *
- * @return array
- */
-function troll_blacklist_punishment_form() {
-  $form['stutter'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Randomly stutter output'),
-    '#default_value' => variable_get('troll_blacklist_stutter', 0),
-    '#description' => t('While outputting content, the troll module will cause Drupal to "sleep" for random intervals of 1-5 seconds to delay output.')
-  );
-  $form['mod_requests'] = array(
-    '#type' => 'radios',
-    '#title' => t('Page request modification'),
-    '#options' => array(t('none'), 'silent_post_drop' => 'Silently drop form post submission data', 'notice_post_drop' => 'Drop form post submission data and give a notice'),
-    '#default_value' => variable_get('troll_blacklist_mod_requests', '0'),
-    '#description' => t('Modifies data sent by visitors from blacklisted IPs before Drupal even has a chance to process it.')
-  );
-  $form['alt_page_output'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Alternate page output'
-  );
-  $form['alt_page_output']['alt_page'] = array(
-    '#type' => 'radios',
-    '#title' => 'Alternate pages',
-    '#options' => array(t('none'), 'blank' => t('Blank pages'), '404' => t('404 every page request'), 'redirect' => t('Redirect to alternate URL')),
-    '#default_value' => variable_get('troll_blacklist_alt_page', '0'),
-    '#description' => t('Sends alternate page output, whether the visitor hits a real URL or not.')
+function troll_menu() {
+  $items['admin/settings/troll'] = array(
+    'title' => 'Troll',
+    'description' => 'Manage visitor IP banning.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_search_form'),
+    'access arguments' => array('administer troll'),
+    'weight' => 0,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/search'] = array(
+    'title' => 'Search Users',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_search_form'),
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+    'access arguments' => array('administer troll'),
+    'weight' => 0,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/search/view'] = array(
+    'title' => 'Search Users',
+    'page callback' => 'troll_search_user_detail',
+    'access arguments' => array('administer troll'),
+    'type' => MENU_CALLBACK,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/search/block'] = array(
+    'title' => 'Block User',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_confirm_block_user_form'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_CALLBACK,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_ban'] = array(
+    'title' => 'IP Banning',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_ip_ban'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 1,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_ban/edit'] = array(
+    'title' => 'IP Ban Form',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_ip_ban_form'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_CALLBACK,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_ban/user'] = array(
+    'title' => 'IP Ban Form',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_confirm_ban_ip_form'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_CALLBACK,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_ban/delete'] = array(
+    'title' => 'Remove Ban',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_confirm_delete_ip_form'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_CALLBACK,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_blacklist'] = array(
+    'title' => 'Blacklists',
+    'page callback' => 'troll_blacklist_summary',
+    'access arguments' => array('administer troll'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 2,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_blacklist/summary'] = array(
+    'title' => 'Summary',
+    'page callback' => 'troll_blacklist_summary',
+    'access arguments' => array('administer troll'),
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+    'weight' => 0,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_blacklist/punishment'] = array(
+    'title' => 'Visitor Punishment',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_blacklist_punishment_form'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 1,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_blacklist/import'] = array(
+    'title' => 'Import Blacklist',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_blacklist_import_form'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 2,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_blacklist/search'] = array(
+    'title' => 'Search Blacklisted IPs',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_blacklist_search_form'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 3,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_blacklist/deleteblack'] = array(
+    'title' => 'Delete Blacklisted IPs',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_confirm_delete_black_block_form'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_CALLBACK,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_blacklist/whitelist'] = array(
+    'title' => 'Whitelist',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_whitelist_form'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 4,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/ip_blacklist/deletewhite'] = array(
+    'title' => 'Delete Whitelisted IPs',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_confirm_delete_white_block_form'),
+    'access arguments' => array('administer troll'),
+    'type' => MENU_CALLBACK,
+    'file' => 'troll.admin.inc',
+  );
+  $items['admin/settings/troll/settings'] = array(
+    'title' => 'Settings',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('troll_admin_settings'),
+    'access arguments' => array('administer site configuration'), 
+    'type' => MENU_LOCAL_TASK,
+    'weight' => 5,
+    'file' => 'troll.admin.inc',
   );
-  $form['alt_page_output']['alt_url'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Redirection URL'),
-    '#default_value' => variable_get('troll_blacklist_alt_url', ''),
-    '#description' => t('URL to redirect blacklisted visitors to if "Redirect to alternate URL" is selected. Start with the appropriate prefix (e.g. http://)')
-  );
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Update Blacklist Punishments'),
-    '#weight' => 1
-  );
-  return $form;
-}
-
-/**
- * Form builder function
- *
- * @uses troll_blacklist_import_form()
- * @return string
- */
-function troll_blacklist_import() {
-  return drupal_get_form('troll_blacklist_import_form');
-}
-
-/**
- * Builds form array for admin to select how to import a new blacklist.
- *
- * @return array
- */
-function troll_blacklist_import_form() {
-  $form['truncate_list'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Truncate/delete existing blacklist before import')
-    );
-  $options = array();
-  $options[0] = '';
-  if (function_exists('gzopen')) {
-    $options['S1gz'] = 'OpenBSD mirror: SPEWS.org Level 1 bzip archive';
-    $options['S2gz'] = 'OpenBSD mirror: SPEWS.org Level 2 bzip archive';
-    $options['OCgz'] = 'OpenBSD mirror: okean.com China bzip archive';
-    $options['OKgz'] = 'OpenBSD mirror: okean.com Korea bzip archive';
-  }
-  $options['S1tx'] = 'SPEWS.org Level 1 text file';
-  $options['S2tx'] = 'SPEWS.org Level 2 text file';
-  $options['OTtx'] = 'okean.com China and Korea text file';
-  $options['OCtx'] = 'okean.com China text file';
-  $options['OKtx'] = 'okean.com Korea text file';
-  $form['select_list'] = array(
-    '#type' => 'select',
-    '#title' => t('Download and import'),
-    '#options' => $options,
-    '#description' => t('Downloads supported blacklist from the internet. Please select a mirror when possible.'),
-    );
-  $form['custom_list'] = array(
-    '#type' => 'textfield',
-    '#title' => t('List URL'),
-    '#description' => t('URL of a list to import. List files should have one address per line in Classless Internet Domain Routing CIDR format (x.x.x.x/x). Individual IPs should still have /32.'),
-    );
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Import List'),
-    '#weight' => 1,
-  );
-  return $form;
-}
-
-/**
- * Decyphers what dropdown selection was chosen to send for parsing out IP blocks
- *
- * @see troll_blacklist_import_form()
- * @see troll_blacklist_parse_save()
- * @param array $edit
- */
-function troll_blacklist_import_list($list) {
-  $files = array('S1gz' => array('gz' => 'http://www.openbsd.org/spamd/spews_list_level1.txt.gz'),
-    'S2gz' => array('gz' => 'http://www.openbsd.org/spamd/spews_list_level2.txt.gz'),
-    'OCgz' => array('gz' => 'http://www.openbsd.org/spamd/chinacidr.txt.gz'),
-    'OKgz' => array('gz' => 'http://www.openbsd.org/spamd/koreacidr.txt.gz'),
-    'S1tx' => array('txt' => 'http://www.spews.org/spews_list_level1.txt'),
-    'S2tx' => array('txt' => 'http://www.spews.org/spews_list_level2.txt'),
-    'OTtx' => array('txt' => 'http://www.okean.com/sinokoreacidr.txt'),
-    'OCtx' => array('txt' => 'http://www.okean.com/chinacidr.txt'),
-    'OKtx' => array('txt' => 'http://www.okean.com/koreacidr.txt'));
-
-  if (!isset($files[$list])) {
-    drupal_set_message(t('Form input not valid'));
-    return false;
-  }
-
-  $file_type = array_keys($files[$list]);
-  troll_blacklist_parse_save($files[$list][$file_type[0]], $file_type[0]);
-}
-
-/**
- * Parses a URL to send for parsing out IP blocks
- *
- * @see troll_blacklist_parse_save()
- * @param array $edit
- */
-function troll_blacklist_import_url($edit) {
-  $url_parts = parse_url($edit['custom_list']);
-  $file_parts = pathinfo($url_parts['path']);
-  troll_blacklist_parse_save($edit['custom_list'], $file_parts['extension']);
-}
-
-/**
- * Parses input file, line by line, searching for IP blocks in CIDR
- * format (x.x.x.x/x). Understands files in text, bzip, and bzip2 format,
- * where the PHP installation supports it. Writes what it finds to the
- * database as long integers.
- *
- * @todo should probably function_exists() the compression file functions
- * @param $file_name string
- * @param $file_type string
- */
-function troll_blacklist_parse_save($file_name, $file_type) {
-  $netmasks = array(
-    0, -2147483648, -1073741824, -536870912, -268435456, -134217728,
-    -67108864, -33554432, -16777216, -8388608, -4194304, -2097152, -1048576,
-    -524288, -262144, -131072, -65536, -32768, -16384, -8192, -4096, -2048,
-    -1024, -512, -256, -128, -64, -32, -16, -8, -4, -2, -1);
-
-  switch ($file_type) {
-    case 'gz':
-      $fp = gzopen($file_name, 'r');
-      break;
-    default:
-      $fp = fopen($file_name, 'r');
-      break;
-  }
-
-  if (is_resource($fp)) {
-    $i = 0;
-    while (!feof($fp)) {
-      $buffer = fgets($fp);
-      if ($buffer{0} != '#' && ($buffer{0} != '/' && $buffer{1} != '/') && !empty($buffer)) {
-        preg_match("/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/([0-9]{1,2})/", $buffer, $matches);
-        // $matches array
-        // 0 = whole string
-        // 1 = i.i.i.i
-        // 2 = s
-        $longip = ip2long($matches[1]);
-        unset($buffer, $matches[0], $matches[1]);
-
-        if ($matches[2] == 32) {
-          $net = $bcast = $longip;
-        }
-        else {
-          $net = $longip & $netmasks[$matches[2]];
-          $bcast = $longip | ($netmasks[$matches[2]] ^ -1);
-        }
-        db_query('DELETE FROM {troll_blacklist} WHERE net = %d AND bcast = %d', $net, $bcast);
-        db_query('INSERT INTO {troll_blacklist} (net, bcast) VALUES (%d, %d)', $net, $bcast);
-        $i++;
-      }
-    }
-    switch ($file_type) {
-      case 'gz':
-        gzclose($fp);
-        break;
-      default:
-        fclose($fp);
-        break;
-    }
-    drupal_set_message(t('%i IP blocks imported', array('%i' => $i)));
-  }
-  else {
-    drupal_set_message(t('Import failed! File could not be read.'));
-  }
-}
-
-/**
- * Form builder function
- *
- * @uses troll_blacklist_search_blacklist_form()
- * @return string
- */
-function troll_blacklist_search_blacklist() {
-  return drupal_get_form('troll_blacklist_search_blacklist_form');
-}
-
-/**
- * Form to search blacklist to see if an IP matches
- *
- * @return array
- */
-function troll_blacklist_search_blacklist_form() {
-  $form['ip_address'] = array(
-    '#type' => 'textfield',
-    '#title' => t('IP Address'),
-    '#size' => 15,
-    '#maxlength' => 15,
-    '#description' => t('Address to search for in the database of imported IP blocks.'),
-    '#required' => TRUE
-    );
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Search Blacklisted IPs'),
-    '#weight' => 1
-  );
-  return $form;
-}
-
-/**
- * Perform search to see if an IP address matches a blacklisted IP block.
- * If no results are found, get redirected to the blacklist management
- * page instead of seeing results.
- *
- * @param $edit array
- * @return string
- */
-function troll_blacklist_search($ip_address) {
-  $longip = _troll_longip($ip_address);
-  $sql = "SELECT net, bcast FROM {troll_blacklist} WHERE net <= %d AND bcast >= %d";
-
-  $headers = array(
-    array('data' => t('Network Address'), 'field' => 'net', 'sort' => 'asc'),
-    array('data' => t('Broadcast Address'), 'field' => 'bcast'),
-    array('data' => t('Actions'), 'field' => 'delete')
-  );
-
-  $sql .= tablesort_sql($headers);
-  $result = pager_query($sql, 25, 0, NULL, $longip, $longip);
-  if (db_num_rows($result) == 0) {
-    drupal_set_message(t('No matches found in blacklist search.'));
-    drupal_goto('admin/settings/troll/ip_blacklist');
-  }
-  while ($row = db_fetch_object($result)) {
-    $printnet = long2ip($row->net);
-    $printbcast = long2ip($row->bcast);
-    $action = l(t('remove'), "admin/settings/troll/ip_blacklist/deleteblack/{$row->net}/{$row->bcast}");
-    $rows[] = array($printnet, $printbcast, $action);
-  }
-
-  $pager = theme('pager', NULL, 25, 0);
-  if (!empty($pager)) {
-    $rows[] = array(array('data' => $pager, 'colspan' => 3));
-  }
-
-  return theme('table', $headers, $rows);
-}
-
-/**
- * Form builder function
- *
- * @param $net string Not used, here for later implementation of whitelist editing
- * @param $bcast string Not used, here for later implementation of whitelist editing
- * @uses troll_whitelist_form()
- * @return string
- */
-function troll_whitelist($net = NULL, $bcast = NULL) {
-  $output = drupal_get_form('troll_whitelist_form', $net, $bcast);
-  $sql = 'SELECT net, bcast FROM {troll_whitelist}';
-
-  $headers = array(
-    array('data' => t('Start/Network Address'), 'field' => 'net', 'sort' => 'asc'),
-    array('data' => t('End/Broadcast Address'), 'field' => 'bcast'),
-    array('data' => t('Actions'), 'field' => 'delete')
-  );
-
-  $sql .= tablesort_sql($headers);
-  $result = pager_query($sql, 25);
-  while($row = db_fetch_object($result)) {
-    $printnet = long2ip($row->net);
-    $printbcast = long2ip($row->bcast);
-    $action = l(t('remove'), "admin/settings/troll/ip_blacklist/deletewhite/{$row->net}/{$row->bcast}");
-    $rows[] = array($printnet, $printbcast, $action);
-  }
-
-  $pager = theme('pager', NULL, 25, 0);
-  if (!empty($pager)) {
-    $rows[] = array(array('data' => $pager, 'colspan' => 3));
-  }
-
-  return $output . theme('table', $headers, $rows);
-}
-
-/**
- * Display form for creating new whitelist block and table of current whitelisted IPs
- *
- * @return array
- */
-function troll_whitelist_form($net, $bcast) {
-  $form['whitelist_addr1'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Starting IP Address'),
-    '#size' => 15,
-    '#maxlength' => 15,
-    '#default_value' => $net ? long2ip($net) : '',
-    '#description' => t('IP or start to range of IPs to whitelist.'),
-    '#required' => TRUE
-  );
-  $form['whitelist_addr2'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Ending IP Address'),
-    '#size' => 15,
-    '#maxlength' => 15,
-    '#default_value' => $bcast ? long2ip($bcast) : '',
-    '#description' => t('End of IP range to whitelist. If whitelisting a single IP, leave this blank.'),
-    '#required' => false
-  );
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => ($net && $bcast) ? t('Update Whitelist IPs') : t('Insert Whitelist IPs'),
-    '#weight' => 1
-  );
-  $form['#action'] = url('admin/settings/troll/ip_blacklist');
-
-  return $form;
-}
-
-/**
- * Insert a new IP block into the whitelist
- *
- * @param array $edit
- */
-function troll_whitelist_insert_ips($whitelist_addr1, $whitelist_addr2) {
-  $longip1 = _troll_longip($whitelist_addr1);
-  $longip2 = _troll_longip(empty($whitelist_addr2) ? $whitelist_addr1 : $whitelist_addr2);
-  if ($longip1 > $longip2) {
-    $temp = $longip1;
-    $longip1 = $longip2;
-    $longip2 = $temp;
-    unset($temp);
-  }
-  db_query("REPLACE INTO {troll_whitelist} (net, bcast) VALUES (%d, %d)", $longip1, $longip2);
-  drupal_set_message(t('IP range %ip1 to %ip2 whitelisted.', array('%ip1' => long2ip($longip1), '%ip2' => long2ip($longip2))));
+  return $items;
 }
 
 /**
@@ -764,7 +269,7 @@ function troll_whitelist_insert_ips($whi
  */
 function _troll_longip($ip) {
   $longip = ip2long($ip);
-  if ($longip === false || $longip == -1) {
+  if ($longip === FALSE || $longip == -1) {
     drupal_set_message(t('IP %ip not valid!', array('%ip' => $ip)));
     drupal_goto('admin/settings/troll/ip_blacklist');
   }
@@ -772,507 +277,6 @@ function _troll_longip($ip) {
 }
 
 /**
- * User search page callback function.
- *
- * @param $op array
- * @param $uid
- * @return string
- */
-function troll_search_users($op = NULL, $uid = NULL) {
-  $form_values = $_POST;
-
-  $output = '';
-  switch ($op) {
-    case 'view':
-      $output = troll_search_user_detail($uid);
-      break;
-    case 'block':
-      troll_block_user($uid);
-      drupal_goto('admin/settings/troll/search');
-      break;
-    default:
-      $output = troll_user_search();
-      $output .= troll_list_users($form_values);
-      break;
-  }
-  return $output;
-}
-
-/**
- *
- * FORM FUNCTIONS
- *
-**/
-
-/**
- * IP banning form.
- *
- * @param $iid int
- * @return array
- */
-function troll_ip_ban_form($iid = NULL) {
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => ($iid) ? t('Update Banned IP') : t('Ban IP'),
-    '#weight' => 1,
-  );
-
-  $ip = db_fetch_object(db_query('SELECT * FROM {troll_ip_ban} WHERE iid = %d', $iid));
-  $form['iid'] = array(
-    '#type' => 'hidden',
-    '#value' => $ip->iid,
-  );
-  $form['ip_address'] = array(
-    '#type' => 'textfield',
-    '#title' => t('IP Address'),
-    '#default_value' => $ip->ip_address,
-    '#description' => t('The IP address to ban.'),
-    '#required' => TRUE
-  );
-  $form['domain_name'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Domain Name'),
-    '#default_value' => ($ip->domain_name ? $ip->domain_name : ($ip->ip_address ? gethostbyaddr($ip->ip_address) : '')),
-    '#description' => t('The Domain Name of the IP address to ban - for reference only.')
-  );
-
-  $timestamp = ($ip->expires ? $ip->expires : time());
-
-  $date = getdate( gmmktime() );
-  $curyear = $date['year'];
-  while ($i < 10) {
-    $years[$curyear+$i] = $curyear+$i;
-    $i++;
-  }
-  $months = array(1 => t('January'), t('February'), t('March'), t('April'), t('May'), t('June'), t('July'), t('August'), t('September'), t('October'), t('November'), t('December'));
-  for ($i = 1; $i <= 31; $i++) {
-    $days[$i] = $i;
-  }
-
-  $form['timestamp'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Expires'),
-    '#prefix' => '<div class="container-inline"><div class="day">',
-    '#suffix' => '</div></div>',
-    '#description' => t('The ban will be removed after this day.')
-  );
-  $form['timestamp']['expires'] = array(
-    '#type' => 'checkbox',
-    '#default_value' => ($ip->expires ? TRUE : FALSE)
-  );
-  $form['timestamp']['month'] = array(
-    '#type' => 'select',
-    '#default_value' => date('n', $timestamp),
-    '#options' => $months
-  );
-  $form['timestamp']['day'] = array(
-    '#type' => 'select',
-    '#default_value' => date('j', $timestamp),
-    '#options' => $days
-  );
-  $form['timestamp']['year'] = array(
-    '#type' => 'select',
-    '#default_value' => date('Y', $timestamp),
-    '#options' => $years
-  );
-
-  $form['#action'] = url('admin/settings/troll/ip_ban');
-  return $form;
-}
-
-/**
- * troll_ip_ban form validate callback function.
- *
- * @param $form_id
- * @param $edit array
- */
-function troll_ip_ban_validate($form_id, $edit) {
-  if (!preg_match('([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})', $edit['ip_address'])) {
-    form_set_error('ip_address', t('Please include an valid IP address'));
-  }
-}
-
-/**
- * IP ban information form.
- */
-function troll_display_ip() {
-
-  $sql = 'SELECT iid, ip_address, domain_name, expires, uid FROM {troll_ip_ban}';
-
-  $headers = array(
-    array('data' => t('IP Address'), 'field' => 'ip_address'),
-    array('data' => t('Domain Name'), 'field' => 'domain_name'),
-    array('data' => t('Expires'), 'field' => 'expires', 'sort' => 'desc'),
-    array('data' => t('Actions'), 'field' => 'delete')
-  );
-
-  $sql .= tablesort_sql($headers);
-  $result = pager_query($sql, 25);
-  while ($row = db_fetch_object($result)) {
-    $thisip = l($row->ip_address, 'admin/settings/troll/ip_ban/edit/'. $row->iid);
-    $thisdom = l(($row->domain_name ? $row->domain_name : gethostbyname($row->ip_address)), 'admin/settings/troll/ip_ban/edit/'. $row->iid);
-    $expires = ($row->expires ? date('M d, Y', $row->expires) : t('never'));
-    $action = l(t('remove'), 'admin/settings/troll/ip_ban/delete/'. $row->iid);
-    $rows[] = array($thisip, $thisdom, $expires, $action);
-  }
-
-  $pager = theme('pager', NULL, 25, 0);
-  if (!empty($pager)) {
-    $rows[] = array(array('data' => $pager, 'colspan' => 5));
-  }
-
-  return theme('table', $headers, $rows);
-}
-
-/**
- * IP ban delete confirmation.
- */
-function troll_confirm_delete_ip($iid) {
-  return drupal_get_form('troll_confirm_delete_ip_form', $iid);
-}
-
-/**
- * IP ban delete confirmation form.
- */
-function troll_confirm_delete_ip_form($iid) {
-  $ip = db_fetch_object(db_query('SELECT * FROM {troll_ip_ban} WHERE iid = %d', $iid));
-  return confirm_form(array(), t('Remove Ban for IP %ip?', array('%ip' => $ip->ip_address)), 'admin/settings/troll/ip_ban'. $edit['field_id'], t('Are you sure you want to remove the ban on this IP?'));
-}
-
-/**
- * Confirmation before deleting a blacklist IP block
- *
- * @param integer $net IP in long format
- * @param integer $bcast IP in long format
- * @return string
- */
-function troll_confirm_delete_black_block($net, $bcast) {
-  $result = db_result(db_query('SELECT COUNT(net) FROM {troll_blacklist} WHERE net = %d AND bcast = %d', $net, $bcast));
-  if (empty($result)) {
-    drupal_set_message(t('No such IP range found in the database.'));
-    drupal_goto('admin/settings/troll/ip_blacklist');
-  }
-  return drupal_get_form('troll_confirm_delete_black_block_form', $net, $bcast);
-}
-
-/**
- * Confirmation form for deleting a blacklist IP block
- *
- * @param integer $net IP in long format
- * @param integer $bcast IP in long format
- */
-function troll_confirm_delete_black_block_form($net, $bcast) {
-  return confirm_form(array(
-    'net' => array(
-      '#type' => 'hidden',
-      '#value' => $net),
-      'bcast' => array(
-        '#type' => 'hidden',
-        '#value' => $bcast)
-      ),
-      t('Remove listing for IP block %ip1 to %ip2?', array('%ip1' => long2ip($net), '%ip2' => long2ip($bcast))
-    ),
-    'admin/settings/troll/ip_blacklist',
-    t('Are you sure you want to remove this IP block from the blacklist?'),
-    t('Confirm Blacklist Removal')
-  );
-}
-
-/**
- * Confirmation before deleting a whitelist IP block
- *
- * @param integer $net IP in long format
- * @param integer $bcast IP in long format
- * @return string
- */
-function troll_confirm_delete_white_block($net, $bcast) {
-  $result = db_result(db_query('SELECT COUNT(net) FROM {troll_whitelist} WHERE net = %d AND bcast = %d', $net, $bcast));
-  if (empty($result)) {
-    drupal_set_message(t('No such IP range found in the database.'));
-    drupal_goto('admin/settings/troll/ip_blacklist');
-  }
-  return drupal_get_form('troll_confirm_delete_white_block_form', $net, $bcast);
-}
-
-/**
- * Confirmation form for deleting a whitelist IP block
- *
- * @param integer $net IP in long format
- * @param integer $bcast IP in long format
- */
-function troll_confirm_delete_white_block_form($net, $bcast) {
-  return confirm_form(array(
-    'net' => array(
-      '#type' => 'hidden',
-      '#value' => $net),
-      'bcast' => array(
-        '#type' => 'hidden',
-        '#value' => $bcast)
-    ),
-    t('Remove listing for IP block %ip1 to %ip2?', array('%ip1' => long2ip($net), '%ip2' => long2ip($bcast))),
-    'admin/settings/troll/ip_blacklist',
-    t('Are you sure you want to remove this IP block from the whitelist?'),
-    t('Confirm Whitelist Removal')
-  );
-}
-
-/**
- * Form builder function
- *
- * @uses troll_search_form()
- * @return sring
- */
-function troll_user_search() {
-  return drupal_get_form('troll_search_form');
-}
-
-/**
- * User search form.
- *
- * @return array
- */
-function troll_search_form() {
-  $form['#action'] = url('admin/settings/troll/search');
-  $form['#redirect'] = FALSE;
-  $form['search'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Search Users'),
-    '#collapsible' => true
-  );
-  $form['search']['username'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Username'),
-    '#description' => t('You can use % for wildcard, so to get all usernames with \'A\' in them, use %A%')
-  );
-  $form['search']['mail'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Email')
-  );
-  $form['search']['ip_address'] = array(
-    '#type' => 'textfield',
-    '#title' => t('IP Address')
-  );
-  $form['search']['date_created'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Account Date Created'),
-    '#description' => t('Enter date in mm/dd/yyyy format. Returns all users created after the date entered.')
-  );
-  $form['search']['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Search Users')
-  );
-
-  return $form;
-}
-
-/**
- * User list form.
- *
- * @param $edit array
- */
-function troll_list_users($edit) {
-
-  $where[] = 'u.uid <> 0';
-
-  if (strlen($edit['username']) > 0) {
-    $where[] = "LOWER(u.name) LIKE '%%%s%%' ";
-    $args[] = drupal_strtolower($edit['username']);
-  }
-  if (strlen($edit['mail']) > 0) {
-    $where[] = "LOWER(u.mail) LIKE '%%%s%%' ";
-    $args[] = drupal_strtolower($edit['mail']);
-  }
-  if (strlen($edit['ip_address']) > 0) {
-    $where[] = "LOWER(t.ip_address) LIKE '%%%s%%' ";
-    $args[] = drupal_strtolower($edit['ip_address']);
-  }
-  if (strlen($edit['date_created']) > 0) {
-    $where[] = "u.created > %d ";
-    $args[] = drupal_strtotime($edit['date_created']);
-  }
-
-  $sql = "SELECT u.uid, u.name, u.mail, u.status, t.ip_address, MAX(t.accessed) AS recorded, u.created FROM {users} u LEFT JOIN {troll_ip_track} t ON u.uid = t.uid";
-
-  $sql .= ' WHERE '. implode(' AND ', $where);
-
-  $headers = array(
-    array('data' => t('Username'), 'field' => 'u.name'),
-    array('data' => t('Email'), 'field' => 'u.mail'),
-    array('data' => t('Status'), 'field' => 'u.status'),
-    array('data' => t('IP Address'), 'field' => 't.ip_address'),
-    array('data' => t('Last Access'), 'field' => 't.created'),
-    array('data' => t('Account Created'), 'field' => 'u.created'),
-    array('data' => t('Actions'), 'field' => 'actions')
-  );
-
-  $sql .= ' GROUP BY u.uid, u.name, u.mail, u.status, t.ip_address, u.created';
-  $sql .= tablesort_sql($headers);
-
-  $count = 'SELECT COUNT(*) FROM {users} u LEFT JOIN {troll_ip_track} t ON u.uid = t.uid WHERE '. implode(' AND ', $where) .' AND u.uid <> 0';
-  $result = pager_query($sql, 25, 0, $count, $args);
-
-  while($user = db_fetch_object($result)) {
-    $name = l($user->name, 'admin/settings/troll/search/view/'. $user->uid, array('title' => t('View detailed user information')));
-    $email = $user->mail;
-    $status = ($user->status ? t('Active') : t('Blocked'));
-    $ip = ($user->ip_address ? l($user->ip_address, 'admin/settings/troll/search/view/'. $user->uid, array('title' => t('View detailed user information'))) : t('none'));
-    $recorded = ($user->recorded ? date('M d, Y', $user->recorded) : t('none recorded'));
-    $created = date('M d, Y', $user->created);
-    $actions = array();
-
-    if (!$user->status) {
-      $actions[] = array('title' => t('Edit User'), 'href' => "user/{$user->uid}/edit");
-    }
-    else if (variable_get('troll_block_role', NULL)) {
-      $actions[] = array('title' => t('Block User'), 'href' => 'admin/settings/troll/search/block/'. $user->uid);
-    }
-    else {
-      $actions[] = array('title' => t('Setup Block Role'), 'href' => 'admin/settings/troll/settings');
-    }
-    if ($user->ip_address) {
-      $actions[] = array('title' => t('Ban IP'), 'href' => 'admin/settings/troll/ip_ban/user/'. $user->uid);
-    }
-    $action = theme('links', $actions);
-    $rows[] = array($name, $email, $status, $ip, $recorded, $created, $action);
-  }
-
-  $pager = theme('pager', NULL, 25);
-
-  if (!empty($pager)) {
-    $rows[] = array(array('data' => $pager, 'colspan' => 7));
-  }
-
-  return theme('table', $headers, $rows);
-}
-
-/**
- * User detail form.
- *
- * @param $uid int
- * @return string
- */
-function troll_search_user_detail($uid) {
-  $u = user_load(array('uid' => $uid));
-  $u->ip = db_fetch_object(db_query('SELECT t.ip_address FROM {troll_ip_track} t WHERE t.uid = %d GROUP BY t.uid, t.ip_address', $uid));
-
-  $roles = $u->roles;
-
-  $form['details'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Account Details for %username', array('%username' => $u->name))
-  );
-
-  $form['details'][] = array(
-    '#type' => 'item',
-    '#title' => t('User Name'),
-    '#value' => theme('username', $u),
-  );
-  $form['details'][] = array(
-    '#type' => 'item',
-    '#title' => t('Email'),
-    '#value' => $u->mail
-  );
-  $form['details'][] = array(
-    '#type' => 'item',
-    '#title' => t('User ID'),
-    '#value' => $uid
-  );
-  $form['details'][] = array(
-    '#type' => 'item',
-    '#title' => t('Account Created'),
-    '#value' => format_date($u->created, 'long')
-  );
-  $form['details'][] = array(
-    '#type' => 'item',
-    '#title' => t('Last Access'),
-    '#value' => format_date($u->changed, 'long')
-  );
-  $form['details'][] = array(
-    '#type' => 'item',
-    '#title' => t('Status'),
-    '#value' => ($u->status ? t('Active') : t('Blocked'))
-  );
-  $form['details'][] = array(
-    '#type' => 'item',
-    '#title' => t('User Roles'),
-    '#value' => implode(', ', $u->roles)
-  );
-  if ($u->status) {
-    $links[] = array('title' => t('Block User'), 'href' => "admin/settings/troll/search/block/$uid");
-  }
-  else {
-    $links[] = array('title' => t('Edit User'), 'href' => "user/$uid/edit");
-  }
-  if ($u->ip->ip_address) {
-    $links[] = array('title' => t('Ban IP'), 'href' => "admin/settings/troll/ip_ban/user/$uid");
-  }
-  $form['details'][] = array(
-    '#type' => 'item',
-    '#title' => t('Actions'),
-    '#value' => theme('links', $links)
-  );
-
-  $content = drupal_render($form);
-
-  // get IP history
-  $results = db_query('SELECT * FROM {troll_ip_track} WHERE uid = %d ORDER BY created DESC', $uid);
-  while ($ip = db_fetch_object($results)) {
-    $banned = db_fetch_object(db_query('SELECT * FROM {troll_ip_ban} WHERE ip_address = \'%s\'', $ip->ip_address));
-    if ($banned->ip_address) {
-      if ($banned->expires && $banned->expires < time()) {
-        $status = l(t('expired'), 'admin/settings/troll/ip_ban/edit/'. $banned->iid, array('title' => t('Edit IP ban information')));
-      }
-      else {
-        $status = l(t('banned'), 'admin/settings/troll/ip_ban/edit/'. $banned->iid, array('title' => t('Edit IP ban information')));
-      }
-    }
-    else {
-      $status = l(t('not banned'), 'admin/settings/troll/ip_ban/ip/'. $ip->ip_address, array('title' => t('Ban this IP')));
-    }
-    $rows[] = array($ip->ip_address, $status, format_date($ip->accessed, 'long'), format_date($ip->created, 'long'), exec('host '. $ip->ip_address));
-  }
-
-  if ($rows) {
-    $pheader = array(t('IP'), t('Status'), t('Last Access'), t('First Access'), t('Host Information'));
-    $posts = theme('table', $pheader, $rows);
-  }
-  $content .= theme('box', t('IP History'), ($posts ? $posts : t('No ip history')));
-
-  // get recent posts
-  $rdat = db_query("SELECT * FROM {node} WHERE uid = %d ORDER BY created DESC LIMIT 5", $uid);
-
-  $posts = NULL;
-  $rows = array();
-  while ($node = db_fetch_object($rdat)) {
-    $rows[] = array(l($node->title, "node/{$node->nid}") .' '. theme('mark', node_mark($node->nid, $node->changed)), $node->type, date('M d, Y', $node->created), ($node->status ? t('published') : t('not published')));
-  }
-  if ($rows) {
-    $pheader = array(t('Title'), t('Type'), t('Created'), t('Status'));
-    $posts = theme('table', $pheader, $rows);
-  }
-
-  $content .= theme('box', t('Recent Posts'), ($posts ? $posts : t('No recent posts')));
-
-  // Get recent comments
-  $cp = 'SELECT * FROM {comments} WHERE uid = %d ORDER BY timestamp DESC';
-  $cdat = db_query($cp, $uid);
-
-  $rows = array();
-  $posts = NULL;
-  while ($comment = db_fetch_object($cdat)) {
-    $rows[] = array(l($comment->subject, 'node/'. $comment->nid, NULL, NULL, 'comment-'. $comment->cid) .' '. theme('mark', node_mark($comment->nid, $comment->changed)), date('M d, Y', $comment->timestamp), ($comment->status ? t('not published') : t('published')));
-  }
-
-  if ($rows) {
-    $cheader = array(t('Subject'), t('Date Created'), t('Status'));
-    $posts = theme('table', $cheader, $rows);
-  }
-  $content .= theme('box', t('Recent Comments'), ($posts ? $posts : t('No recent comments')));
-
-  return $content;
-}
-
-/**
  *
  * DATABASE FUNCTIONS
  *
@@ -1283,10 +287,10 @@ function troll_search_user_detail($uid) 
  */
 function troll_remove_ip($iid) {
   if (db_query('DELETE FROM {troll_ip_ban} WHERE iid = %d', $iid)) {
-    drupal_set_message(t('IP ban removed'));
+    drupal_set_message(t('IP ban removed.'));
   }
   else {
-    drupal_set_message(t('An error occurred, IP ban not removed'));
+    drupal_set_message(t('An error occurred, IP ban not removed.'));
   }
 }
 
@@ -1297,24 +301,24 @@ function troll_remove_ip($iid) {
  */
 function troll_remove_blacklist($net, $bcast) {
   if (db_query('DELETE FROM {troll_blacklist} WHERE net = %d AND bcast = %d', $net, $bcast)) {
-    drupal_set_message(t('Blacklist block removed'));
+    drupal_set_message(t('Blacklist block removed.'));
   }
   else {
-    drupal_set_message(t('An error occurred, blacklist block not removed'));
+    drupal_set_message(t('An error occurred, blacklist block not removed.'));
   }
 }
 
 /**
- * Removes IP block from the whitelist
+ * Removes IP block from the whitelist.
  *
  * @param $edit array
  */
 function troll_remove_whitelist($net, $bcast) {
   if (db_query('DELETE FROM {troll_whitelist} WHERE net = %d AND bcast = %d', $net, $bcast)) {
-    drupal_set_message(t('IP whitelist removed'));
+    drupal_set_message(t('IP whitelist removed.'));
   }
   else {
-    drupal_set_message(t('An error occurred, IP whitelist not removed'));
+    drupal_set_message(t('An error occurred, IP whitelist not removed.'));
   }
 }
 
@@ -1326,16 +330,15 @@ function troll_remove_whitelist($net, $b
 function troll_insert_ip($edit) {
   global $user;
 
-  $expires = ($edit['expires'] ? mktime(23, 59, 0, $edit['month'], $edit['day'], $edit['year']) : 0);
+  $expires = (isset($edit['expires']) ? mktime(23, 59, 0, $edit['month'], $edit['day'], $edit['year']) : 0);
 
   db_query("DELETE FROM {troll_ip_ban} WHERE ip_address = '%s'", $edit['ip_address']);
   if (db_query("INSERT INTO {troll_ip_ban} (ip_address, domain_name, created, expires, uid) VALUES ('%s', '%s', %d, %d, %d)", $edit['ip_address'], $edit['domain_name'], time(), $expires, $user->uid)) {
     drupal_set_message(t('IP ban added: %ip', array('%ip' => $edit['ip_address'])));
   }
   else {
-    drupal_set_message(t('An error occurred, IP ban not created'));
+    drupal_set_message(t('An error occurred. IP ban not created.'));
   }
-  drupal_goto('admin/settings/troll/ip_ban');
 }
 
 /**
@@ -1346,13 +349,13 @@ function troll_insert_ip($edit) {
 function troll_update_ip($edit) {
   global $user;
 
-  $expires = ($edit['expires'] ? mktime(23, 59, 0, $edit['month'], $edit['day'], $edit['year']) : 0);
+  $expires = (isset($edit['expires']) ? mktime(23, 59, 0, $edit['month'], $edit['day'], $edit['year']) : 0);
 
   if (db_query("UPDATE {troll_ip_ban} SET ip_address = '%s', domain_name = '%s', expires = %d, uid = %d WHERE iid = %d", $edit['ip_address'], $edit['domain_name'], $expires, $user->uid, $edit['iid'])) {
     drupal_set_message(t('IP ban updated: %ip', array('%ip' => $edit['ip_address'])));
   }
   else {
-    drupal_set_message(t('An error occurred, IP ban not updated'));
+    drupal_set_message(t('An error occurred, IP ban not updated.'));
   }
 }
 
@@ -1360,12 +363,12 @@ function troll_update_ip($edit) {
 /**
  * Logs IP information for users in the database.
  */
-function troll_check_ip(){
+function troll_check_ip() {
   global $user;
   $sql = "SELECT uid FROM {troll_ip_track} WHERE ip_address = '%s' AND uid = %d";
   $chk = db_query($sql, $_SERVER['REMOTE_ADDR'], $user->uid);
   $check = db_fetch_array($chk);
-  if (!isset($check['uid'])){
+  if (!isset($check['uid'])) {
     $isql = "INSERT INTO {troll_ip_track} (uid, ip_address, created) VALUES (%d, '%s', %d)";
     db_query($isql, $user->uid, $_SERVER['REMOTE_ADDR'], time());
   }
@@ -1395,23 +398,16 @@ function troll_is_blacklisted() {
  * @param $uid int
  */
 function troll_block_user($uid) {
+  $name = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $uid));
   db_query('UPDATE {users} SET status = 0 WHERE uid = %d', $uid);
   db_query('DELETE FROM {users_roles} WHERE uid = %d', $uid);
   sess_destroy_uid($uid);
   if (variable_get('troll_block_role', NULL)) {
+    $role = db_result(db_query("SELECT name from {role} WHERE rid = %d", variable_get('troll_block_role', 0)));
     db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $uid, variable_get('troll_block_role', '0'));
+    drupal_set_message(t('Blocked user !link and assigned role %role.', array('!link' => l($name, "admin/settings/troll/search/view/$uid"), '%role' => $role)));
   }
-  drupal_set_message(t('Blocked user !link', array('!link' => l($uid, "admin/settings/troll/search/view/$uid"))));
-}
-
-/**
- * For functions that need tables that only exist after updates
- *
- * @return bool
- */
-function _troll_updated_schema() {
-  if (!preg_match("/update\.php$/", $_SERVER['PHP_SELF'])) {
-    return db_result(db_query("SELECT schema_version FROM {system} WHERE name = 'troll' AND type = 'module' AND status = 1"));
+  else {
+    drupal_set_message(t('Blocked user !link.', array('!link' => l($name, "admin/settings/troll/search/view/$uid"))));
   }
-  return false;
 }
