<?php
///////////////////////////////////////////////////////////////////////////////////////////////////////
// BotBanish 9.0.05
// Randem Systems: https://randemsystems.support
// Delete All BotBanish Data, Tables and Files
// Date: 08/02/2026
// Usage: require_once BotBanishDeleteTableData.php
//
///////////////////////////////////////////////////////////////////////////////////////////////////////

function BotBanishUninstallSetGlobals() {

	global $BotBanishSettings;
	
	switch (INTERNAL) {

		case true:

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

				if (!defined($key))
					define($key, $value);
			}

			break;

		case false:

			$char = '*';
			$start = str_repeat($char . ' ', 5);
			$end = str_repeat(' ' . $char, 5);
			$section = '# %s%s%s';

			BotBanishUninstallDefineGlobals('BOTBANISH_CODE_START', '# * * * * * BotBanish CODE Start * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_CODE_END', '# * * * * * BotBanish CODE End * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_RULE_START', '# * * * * * BotBanish RULES Start * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_RULE_END', '# * * * * * BotBanish RULES End * * * * *');

			BotBanishUninstallDefineGlobals('BOTBANISH_XMLRPC_START', '# * * * * * BotBanish XMLRPC Start * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_XMLRPC_END', '# * * * * * BotBanish XMLRPC End * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_HTACCESS_START', '# * * * * * BotBanish HTACCESS Start * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_HTACCESS_END', '# * * * * * BotBanish HTACCESS End * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_WPCONFIG_START', '# * * * * * BotBanish WPCONFIG Start * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_WPCONFIG_END', '# * * * * * BotBanish WPCONFIG End * * * * *');

			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_REWRITE_BLACKLIST_START', sprintf($section, $start, 'BotBanish BOT Blacklist Start (REWRITECOND)', $end));
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_REWRITE_BLACKLIST_END', sprintf($section, $start, 'BotBanish BOT Blacklist End (REWRITECOND)', $end));
			
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_REWRITE_WHITELIST_START', sprintf($section, $start, 'BotBanish BOT Whitelist Start (REWRITECOND)', $end));
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_REWRITE_WHITELIST_END', sprintf($section, $start, 'BotBanish BOT Whitelist End (REWRITECOND)', $end));

			// BotBanish .htaccess tags

			// IP Blacklist
			
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_IP_BLACKLIST_START', '# * * * * * BotBanish IP Blacklist Start * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_IP_BLACKLIST_END', '# * * * * * BotBanish IP Blacklist End * * * * *');
			
			BotBanishUninstallDefineGlobals('BOTBANISH_REWRITECOND_BLACKLIST_START', PHP_EOL . 'RewriteCond %{HTTP_USER_AGENT}' . PHP_EOL);
			BotBanishUninstallDefineGlobals('BOTBANISH_REWRITECOND_BLACKLIST_END', PHP_EOL . 'RewriteRule .* - [G,L,F]' . PHP_EOL);
				
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_IP_BLACKLIST_START_2_4', $BotBanishSettings['BOTBANISH_TAG_IP_BLACKLIST_START']);
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_IP_BLACKLIST_END_2_4', $BotBanishSettings['BOTBANISH_TAG_IP_BLACKLIST_END']);
			
			// IP Whitelist
			
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_IP_WHITELIST_START', '# * * * * * BotBanish IP Whitelist Start * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_IP_WHITELIST_END', '# * * * * * BotBanish IP Whitelist End * * * * *');

			BotBanishUninstallDefineGlobals('BOTBANISH_REWRITECOND_WHITELIST_START', PHP_EOL . 'RewriteCond %{HTTP_USER_AGENT}' . PHP_EOL);
			BotBanishUninstallDefineGlobals('BOTBANISH_REWRITECOND_WHITELIST_END', PHP_EOL . 'RewriteRule .* - [S=1]' . PHP_EOL);

			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_IP_WHITELIST_START_2_4', $BotBanishSettings['BOTBANISH_TAG_IP_WHITELIST_START']);
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_IP_WHITELIST_END_2_4', $BotBanishSettings['BOTBANISH_TAG_IP_WHITELIST_END']);
				
			// BOT Blacklist
			
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_BLACKLIST_START', '# * * * * * BotBanish BOT Blacklist Start * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_BLACKLIST_END', '# * * * * * BotBanish BOT Blacklist End * * * * *');

			BotBanishUninstallDefineGlobals('BOTBANISH_BOT_REWRITECOND_BLACKLIST_2_4', 'RewriteCond %%{HTTP_USER_AGENT} ');
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_BLACKLIST_START_2_4', $BotBanishSettings['BOTBANISH_TAG_BOT_BLACKLIST_START']);
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_BLACKLIST_END_2_4', $BotBanishSettings['BOTBANISH_TAG_BOT_BLACKLIST_END']);

			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_REWRITECOND_BLACKLIST_START_2_4', sprintf($section, $start, 'BotBanish BOT Blacklist Start (REWRITECOND)', $end));
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_REWRITECOND_BLACKLIST_END_2_4', sprintf($section, $start, 'BotBanish BOT Blacklist End (REWRITECOND)', $end));

			// BOT Whitelist
			
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_WHITELIST_START', '# * * * * * BotBanish BOT Whitelist Start * * * * *');
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_WHITELIST_END', '# * * * * * BotBanish BOT Whitelist End * * * * *');

			BotBanishUninstallDefineGlobals('BOTBANISH_BOT_REWRITECOND_WHITELIST_2_4', 'RewriteCond %%{HTTP_USER_AGENT} ');
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_WHITELIST_START_2_4', $BotBanishSettings['BOTBANISH_TAG_BOT_WHITELIST_START']);
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_WHITELIST_END_2_4', $BotBanishSettings['BOTBANISH_TAG_BOT_WHITELIST_END']);

			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_REWRITECOND_WHITELIST_START_2_4', sprintf($section, $start, 'BotBanish BOT Whitelist Start (REWRITECOND)', $end));
			BotBanishUninstallDefineGlobals('BOTBANISH_TAG_BOT_REWRITECOND_WHITELIST_END_2_4', sprintf($section, $start, 'BotBanish BOT Whitelist End (REWRITECOND)', $end));
	
			break;
	}
}

function BotBanishUninstallDefineGlobals($variable, $value, $global = false) {
	global $BotBanishSettings;

	// Defines cannot be redefined (they are static) but we can update the BotBanish Settings array for dynamic changes

	$value = is_numeric($value) ? intval($value) : $value;

	if ($global) {

		if (!defined($variable))
			define($variable, $value);
	}

	$BotBanishSettings[$variable] = $value;
}

function BotBanishUninstallRemoveCode() {

	BotBanishUninstallDisplayIt( 'BotBanish Code Removal Started<br>');

	global $BotBanishSettings, $sourcedir, $boarddir;

	$items = array(
		array(
			'type' => 'rules',
			'rules' => array(
				array('rule_start' => '// ' . $BotBanishSettings['BOTBANISH_CODE_START'], 'rule_end' => '// ' . $BotBanishSettings['BOTBANISH_CODE_END']),
			)
		)
	);

	// Remove BotBanish code from all modified files

	$files = array(

		$sourcedir . '/QueryString.php',
		$boarddir . '/index.php',
		$sourcedir . '/LogInOut.php',
	);

	foreach ($files as $file) {

		if (BotBanishUninstallUnModifyRuleBlocks($file, $items))
			BotBanishUninstallDisplayIt( '&emsp;File: ' . $file . '<br>');
	}

	// Remove BotBanish code from all modified templates in all Themes

	$themedir = $boarddir . '/Themes/';
	$dirs = glob($themedir . '*', GLOB_ONLYDIR);

	$files = array(

		'/Register.template.php',
		'/index.template.php',
		'/Packages.template.php',
		'/Profile.template.php',
	);

	foreach ($dirs as $dir) {

		foreach ($files as $file) {

			$filename = $dir . $file;

			if (BotBanishUninstallUnModifyRuleBlocks($filename, $items));
				BotBanishUninstallDisplayIt( '&emsp;File: ' . $filename . '<br>');
		}
	}

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

function BotBanishUninstallUnModifyRuleBlocks($filename, $items) {

	if (!file_exists($filename))
		return false;

	$source = BotBanishUninstallReadFile($filename);

	if (empty($source))
		return;

	foreach ($items as $item) {

		switch($item['type']) {

			case 'data':

				$source = BotBanishUninstallRemoveData($item , $source);

				break;

			case 'rules':

				foreach ($item['rules'] as $rule)
					$source = BotBanishUninstallRemoveRuleBlock("\n\t" . $rule['rule_start'] . "\n", "\n\t" . $rule['rule_end'] . "\n", $source);

				break;
		}
	}

	BotBanishUninstallWriteFile($filename, $source);
	return true;
}

function BotBanishUninstallRemoveRuleBlock($start_entry, $end_entry, $source_data) {

	$lines = explode($start_entry, $source_data);
	$str = '';

	foreach ($lines as $line) {

		$items = explode($end_entry, $line);

		if (count($items) < 2)

			$str .= $line;
		else
			$str .= $items[1];
	}

	return $str;
}

function BotBanishUninstallRemoveData($data, $source) {

	if (!is_array($data))
		$data = array($data);

	str_replace($data, '', $source);
	return $source;
}

function BotBanishUninstallRemovePackageList() {

	global $boarddir, $db_prefix, $context;

	// Remove all evidence of package Last in First Out

	if (!defined('SMF_VERSION')) {

		$sql = 'SELECT `value` FROM ' . $db_prefix . 'settings WHERE `variable` = "smfVersion"';
		$rows = BotBanishUninstallExecuteSQL($sql);

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

			BotBanishUninstallDisplayIt('No SMF Version Present');
			exit;
		}

		define('SMF_VERSION', $rows[0]['value']);
		define('SMF_FULL_VERSION', 'SMF ' . SMF_VERSION);
	}

	$sql = 'SELECT id_install, filename, package_id, name, version, id_member_installed, member_installed,
					time_installed, id_member_removed, member_removed, time_removed, install_state, failed_steps, themes_installed, db_changes
					FROM ' . $db_prefix . 'log_packages WHERE filename LIKE "%BotBanish%"
					ORDER BY time_installed DESC';

	$rows = BotBanishUninstallExecuteSQL($sql);

	// If no information is found in the log_packages table;
	// scan the package folder for an archive file to use for uninstall

	if (!is_array($rows)) {

		$files = glob($boarddir . '/Packages/BotBanish*');
		rsort($files, SORT_STRING);
		$rows = array();
		$i = 0;

		foreach ($files as $file) {

			$rows[$i]['id_install'] = 99999;
			$rows[$i]['filename'] = $file;
			$rows[$i]['package_id'] = 99999;
			$rows[$i]['name'] = $file;
			$rows[$i]['version'] = 99999;
			$rows[$i]['id_member_installed'] = 0;
			$rows[$i]['member_installed'] = 0;
			$rows[$i]['time_installed'] = time();
			$rows[$i]['id_member_removed'] = 0;
			$rows[$i]['member_removed'] = 'Admin';
			$rows[$i]['time_removed'] = time();
			$rows[$i]['install_state'] = 1;
			$rows[$i]['failed_steps'] = BotBanishUninstallSafeSerialize(array());
			$rows[$i]['themes_installed'] = 1;
			$rows[$i]['db_changes'] = '';
		}
	}

	foreach ($rows as $row) {

		$context['themes_locked'] = true;

//		PackageUninstall($row);

		if (!file_exists($boarddir . 'Packages/' . $row['filename'])) {

			$sql = 'DELETE FROM ' . $db_prefix . 'log_packages WHERE id_install = "' . $row['id_install'] . '"';
			BotBanishUninstallExecuteSQL($sql);
		}
	}

	$context['themes_locked'] = false;
}

function BotBanishUninstallCleanupHTACCESS($dir) {

	BotBanishUninstallDisplayIt('BotBanish .htaccess File Cleanup Started<br>');

	global $BotBanishSettings;
	
	//=================================================================================================
	// Check to see if we have information in the .htaccess file, if so we will try to remove it
	//=================================================================================================

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

		$htaccess_array = BotBanishUninstallGetHTACCESSLocations();
	else
		$htaccess_array = BotBanishGetHTACCESSLocations();
	
	foreach ($htaccess_array as $htaccess_folder) {

		// Backup .htaccess file is it exists

		$filename = $htaccess_folder . '.htaccess';

		if (!file_exists($filename)) {

			BotBanishUninstallDisplayIt('&emsp;.htaccess file not found - ' . $filename . '<br>');
			continue;
		}

		copy($filename, $filename . BotBanishUninstallGetTimeExtension());

		$htaccess_data = BotBanishUninstallHTACCESSReadFile($filename);

		// Attempt the group entry

		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_HTACCESS_START'], $BotBanishSettings['BOTBANISH_HTACCESS_END'], $htaccess_data);
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_XMLRPC_START'], $BotBanishSettings['BOTBANISH_XMLRPC_END'], $htaccess_data);
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_WPCONFIG_START'], $BotBanishSettings['BOTBANISH_WPCONFIG_END'], $htaccess_data);

		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_RULE_START'], $BotBanishSettings['BOTBANISH_RULE_END'], $htaccess_data);
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_CODE_START'], $BotBanishSettings['BOTBANISH_CODE_END'], $htaccess_data);
		
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_TAG_BOT_REWRITE_BLACKLIST_START'], $BotBanishSettings['BOTBANISH_TAG_BOT_REWRITE_BLACKLIST_END'], $htaccess_data);
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_TAG_BOT_REWRITE_WHITELIST_START'], $BotBanishSettings['BOTBANISH_TAG_BOT_REWRITE_WHITELIST_END'], $htaccess_data);
		
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_TAG_IP_BLACKLIST_START'], $BotBanishSettings['BOTBANISH_TAG_IP_BLACKLIST_END'], $htaccess_data);
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_TAG_BOT_BLACKLIST_START'], $BotBanishSettings['BOTBANISH_TAG_BOT_BLACKLIST_END'], $htaccess_data);
		
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_TAG_IP_BLACKLIST_START_2_4'], $BotBanishSettings['BOTBANISH_TAG_IP_BLACKLIST_END_2_4'], $htaccess_data);
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_TAG_BOT_BLACKLIST_START_2_4'], $BotBanishSettings['BOTBANISH_TAG_BOT_BLACKLIST_END_2_4'], $htaccess_data);
		
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_TAG_IP_WHITELIST_START_2_4'], $BotBanishSettings['BOTBANISH_TAG_IP_WHITELIST_END_2_4'], $htaccess_data);
		$htaccess_data = BotBanishUninstallHTACCESSRemoveRuleBlock($BotBanishSettings['BOTBANISH_TAG_BOT_WHITELIST_START_2_4'], $BotBanishSettings['BOTBANISH_TAG_BOT_WHITELIST_END_2_4'], $htaccess_data);

		BotBanishUninstallHTACCESSWriteFile($htaccess_data, array(), $filename);
		BotBanishUninstallDisplayIt('&emsp;Cleaning ' . $filename . '<br>');
	}

	BotBanishUninstallDisplayIt( 'BotBanish .htaccess File Cleanup Complete<br><br>');
}

function BotBanishUninstallHTACCESSRemoveRuleBlock($start_entry, $end_entry, $htaccess_data) {

	if (empty($htaccess_data)) return $htaccess_data;

	$entries = array($start_entry, $end_entry);
	$new_entries = array();

	$entries = array_merge($entries, $new_entries);
	$tags = array();

	foreach ($entries as $key => $value)
		$tags[$key] = array_keys($htaccess_data, $value, false);

	$i = 0;
	$index = array();

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

		if (!empty($tags[$key])) {

			foreach ($value as $key1 => $value1)
				$index[$value1] = $value1;
		}
	}

	ksort($index);

	$num = count($index);

	if (intval($num / 2) != ($num / 2)) {

		BotBanishUninstallDisplayIt('Mis-Matched Begin/End Markers Found - Begin: ' . $start_entry . ' - End: ' . $end_entry);
		return;
	}

	$start = 0;
	$end = 0;

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

		$end = empty($end) && !empty($start) ? $value : $end;
		$start = empty($start) ? $value : $start;

		if (!empty($end)) {

			for ($i = $start; $i <= $end; $i++)
				unset ($htaccess_data[$i]);

			$start = 0;
			$end = 0;
		}
	}

	return $htaccess_data;
}

function BotBanishUninstallHTACCESSReadFile($htaccess_name = '') {

	$lines = array();

	if (file_exists($htaccess_name))
		$lines = file($htaccess_name, FILE_IGNORE_NEW_LINES);

	return $lines;
}

function BotBanishUninstallHTACCESSWriteFile($htaccess_data, $lines, $htaccess_name = '') {

	if (empty($htaccess_name))
		return;

	// If the files folder does not already exist, do NOTHING!!!

	$dir = str_ireplace(basename($htaccess_name), '', $htaccess_name);

	if (!is_dir($dir))
		return;

	$lines = !is_array($lines) ? array($lines) : $lines;
	$htaccess_data = !is_array($htaccess_data) ? array($htaccess_data) : $htaccess_data;

	// Write the new file

	$htaccess_data = array_merge($lines , $htaccess_data);
	$data = implode(PHP_EOL, $htaccess_data);

	$file = fopen($htaccess_name, 'w');

	if (isset($file)) {

		$output = BotBanishUninstall_UTF8_Encode ($data);
		$output = BotBanishUninstallRemoveExtraCRLF($output);

		fwrite ($file, trim($output));
		fflush($file);
		fclose($file);
	}
}

function BotBanishUninstall_UTF8_Encode(string $str): string {

	if (function_exists('mb_convert_encoding')) {

		$output = mb_convert_encoding($str, 'UTF-8', mb_list_encodings());

	} else {

		if (function_exists('iconv')) {

			$output = iconv('ISO-8859-1', 'UTF-8', $str);

		} else {

			$str .= $str;
			$len = strlen($str);

			for ($i = $len >> 1, $j = 0; $i < $len; ++$i, ++$j) {

				switch (true) {

					case $str[$i] < "\x80": $str[$j] = $str[$i]; break;
					case $str[$i] < "\xC0": $str[$j] = "\xC2"; $str[++$j] = $str[$i]; break;
					default: $str[$j] = "\xC3"; $str[++$j] = \chr(\ord($str[$i]) - 64); break;
				}
			}

			$output = substr($str, 0, $j);
		}
	}

    return $output;
}

function BotBanishUninstallRemoveExtraCRLF($data) {

	$data = str_replace('<br>' . '<br>' . '<br>', '<br>', $data);
	return $data;
}

function BotBanishUninstallDeleteDirectorySPL($dir) {

    if (!is_dir($dir))
        return false;

    $iterator = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST);

    foreach ($files as $fileinfo) {

        if ($fileinfo->isDir())

            rmdir($fileinfo->getRealPath());
        else
            unlink($fileinfo->getRealPath());
    }

    return rmdir($dir);
}

function BotBanishUninstallFolderDeletion($folders) {

	BotBanishUninstallDisplayIt('BotBanish Folder Deletion Started<br>');

	$folders = array_unique($folders);

	foreach ($folders as $folder) {

//		BotBanishUninstallDisplayIt( '&emsp;Folder: ' . $folder . '<br>');
		BotBanishUninstallDeleteFolder(rtrim($folder, '/') . '/');
	}

	BotBanishUninstallDisplayIt( 'BotBanish Folder Deletion Complete<br><br>');
	return $folders;
}

function BotBanishUninstallDeleteFolder($dirPath) {

	if (BotBanishUninstallDeleteDirectorySPL($dirPath))

		BotBanishUninstallDisplayIt("&emsp;Directory deleted successfully - " . $dirPath . '<br>');
	else
		BotBanishUninstallDisplayIt("&emsp;Directory does not exist - " . $dirPath . '<br>');
}

function BotBanishUninstallFileDeletion($folders) {

	BotBanishUninstallDisplayIt('BotBanish File Deletion Started<br>');

	// Attempt to cleanup all files that we may have installed or created that may have been left behind

	$files = array(
		'BotBanish_RegisterAccount.html',
		'BotBanish_RegisterAccount.php',
		'Settings_Client.php',
		'BotBanish_Settings.php',
	);

	switch (SYSTEM) {

		case 'WORDPRESS':

			$files[] = 'BotBanish_WP_Settings.php';
			$folders[] = ABSPATH;
			break;

		case 'SMF':

			global $boarddir;

			$folders[] = $boarddir;
			$addFiles = array('DatabaseIntegrate.php',
								'DatabaseDeIntegrate.php',
								'BotBanishIntegrate.php',
								'BotBanishDeIntegrate.php',
								'BotBanishIntegrate.php',
							);
			$files = array_merge($files, $addFiles);
			break;
	}

	$folders = array_unique($folders);

	$deleted = 0;

	if (!empty($folders)) {

		foreach ($folders as $folder) {

			foreach ($files as $file) {

				$filename = $folder . '/' . $file;

				if (file_exists($filename)) {

					$deleted++;
					unlink($filename);
					BotBanishUninstallDisplayIt('&emsp;Deleted - ' . $filename . '<br>');
				}
			}
		}

	}

	if (!$deleted)
		BotBanishUninstallDisplayIt('&emsp;No Files to Remove<br>');

	BotBanishUninstallDisplayIt( 'BotBanish File Deletion Complete<br><br>');
}


function BotBanishUninstallReadFile($filename) {

	global $BotBanishText;

	$data = '';

	if (file_exists($filename) && (filesize($filename) > 0)){

		$data = file_get_contents($filename);
	}else{
		BotBanishUninstallDisplayIt($filename . $BotBanishText['BotBanish_NotFound'] . '<br>');
	}

	return $data;
}

function BotBanishUninstallWriteFile($filename, $data, $append = false) {

	if (empty($filename)) {

		BotBanishUninstallLogError('BotBanishUninstallWriteFile() - No filename present', '', 'Error');
		return;
	}

	if (empty($data)) {

		BotBanishUninstallLogError('BotBanishUninstallWriteFile() - No data present', '', 'Error');
		return;
	}

	$data = BotBanishUninstall_EncodeToUtf8($data);

	$folder = dirname($filename) . '/';
	if (!is_dir($folder)) @mkdir ($folder, 0755, true);

	if (!file_exists($filename)) $append = false;

	if ($append)

		$bytes = file_put_contents($filename, $data, FILE_APPEND);
	else
		$bytes = file_put_contents($filename, $data);
}

function BotBanishUninstall_EncodeToUtf8($string) {
     return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}

function BotBanishUninstall_EncodeToIso($string) {
     return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}

function BotBanishUninstallSafeUnserialize($data) {

	if (BotBanishUninstallIsSerialized($data)) {

		$tmp = stripslashes($data);
		BotBanishUninstallRestoreErrorHandler();
		$str = @unserialize($tmp);
		BotBanishUninstallSetErrorHandler();

		if (!is_array($str))
			$str = unserialize($data);

		if (!is_array($str)) {

			BotBanishUninstallDisplayIt('Unserialization Error: ' . $data . '<br>' . '<br>' . '$tmp = ' . $tmp . '<br>' . '<br>' . '$str = ' . $str);
			$str = array();
		}

	} else {

		$str = $data;
	}

	return $str;
}

function BotBanishUninstallSafeSerialize($data) {

	$str = $data;

	if (!BotBanishUninstallIsSerialized($data)) {

		if (is_array($data)) {

			$str = addslashes(serialize($data));
			$tmp = unserialize(stripslashes($str));

			if (!is_array($tmp)) {

				BotBanishUninstallDisplayIt('Serialization Error: ' . $data . '<br>' . '<br>' . '$tmp = ' . $tmp . '<br>' . '<br>' . '$str = ' . $str);
				$str = array();
			}
		}
	}

	return $str;
}

function BotBanishUninstallIsSerialized( $data, $strict = true ) {

    // If it isn't a string, it isn't serialized. : ''
    if ( ! is_string( $data ) ) {
        return false;
    }
    $data = trim( $data );
    if ( 'N;' === $data ) {
        return true;
    }
    if ( strlen( $data ) < 4 ) {
        return false;
    }
    if ( ':' !== $data[1] ) {
        return false;
    }
    if ( $strict ) {
        $lastc = substr( $data, -1 );
        if ( ';' !== $lastc && '}' !== $lastc ) {
            return false;
        }
    } else {
        $semicolon = strpos( $data, ';' );
        $brace     = strpos( $data, '}' );
        // Either ; or } must exist.
        if ( false === $semicolon && false === $brace ) {
            return false;
        }
        // But neither must be in the first X characters.
        if ( false !== $semicolon && $semicolon < 3 ) {
            return false;
        }
        if ( false !== $brace && $brace < 4 ) {
            return false;
        }
    }
    $token = $data[0];
    switch ( $token ) {
        case 's':
            if ( $strict ) {
                if ( '"' !== substr( $data, -2, 1 ) ) {
                    return false;
                }
            } elseif ( false === strpos( $data, '"' ) ) {
                return false;
            }
            // Or else fall through.
        case 'a':
        case 'O':
            return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
        case 'b':
        case 'i':
        case 'd':
            $end = $strict ? '$' : '';
            return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
    }
    return false;
}

function BotBanishUninstallGetHTACCESSLocations() {

	$htaccess_array = array();

	switch (SYSTEM) {

		case 'WORDPRESS':

			$htaccess_array[] = ABSPATH;
			break;

		case 'SMF':

			global $boarddir;

			$htaccess_array[] = $boarddir . '/';
			break;
	}

	$htaccess_array[] = BOTBANISH_DIR;
	
	// No duplicate folders!
	// Insure proper slash usage!!!

	foreach ($htaccess_array as $key => $value)
		$htaccess_array[$key] = str_ireplace('\\', '/', $value);

	$htaccess_array = array_unique($htaccess_array);
	array_filter($htaccess_array);

	return $htaccess_array;
}

function BotBanishUninstallGetTimeExtension() {

	$ext = str_ireplace(array('/', '-', ':', ' '), '', BotBanishUninstallGetCorrectTime());
	return $ext;
}

function BotBanishUninstallGetCorrectTimeB() {

	return strtotime(date('H:i:s', strtotime(BotBanishUninstallGetCorrectDateTime())));
}

function BotBanishUninstallGetCorrectTime($tz = '') {

	$tz = BotBanishUninstallGetTimeZone($tz);
	$dateB = date_create(BotBanishUninstallGetCorrectDateTime($tz));
	$date = date_format($dateB, 'H:i:s');
	return $date;
}

function BotBanishUninstallGetCorrectDateTime($tz = '') {

	$tz = BotBanishUninstallGetTimeZone($tz);
	$userTimezone = new DateTimeZone($tz);
	$gmtTimezone = new DateTimeZone('GMT');
	$myDateTime = new DateTime('now', $gmtTimezone);
	$offset = $userTimezone->getOffset($myDateTime);
	$myInterval=DateInterval::createFromDateString((string)$offset . 'seconds');
	$myDateTime->add($myInterval);
	$date = $myDateTime->format('Y-m-d H:i:s');
	return $date;
}

function BotBanishUninstallGetTimeZone($tz = '') {

	$timezone = isset($_SERVER['TZ']) ? $_SERVER['TZ'] : date_default_timezone_get();

	return $timezone;
}

function BotBanishUninstallDisplayIt($data, $html = false, $append = true ) {

	if (!$html)
		$data = BotBanishUninstallGetCorrectDateTime() . '  ' . $data;

	if (!defined('SILENT')  || !SILENT)
		echo $data;

	// Contains HTML and should not be written to File
	
	if ($html)
		return;
		
	// Always write non html to log file!

	$filename = $_SERVER['DOCUMENT_ROOT'] . '/BotBanishUninstall.log';
	$data = str_ireplace(array('<br>', '</br>', '&emsp;'), array(PHP_EOL, PHP_EOL, "\t"), $data);
//	$data = preg_replace("/\n\s+/", "\n", rtrim(html_entity_decode(strip_tags($data))));
	
	if ($append)

		$bytes = file_put_contents($filename, $data, FILE_APPEND);
	else
		$bytes = file_put_contents($filename, $data);
}

function BotBanishUninstallGetFolders($delete = true) {

	switch (SYSTEM) {

		case 'WORDPRESS':

			$folders = glob(ABSPATH . '/wp-content/plugins/botbanish*', GLOB_ONLYDIR);
			
			if (empty($folders))
				$folders = glob(ABSPATH . '/wp-content/plugins/BotBanish*', GLOB_ONLYDIR);

			if (!defined('BOTBANISH_DIR')) {
				
				if (!empty($folders))

					define('BOTBANISH_DIR', realpath($folders[0]) . '/bot/');
				else
					define('BOTBANISH_DIR', ABSPATH);
			}

			$folders[] = ABSPATH . '/wp-content/BotBanish_Data/';
			break;

		case 'SMF':

			global $boarddir;

			if (!defined('BOTBANISH_DIR'))
				define('BOTBANISH_DIR', $boarddir . '/BotBanish/bot/');

			BotBanishUninstallRemoveCode();
			
			if ($delete)
				
				$folders = array($boarddir . '/BotBanish_Data/', $boarddir . '/BotBanish/');
			else
				$folders = array($boarddir . '/BotBanish/');
				
			break;

		case 'WEBSITE':

			if (!defined('BOTBANISH_DIR'))
				define('BOTBANISH_DIR', $_SERVER['DOCUMENT_ROOT'] . '/BotBanish/bot/');

			$folders = array($_SERVER['DOCUMENT_ROOT']. '/BotBanish_Data/',  $_SERVER['DOCUMENT_ROOT'] . '/BotBanish/');
			break;
	}

	return $folders;
}
?>