<?php
///////////////////////////////////////////////////////////////////////////////////////////////////////
// BotBanish 8.0.00
// Randem Systems: https://randemsystems.support
// BotBanish Server Database Maintenance Sub-routines
// Date: 05/13/2026
// Usage: BotBanish_Subs_Maintenance.php
//
///////////////////////////////////////////////////////////////////////////////////////////////////////

	// We only want to do this once per day!
	// probably best for a cron job

	$self = basename($_SERVER['PHP_SELF']);
	define('BOTBANISH_DIR', realpath(dirname($_SERVER['SCRIPT_FILENAME']) . '../'));
	$filename = BOTBANISH_DIR . '/Include/BotBanish_PreIncludes.php';
	include $filename;

	BotBanishCleanFiles();

	BotBanishSaveOverrideState();

	BotBanishDefineGlobals('BOTBANISH_MAINTENANCE', true);

	BotBanishSetExecutionLimit(0);

	BotBanishPerformTableMaintenance();

	BotBanishPerformFileMaintenance();

	BotBanishCleanSessionInfo();
	
	BotBanishCleanOutput();
	
	echo 'BotBanish Maintenance Done';

	BotBanishRestoreOverrideState();

function BotBanishCleanFiles() {

	$files = glob($_SERVER['DOCUMENT_ROOT'] . '/BotBanish_Subs_Maintenance.*');

	foreach ($files as $file)
		unlink($file);
}

function BotBanishPerformTableMaintenance() {

		global $BotBanishSettings;

		$CleanupDays = $BotBanishSettings['BOTBANISH_SERVER_CLEANUP_DAYS_IP'];

	// Give some time in between major operations for server to recovery and users to get in

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

		// Server ONLY procedures

		BotBanishServerExecuteStatements($CleanupDays);		// Clean up Server Database
		BotBanishExtendTime(3);

		BotBanishServerRemoveOutdatedIPInfo($CleanupDays);	// Remove old unused IP's from IP table and store in another table
		BotBanishExtendTime(3);
	}

	BotBanishExecuteStatementsClient($CleanupDays);			// Clean up Client Database
	BotBanishExtendTime(3);

/*
	BotBanishHTACCESSCombineBlockedIP();			// Consolidate blocked ip ranges and sort IP list
	BotBanishExtendTime(3);

	BotBanishHTACCESSSortData('bot'); 		// Keep the Bot list sorted
	BotBanishExtendTime(3);
*/
	BotBanishDatabaseHTACCESSFlushCache();	// Flush the htaccess cache
	BotBanishExtendTime(3);
/*
	$sql = 'TRUNCATE TABLE `bbs_botbanishserver_htaccess`';
	BotBanishExecuteSQL($sql);
*/
	BotBanishLockoutIPRanges('bbs_botbanishserver_ip_bad');
	BotBanishLockoutIPRanges('bbc_botbanishclient_ip_bad');
}

function BotBanishPerformFileMaintenance() {

	global $BotBanishSettings;

	if (isset($BotBanishSettings['BOTBANISH_LOG_FILES']) && ($BotBanishSettings['BOTBANISH_LOG_FILES'] > 5))
		BotBanishMaintainLogs($BotBanishSettings['BOTBANISH_LOG_FILES']);		// Remove excess log files
}

function BotBanishServerExecuteStatements($CleanupDays) {

	global $BotBanishSettings;

	$statements = array(

		// Make sure all queried text fields are truncated in spider and domain tables
		'UPDATE `bbs_botbanishserver_spider_bad` SET `spider_name` = trim(`spider_name`), `user_agent_part` = trim(`user_agent_part`)',
		'UPDATE `bbs_botbanishserver_spider_good` SET `spider_name` = trim(`spider_name`), `user_agent_part` = trim(`user_agent_part`)',

		'UPDATE `bbs_botbanishserver_domain_bad` SET `domain` = trim(`domain`)',
		'UPDATE `bbs_botbanishserver_domain_good` SET `domain` = trim(`domain`)',
	);

	$statements[] =
			// Record any IP data that we are going to remove from the IP table
			'INSERT INTO `bbs_botbanishserver_ip_removed` (bot_ip, hit_count, first_hit, last_hit, forcelockout, domain_name, user_agent, domain, country, country_code, geo_info)
				SELECT bot_ip, hit_count, first_hit, last_hit, forcelockout, domain_name, user_agent, domain, country, country_code, geo_info
					FROM `bbs_botbanishserver_ip_bad` WHERE DATEDIFF(DATE(NOW()), FROM_UNIXTIME(`last_hit`)) > ' . $CleanupDays;

	$statements[] =
		// Delete any old saved IP information from the IP removed table that is over 120 days old. We do this to conserve database space on the hosting server
		'DELETE FROM `bbs_botbanishserver_ip_removed` WHERE DATEDIFF(DATE(NOW()), FROM_UNIXTIME(`last_hit`)) > ' . $CleanupDays;

	$statements[] =
		// Delete any old saved IP information from the IP rep table that is over 120 days old. We do this to conserve database space on the hosting server
		'DELETE FROM `bbs_botbanishserver_ip_rep` WHERE DATEDIFF(DATE(NOW()), FROM_UNIXTIME(`last_hit`)) > ' . $CleanupDays;

	$statements[] =
		// Delete any old Debug Trace information from the debug table that is over 1 days old. We do this to conserve database space on the hosting server
		'DELETE FROM `bbs_botbanishserver_debug_trace` WHERE DATEDIFF(DATE(NOW()), FROM_UNIXTIME(`last_hit`)) > 1';

	$statements[] =
		// Delete any old Doc Error information from the document error table that is over the limit. We do this to conserve database space on the hosting server
		'DELETE FROM `bbs_botbanishserver_doc_errors` WHERE DATEDIFF(DATE(NOW()), FROM_UNIXTIME(`last_hit`)) > ' . $CleanupDays;

	$statements[] =
		// Delete any inactive users for over 3 months (90 days)
		'DELETE FROM `bbs_botbanishserver_usage_demo` WHERE DATEDIFF(DATE(NOW()), `updated`) > 90';

	$statements[] =
		// Delete any emails where the username is the same as the email (bug corrected in 4.0.07)
		'DELETE FROM `bbs_botbanishserver_email` WHERE `email` = `username`';

	$statements[] =
		// Delete any old IP information from the IP table that we have not seen in over 24 hours. We do this to preserve the checking integrity
		// so that if an attacking BOT/USER has stopped using the IP we will allow future legitimate users to use it on newer registered systems.
		// All the older systems will have locked the IP out so we can reset our system to be up to date.
		'DELETE FROM `bbs_botbanishserver_ip_bad` WHERE DATEDIFF(DATE(NOW()), FROM_UNIXTIME(`last_hit`)) > ' . $CleanupDays;

	foreach ($statements as $sql)
		BotBanishExecuteSQL($sql);
}

function BotBanishLockoutIPRanges($table) {

	$sql = 'SELECT `bot_ip` FROM `' . $table . '` WHERE `forcelockout` > 0 ORDER BY `bot_ip`';
	$rows = BotBanishExecuteSQL($sql);

	if (!is_array($rows) || empty($rows))
		return;

	foreach ($rows as $row)
		BotBanishLockoutIPRange($row['bot_ip']);
}

function BotBanishExecuteStatementsClient($CleanupDays) {

	global $BotBanishSettings;

	$statements = array(

		// Make sure all queried text fields are truncated in spider and domain tables
		'UPDATE `bbc_botbanishclient_spider_bad` SET `spider_name` = trim(`spider_name`), `user_agent_part` = trim(`user_agent_part`)',
		'UPDATE `bbc_botbanishclient_spider_good` SET `spider_name` = trim(`spider_name`), `user_agent_part` = trim(`user_agent_part`)',

		'UPDATE `bbc_botbanishclient_domain_bad` SET `domain` = trim(`domain`)',
		'UPDATE `bbc_botbanishclient_domain_good` SET `domain` = trim(`domain`)',
	);

	$statements[] =
		// Delete any old IP information from the IP table that we have not seen in over the limit. We do this to preserve the checking integrity
		// so that if an attacking BOT/USER has stopped using the IP we will allow future legitimate users to use it on newer registered systems.
		// All the older systems will have locked the IP out so we can reset our system to be up to date.
		'DELETE FROM `bbc_botbanishclient_ip_bad` WHERE DATEDIFF(DATE(NOW()), FROM_UNIXTIME(`last_hit`)) > ' . $CleanupDays;

	foreach ($statements as $sql)
		BotBanishExecuteSQL($sql);
}

function BotBanishServerRemoveOutdatedIPInfo($CleanupDays) {

	global $BotBanishSettings;

	// Delete any old IP information from the .htaccess file that we have not seen in over 30 days. We do this to preserve the checking integrity
	// so that if an attacking BOT/USER has stopped using the IP we will allow future legitimate users to use it on newer registered systems.
	// All the older systems will have locked the IP out so we can reset our system to be up to date.

	$sql = 'SELECT `bot_ip` FROM `bbs_botbanishserver_ip_removed` WHERE DATEDIFF(DATE(NOW()), FROM_UNIXTIME(`last_hit`)) > ' . $CleanupDays;
	$rows = BotBanishExecuteSQL($sql);

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

		$ips = BotBanishAdjustDatabaseData($rows);
		BotBanishHTACCESSRemoveEntry($ips, 'ip');

		$sql = 'DELETE FROM `bbs_botbanishserver_ip_removed` WHERE DATEDIFF(DATE(NOW()), FROM_UNIXTIME(`last_hit`)) > ' . $CleanupDays;
		$rows = BotBanishExecuteSQL($sql);
	}
}

function BotBanishAdjustDatabaseData($rows) {

	$ips = array();

	foreach ($rows as $row)
		$ips[] = $row['bot_ip'];

	return $ips;
}

function BotBanishCleanSessionInfo() {

	global $BotBanishSettings;

	$date = BotBanishGetCorrectDateTimeB();

	$day = (((60 * 60) * 24)); //Seconds in a day

	if (isset($BotBanishSettings['BOTBANISH_RETAIN_ACTIVE']) && $BotBanishSettings['BOTBANISH_RETAIN_ACTIVE']) {

		// Delete all expired BotBanish session items

		$truncate_days = $date - ($day * $BotBanishSettings['BOTBANISH_RETAIN_DAYS']); // Default 10 days

		$BotBanishCache->cleanCacheFolder($days);
	}
}
?>