From 7c0118fa65f7a466f8796d4db8061d34b6a33a5b Mon Sep 17 00:00:00 2001
From: Hans Fredrik Nordhaug <hansfn@gmail.com>
Date: Fri, 2 Dec 2011 12:47:52 +0100
Subject: [PATCH] Issue #1102160 by hansfn: Ported module to Drupal 7. Reviewed code using the Coder module.

---
 README.txt            |   17 +++++++--
 badbehavior.admin.inc |   65 +++++++++++++++++----------------
 badbehavior.info      |    3 +-
 badbehavior.install   |   36 +++++++++---------
 badbehavior.module    |   95 ++++++++++++++++++++++++++++++++++++------------
 5 files changed, 139 insertions(+), 77 deletions(-)
 mode change 100755 => 100644 badbehavior.info
 mode change 100755 => 100644 badbehavior.install

diff --git a/README.txt b/README.txt
index 68a6bd7..a380df4 100644
--- a/README.txt
+++ b/README.txt
@@ -12,6 +12,7 @@ Original Drupal module by:
 - David Angier (http://drupal.org/user/27546)
 
 Additional commits for module improvement by:
+- Hans Fredrik Nordhaug (http://drupal.org/user/40521)
 - Steven Wittens (http://drupal.org/user/10)
 - William Roboly (http://drupal.org/user/48120)
 - Sean Robertson (http://drupal.org/user/7074)
@@ -54,13 +55,23 @@ system cracker.
    REQUIREMENTS
 ----------------------------------------------------------
 
-- Drupal 6.x
-- PHP 4.3.0 or greater
+- Drupal 7.x
 - BadBehavior 2.1.15
 
 
 ----------------------------------------------------------
-   INSTALLATION
+   INSTALLATION WITH DRUSH
+----------------------------------------------------------
+
+With Drush, you can do the normal
+
+   drush dl badbehavior
+   drush en badbehavior
+
+and it will even install the BadBehavior PHP script automatically.
+
+----------------------------------------------------------
+   INSTALLATION WITH FTP/MANUALLY 
 ----------------------------------------------------------
 
 1. Extract the tarball into the modules folder of your Drupal install.
diff --git a/badbehavior.admin.inc b/badbehavior.admin.inc
index 50b94a0..cf3b956 100644
--- a/badbehavior.admin.inc
+++ b/badbehavior.admin.inc
@@ -18,28 +18,31 @@ function badbehavior_overview() {
     array('data' => t('Agent'), 'field' => 'w.user_agent', 'colspan' => 2)
   );
   $logtype = variable_get('badbehavior_logging', 1);
+
+  $rows = array();
+  $query = FALSE;
   if ($logtype == 'verbose') {
-    $sql = 'SELECT w.* FROM {bad_behavior_log} w '. tablesort_sql($header);
+    $query = db_select('bad_behavior_log', 'w')->extend('TableSort')->orderByHeader($header);
+    $query->fields('w');
   }
   elseif ($logtype == '1') {
-    $sql = "SELECT w.* FROM {bad_behavior_log} w WHERE w.key <> '00000000' " . tablesort_sql($header);
-  }
-  else {
-    $sql = '';
-  }
-  if ($sql) {
-  $result = pager_query($sql, 50);
-  while ($behave = db_fetch_object($result)) {
-    $response = bb2_get_response($behave->key);
-    $behave->localdate = bb2_convertdate($behave->date);
-    $rows[] = array('data' => array($response['response'], $response['log'], $behave->localdate, $behave->ip, $behave->user_agent, l(t('details'), "admin/reports/badbehavior/event/$behave->id")));
-  }
+    $query = db_select('bad_behavior_log', 'w')->extend('TableSort')->orderByHeader($header);
+    $query->fields('w')->condition('w.key', '00000000', '<>');
+  } 
+  if ($query) {
+    $result = $query->extend('PagerDefault')->limit(50)->execute();
+    while ($behave = $result->fetchObject()) {
+      $response = bb2_get_response($behave->key);
+      $behave->localdate = bb2_convertdate($behave->date);
+      $rows[] = array('data' => array($response['response'], $response['log'], $behave->localdate, $behave->ip, $behave->user_agent, l(t('details'), "admin/reports/badbehavior/event/$behave->id")));
+    }
   }
-  if (!$rows) {
+  if (empty($rows)) {
     $rows[] = array(array('data' => t('No log messages available.'), 'colspan' => '6'));
   }
 
-  $output = theme('table', $header, $rows) . theme('pager', NULL, 50, 0);
+  $output = theme('table', array('header' => $header, 'rows' => $rows)) .
+    theme('pager', array('quantity' => 50));
 
   return $output;
 }
@@ -49,34 +52,34 @@ function badbehavior_event($id = NULL) {
     return 'Bad Behavior is not installed correctly. See the <a href="/sites/all/modules/badbehavior/README.txt">README.txt</a> for installation details.';
   }
   $output = '';
-  $result = db_query('SELECT w.* FROM {bad_behavior_log} w WHERE w.id = %d', $id);
-  if ($behave = db_fetch_object($result)) {
+  $result = db_query('SELECT w.* FROM {bad_behavior_log} w WHERE w.id = :id', array(':id' => $id));
+  if ($behave = $result->fetchObject()) {
       $response = bb2_get_response($behave->key);
       $behave->localdate = bb2_convertdate($behave->date);
       $output .= '<table border="1" cellpadding="2" cellspacing="2">';
-      $output .= ' <tr><th>'. t('IP Addr') .'</th><td>';
+      $output .= ' <tr><th>' . t('IP Addr') . '</th><td>';
     if ($behave->ip) {
-      $output .= $behave->ip .'</td></tr>'; }
+      $output .= $behave->ip . '</td></tr>'; }
     else {
       $output .= '<span style="color:red">Possible Proxy Settings Error:</span> No IP address reported</td></tr>';
     }
-      $output .= ' <tr><th>'. t('Hostname') .'</th><td>';
+      $output .= ' <tr><th>' . t('Hostname') . '</th><td>';
     if ($behave->ip) {
-      $output .= gethostbyaddr($behave->ip) .' ('. l('whois', 'http://www.whois.sc/'. $behave->ip) .')</td></tr>';
+      $output .= gethostbyaddr($behave->ip) . ' (' . l(t('whois'), 'http://www.whois.sc/' . $behave->ip) . ')</td></tr>';
     }
     else {
       $output .= '<span style="color:red">Possible Proxy Settings Error:</span> No hostname reported</td></tr>';
     }
-      $output .= ' <tr><th>'. t('Date') .'</th><td>'. $behave->localdate .'</td></tr>';
-      $output .= ' <tr><th>'. t('Request type') .'</th><td>'. $behave->request_method .'</td></tr>';
-      $output .= ' <tr><th>'. t('URI') .'</th><td>'. $behave->request_uri .'</td></tr>';
-      $output .= ' <tr><th>'. t('Protocol') .'</th><td>'. $behave->server_protocol .'</td></tr>';
-      $output .= ' <tr><th>'. t('User Agent') .'</th><td>'. $behave->user_agent .'</td></tr>';
-      $output .= ' <tr><th>'. t('Headers') .'</th><td>'. $behave->http_headers .'</td></tr>';
-      $output .= ' <tr><th>'. t('Request Entity') .'</th><td>'. $behave->request_entity .'</td></tr>';
-      $output .= ' <tr><th>'. t('Denied Reason') .'</th><td>'. $response['log'] .'</td></tr>';
-      $output .= ' <tr><th>'. t('Explanation') .'</th><td>'. $response['explanation'] .'</td></tr>';
-      $output .= ' <tr><th>'. t('Response') .'</th><td>'. $response['response'] .'</td></tr>';
+      $output .= ' <tr><th>' . t('Date') . '</th><td>' . $behave->localdate . '</td></tr>';
+      $output .= ' <tr><th>' . t('Request type') . '</th><td>' . $behave->request_method . '</td></tr>';
+      $output .= ' <tr><th>' . t('URI') . '</th><td>' . $behave->request_uri . '</td></tr>';
+      $output .= ' <tr><th>' . t('Protocol') . '</th><td>' . $behave->server_protocol . '</td></tr>';
+      $output .= ' <tr><th>' . t('User Agent') . '</th><td>' . $behave->user_agent . '</td></tr>';
+      $output .= ' <tr><th>' . t('Headers') . '</th><td>' . $behave->http_headers . '</td></tr>';
+      $output .= ' <tr><th>' . t('Request Entity') . '</th><td>' . $behave->request_entity . '</td></tr>';
+      $output .= ' <tr><th>' . t('Denied Reason') . '</th><td>' . $response['log'] . '</td></tr>';
+      $output .= ' <tr><th>' . t('Explanation') . '</th><td>' . $response['explanation'] . '</td></tr>';
+      $output .= ' <tr><th>' . t('Response') . '</th><td>' . $response['response'] . '</td></tr>';
       $output .= '</table>';
   }
   return $output;
diff --git a/badbehavior.info b/badbehavior.info
old mode 100755
new mode 100644
index c307d9d..9632f62
--- a/badbehavior.info
+++ b/badbehavior.info
@@ -1,4 +1,5 @@
 name = Bad Behavior
 description = Stop comment spam before it starts by trapping and blocking spambots before they have a chance to post comments.
 package = Spam control
-core = 6.x
+core = 7.x
+configure = admin/config/system/badbehavior
diff --git a/badbehavior.install b/badbehavior.install
old mode 100755
new mode 100644
index b2e55fc..bf6c4eb
--- a/badbehavior.install
+++ b/badbehavior.install
@@ -5,7 +5,9 @@
  * Install, update and uninstall functions for the Bad Behavior module.
  */
 
-// Implements hook_schema().
+/**
+ * Implements hook_schema().
+ */
 function badbehavior_schema() {
   $schema['bad_behavior_log'] = array(
     'description' => 'Stores hit logs for the Bad Behavior module.',
@@ -19,7 +21,8 @@ function badbehavior_schema() {
         'not null' => TRUE,
       ),
       'date' => array(
-        'type' => 'datetime',
+        'mysql_type' => 'DATETIME',
+        'pgsql_type' => 'timestamp without time zone',
         'not null' => TRUE,
         'default' => '1970-01-01 00:00:00',
       ),
@@ -62,7 +65,9 @@ function badbehavior_schema() {
   return $schema;
 }
 
-// Implements hook_requirements().
+/**
+ * Implements hook_requirements().
+ */
 function badbehavior_requirements($phase) {
   $requirements = array();
   if ($phase == 'runtime') {
@@ -93,21 +98,17 @@ function badbehavior_requirements($phase) {
   return $requirements;
 }
 
-// Implements hook_install().
+/**
+ * Implements hook_install().
+ */
 function badbehavior_install() {
-  drupal_install_schema('badbehavior');
-  // Set module weight for the badbehavior module
-  $thestatus = array();
-  $thestatus[] =   db_query("UPDATE {system} SET weight = -999 WHERE type = 'module' AND name = 'badbehavior'");
-  // If there is one FALSE value in the status array, there was an error.
-  if (array_search(FALSE, $thestatus) !== FALSE) {
-    drupal_set_message(t('Setting the module weight of Bad Behavior failed.'), 'error');
-  }
+  db_query("UPDATE {system} SET weight = -999 WHERE type = 'module' AND name = 'badbehavior'");
 }
 
-// Implements hook_uninstall().
+/**
+ * Implements hook_uninstall().
+ */
 function badbehavior_uninstall() {
-  drupal_uninstall_schema('badbehavior');
   variable_del('badbehavior_mail');
   variable_del('badbehavior_email');
   variable_del('badbehavior_logging');
@@ -140,12 +141,11 @@ function badbehavior_update_6100() {
   variable_set('badbehavior_strict', $strict);
   variable_del('badbehavior_strict_mode_enable');
 
-  return array();
+  return t('Renamed some variables for Bad Behavior.');
 }
 
 // Reset module weight for earliest possible loading position.
 function badbehavior_update_6200() {
-  $retfun = array();
-  $retfun[] = update_sql("UPDATE {system} SET weight = -999 WHERE type = 'module' AND name = 'badbehavior'");
-  return $retfun;
+  db_query("UPDATE {system} SET weight = -999 WHERE type = 'module' AND name = 'badbehavior'");
+  return t('Set the initial weight for the Bad Behavior module');
 }
diff --git a/badbehavior.module b/badbehavior.module
index 447a3f7..3750040 100644
--- a/badbehavior.module
+++ b/badbehavior.module
@@ -1,9 +1,16 @@
 <?php
 
+/**
+ * @file
+ * Integrates Bad Behavior with Drupal.
+ */
+
 // Point BB scripts path to new universal libraries directory.
 define('BB2_CWD', './sites/all/libraries/bad-behavior');
 
-// Implements hook_help().
+/**
+ * Implements hook_help().
+ */
 function badbehavior_help($path, $arg) {
   $output = '';
   switch ($path) {
@@ -14,14 +21,27 @@ function badbehavior_help($path, $arg) {
   return $output;
 }
 
-// Implements hook_perm().
-function badbehavior_perm() {
-  return array('administer bad behavior', 'bypass bad behavior protection');
+/**
+ * Implements hook_permission().
+ */
+function badbehavior_permission() {
+  return array(
+    'administer bad behavior' => array(
+      'title' => t('Administer the Bad Behavior module'),
+      'description' => t('Perform administration tasks for the Bad Behavior module.'),
+    ),
+    'bypass bad behavior protection' => array(
+      'title' => t('Bypass Bad Behavior protection'),
+      'description' => t('Don\'t examine the HTTP requests from users with this permission.'),
+    )
+  );
 }
 
-// Implements hook_menu().
+/**
+ * Implements hook_menu().
+ */
 function badbehavior_menu() {
-  $items['admin/settings/badbehavior'] = array(
+  $items['admin/config/system/badbehavior'] = array(
     'title' => 'Bad Behavior',
     'description' => 'Configure automatic spam blocking for your site.',
     'page callback' => 'drupal_get_form',
@@ -46,20 +66,28 @@ function badbehavior_menu() {
   return $items;
 }
 
-// Implements hook_boot().
+/**
+ * Implements hook_boot().
+ */
 function badbehavior_boot() {
-  if (!$GLOBALS['user']->uid) {
+  // Don't use Bad Behavior if we are running Drupal from the command line
+  // using for example Drush or if we are logged in.
+  if (!drupal_is_cli() && !$GLOBALS['user']->uid) {
     badbehavior_start_badbehavior();
   }
 }
 
-// Implements hook_init().
+/**
+ * Implements hook_init().
+ */
 function badbehavior_init() {
-  if ($GLOBALS['user']->uid) {
+  // Don't use Bad Behavior if we are running Drupal from the command line
+  // using for example Drush or if we are logged in.
+  if (!drupal_is_cli() && !$GLOBALS['user']->uid) {
     badbehavior_start_badbehavior();
   }
-// Adds CSS to hide Project Honey Pot QuickLink link in the footer of every page.
-  drupal_add_css(drupal_get_path('module', 'badbehavior') .'/badbehavior.css');
+  // Adds CSS to hide Project Honey Pot QuickLink link in the footer of every page.
+  drupal_add_css(drupal_get_path('module', 'badbehavior') . '/badbehavior.css');
 }
 
 function badbehavior_start_badbehavior() {
@@ -72,12 +100,16 @@ function badbehavior_start_badbehavior() {
   }
 }
 
-// Load BadBehavior library files.
+/**
+ * Loads BadBehavior library files.
+ */
 function badbehavior_load_includes() {
-  if (is_file(BB2_CWD .'/bad-behavior/core.inc.php') && is_file(BB2_CWD .'/bad-behavior/responses.inc.php') && is_file(BB2_CWD .'/bad-behavior-mysql.php')) {
-    require_once(BB2_CWD .'/bad-behavior/core.inc.php');
-    require_once(BB2_CWD .'/bad-behavior/responses.inc.php');
-    require_once(BB2_CWD .'/bad-behavior-mysql.php');
+  if (is_file(BB2_CWD . '/bad-behavior/core.inc.php') &&
+      is_file(BB2_CWD . '/bad-behavior/responses.inc.php') &&
+      is_file(BB2_CWD . '/bad-behavior-mysql.php')) {
+    require_once(BB2_CWD . '/bad-behavior/core.inc.php');
+    require_once(BB2_CWD . '/bad-behavior/responses.inc.php');
+    require_once(BB2_CWD . '/bad-behavior-mysql.php');
     return TRUE;
   }
   else {
@@ -97,7 +129,11 @@ function bb2_db_affected_rows() {
 
 // Escape a string for database usage
 function bb2_db_escape($string) {
-  return db_escape_string($string);
+  // Can't use ...
+  // return Database::getConnection()->quote($string);
+  // Obsolete and can't use mysql_real_escape.
+  // return db_escape_string();
+  return addslashes($string);
 }
 
 // Return the number of rows in a particular query.
@@ -115,9 +151,12 @@ function bb2_db_query($query) {
   set_error_handler('badbehavior_db_errortrap');
   $result = db_query($query);
   restore_error_handler();
-  if ($result == FALSE)
+  if ($result == FALSE) {
     return FALSE;
-  return db_affected_rows();
+  }
+  else {
+    return $result->rowCount();
+  }
 }
 
 // Return all rows in a particular query.
@@ -170,7 +209,7 @@ function bb2_relative_path() {
 
 // Converts dates in BB log screen output to server's time zone.
 function bb2_convertdate($bbdate) {
-  $timestamp = strtotime($bbdate .' UTC');
+  $timestamp = strtotime($bbdate . ' UTC');
   if (variable_get('badbehavior_log_timeformat', '24') == '24') {
     return format_date($timestamp, 'custom', 'Y-m-d H:i:s');
   }
@@ -179,9 +218,17 @@ function bb2_convertdate($bbdate) {
   }
 }
 
-// Adds a hidden Project Honey Pot QuickLink link to the footer of every page.
-function badbehavior_footer() {
+/**
+ * Implements hook_page_build().
+ *
+ * Adds a hidden Project Honey Pot QuickLink link to the footer of every page.
+ */
+function badbehavior_page_build() {
   if (variable_get('badbehavior_httpbl_quicklink', '')) {
-    return '<span class="bbhtthappsb"><a href="' . variable_get('badbehavior_httpbl_quicklink', '') . '">' . variable_get('badbehavior_httpbl_quicklinktext', 'Customize This') . '</a></span>' . "\n";
+    $page['page_bottom']['badbehavior']= array(
+      '#type' => 'markup',
+      '#markup' => '<span class="bbhtthappsb"><a href="' . variable_get('badbehavior_httpbl_quicklink', '') .
+        '">' . variable_get('badbehavior_httpbl_quicklinktext', 'Customize This') . '</a></span>' . "\n"
+    );
   }
 }
-- 
1.5.4.7

