<?php
/*
Bad Behavior - detects and blocks unwanted Web accesses
Copyright (C) 2005,2006,2007,2008,2009 Michael Hampton

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

As a special exemption, you may link this program with any of the
programs listed below, regardless of the license terms of those
programs, and distribute the resulting program, without including the
source code for such programs: ExpressionEngine

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

Please report any problems to badbots AT ioerror DOT us
*/

// This file is the entry point for Bad Behavior 2 in phpwcms.

// obligate check for phpwcms constants
if (!defined('PHPWCMS_ROOT')) {
   die("You Cannot Access This Script Directly, Have a Nice Day.");
}
// ----------------------------------------------------------------

$_SERVER['REMOTE_ADDR'] = getRemoteIP();


define('BB2_CWD', PHPWCMS_ROOT.'/include/inc_ext/bad-behavior');

// core path setting based on phpwcms' values
define('BB2_CORE', BB2_CWD.'/bad-behavior');

// Settings you can adjust for Bad Behavior.
// Most of these are unused in non-database mode.
$bb2_settings_defaults = array(
	'log_table' => DB_PREPEND.'phpwcms_bad_behavior',
	'display_stats' => true,
	'strict' => false,
	'verbose' => false,
	'logging' => true,
	'httpbl_key' => '',
	'httpbl_threat' => '25',
	'httpbl_maxage' => '30',
	'offsite_forms' => false
);

// Bad Behavior callback functions.

// Return current time in the format preferred by your database.
function bb2_db_date() {
	return gmdate('Y-m-d H:i:s');	// Example is MySQL format
}

// Return affected rows from most recent query.
function bb2_db_affected_rows() {
	return false;
}

// Escape a string for database usage
function bb2_db_escape($string) {
	// return mysql_real_escape_string($string);
	return aporeplace($string);	// No-op when database not in use.
}

// Return the number of rows in a particular query.
function bb2_db_num_rows($result) {
	if ($result !== FALSE)
		return count($result);
	return 0;
}

// Run a query and return the results, if any.
// Should return FALSE if an error occurred.
// Bad Behavior will use the return value here in other callbacks.
function bb2_db_query($query) {

	$result = @mysql_query($query, $GLOBALS['db']);
	
	if($result === false) {
		return false;
	} elseif($result === true) {
		return true;	
	} else {
		$query_result = array();
		while($row = mysql_fetch_assoc($result)) {
			$query_result[] = $row;
		}
		mysql_free_result($result);
		return $query_result;
	}
	return false;
}

// Return all rows in a particular query.
// Should contain an array of all rows generated by calling mysql_fetch_assoc()
// or equivalent and appending the result of each call to an array.
function bb2_db_rows($result) {
	return $result;
}

// Return emergency contact email address.
function bb2_email() {
	return $GLOBALS['phpwcms']['admin_email'];
}

// retrieve settings from database
// Settings are hard-coded for non-database use
function bb2_read_settings() {

	if(isset($GLOBALS['phpwcms']['bad_behavior_settings']) && is_array($GLOBALS['phpwcms']['bad_behavior_settings'])) {
		$settings = $GLOBALS['phpwcms']['bad_behavior_settings'];
	} else {
		$settings = array();
	}
	$bb2_settings_defaults = array(
		'log_table' => DB_PREPEND.'phpwcms_bad_behavior',
		'display_stats' => true,
		'strict' => false,
		'verbose' => false,
		'db_installed' => true,
		'logging' => true,
		'httpbl_key' => '',
		'httpbl_threat' => '25',
		'httpbl_maxage' => '30',
		'offsite_forms' => false
	);

	return array_merge($bb2_settings_defaults, $settings);
}

// write settings to database
function bb2_write_settings($settings) {
	return false;
}

// Insert a new record
function bb2_insert($settings, $package, $key)
{
	$ip = bb2_db_escape($package['ip']);
	$date = bb2_db_date();
	$request_method = bb2_db_escape($package['request_method']);
	$request_uri = bb2_db_escape($package['request_uri']);
	$server_protocol = bb2_db_escape($package['server_protocol']);
	$user_agent = bb2_db_escape($package['user_agent']);
	$headers = $request_method.' '.$request_uri.' '.$server_protocol."\n";
	foreach ($package['headers'] as $h => $v) {
		$headers .= bb2_db_escape("$h: $v\n");
	}
	$request_entity = "";
	if (!strcasecmp($request_method, "POST")) {
		foreach ($package['request_entity'] as $h => $v) {
			$request_entity .= bb2_db_escape("$h: $v\n");
		}
	}
	return "INSERT INTO `" . bb2_db_escape($settings['log_table']) . "`
		(`ip`, `date`, `request_method`, `request_uri`, `server_protocol`, `http_headers`, `user_agent`, `request_entity`, `key`) VALUES
		('$ip', '$date', '$request_method', '$request_uri', '$server_protocol', '$headers', '$user_agent', '$request_entity', '$key')";
}

// installation
function bb2_install() {
	$settings = bb2_read_settings();
	if(empty($settings['db_installed'])) {
		bb2_db_query(bb2_table_structure($settings['log_table']));
	}
}

// Screener
// Insert this into the <head> section of your HTML through a template call
// or whatever is appropriate. This is optional we'll fall back to cookies
// if you don't use it.
function bb2_insert_head() {
	global $bb2_javascript;
	//echo $bb2_javascript;
	$GLOBALS['block']['custom_htmlhead']['bad_behavior'] = '  '.$bb2_javascript;
}

// Display stats? This is optional.
function bb2_insert_stats($force = false) {
	$settings = bb2_read_settings();

	if ($force || $settings['display_stats']) {
		$blocked = bb2_db_query("SELECT COUNT(*) FROM " . $settings['log_table'] . " WHERE `key` NOT LIKE '00000000'");
		if ($blocked !== FALSE) {
			echo sprintf('<p><a href="http://www.bad-behavior.ioerror.us/">%1$s</a> %2$s <strong>%3$s</strong> %4$s</p>', __('Bad Behavior'), __('has blocked'), $blocked[0]["COUNT(*)"], __('access attempts in the last 7 days.'));
		}
	}
}

// Return the top-level relative path of wherever we are (for cookies)
// You should provide in $url the top-level URL for your site.
function bb2_relative_path() {
	//$url = parse_url(get_bloginfo('url'));
	//return $url['path'] . '/';
	return PHPWCMS_URL;
}

// Calls inward to Bad Behavor itself.
require_once(BB2_CWD . '/bad-behavior/version.inc.php');
require_once(BB2_CWD . '/bad-behavior/core.inc.php');

bb2_start(bb2_read_settings());

?>