<?php
///////////////////////////////////////////////////////////////////////////////////////////////////////
// BotBanish 7.1.06
// Randem Systems: https://randemsystems.support
// Stand Alone Database Routines
// Date: 04/02/2026
// Usage: include BotBanishDatabaseRtns.php
//
///////////////////////////////////////////////////////////////////////////////////////////////////////

function BotBanishUninstallBrowserNoCache() {

	// Set headers to prevent caching
	header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
	header("Cache-Control: post-check=0, pre-check=0", false);
	header("Pragma: no-cache");
}

function BotBanishUninstallProcessWPSettingsFile($filename, $config_file) {

	$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($config_file, $data);
}

function BotBanishUninstallProcessBotBanishSettingsFile($filename, $config_file) {

	$lines = file($filename);
	$data = '';

	foreach ($lines as $line) {
		
		if (stripos($line, 'BotBanishDefineGlobals') !== false)
			$data .= $line . PHP_EOL;		
	}
	
	// Eliminate loading of Settings_Client.php. We only want the defines

	file_put_contents($config_file, $data);
}

function BotBanishUninstallExecuteSQL($sql) {

	$conn = BotBanishUninstallDatabaseOpen();

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

	$rows = array();
	$result = BotBanishUninstallPerformQuery($conn, $sql);

	if (is_object($result)) {

		$rows = BotBanishUninstallExtractResults($result);
		BotBanishUninstallResultRelease($result);
	}

	BotBanishUninstallDatabaseClose($conn);

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

		$subject = 'SQL Execute Error:';
		$body = $rows[0]['error'];
		BotBanishUninstallDisplayIt( $subject . '<br>' . $body . '<br>');
	}

	return $rows;
}

function BotBanishUninstallPerformQuery($conn, $sql_statement) {

	try {

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

	} catch (Exception $f) {

		BotBanishUninstallDisplayIt( 'SQL Query Error: ' . $sql_statement . '<br>' . $f . '<br>');
		$result = false;
	}

	return $result;
}

function BotBanishUninstallDatabaseOpen() {

	$conn = false;

	if (defined('INTERNAL') && !INTERNAL)

		$data = BotBanishUninstallGetDatabaseInfo();
	else
		$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) {

		try {

			$conn = mysqli_connect($data['server'], $data['username'], $data['password'], $data['database']);

		} catch (mysqli_sql_exception $f) {

			BotBanishUninstallDisplayIt( 'Connection Failed:<br>');
			return false;
		}
	}

	return $conn;
}

function BotBanishUninstallDatabaseClose($conn) {

	if (is_object($conn)) {

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

function BotBanishUninstallShowBotBanishTableInfo($delete = false) {

	$sql = 'SHOW TABLE STATUS WHERE name LIKE "%botbanish%"';
	$tables = BotBanishUninstallExecuteSQL($sql);

	if (!empty($tables)) {

		BotBanishUninstallDisplayIt( '<table width="50%" cellpadding="0" cellspacing="0" border="0">
			<tr>
				<td colspan="3">Existing tables:</td>
			</tr>', true);

		BotBanishUninstallDisplayIt( '<tr style="background-color: #0099cc;"><td>Table Name</td><td>Engine</td><td>Rows</td><td>Collation</td></tr>', true);

		foreach ($tables as $table) {

			$sql = 'SELECT COUNT(*) FROM `' . $table['Name'] . '`';
			$rows = BotBanishUninstallExecuteSQL($sql);
			$count = $rows[0]['COUNT(*)'];

			if ($delete) {

				$sql = 'DROP TABLE `' . $table['Name'] . '`';
				BotBanishUninstallExecuteSQL($sql);
			}

			BotBanishUninstallDisplayIt( '<tr ><b><td>' . $table['Name'] . '</td><td>' . $table['Engine'] . '</td><td>' . $count . '</td><td>' . $table["Collation"] . '</td></b></tr>', true);
		}

		BotBanishUninstallDisplayIt( '</table>', true);

	} else {

		BotBanishUninstallDisplayIt( '&emsp;No Tables to Remove<br>');
	}
}

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

	$tables = array();

	if (defined('INTERNAL') && !INTERNAL)

		$data = BotBanishUninstallGetDatabaseInfo();
	else
		$data = BotBanishGetDatabaseInfo();

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

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

	$rows = BotBanishUninstallExecuteSQL($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;
		}
	}

	return $tables;
}

function BotBanishUninstallExtractResults($result) {

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

	if (is_object($result)) {

		try {

			$rowcount = mysqli_num_rows($result);

		} catch (Exception $f) {

			$rows[0]['error'] = $f;
		}

		if ($rowcount > 0) {

			$rows = array();

			try {

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

			} catch (Exception $f) {

				$rows[0]['error'] = $f;
			}
		}

	} else {

		if ($result === false) {

			$rows[0]['error'] = 'BotBanish_ErrorText' . '<br>' . '<br>' . $sql . '<br>' . '<br>';
			$rows[0]['error'] .= mysqli_errno($conn) . ": " . mysqli_error($conn) . '<br>' . '<br>';

			global $db_server, $db_name;
			$rows[0]['error'] .= '<br>' . $db_server . '<br>' . $db_name. '<br>';
		}
	}

	return $rows;
}

function BotBanishUninstallResultRelease($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 BotBanishUninstallRemoveHooks() {

	global $BotBanishSettings;
	BotBanishUninstallDisplayIt( 'BotBanish Hook Removal Started<br>');

	// Remove all BotBanish hooks old and new!

	$table = $BotBanishSettings['BOTBANISH_TABLE_PREFIX'] . 'settings';

	$sql = 'SELECT `variable`, `value` FROM `' . $table . '` WHERE `variable` LIKE "%integrate%"';
	$rows = BotBanishUninstallExecuteSQL($sql, true, true);

	foreach ($rows as $row) {

		if (stripos($row['value'], 'BotBanish') === false)
			continue;

		$items = explode(',', $row['value']);

		foreach ($items as $key => $item) {

			if (stripos($item, 'BotBanish') !== false)
				unset($items[$key]);
		}

		if (!empty($items)) {

			$newvalue = implode(',', $items);
			$sql = 'UPDATE `' . $table . '` SET `value` = "' . $newvalue . '" WHERE `variable` = "' . $row['variable'] . '"';

		} else {

			$sql = 'DELETE FROM `' . $table . '` WHERE `variable` = "' . $row['variable'] . '"';
		}

		BotBanishUninstallExecuteSQL($sql, true, true);
		BotBanishUninstallDisplayIt( '&emsp;Hook - ' . $row['variable'] . '<br>');
	}

	if (empty($rows))
		BotBanishUninstallDisplayIt( '&emsp;No Hooks to Remove<br>');

	BotBanishUninstallDisplayIt( 'BotBanish Hook Removal Complete<br><br>');
}

function BotBanishUninstallGetDatabaseInfo() {

	switch(SYSTEM) {

		case 'SMF':

			global $db_server, $db_port, $db_user, $db_passwd, $db_name, $db_prefix;
			
			$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':

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

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

			$server_name = isset($_METHOD['BOTBANISH_DB_SERVERNAME']) ? $_METHOD['BOTBANISH_DB_SERVERNAME'] : BOTBANISH_DB_SERVERNAME;
			$port = isset($_METHOD['BOTBANISH_DB_PORT']) ? $_METHOD['BOTBANISH_DB_PORT'] : BOTBANISH_DB_PORT;
			$user_name = isset($_METHOD['BOTBANISH_DB_USERNAME']) ? $_METHOD['BOTBANISH_DB_USERNAME'] : BOTBANISH_DB_USERNAME;
			$password = isset($_METHOD['BOTBANISH_DB_PASSWORD']) ? $_METHOD['BOTBANISH_DB_PASSWORD'] : BOTBANISH_DB_PASSWORD;
			$database_name = isset($_METHOD['BOTBANISH_DB_NAME']) ? $_METHOD['BOTBANISH_DB_NAME'] : BOTBANISH_DB_NAME;
			$tblprefix = '';
			$collation = isset($_METHOD['BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT']) ? $_METHOD['BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT'] : BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT;
			$charset = isset($_METHOD['BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT']) ? $_METHOD['BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT'] : BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT;
			break;
	}

	$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 BotBanishUninstallSetDBInfo() {

	global $BotBanishSettings;
	
	$dbInfo = BotBanishUninstallGetDatabaseInfo();
	
	BotBanishUninstallDefineGlobals('BOTBANISH_TABLE_PREFIX', $dbInfo['tblprefix']);
	BotBanishUninstallDefineGlobals('BOTBANISH_DB_PORT', $dbInfo['port']);
	BotBanishUninstallDefineGlobals('BOTBANISH_DB_NAME', $dbInfo['database']);
	BotBanishUninstallDefineGlobals('BOTBANISH_DB_USERNAME', $dbInfo['username']);
	BotBanishUninstallDefineGlobals('BOTBANISH_DB_PASSWORD', $dbInfo['password']);
	BotBanishUninstallDefineGlobals('BOTBANISH_DB_HOST', $dbInfo['server']);
	BotBanishUninstallDefineGlobals('BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT', $dbInfo['collation']);
	BotBanishUninstallDefineGlobals('BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT', $dbInfo['charset']);
}

function BotBanishUninstallTableDeletion() {

	global $BotBanishSettings;
	
	BotBanishUninstallDisplayIt('BotBanish Table Deletetion Started<br>');

	BotBanishUninstallShowBotBanishTableInfo(true);

	if (SYSTEM == 'WORDPRESS') {

		$sql = 'DELETE FROM `' . $BotBanishSettings['BOTBANISH_TABLE_PREFIX'] . 'options` WHERE `option_name` LIKE "%botbanish%"';
		BotBanishUninstallExecuteSQL($sql);
		BotBanishUninstallDisplayIt( '&emsp; Deleted - BotBanish WordPress Options<br>');
	}

	BotBanishUninstallDisplayIt( 'BotBanish Table Deletetion Complete<br><br>');
}
?>