<?php
///////////////////////////////////////////////////////////////////////////////////////////////////////
// BotBanish 9.0.02
// Randem Systems: https://randemsystems.support
// BotBanish Prepare Cache Upload File
// Date: 07/11/2026
// Usage:
//
///////////////////////////////////////////////////////////////////////////////////////////////////////

function BotBanishPrepareCacheFile() {

	$cacheFile = BotBanishGetCacheFile();

	if (file_exists($cacheFile)) {

		global $BotBanishSettings;
		
		require $BotBanishSettings['BOTBANISH_SUBS_DIR'] . 'BotBanish_FileUpload.php';
		BotBanishUploadCacheFile('', $BotBanishSettings['BOTBANISH_STATIC_TEMP_DIR'], 'zip', false);
	}
}

function BotBanishGetCacheFile() {

	global $BotBanishSettings;

	$table = 'bbc_botbanishclient_geo';

	// If the "Uploaded" field does not exist, create it with the index.

	$table_columns = BotBanishGetTableColumns($table);
	$field = 'uploaded';
	$zipFile = false;

	if (!isset($table_columns[$field])) {

		$sql = 'ALTER TABLE `' . $table . '` ADD `' . $field . '` INT NOT NULL DEFAULT "0" AFTER `updated`';
		BotBanishExecuteSQL($sql, true, true);

		$sql = 'ALTER TABLE `' . $table . '` ADD KEY `' . $field . '` (`' . $field . '`)';
		BotBanishExecuteSQL($sql, true, true);
	}

	$sql = 'SELECT `bot_ip`, `country`, `country_code`, `geo_info` FROM `' . $table . '` WHERE `' . $field . '` = false AND `country` != ""';
	$rows = BotBanishExecuteSQL($sql, true, true);

	if (!empty($rows)) {

		$basename = 'BotBanish_Cache_' . BotBanishGetCorrectDateTimeB();
		$filename = $BotBanishSettings['BOTBANISH_STATIC_TEMP_DIR'] . $basename . '.php';
		$str = '<?php' . PHP_EOL . '$cacheData = ' . var_export($rows, true) . ';' . PHP_EOL . 'return $cacheData;' . PHP_EOL . '?>';

		if (file_exists($filename))
			unlink($filename);

		BotBanishWriteFile($filename, $str);

		$zipFile = $BotBanishSettings['BOTBANISH_STATIC_TEMP_DIR'] . $basename . '.zip';
		$selections = array($filename);
		
		ZipArchiveIt($selections, $zipFile);
		
		// Update all rows that we have processed
		
		foreach ($rows as $row) {

			$sql = 'UPDATE `' . $table . '` SET `uploaded` = 1 WHERE `bot_ip` = "' . $row['bot_ip'] . '"';
			BotBanishExecuteSQL($sql);
		}

		if (file_exists($filename))
			unlink($filename);
	}

	return $zipFile;
}
?>