<?php
///////////////////////////////////////////////////////////////////////////////////////////////////////
// BotBanish 9.0.03
// Randem Systems: https://randemsystems.support
// BotBanish Database Sub-routines for Websites
// Date: 07/22/2026
// Usage:
//
///////////////////////////////////////////////////////////////////////////////////////////////////////

function BotBanishExecuteSQL($sql_statement, $original = false, $ignore_errors = false, $single = false) {

	global $BotBanishSettings, $BotBanishSQL, $sourcedir;

	$result = '';
	$rows = array();

	if (!$original)
		$sql_statement = strtolower($sql_statement);

	$BotBanishSQL = $sql_statement;

	$sql = str_ireplace('``', '`', $sql_statement);
	BotBanishLogSQL($sql);

	if (!function_exists('BotBanishSendPostData'))
		require_once $BotBanishSettings['BOTBANISH_SUBS_DIR'] . 'BotBanish_Subs.php';

	if (!isset($GLOBALS['override']) || $GLOBALS['override'] === false) {

		if (defined('ABSPATH')) {

			require_once $BotBanishSettings['BOTBANISH_SUBS_DIR'] . 'BotBanish_Subs_WordPress.php';
			require_once $BotBanishSettings['BOTBANISH_SUBS_DIR'] . 'BotBanish_Subs_DB_WordPress.php';
			$rows = BotBanishProcessWordPressSQL($sql_statement);
			return $rows;
		}

		// If we are on SMF we convert the sql statement to a SMF version of the statement
		// and let SMF process the request. We must remove types of database field ticks due to SMF configuration
		// of $db_prefix and $db_name fields because the parser will get confused on table names.

		if (isset($sourcedir)) {

			if (class_exists('PHPSQLParser')) {

				global $SQL_Parser;
				if (!is_object($SQL_Parser)) $SQL_Parser = new PHPSQLParser;

				$sqlParsed = $SQL_Parser->parse($sql);
				require_once $BotBanishSettings['BOTBANISH_SUBS_DIR'] . 'BotBanish_Subs_SMF.php';
				require_once $BotBanishSettings['BOTBANISH_SUBS_DIR'] . 'BotBanish_Subs_DB_SMF.php';
				$rows = BotBanishCreateSMFStatement($sqlParsed, $sql);
				return $rows;
			}
		}
	}

	$rows = array();
	$conn = BotBanishDatabaseOpen();

	if (!$conn)
		return $rows;
	
	$result = BotBanishPerformQuery($conn, $sql_statement, $single);

	if (is_object($result)) {

		$rows = BotBanishExtractResults($result);
		BotBanishResultRelease($result);
	}

	BotBanishDatabaseClose($conn);

	if (isset($rows[0]['error'])) {

		$subject = 'SQL Execute Error:';
		$body = $rows[0]['error'];
		BotBanishLogError($subject . PHP_EOL . $body, $sql_statement,'SQL');

		if (isset($BotBanishSettings['BOTBANISH_SERVER']) && $BotBanishSettings['BOTBANISH_SERVER'])

			BotBanishReturnData($rows);
		else
			BotBanishSendMail($subject, $body, true);
	}

	return $rows;
}

function BotBanishPerformQuery($conn, $sql_statement, $single) {

	try {

		$result = mysqli_query($conn, $sql_statement);

	} catch (Exception $f) {

		BotBanishLogError('SQL Query Error: ' . $sql_statement, $f, 'SQL');
		$result = false;
	}

	return $result;
}

function BotBanishExtractResults($result) {

	global $BotBanishSettings;

	$rows = array();
	$rowcount = -1;

	if (is_object($result)) {

		try {

			$rowcount = mysqli_num_rows($result);

		} catch (Exception $f) {

			BotBanishLogError('SQL Extract Error:', $f, 'SQL');
			$rows[0]['error'] = $f;
		}

		if ($rowcount > 0) {

			$rows = array();

			try {

				while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
					$rows[] = $row;

				BotBanishLogSQL('Good(' .$rowcount . ')');

			} catch (Exception $f) {

				$rows[0]['error'] = $f;
				BotBanishLogError('SQL Fetch Error:', $f, 'SQL');
				BotBanishLogSQL('Bad(' .$f . ')');
			}
		}

	} else {

		if ($result === false) {

			$rows[0]['error'] = $BotBanishText['BotBanish_ErrorText'] . PHP_EOL . PHP_EOL . $sql . PHP_EOL . PHP_EOL;
			$rows[0]['error'] .= mysqli_errno($conn) . ": " . mysqli_error($conn) . PHP_EOL . PHP_EOL;

			if (!isset($BotBanishSettings['BOTBANISH_DB_SERVERNAME'])) {

				global $db_server, $db_name;

				BotBanishDefineGlobals('BOTBANISH_DB_SERVERNAME', $db_server);
				BotBanishDefineGlobals('BOTBANISH_DB_NAME', $db_name);
			}

			$rows[0]['error'] .= PHP_EOL . $BotBanishText['BotBanish_ServerLabel'] . $BotBanishSettings['BOTBANISH_DB_SERVERNAME'] . PHP_EOL . $BotBanishText['botbanish_infobaseLabel'] . $BotBanishSettings['BOTBANISH_DB_NAME'] . PHP_EOL . $BotBanishText['BotBanish_VersionLabel'] . $BotBanishSettings['BOTBANISH_VERSION'];

			BotBanishLogError('SQL Extract Error:', $rows[0]['error'], 'SQL');
			BotBanishLogSQL('Bad(' .$rows[0]['error'] . ')');
		}
	}

	return $rows;
}

function BotBanishResultRelease($result) {

	// Release any memory held by a mySQL query

	if (isset($result) && is_object($result)) {

		if (defined('OO')) {

			$result->free();
		}else{
			mysqli_free_result($result);
		}
	}
}

function BotBanishDatabaseOpen() {

	$conn = false;

	$data = BotBanishGetDatabaseInfo();

	mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);	// Allow mysqli error to be trapped

	try {

		$conn = mysqli_connect($data['server'], $data['username'], $data['password'], $data['database']);
		$conn->set_charset($data['charset']);
		$conn->query('SET collation_connection = ' . $data['collation']);

	} catch (mysqli_sql_exception $e) {
	
		// Now log the actual error;
		
		$msg = 'BotBanishDatabaseOpen() - Connection Failed:' . PHP_EOL;
		BotBanishLogError($msg . BotBanishFormatArray($data), $e, 'Connection');
		$conn = false;
	}

	mysqli_report(MYSQLI_REPORT_OFF);
	
	return $conn;
}

function BotBanishGetDatabaseInfo() {

	global $BotBanishSettings;

	$system = BotBanishCheckSystem();

	switch($system['system']) {

		case 'SMF':

			global $db_server, $db_user, $db_passwd, $db_name, $db_port, $db_prefix;

			if (!isset($db_name) || empty($db_name)) {

				$dir = BotBanishGetConfigLocation('Settings.php');
				require $dir . 'Settings.php';
			}

			$server_name = $db_server;
			$port = $db_port;
			$user_name = $db_user;
			$password = $db_passwd;
			$database_name = $db_name;
			$tblprefix = $db_prefix;
			$collation = 'utf8_general_ci';
			$charset = 'utf8';
			break;

		case 'WORDPRESS':

			if (!defined('DB_NAME')) {

				$dir = BotBanishGetConfigLocation('wp-config.php');
				$filename = $dir . 'wp-config.php';
				if (!defined('WORDPRESS')) define('WORDPRESS', 1);
				BotBanishProcessWPSettingsFile($filename);
				require 'BotBanish_WP_Settings.php';
			}


			$server_name = DB_HOST;
			$port = 0;
			$user_name = DB_USER;
			$password = DB_PASSWORD;
			$database_name = DB_NAME;
			$collation = DB_COLLATE;
			$charset = DB_CHARSET;

			global $table_prefix;

			$tblprefix = $table_prefix;
			break;

		case 'OPENCART':
		case 'SERVER':
		case 'WEBSITE':
		default:

			$server_name = isset($_POST['BOTBANISH_DB_SERVERNAME']) ? $_POST['BOTBANISH_DB_SERVERNAME'] : $BotBanishSettings['BOTBANISH_DB_SERVERNAME'];
			$port = isset($_POST['BOTBANISH_DB_PORT']) ? $_POST['BOTBANISH_DB_PORT'] : $BotBanishSettings['BOTBANISH_DB_PORT'];
			$user_name = isset($_POST['BOTBANISH_DB_USERNAME']) ? $_POST['BOTBANISH_DB_USERNAME'] : $BotBanishSettings['BOTBANISH_DB_USERNAME'];
			$password = isset($_POST['BOTBANISH_DB_PASSWORD']) ? $_POST['BOTBANISH_DB_PASSWORD'] : $BotBanishSettings['BOTBANISH_DB_PASSWORD'];
			$database_name = isset($_POST['BOTBANISH_DB_NAME']) ? $_POST['BOTBANISH_DB_NAME'] : $BotBanishSettings['BOTBANISH_DB_NAME'];
			$tblprefix = '';
			$collation = 'utf8_general_ci';
			$charset = 'utf8';
			break;
	}

	if (isset($BotBanishSettings['BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT']))
		$collation = isset($_POST['BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT']) ? $_POST['BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT'] : $BotBanishSettings['BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT'];
	
	if (isset($BotBanishSettings['BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT']))
		$charset = isset($_POST['BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT']) ? $_POST['BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT'] : $BotBanishSettings['BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT'];

	$database_info = array('server' => $server_name, 'port' => $port, 'username' => $user_name, 'password' => $password, 'database' => $database_name, 'collation' => $collation, 'charset' => $charset, 'tblprefix' => $tblprefix);
	return $database_info;
}

function BotBanishProcessWPSettingsFile($filename) {

	$data = file_get_contents($filename);

	// Eliminate loading of wp-settings.php. We only want the defines

	$data = str_ireplace('require', '// require', $data) . PHP_EOL . '?>';
	file_put_contents('BotBanish_WP_Settings.php', $data);
}

function BotBanishDatabaseClose($conn) {

	if (is_object($conn)) {

		if (isset($conn->server_info))
			mysqli_close($conn);
	}
}

function BotBanishBuildSQLStatementUpdate($row, $table, $useIndex = false) {

	$params = BotBanishBuildSQLStatementInsert($row, $table, $useIndex, false, true);
	return $params;
}

function BotBanishBuildSQLStatementInsert($row, $table, $useIndex = false, $updated = false, $update_statement = false) {

static $static_table = '';
static $static_columns = array();
static $static_unique = array();

	$numerics = array('integer', 'int', 'bigint', 'mediumint', 'smallint', 'tinyint', 'bit', 'float', 'double', 'decimal', 'numeric');
	$values = '';
	$columns = '';
	$updates = '';

	// All data that needs slashes should have addslashes() done to it prior to this routine except serialized data

	if ($static_table != $table) {

		// Make sure the table name does not already have the BotBanish prefix

		$unique = BotBanishGetTableUniqueIndexes($table);
		$table_columns = BotBanishGetTableColumns($table);

		$static_table = $table;
		$static_columns = $table_columns;
		$static_unique = $unique;

	} else {

		$table_columns = $static_columns;
		$unique = $static_unique;
	}

	$error_check = BotBanishArrayCheck($row);

	if ($error_check['valid']) {

		foreach($row as $key => $value) {

			// If the asked for column does not exist in table, skip it

			if (!isset($table_columns[$key]))
				continue;

			// Ignore updated columns, they are auto filled

			if (($key == 'updated') && ($updated = false)) continue;

			$columns .= '`' . $key . '`, ';
			$str = intval($value);

			if (!in_array($table_columns[$key], $numerics)) {

				if (is_array($value))

					$value = BotBanishSafeSerialize($value);
				else
					$value = !empty($value) ? addslashes(trim($value, ' ')) : '';

				// if data is serialized and contains double quotes, surround with single quotes instead.

				if (stripos($value, '"') !== false)

					$str = "'" . $value . "'";
				else
					$str = '"' . $value . '"';
			}

			$values .= $str . ', ';

			// Unique keys should be listed in array.
			// We won't use them on UPDATE statements

			if (((is_array($unique) && !in_array($key, $unique)) || $useIndex) || $update_statement)
				$updates .= '`' . $key . '` = ' .  $str . ', ';
		}

		if (strlen($columns) > 1)
			$columns = substr($columns, 0, strlen($columns)-2);		// Remove

		if (strlen($values) > 1)
			$values = substr($values, 0, strlen($values)-2);		// trailing

		if (strlen($updates) > 1)
			$updates = substr($updates, 0, strlen($updates)-2);		// comma

		$params = array(
			'columns' => $columns,
			'values' => $values,
			'updates' => $updates,
		);
	}

	return $params;
}

function BotBanishBuildSQLStatementSelect($columns) {

	$column_names = array();

	foreach ($columns as $key => $value)
		$column_names[$key] = '`' . $key . '`';

	$select = implode(',', $column_names);
	return $select;
}

function BotBanishGetTableColumns($table) {

	global $BotBanishTableColumns;

	$data = BotBanishGetDatabaseInfo();

	if (isset($BotBanishTableColumns[$table])) return $BotBanishTableColumns[$table];
	$table = str_replace('`', '', $table);

	$sql = 'SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE (TABLE_SCHEMA = "' . $data['database'] . '")
				AND (TABLE_NAME = "' . $table . '")';

	$rows = BotBanishExecuteSQL($sql, true, true);

	if (!empty($rows) && is_array($rows)) {

		foreach ($rows as $row)
				$BotBanishTableColumns[$table][$row['COLUMN_NAME']] = $row['DATA_TYPE'];

		return $BotBanishTableColumns[$table];
	}

	return false;
}

function BotBanishGetTableUniqueIndexes($table) {

	$data = BotBanishGetDatabaseInfo();

	$columns = array();
	$table = str_replace('`', '', $table);

	$sql = 'SELECT * FROM information_schema.STATISTICS WHERE (`TABLE_SCHEMA` = "' . $data['database'] . '")
					AND (`TABLE_NAME` = "' . $table . '")
					AND `NON_UNIQUE` = 0';

	$rows = BotBanishExecuteSQL($sql, true, true);

	if (!empty($rows) && is_array($rows)) {

		foreach ($rows as $row)
			$columns[] = $row['COLUMN_NAME'];

		return $columns;
	}

	return false;
}

function BotBanishGetTableAutoIncrement($table) {

	$columns = array();
	$data = BotBanishGetDatabaseInfo();

	$sql = 'SELECT COLUMN_NAME, EXTRA FROM information_schema.COLUMNS WHERE (TABLE_SCHEMA = "' . $data['database'] . '")
				AND (TABLE_NAME = "' . $table . '")
				AND (EXTRA = "auto_increment")';

	$rows = BotBanishExecuteSQL($sql, true, true);

	if (!empty($rows) && is_array($rows)) {

		foreach ($rows as $row)
				$columns[$row['COLUMN_NAME']] = $row['EXTRA'];

		return $columns;
	}

	return false;
}

function BotBanishGetTablePrimaryKey($table) {

	$columns = array();
	$data = BotBanishGetDatabaseInfo();

	$sql = 'SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE (TABLE_SCHEMA = "' . $data['database'] . '")
				AND (TABLE_NAME = "' . $table . '")
				AND (COLUMN_KEY = "PRI")';

	$rows = BotBanishExecuteSQL($sql, true, true);

	if (!empty($rows) && is_array($rows)) {

		foreach ($rows as $row)
				$columns[$row['COLUMN_NAME']] = $row['DATA_TYPE'];

		return $columns;
	}

	return false;
}

function BotBanishClientLocalSelectDeny($ip) {

	$sql = 'SELECT `deny`, `created` FROM `' . 'bbc_botbanishclient_ip_bad` WHERE `bot_ip` = "' . $ip . '" LIMIT 1';
	$deny = BotBanishExecuteSQL($sql);
	return $deny;
}

function BotBanishClientLocalSelectHitCount($ip) {

	$sql = 'SELECT `hit_count` FROM `' . 'bbc_botbanishclient_ip_bad` WHERE `bot_ip` = "' . $ip . '" LIMIT 1';
	$row = BotBanishExecuteSQL($sql);
	return $row;
}

function BotBanishLogErrorDB($str) {
	global $botbanish_info;

	$date =  BotBanishGetCorrectTime();

	$row = array();

	$row['datetime'] = $date;
	$row['domain_name'] = isset($botbanish_info['DOMAIN_NAME']) ? $botbanish_info['DOMAIN_NAME'] : $_SERVER['SERVER_NAME'];
	$row['message'] = addslashes($str);

	$table = 'bbs_botbanishserver_errors';
	$params = BotBanishBuildSQLStatementInsert($row, $table);

	$sql = 'INSERT INTO `' . $table .'` (' . $params['columns'] . ') VALUES (' . $params['values'] . ')';

	if (isset($params['updates']) && !empty($params['updates']))
		$sql .= ' ON DUPLICATE KEY UPDATE ' . $params['updates'];

	BotBanishExecuteSQL($sql);
}

function BotBanishDatabaseUninstall() {

	global $BotBanishSettings;

	$date =  BotBanishGetCorrectTime();
	$data = BotBanishGetDatabaseInfo();

	// Setup a new database container to hold the old data

	$sql = array();
	$sql[] = 'DROP DATABASE IF EXISTS `' . $data['database'] . '_' . $date .'`';
	BotBanishDatabaseOperations($sql);

	if (isset($BotBanishSettings['BOTBANISH_RENAME_TABLES']) && ($BotBanishSettings['BOTBANISH_RENAME_TABLES'] == true)){

		$sql = array();
		$sql[] = 'CREATE DATABASE IF NOT EXISTS `' . $data['database'] . '_' . $date .'` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci';
		$sql[] = 'USE `' . $data['databae_name'] . '_' . $date .'`';

		BotBanishDatabaseOperations($sql);

		// Transfer the old data to the new container

		$sql = 'SELECT table_name FROM information_schema.tables WHERE table_schema = "' . $data['database'] . '"';
		$tables = BotBanishExecuteSQL($sql);

		if (is_array($tables)){

			foreach ($tables as $table){

				$sql = 'RENAME TABLE `' . $data['database'] . '`.`' . $table['table_name'].'` TO `' . $data['database'] . '_' . $date . '`.`' . $table['table_name'] . '`';
				BotBanishExecuteSQL($sql);
			}
		}
	}

	// Relinquish the old container

	$sql = array();
	$sql[] = 'DROP DATABASE IF EXISTS `' . $data['database'] .'`';
	BotBanishDatabaseOperations($sql);
}

function BotBanishLogWebsitePage($ip, $pagename, $userid = 0, $system = 'WEBSITE') {

	// If this user is in our DNB table; there is no reason to log them

	if (empty($ip))
		return;	// Nothing we can do here!!!

	global $BotBanishSettings, $BotBanishSession;

	// Ok, ready to log

	$table = 'bbc_botbanishclient_website_visits';
	$datetime = BotBanishGetCorrectDateTime($BotBanishSettings['BOTBANISH_TIMEZONE']);

	$row = array();
	$row['user_id'] = intval($userid);
	$row['page_name'] = addslashes(urldecode($pagename));
	$row['ip_addr'] = $ip;
	$row['http_user_agent'] = isset($_SERVER['HTTP_USER_AGENT']) ? addslashes(BotBanishFixUserAgent($_SERVER['HTTP_USER_AGENT'])) : $BotBanishSettings['BOTBANISH_HTTP_USER_AGENT'];
	$row['http_referer'] = isset($_SERVER['HTTP_REFERER']) ? addslashes($_SERVER['HTTP_REFERER']) : '';
	$row['rpt_date'] = $datetime;
	$row['date'] = $datetime;
	$row['hostname'] = addslashes(gethostbyaddr($_SERVER['REMOTE_ADDR']));
	$row['system'] = $system;

	$row['page_name'] = BotBanishEliminateData($row['page_name']);
	$row['http_referer'] = BotBanishEliminateData($row['http_referer']);

	// Add country and country code

	$country_info = $BotBanishSession->getSessionKey('countryinfo');
	$geo_data = $BotBanishSession->getSessionKey('geodata');

	$row['country'] = !empty($country_info['country']) ? $country_info['country'] : '';
	$row['country_code'] = !empty($country_info['country_code']) ? $country_info['country_code'] : '';
	$row['geo_info'] = BotBanishSafeSerialize($geo_data);

	$params = BotBanishBuildSQLStatementInsert($row, $table);
	$sql = 'INSERT INTO `' . $table . '` (' . $params['columns'] . ') VALUES (' . $params['values'] . ')';

	if (isset($params['updates']) && !empty($params['updates']))
		$sql .= ' ON DUPLICATE KEY UPDATE ' . $params['updates'];

	BotBanishExecuteSQL($sql);
}

function BotBanishSaveTables($saveTables) {


	$tables = BotBanishGetTableNames('_save');
	$sql = '';

	foreach ($tables as $table)
		$sql .= 'DROP TABLE IF EXISTS `' . $table . '`;' . PHP_EOL;

	$tables = BotBanishGetTableNames('botbanish');

	foreach ($tables as $table) {

		if (stripos($table, '_save') !== false)
			continue;

		$found = false;

		foreach($saveTables as $saveTable) {

			 if (stripos($table, $saveTable) !== false) {

				$found = true;
				break;
			}
		}

		if ($found) {

			$table_saved = $table . '_save';
			$sql .= 'DROP TABLE IF EXISTS `' . $table_saved . '`;' . PHP_EOL;
			$sql .= 'ALTER TABLE `' . $table . '` RENAME TO `' . $table_saved . '`;' . PHP_EOL;

		} else {

			if (stripos($table, '_audit_') === false)
				$sql .= 'DROP TABLE IF EXISTS `' . $table . '`;' . PHP_EOL;
		}
	}

	return $sql;
}

function BotBanishSettingsTablePutValues($dataArray = array(), $update = false) {

	global $BotBanishSettings;

	if (empty($dataArray))
		return;

	BotBanishSaveSession();
	
	$savedUpdate = $update;
	BotBanishSaveOverrideState();

	// If we are installing the server create the client settinge table also

	$system = BotBanishCheckSystem();
	$tables = array();

	switch (strtoupper($system['install_type'])) {

		case 'SERVER':

			$tables[] = 'bbs_botbanishserver_settings';
			break;

		case 'CLIENT':

			$tables[] = 'bbc_botbanishclient_settings';
			break;
	}

	foreach ($tables as $table) {

		switch ($table) {

			case 'bbc_botbanishclient_settings':

				$dataArray['BOTBANISH_CLIENT'] = 1;
				$dataArray['BOTBANISH_SERVER'] = 0;
				break;

			case 'bbs_botbanishserver_settings':

				$dataArray['BOTBANISH_CLIENT'] = 0;
				$dataArray['BOTBANISH_SERVER'] = 1;
				break;
		}

		ksort($dataArray);

		$dataArray = BotBanishExcludeData($dataArray);

		$sql = '';

		foreach ($dataArray as $key => $value) {

			switch ($key) {

				case 'BOTBANISH_DIR':
				case 'BOTBANISH_STATIC_DIR':
				case 'BOTBANISH_INSTALL_URL':
				case 'BOTBANISH_INSTALL_DIR':

					if ((isset($BotBanishSettings['BOTBANISH_INSTALL']) && $BotBanishSettings['BOTBANISH_INSTALL']))
						$update = true;
					
					$value = str_replace('\\', '/', $value);
					break;

				case 'BOTBANISH_404_EXTENSIONS':

					BotBanishCreate404ExtensionsFile($value);
					break;

				default:

					// If we are doing an install we need to update all the paths!!!

					$part = substr($key, strlen($key) - 4);

					switch ($part) {

						case '_URL':

							if ((isset($BotBanishSettings['BOTBANISH_INSTALL']) && $BotBanishSettings['BOTBANISH_INSTALL']))
								$update = true;

							$value = str_ireplace($BotBanishSettings['BOTBANISH_INSTALL_URL'], '', $value);
							break;

						case '_DIR':

							if ((isset($BotBanishSettings['BOTBANISH_INSTALL']) && $BotBanishSettings['BOTBANISH_INSTALL']))
								$update = true;

							$value = str_replace('\\', '/', $value);
							$value = str_ireplace(array($BotBanishSettings['BOTBANISH_DIR'], $BotBanishSettings['BOTBANISH_STATIC_DIR']), '', $value);
							break;
					}
			}

			$row = array(
						'name' => $key,
						'value' => is_bool($value) ? intval($value) : $value,
						'type' => 1
						);

			if ((isset($BotBanishSettings['BOTBANISH_INSTALL']) && $BotBanishSettings['BOTBANISH_INSTALL']) && !$update) {

				// On install we should not change any existing data. Only add new data

				$params = BotBanishBuildSQLStatementInsert($row, $table);
				$sql .= 'INSERT IGNORE INTO `' . $table . '` (' . $params['columns'] . ') VALUES (' . $params['values'] . ');' . PHP_EOL;

			} else {

				$params = BotBanishBuildSQLStatementUpdate($row, $table);
				$sql .= 'INSERT INTO `' . $table . '` (' . $params['columns'] . ') VALUES (' . $params['values'] . ')' .
								' ON DUPLICATE KEY UPDATE ' . $params['updates'] . ';' . PHP_EOL;
			}

			$update = $savedUpdate;
		}

		BotBanishExecuteSQLAsync($sql, false);
	}

	BotBanishRestoreOverrideState();
}

function BotBanishSettingsTableGetValues() {

	global $BotBanishSettings;

	BotBanishSaveOverrideState();
	BotBanishSetLanguage();

	BotBanishCheckMemoryUsage('BotBanishSettingsTableGetValues Start');

	$system = BotBanishCheckSystem();

	if (isset($BotBanishSettings['BOTBANISH_SERVER']) && $BotBanishSettings['BOTBANISH_SERVER'])

		$table = 'bbs_botbanishserver_settings';
	else
		$table = 'bbc_botbanishclient_settings';

	// If the table does not exist, return an empty array.
	// Table may not exist at installation time.

	$tables = BotBanishGetTableNames($table);

	if (empty($tables))
		return $BotBanishSettings;

	// Get all of the settings from the database (except URLS)

	$sql = 'SELECT `name`, `value` FROM `' . $table . '` WHERE `type` = 1 ORDER BY `name`';
	$rows = BotBanishExecuteSQL($sql, true, true);

	if (is_array($rows) && !empty($rows)) {

		// Update all values

		$BotBanishSettings = BotBanishAdjustFolderNames($rows);
		$BotBanishSettings = BotBanishAdjustArrayValues($BotBanishSettings);
	}

	$timeZones = BotBanishSetTimeZones();
	$BotBanishSettings = array_merge($BotBanishSettings, $timeZones);

	ksort($BotBanishSettings);

	BotBanishSetLanguage($BotBanishSettings['BOTBANISH_LANGUAGE_SELECT']);

	if (isset($BotBanishSettings['BOTBANISH_TIMEZONE']) && !empty($BotBanishSettings['BOTBANISH_TIMEZONE']))
		date_default_timezone_set($BotBanishSettings['BOTBANISH_TIMEZONE']);

	if ($system['system'] != 'SERVER') {
			
			if (isset($GLOBALS['BotBanishSession']) && is_object($GLOBALS['BotBanishSession'])) {
				
				$BotBanishSession = $GLOBALS['BotBanishSession'];
			
			} else {
				
				require_once $BotBanishSettings['BOTBANISH_SUBS_DIR'] . 'BotBanish_Session.php';
				$BotBanishSession = new BotBanishSession;
				$GLOBALS['BotBanishSession'] = $BotBanishSession;
			}
	}

	BotBanishSetVersion();
	
	BotBanishRestoreOverrideState();
	BotBanishCheckMemoryUsage('BotBanishSettingsTableGetValues End');
	return $BotBanishSettings;
}

function BotBanishCreate404ExtensionsFile($items) {
		
	global $BotBanishSettings;

	$BotBanishSettings['BOTBANISH_DEBUG_OVERRIDE'] = '404';

	$lines = BotBanishGet404Extensions(true);

	foreach ($lines as $key => $line) {

		if (stripos($line, 'extensions =') !== false) {
			
			$lines[$key] =  "\t" . '$extensions = "' . $items . '"' . PHP_EOL;
			break;
		}
	}
	
	$filename = $BotBanishSettings['BOTBANISH_INCLUDE_DIR'] . 'BotBanish_404_Extensions.php';
	BotBanishWriteFile($filename, $lines, false, true);
}

function BotBanishAdjustArrayValues($BotBanishSettings) {

	// Update all arrays

	foreach ($BotBanishSettings as $key => $value) {

		if (BotBanishIsSerialized($value)) {

			$value = BotBanishSafeUnserialize($value);

			if (is_array($value)) {

				foreach($value as $key_1 => $val)
					$value[$key_1] = BotBanishSafeUnserialize($val);
			}

			$BotBanishSettings[$key] = $value;
		}
	}

	return $BotBanishSettings;
}

function BotBanishExcludeData($dataArray) {

	global $BotBanishSettings;

	// Remove any data not to be written to database.
	// These values can be changed at runtime so don't store them.

//	$deletes = array_merge($BotBanishSettings['BOTBANISH_EXCLUDE_VARS'], array('SERVER_URL', 'WEBSERVER'));
	BotBanishStartUp();
	$deletes = array_merge($BotBanishSettings['BOTBANISH_EXCLUDE_VARS'], array('SERVER_URL', 'WEBSERVER'));

	foreach ($deletes as $exclude) {

		if (isset($dataArray[$exclude]))
			unset($dataArray[$exclude]);
	}
/*
	foreach ($dataArray as $key => $value) {

		if (stripos($key, 'BOTBANISH_DB_') !== false)
			unset($dataArray[$key]);
	}
*/
	return $dataArray;
}

function BotBanishSetTimeZones() {

	// Setup time zones

	$table = 'botbanish_timezones';
	$tables = BotBanishGetTableNames($table);
	$dataArray = array();

	if (!empty($tables)) {

		$sql = 'SELECT `gmt`, `area`, `timezone` FROM `' . $table . '` WHERE 1 ORDER BY `gmt` DESC';
		$rows = BotBanishExecuteSQL($sql, true, true);
		$time_zones = array();
		$time_zone_areas = array();

		if (is_array($rows) && !empty($rows)) {

			foreach($rows as $row) {

				$tz = '[' . $row['gmt'] . '] - ' . $row['area'];
				$time_zone_areas[$tz] = $tz;
				$time_zones[$tz] = $row['timezone'];
			}

			$dataArray['BOTBANISH_TIMEZONES'] = $time_zones;
			$dataArray['BOTBANISH_TIMEZONE_AREAS'] = $time_zone_areas;
		}

		$dataArray['BOTBANISH_TIMEZONE'] = isset($_SERVER['TZ']) ? $_SERVER['TZ'] : 'Pacific/Honolulu';
	}

	return $dataArray;
}

function BotBanishAdjustFolderNames($rows) {

	$settings = array();
	
	foreach ($rows as $row)
		$settings[$row['name']] = $row['value'];
	
	foreach ($settings as $key => $value) {

		switch ($key) {

			case 'BOTBANISH_STATIC_DIR':
			case 'BOTBANISH_INSTALL_URL':
			case 'BOTBANISH_DIR':
			case 'BOTBANISH_INSTALL_DIR':

				break;

			default:

				// Just in case old data got into database

//				if (strlen($key) > 10) {

					$part = substr($key, strlen($key) - 4);

					switch ($part) {

						case '_URL':

							$dir = isset($settings['BOTBANISH_INSTALL_URL']) ? $settings['BOTBANISH_INSTALL_URL'] : '';
							$settings[$key] = $dir . $value;
							break;

						case '_DIR':

							if (stripos($key, 'STATIC') === false)

								$dir = isset($settings['BOTBANISH_DIR']) ? $settings['BOTBANISH_DIR'] : '';
							else
								$dir = isset($settings['BOTBANISH_STATIC_DIR']) ? $settings['BOTBANISH_STATIC_DIR'] : '';

							$settings[$key] = $dir . $value;
							break;

						default:

							$settings[$key] = $value;
							break;
					}
//				}
				break;
		}
	}

	return $settings;
}

function BotBanishEliminateData($str) {

	global $BotBanishSettings;

	// Eliminate any session or other extraneous information

	if (((isset($BotBanishSettings['BOTBANISH_REFERER_DATA']) && $BotBanishSettings['BOTBANISH_REFERER_DATA']))
		|| (isset($BotBanishSettings['BOTBANISH_PAGE_DATA']) && $BotBanishSettings['BOTBANISH_PAGE_DATA'])) {

		$eliminate = array('?');

		foreach ($eliminate as $item) {

			$pos = stripos($str, $item);

			if ($pos !== false)
				$str = substr($str, 0, $pos);
		}
	}

	return $str;
}

function BotBanishCheckInstallation() {

	// If BotBanish is not installed, continue...

	$table = 'bbc_botbanishclient_settings';
	$tables = BotBanishGetTableNames($table);

	if (!is_array($tables) || empty($tables))
		return true;

	// Check to see if BotBanish was already installed and a prior version to 6.0.x

	$sql = 'SELECT `value` FROM `' . $table . '` WHERE `name` = "BOTBANISH_VERSION_NO"';
	$rows = BotBanishExecuteSQL($sql, true, true);
	$row = BotBanishLimitReturn($rows);

	if (!is_array($row) || empty($row) || (intval($row['value']) < 6000)) {

		$msg = 'Prior version of BotBanish must be completely uninstalled first';
		BotBanishAlert($msg);
		BotBanishExit(true);
	}

	return true;
}

function BotBanishDatabaseOperations($sql) {

	global $sourcedir;

	// Force database operations if operating under SMF

	BotBanishSaveOverrideState();

	foreach ($sql as $statement)
		BotBanishExecuteSQL($statement, true, true);

	BotBanishRestoreOverrideState();
}

function BotBanishGetTableNames ($tablename, $actual = false) {

	BotBanishSaveOverrideState();

	$tables = array();

	$data = BotBanishGetDatabaseInfo();
	if (empty($data['server'])) return array();

	if ($tablename === '*')

		$sql = 'SELECT `TABLE_NAME` FROM information_schema.TABLES WHERE (`TABLE_SCHEMA` = "' . $data['database'] . '")';
	else
		$sql = 'SELECT `TABLE_NAME` FROM information_schema.TABLES WHERE (`TABLE_SCHEMA` = "' . $data['database'] . '") AND (`TABLE_NAME` ';

	if ($tablename !== '*') {

		if ($actual)

			$sql .= ' = "' . $tablename . '")';
		else
			$sql .= ' LIKE "%' . $tablename . '%")';

	}

	$rows = BotBanishExecuteSQL($sql, true, false);

	if (!empty($rows) && is_array($rows)) {

		// Strip off any quotes and or database name that may be in the prefix

		$db_name = str_replace('`', '', $data['database']);
		$pos = strripos($db_name, '.');

		if ($pos !== false)
			$db_name = substr($db_name, $pos + 1);

		foreach ($rows as $row) {

			$table = str_ireplace(array($db_name . '.', '`'), '', $row['TABLE_NAME']);
			$tables[] = $table;
		}
	}

	BotBanishRestoreOverrideState();
	return $tables;
}


//	global $BotBanishSettings;

//	require_once $BotBanishSettings['BOTBANISH_SUBS_DIR'] . 'BotBanish_SplitSQLAsync.php';
?>