<?php
///////////////////////////////////////////////////////////////////////////////////////////////////////
// BotBanish 9.0.02
// Randem Systems: https://randemsystems.support
// BotBanish Server Install
// Date: 07/19/2026
// Usage:
//
// Function:
//		Installing the Client/Server Tables
//		Create the BOT tables that we will need
//		We also import the IPs from the local .htaccess file to help avoid duplication
///////////////////////////////////////////////////////////////////////////////////////////////////////

	// Only run pre-install test if on OpenCart. Website installs have their own selection screen

	if (defined('DIR_APPLICATION'))
		BotBanish_PreInstall_Test();

	BotBanishInstallStart();

function BotBanishInstallStart() {

	global $BotBanishSettings, $BotBanishText, $install, $txt;

	require_once BOTBANISH_DIR . 'Include/BotBanish_PreIncludes.php';
	require_once BOTBANISH_DIR . 'Include/BotBanish_Setup.php';
	require_once BOTBANISH_DIR . 'Include/BotBanish_Defines.php';
//	require_once BOTBANISH_DIR . 'Subs/BotBanish_Subs_DumpDatabase.php';
//	require_once BOTBANISH_DIR . 'Subs/BotBanish_Subs_AdjustDatabase.php';

	BotBanishPreInstallCleanUp(BOTBANISH_DIR);

	$system = BotBanishCheckSystem();

	$screenData = !empty($_POST) ? $_POST : $BotBanishSettings;
	$BotBanishSettings = array_merge($BotBanishSettings, $_POST);

	$BotBanishSettings['BOTBANISH_INSTALL'] = 1;

	BotBanishSetLanguage();

	$BotBanishSettings_saved = $BotBanishSettings;
	
	// Create BotBanish database tables.
	
	$records = BotBanishCreateDatabase();
	BotBanishSetLanguage();

	//----------------------------------------------------------------------
	// Backup .htaccess files, create honeypot, index.php and favicon files
	//----------------------------------------------------------------------

	BotBanishSetTimeZone($BotBanishSettings['BOTBANISH_TIMEZONE']);
	$icons = array('android-chrome-192x192.png', 'android-chrome-512x512.png', 'apple-touch-icon.png', 'favicon-16x16.png', 'favicon.ico', 'favicon-32x32.png');
	
	BotBanishPrepareHTACCESS();

	BotBanish_HTMLHoneyPotCreate();
	$BotBanishSettings['BOTBANISH_CONFIGURATION'] = 0;  // Turn off install configuration indicator
	BotBanishDefineGlobals('BOTBANISH_ACTIVE', 1);		// Turn BotBanish On

	if (defined('ABSPATH'))
		$BotBanishSettings['BOTBANISH_WORDPRESS_ROOT'] = ABSPATH;
	
	if (defined('SMF')) {
			
		global $boarddir;
		$BotBanishSettings['BOTBANISH_SMF_ROOT'] = $boarddir . '/';
	}
	
	$BotBanishSettings = array_merge($BotBanishSettings_saved, $BotBanishSettings, BotBanishUpdateDatabaseInfo());
	ksort($BotBanishSettings);

	BotBanishSettingsTablePutValues($BotBanishSettings);
	BotBanishSetupDNB();

	if (defined('SMF'))
		BotBanishInstallForSMF();

	// Update HTML files if needed

	$records['updated'] = 0;
	$records['filecount'] = 0;

	BotBanishCreateSettingsFile($screenData);
	
	if ($BotBanishSettings['BOTBANISH_UPDATE_HTML_ACTIVE']) {

		$records_html = BotBanishModifyHTMLFiles();
		$records = array_merge($records, $records_html);
	}

	$type = $BotBanishSettings['BOTBANISH_SERVER'] == 1 ? 'BotBanishServer_InstallComplete' : 'BotBanishClient_InstallComplete';
	$complete = '<br>' . $BotBanishSettings['BOTBANISH_USER_HOST'] . ':  ' . sprintf($BotBanishText[$type], $records['ip'], $records['bot'], $records['filecount'], $records['updated']);

	if ($records['filecount'] > 0)
		$complete .= '<br><br>' . BotBanishGrabArray($records['files']) . '<br><br>';

	$install['Complete'] = str_replace(array("\n", "\r"), array('<br>', ''), $complete);

	if (defined('SMF')) {

		$str = str_replace(array("\n", "\r"), array('<br>', ''), $complete);
		$txt['package_installed_done'] = $BotBanishSettings['BOTBANISH_HEADER_HTML'] . $txt['package_installed_done'] . '<br>' . $str;
		
		$filename = $BotBanishSettings['BOTBANISH_DOCS_DIR'] . 'BotBanish_Readme_' . $BotBanishSettings['BOTBANISH_SYSTEM'] . ' - ' . ucwords($BotBanishSettings['BOTBANISH_LANGUAGE_SELECT']) . '.html';
		
		if (file_exists($filename))
			
			$txt['package_installed_done'] .= file_get_contents($filename);
		else
			$txt['package_installed_done'] .= '<br><br>File does not exist: ' . $filename . '<br>Please check your FTP system';
	
		$txt['extracting'] = 'BotBanish';
	}
	
	// Let the server know we exist
	
	if ($url = BotBanishFindServer()) {
		
		$file = $BotBanishSettings['BOTBANISH_STATIC_TEMP_DIR'] . 'ack.txt';
		file_put_contents($file, 'here');
		BotBanishUploadFile($url, $file);
		
		if (file_exists($file))
			unlink($file);
	}
	
	BotBanishRestoreErrorHandler();
}

function BotBanishCreateSettingsFile($screenData) {
	
	global $BotBanishSettings;

	require_once BOTBANISH_DIR . 'Subs/BotBanish_TransferFile.php';
	$system = BotBanishCheckSystem();
	
	switch (strtoupper($system['install_type'])) {

		case 'SERVER':
		
			$BotBanishSettingsFile1 = $BotBanishSettings['BOTBANISH_SERVER_DIR'] . 'Settings_Server.php';
			$BotBanishSettingsFile2 =  $BotBanishSettings['BOTBANISH_DIR'] . 'Settings_Server.php';
			BotBanishSetSettingsInstall($BotBanishSettingsFile1, $BotBanishSettingsFile2, $screenData, 'Server');
			BotBanishRecursiveCopy($BotBanishSettings['BOTBANISH_IMAGES_DIR'], $BotBanishSettings['BOTBANISH_DIR'] . 'Images/');
			BotBanishRecursiveCopy($BotBanishSettings['BOTBANISH_DOCS_DIR'] . 'icons/', $BotBanishSettings['BOTBANISH_DIR'] . 'Images/icons/');
			break;
			
		default:
		
			$BotBanishSettingsFile1 = $BotBanishSettings['BOTBANISH_CLIENT_DIR'] . 'Settings_Client.php';
			$BotBanishSettingsFile2 =  $BotBanishSettings['BOTBANISH_DIR'] . 'Settings_Client.php';
			BotBanishSetSettingsInstall($BotBanishSettingsFile1, $BotBanishSettingsFile2, $screenData, 'Client');
			break;
	}
}

function BotBanishSetSettingsInstall($source, $dest, $settings, $installType) {

	global $BotBanishSettings;

	require_once $BotBanishSettings['BOTBANISH_SUBS_DIR'] . 'BotBanish_Settings_Update_Website.php';

	if (defined('ABSPATH')) {

		global $wpdb;

		$serverInfo = array(
			'BOTBANISH_DB_PORT' => '',
			'BOTBANISH_TIMEZONE' => isset($_SERVER['TZ']) ? $_SERVER['TZ'] : date_default_timezone_get(),
			'BOTBANISH_DB_NAME' => $wpdb->dbname,
			'BOTBANISH_DB_USERNAME' => $wpdb->dbuser,
			'BOTBANISH_DB_PASSWORD' => $wpdb->dbpassword,
			'BOTBANISH_DB_SERVERNAME' => $wpdb->dbhost,
			'BOTBANISH_HOST' => $wpdb->dbhost,
			'BOTBANISH' => 1,
			'BOTBANISH_SERVER' => 0,
			'BOTBANISH_CLIENT' => 1,
			'BOTBANISH_SYSTEM' => 'WORDPRESS',
			'BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT' => $BotBanishSettings['BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT'],
			'BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT' => $BotBanishSettings['BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT'],
		);

	} else {

		switch (strtoupper($installType)) {
			
			case 'CLIENT':

				$serverInfo = array(
					'BOTBANISH' => 1,
					'BOTBANISH_SERVER' => 0,
					'BOTBANISH_CLIENT' => 1,
					'BOTBANISH_TIMEZONE' => $BotBanishSettings['BOTBANISH_TIMEZONE'],
					'BOTBANISH_SYSTEM' => $BotBanishSettings['BOTBANISH_SYSTEM'],
					'BOTBANISH_USER_HOST' => $BotBanishSettings['BOTBANISH_USER_HOST'],
				);
				break;

			case 'SERVER':

				$serverInfo = array(
					'BOTBANISH_DB_SERVERNAME_PRIMARY' => $BotBanishSettings['BOTBANISH_DB_SERVERNAME'],
					'BOTBANISH_DB_PORT_PRIMARY' => $BotBanishSettings['BOTBANISH_DB_PORT'],
					'BOTBANISH_DB_USERNAME_PRIMARY' => $BotBanishSettings['BOTBANISH_DB_USERNAME'],
					'BOTBANISH_DB_PASSWORD_PRIMARY' => $BotBanishSettings['BOTBANISH_DB_PASSWORD'],
					'BOTBANISH_DB_NAME_PRIMARY' => $BotBanishSettings['BOTBANISH_DB_NAME'],
					'BOTBANISH_HOST_PRIMARY' => $BotBanishSettings['BOTBANISH_DB_SERVERNAME'],
					'BOTBANISH_SERVER' => 1,
					'BOTBANISH_CLIENT' => 0,
				);
				break;
		}
	}

	$serverInfo = array_merge($serverInfo, array(
		'BOTBANISH_DB_SERVERNAME' => $BotBanishSettings['BOTBANISH_DB_SERVERNAME'],
		'BOTBANISH_DB_PORT' => $BotBanishSettings['BOTBANISH_DB_PORT'],
		'BOTBANISH_DB_USERNAME' => $BotBanishSettings['BOTBANISH_DB_USERNAME'],
		'BOTBANISH_DB_PASSWORD' => $BotBanishSettings['BOTBANISH_DB_PASSWORD'],
		'BOTBANISH_DB_NAME' => $BotBanishSettings['BOTBANISH_DB_NAME'],
		'BOTBANISH_HOST' => $BotBanishSettings['BOTBANISH_DB_SERVERNAME'],
		'BOTBANISH_DB_PREFIX' => '',
		'BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT' => $BotBanishSettings['BOTBANISH_DATABASE_TABLE_CHARSET_DEFAULT'],
		'BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT' => $BotBanishSettings['BOTBANISH_DATABASE_TABLE_COLLATION_DEFAULT'],
	));

	$serverInfo['BOTBANISH_DIR'] = BOTBANISH_DIR;
	
	$system = BotBanishCheckSystem();
	$serverInfo['BOTBANISH_SYSTEM'] = $system['system'];

	foreach ($serverInfo as $key => $value)
		$settings[$key] = $value;

	$str = BotBanishSettingsCreate($serverInfo) . PHP_EOL;

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

		$value = is_numeric($value) ? $value : "'" . addslashes($value) . "'";
		$str .= "\t" . "BotBanishDefineGlobals('" . $key . "'," . $value . ");" . PHP_EOL;
	}

	// Let's update the database setting in the passed settings file

	$data = file_get_contents($source);
	$data = str_ireplace('//***BOTBANISH SETTINGS***', $str, $data);
	BotBanishWriteFile($dest, $data);
	
	BotBanishSettingsTablePutValues($serverInfo);
	$BotBanishSettings = array_merge($BotBanishSettings, $serverInfo);
}

 function BotBanishIndexUpdate($source, $dest) {

	// Let's update the database setting in the passed settings file

	$data = file_get_contents($source);
	$str = "	require_once '" . $BotBanishSettings['BOTBANISH_DIR'] . "Settings_Client.php';";
	$data = str_ireplace($BotBanishSettings['BOTBANISH_REPLACE'], $str, $data);
	BotBanishWriteFile($dest, $data);
}

function BotBanish_PreInstall_Test() {

	$action = isset($_GET['install_action']) ? $_GET['install_action'] : '';

	if (!isset($_POST['BOTBANISH_POST_CODE'])) {

		switch ($action) {

			case 'quit':
				exit;
				break;

			case 'continue':
				break;

			case '':

				$filename = realpath('../../Subs/BotBanish_PreInstall.php');
				include $filename;

				$scripturl = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . str_ireplace($_SERVER['DOCUMENT_ROOT'], '' , $_SERVER['SCRIPT_FILENAME']);

				echo '
				<button onclick="window.location.href=\'' . $scripturl . '?install_action=continue\'' . '">Continue</button>
				<button onclick="window.location.href=\'' . $scripturl . '?install_action=quit\'' . '">Quit</button>';
				exit;
				break;

			default:
				break;
		}
	}
}

function BotBanishSetupDNB() {

	global $BotBanishSettings, $BotBanishText;

	//*******************************************************************************************************
	// Make sure that BotBanish never automatically locks out this install from itself or the server
	//*******************************************************************************************************

	$tables = array('bbc_botbanishclient_ip_good', 'bbs_botbanishserver_ip_good');
	$ips = (isset($BotBanishSettings['BOTBANISH_LOCAL_ADDR']) && !empty($BotBanishSettings['BOTBANISH_LOCAL_ADDR'])) ? explode(',', $BotBanishSettings['BOTBANISH_LOCAL_ADDR']) : array('::1', '127.0.0.1');
	$ips[] = BotBanishGetIP();
	$ips[] = gethostbyname('botbanish.com');
	$ips[] = gethostbyname('botbanishserver.com');
	array_filter(array_map('trim', $ips));

	BotBanishDefineGlobals('BOTBANISH_LOCAL_ADDR', implode(',', $ips));

	$row = array();
	$row['name'] = 'BotBanish';
	$row['active'] = 1;

	foreach ($tables as $table) {

		// If we are only processing the client do not attempt on the server.
		// Processing the server installs both client and server

		if (isset($BotBanishSettings['BOTBANISH_CLIENT']) && ($BotBanishSettings['BOTBANISH_CLIENT']) && stripos($table, 'server') !== false)
			break;

		foreach ($ips as $ip) {

			$row['bot_ip'] = $ip;

			$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, true, true);
		}
	}
}

function BotBanishSMFBannedIPImport() {

	if (!defined('SMF'))
		return;

	global $BotBanishSettings;
	
	if (isset($BotBanishSettings['BOTBANISH_REDIRECT_ONLY_ACTIVE']) && $BotBanishSettings['BOTBANISH_REDIRECT_ONLY_ACTIVE'])
		return;
	
	$records = 0;
	$table = 'bbc_botbanishclient_ip_bad';

	global $sourcedir;
	require_once $sourcedir . '/ManageBans.php';
	$list = list_getBanLogEntries(1, 1000, 'ip');
	$ip_list = array();

	foreach ($list as $row)
		$ip_list[] = $row['ip'];

	$records = count($ip_list);
	BotBanishBlockedIPInsert($ip_list, $table);

	return $records;
}

function BotBanishUpdateDatabaseInfo() {

	// We need to retain any useful settings from the old installation to place into the new one

	global $BotBanishSettings;

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

	switch ($system['system']) {

		case 'WORDPRESS':

			delete_option( 'botbanishfirewall_client_option_name' );
			
			break;

		case 'SMF':

			break;

		case 'WEBSITE':

			break;
	}

	$update = array(
					'BOTBANISH_VERSION_CLIENT' => $BotBanishSettings['BOTBANISH_VERSION_CLIENT'],
					'BOTBANISH_VERSION_SERVER' => $BotBanishSettings['BOTBANISH_VERSION_SERVER'],
					'BOTBANISH_VERSION_DATABASE' => $BotBanishSettings['BOTBANISH_VERSION_DATABASE'],
					'BOTBANISH_APACHE_VERSION' => $BotBanishSettings['BOTBANISH_APACHE_VERSION'],
					'BOTBANISH_VERSION_NO' => $BotBanishSettings['BOTBANISH_VERSION_NO'],
					'BOTBANISH_VERSION_PHP' => $BotBanishSettings['BOTBANISH_VERSION_PHP'],
					'BOTBANISH_VERSION' => $BotBanishSettings['BOTBANISH_VERSION'],
					);

	$system = BotBanishCheckSystem();
	$sql = '';

	// Make sure no database information is retained in the database.

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

		case 'SERVER':

			$sql .= 'DELETE FROM `bbs_botbanishserver_settings` WHERE `name` LIKE "%BOTBANISH_DB%";' . PHP_EOL;
			break;
			
		case 'CLIENT':

			$sql = 'DELETE FROM `bbc_botbanishclient_settings` WHERE `name` LIKE "%BOTBANISH_DB%";' . PHP_EOL;
			break;
	}

	BotBanishExecuteSQLAsync($sql);

	$updates = array_merge($updates, $update);
	return $updates;
}

function BotBanishPreInstallCleanUp($installDir) {

	// Make sure no settings files exist or installation may fail.

	$filenames = array(
						'BotBanish_Settings.php',
						'Settings_Client.php',
						'Settings_Server.php',
					);

	foreach ($filenames as $filename) {

		$name = $installDir . $filename;

		if (file_exists($name))
			unlink($name);
	}
}
?>