<?php
#  ________         ____________      _____ ________                       ________      
#  ___  __ )____  _____  /___  /_____ __  /____  __ \______________ ______ ___  __/      
#  __  __  |_  / / /__  / __  / _  _ \_  __/__  /_/ /__  ___/_  __ \_  __ \__  /_        
#  _  /_/ / / /_/ / _  /  _  /  /  __// /_  _  ____/ _  /    / /_/ // /_/ /_  __/        
#  /_____/  \__,_/  /_/   /_/   \___/ \__/  /_/      /_/     \____/ \____/ /_/           
#  ________                             _____ _____              ________                
#  __  ___/_____ ___________  _____________(_)__  /______  __    ___  __ \______________ 
#  _____ \ _  _ \_  ___/_  / / /__  ___/__  / _  __/__  / / /    __  /_/ /__  ___/_  __ \
#  ____/ / /  __// /__  / /_/ / _  /    _  /  / /_  _  /_/ /     _  ____/ _  /    / /_/ /
#  /____/  \___/ \___/  \__,_/  /_/     /_/   \__/  _\__, /      /_/      /_/     \____/ 
#                                                   /____/                               
# 42756C6C657450726F6F66 5365637572697479 50726F 
#
/*	The Copyright, AITpro Software Products License Information must remain
	intact or all BulletProof Security Pro warranties, guarantees, liabilities are void.
	
	Copyright (C) Edward Alexander, AIT-pro.com. All rights reserved.

	AITpro Software Products License Information:
	BY DOWNLOADING, INSTALLING, COPYING, ACCESSING, OR USING BulletProof Security Pro YOU AGREE TO THE TERMS OF THIS AGREEMENT. 
	IF YOU 	ARE ACCEPTING THESE TERMS ON BEHALF OF ANOTHER PERSON OR A COMPANY OR OTHER LEGAL ENTITY, YOU REPRESENT AND WARRANT
	THAT YOU HAVE FULL AUTHORITY TO BIND THAT PERSON, COMPANY, OR LEGAL ENTITY TO THESE TERMS. IF YOU DO NOT AGREE TO THESE TERMS,
	* DO NOT DOWNLOAD, INSTALL, COPY, ACCESS, OR USE BulletProof Security Pro; AND
	* PROMPTLY RETURN BulletProof Security Pro TO THE PARTY FROM WHOM YOU ACQUIRED IT. IF YOU DOWNLOADED BulletProof Security Pro
	FROM THE AITPRO WEBSITE, CONTACT AITPRO FOR A REFUND IF APPLICABLE.
	
	AITpro Software Products License Information continued:
	You agree to keep the AITpro Software Products License for BulletProof Security Pro, unmodified or altered in any way,
	with the original copy of BulletProof Security Pro that you have and any and all copies or partial copies of BulletProof
	Security Pro that You make. 
*/
// Direct calls to this file are Forbidden when core files are not present 
if ( ! current_user_can('manage_options') ) { 
		header('Status: 403 Forbidden');
		header('HTTP/1.1 403 Forbidden');
		exit();
}
	
// Setup Wizard - Add ini_set options to wp-config.php - wp-config.php will be locked by the Wizard later in the Setup process
function bpsSetupWizardIniSetOptions() {
	
	if ( current_user_can('manage_options') ) {

		$SWflockPreCheck = get_option('bulletproof_security_options_setup_wizard_flock');
		$options = get_option('bulletproof_security_options_iniSet');
		$filename = ABSPATH . 'wp-config.php';
		$permswpconfig = @substr(sprintf('%o', fileperms($filename)), -4);
		$sapi_type = php_sapi_name();
		$wpconfigBackup = WP_CONTENT_DIR . '/bps-backup/autorestore/root-files/wp-config.php';
		$subject = file_get_contents($filename);
		$pattern = '/\/\*\* BEGIN BPS Pro ini_set Settings \*\*\/(.*?)\/\*\* END BPS Pro ini_set Settings \*\*\//s';
		//$pattern2 = '/\* That\'s all, stop editing! Happy blogging. \*/';	
		$pattern2 = '/(if\s\(\s!(\s|)defined\((\s|)\'ABSPATH\'(\s|)\)\s\)(.*\s*){1}(\s|){1,}define\((\s|)\'ABSPATH\',\sdirname\((\s|)__FILE__(\s|)\)\s\.\s\'\/\'(\s|)\);)/';
		$pattern3 = '/(if\s\(\s!(\s|)defined\((\s|)\'ABSPATH\'(\s|)\)\s\)(.*\s*){1}(\s|){1,}define\((\s|)\'ABSPATH\',\s__DIR__(\s|)\.(\s|)\'\/\'(\s|)\);)/';

	$replacement = "/** BEGIN BPS Pro ini_set Settings **/
@error_reporting(".$options['bps_iniSet_ErrorReporting'].");
@ini_set('log_errors','".$options['bps_iniSet_LogErrors']."');
@ini_set('error_log','".$options['bps_iniSet_ErrorLog']."'); // add the path to your php error log
@ini_set('log_errors_max_len','".$options['bps_iniSet_LogErrorsMaxLen']."');
@ini_set('memory_limit','".$options['bps_iniSet_MemoryLimit']."');
@ini_set('session.cookie_httponly','".$options['bps_iniSet_session_cookie_httponly']."');
@ini_set('session.use_only_cookies','".$options['bps_iniSet_session_use_only_cookies']."');
@ini_set('session.cookie_secure','".$options['bps_iniSet_session_cookie_secure']."');
@ini_set('ignore_repeated_errors','".$options['bps_iniSet_IgnoreRepeatedErrors']."');
@ini_set('ignore_repeated_source','".$options['bps_iniSet_IgnoreRepeatedSource']."');
@ini_set('allow_url_include','".$options['bps_iniSet_AllowUrlInclude']."');
@ini_set('define_syslog_variables','".$options['bps_iniSet_DefineSyslogVar']."');
@ini_set('display_errors','".$options['bps_iniSet_DisplayErrors']."');
@ini_set('display_startup_errors','".$options['bps_iniSet_DisplayStartupErrors']."');
@ini_set('implicit_flush','".$options['bps_iniSet_ImplicitFlush']."');
@ini_set('magic_quotes_runtime','".$options['bps_iniSet_MagicQuotesRuntime']."');
@ini_set('max_execution_time','".$options['bps_iniSet_MaxExecutionTime']."');
@ini_set('mysql.connect_timeout','".$options['bps_iniSet_MysqlConnectTimeout']."');
@ini_set('mysql.trace_mode','".$options['bps_iniSet_MysqlTraceMode']."');
@ini_set('report_memleaks','".$options['bps_iniSet_ReportMemleaks']."');
/** END BPS Pro ini_set Settings **/";

		$successTextBegin = '<font color="green"><strong>';
		$successTextEnd = '</strong></font><br>';
		$failTextBegin = '<font color="#fb0101"><strong>';
		$failTextEnd = '</strong></font><br>';	
	
		if ( is_dir( WP_CONTENT_DIR . '/bps-backup/autorestore/root-files' ) ) {
			echo $successTextBegin.WP_CONTENT_DIR . '/bps-backup/autorestore/root-files'.__(' Folder created Successfully!', 'bulletproof-security').$successTextEnd;	
		
		} else {
		
		if ( ! is_dir( WP_CONTENT_DIR . '/bps-backup/autorestore/root-files' ) ) {
			mkdir( WP_CONTENT_DIR . '/bps-backup/autorestore/root-files', 0755, true );
			@chmod( WP_CONTENT_DIR . '/bps-backup/autorestore/root-files/', 0755 );
			echo $successTextBegin.WP_CONTENT_DIR . '/bps-backup/autorestore/root-files'.__(' Folder created Successfully!', 'bulletproof-security').$successTextEnd;
		}
	}

		if ( ! file_exists($filename) ) {
			echo '<br>'.$failTextBegin.__('Error: A wp-config.php file was NOT found in your website root folder.', 'bulletproof-security').$failTextEnd.__('If you have moved your wp-config.php file to another folder location then you will need to add the BPS Pro ini_set code to your wp-config.php file manually.', 'bulletproof-security').'<br>'.__('The BPS ini_set code can be found in this file /bulletproof-security/admin/php/php-directives-code-for-wp-config. Setup instructions are included in the file.', 'bulletproof-security').'<br>';
		}

		// This writes the ini_set code again if the Setup Wizard is run again and the old ini_set code already exists
		if ( file_exists($filename) && preg_match($pattern, $subject, $matches) && $options['bps_iniSet_ErrorLog'] != '' && $options['bps_iniSet_LogErrorsMaxLen'] != '' && $options['bps_iniSet_MemoryLimit'] != '' && $options['bps_iniSet_MaxExecutionTime'] != '' && $options['bps_iniSet_MysqlConnectTimeout'] != '') {
			
			if ( @substr($sapi_type, 0, 6) != 'apache' || @$permswpconfig != '0666' || @$permswpconfig != '0777') { // Windows IIS, XAMPP, etc
				@chmod($filename, 0644);
			}		
			
			$stringReplace = @file_get_contents($filename);
			$stringReplace = preg_replace('/\/\*\* BEGIN BPS Pro ini_set Settings \*\*\/(.*?)\/\*\* END BPS Pro ini_set Settings \*\*\//s', $replacement, $stringReplace);
			
			if ( file_put_contents($filename, $stringReplace) ) {		
				@copy($filename, $wpconfigBackup);	
				echo $successTextBegin.__(' ini_set Options created in wp-config.php Successfully!', 'bulletproof-security').$successTextEnd;
				echo $successTextBegin.$wpconfigBackup.__(' copied to AutoRestore Backup Successfully!', 'bulletproof-security').$successTextEnd;
				
				// checking the DB value for the root .htaccess is correct and not a mistake
				$fl_override_options = get_option('bulletproof_security_options_flock_eol');
				
				if ( isset($fl_override_options['bps_file_lock_override']) && $fl_override_options['bps_file_lock_override'] == 'On' ) {
					
					if ( $SWflockPreCheck['bps_wizard_root_htaccess_flock'] == 'yes') {
						@chmod($filename, 0400);
					}		
				}
			}
		}

		$string = @file_get_contents($filename);

$ini_set_code = "/** BEGIN BPS Pro ini_set Settings **/
@error_reporting(".$options['bps_iniSet_ErrorReporting'].");
@ini_set('log_errors','".$options['bps_iniSet_LogErrors']."');
@ini_set('error_log','".$options['bps_iniSet_ErrorLog']."'); // add the path to your php error log
@ini_set('log_errors_max_len','".$options['bps_iniSet_LogErrorsMaxLen']."');
@ini_set('memory_limit','".$options['bps_iniSet_MemoryLimit']."');
@ini_set('session.cookie_httponly','".$options['bps_iniSet_session_cookie_httponly']."');
@ini_set('session.use_only_cookies','".$options['bps_iniSet_session_use_only_cookies']."');
@ini_set('session.cookie_secure','".$options['bps_iniSet_session_cookie_secure']."');
@ini_set('ignore_repeated_errors','".$options['bps_iniSet_IgnoreRepeatedErrors']."');
@ini_set('ignore_repeated_source','".$options['bps_iniSet_IgnoreRepeatedSource']."');
@ini_set('allow_url_include','".$options['bps_iniSet_AllowUrlInclude']."');
@ini_set('define_syslog_variables','".$options['bps_iniSet_DefineSyslogVar']."');
@ini_set('display_errors','".$options['bps_iniSet_DisplayErrors']."');
@ini_set('display_startup_errors','".$options['bps_iniSet_DisplayStartupErrors']."');
@ini_set('implicit_flush','".$options['bps_iniSet_ImplicitFlush']."');
@ini_set('magic_quotes_runtime','".$options['bps_iniSet_MagicQuotesRuntime']."');
@ini_set('max_execution_time','".$options['bps_iniSet_MaxExecutionTime']."');
@ini_set('mysql.connect_timeout','".$options['bps_iniSet_MysqlConnectTimeout']."');
@ini_set('mysql.trace_mode','".$options['bps_iniSet_MysqlTraceMode']."');
@ini_set('report_memleaks','".$options['bps_iniSet_ReportMemleaks']."');
/** END BPS Pro ini_set Settings **/";

		// This writes new ini_set code if ini_set code does NOT exist yet and if the wp-config.php file code is older
		if ( file_exists($filename) && ! preg_match($pattern, $subject, $matches) && preg_match($pattern2, $subject, $matches) && $options['bps_iniSet_ErrorLog'] != '' ) {
			
			if ( @substr($sapi_type, 0, 6) != 'apache' || @$permswpconfig != '0666' || @$permswpconfig != '0777') { // Windows IIS, XAMPP, etc
				@chmod($filename, 0644);
			}	
			
			$stringReplace = preg_replace($pattern2, $ini_set_code . "\n\n/** Absolute path to the WordPress directory. */\n$1", $string);
			
			if ( file_put_contents($filename, $stringReplace) ) {
				@copy($filename, $wpconfigBackup);	
				echo $successTextBegin.__(' ini_set Options created in wp-config.php Successfully!', 'bulletproof-security').$successTextEnd;
				echo $successTextBegin.$wpconfigBackup.__(' copied to AutoRestore Backup Successfully!', 'bulletproof-security').$successTextEnd;
				
				$fl_override_options = get_option('bulletproof_security_options_flock_eol');
				
				if ( $fl_override_options['bps_file_lock_override'] == 'On' ) {				
				
					if ( $SWflockPreCheck['bps_wizard_root_htaccess_flock'] == 'yes') {
						@chmod($filename, 0400);
					}			
				}
			}
		}
	
		// This writes new ini_set code if ini_set code does NOT exist yet and if the wp-config.php file code is newer
		if ( file_exists($filename) && ! preg_match($pattern, $subject, $matches) && preg_match($pattern3, $subject, $matches) && $options['bps_iniSet_ErrorLog'] != ''	) {
			
			if ( @substr($sapi_type, 0, 6) != 'apache' || @$permswpconfig != '0666' || @$permswpconfig != '0777') { // Windows IIS, XAMPP, etc
				@chmod($filename, 0644);
			}	
			
			$stringReplace = preg_replace($pattern3, $ini_set_code . "\n\n/** Absolute path to the WordPress directory. */\n$1", $string);
			
			if ( file_put_contents($filename, $stringReplace) ) {
				@copy($filename, $wpconfigBackup);	
				echo $successTextBegin.__(' ini_set Options created in wp-config.php Successfully!', 'bulletproof-security').$successTextEnd;
				echo $successTextBegin.$wpconfigBackup.__(' copied to AutoRestore Backup Successfully!', 'bulletproof-security').$successTextEnd;
				
				$fl_override_options = get_option('bulletproof_security_options_flock_eol');
				
				if ( $fl_override_options['bps_file_lock_override'] == 'On' ) {				
				
					if ( $SWflockPreCheck['bps_wizard_root_htaccess_flock'] == 'yes') {
						@chmod($filename, 0400);
					}			
				}
			}			
		}
	}
}

// Setup Wizard - Create the Plugin Firewall .htaccess file using whitelist DB option values saved during Pre-Installation Wizard
// 11: now using mod_rewrite. This additional function is also used in bpsPro_new_feature_autoupdate() for BPS Pro 11 upgrades
// 11.5 Change|BugFix: Whitelist by Hostname (domain name) and IP Address tool - previously called Allow from tool.
// 11.8: This function is used in bps_Plugins_Folder_Lockdown()
// 14.1: BugFix: The Plugin Firewall was being turned On even if someone had turned it Off.
function bpsSetupWizardPluginFirewall_File() {
	
	if ( current_user_can('manage_options') ) {

		$HFiles_options = get_option('bulletproof_security_options_htaccess_files');
		
		if ( esc_html($_SERVER['QUERY_STRING']) == 'page=bulletproof-security/admin/wizard/wizard.php' ) {

			$CURLoptions = get_option('bulletproof_security_options_wizard_curl');
			
			if ( $CURLoptions['bps_wizard_curl_scan'] == 'Off' || $HFiles_options['bps_htaccess_files'] == 'disabled' ) {
				echo '<strong><font color="green">'.__('Plugin Firewall cURL Scanning is Turned Off.', 'bulletproof-security').'</font></strong><br>';	
			}
		}

	if ( isset($HFiles_options['bps_htaccess_files']) && $HFiles_options['bps_htaccess_files'] != 'disabled' ) {

	$PFW_options = get_option('bulletproof_security_options_pfirewall');
	$successTextBegin = '<font color="green"><strong>';
	$successTextEnd = '</strong></font><br>';
	
	// create the Plugin Firewall .htaccess file
	$PluginsHtaccessMaster = WP_PLUGIN_DIR . '/bulletproof-security/admin/htaccess/plugins.htaccess';
	$PluginsHtaccess = WP_PLUGIN_DIR . '/.htaccess';
	$PluginsHtaccessARQ = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/bulletproof-security/admin/htaccess/plugins.htaccess';
	$PluginsHtaccessARQplugins = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/.htaccess';
	$pluginsHtaccessMasterTXT = WP_PLUGIN_DIR . '/bulletproof-security/admin/htaccess/plugins-htaccess-master.txt';
	$pluginsHtaccessMasterTXTARQ = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/bulletproof-security/admin/htaccess/plugins-htaccess-master.txt';
	$bps_get_public_ip = bpsPro_get_proxy_real_ip_address();

	if ( isset($PFW_options['bps_pfw_paypal']) && $PFW_options['bps_pfw_paypal'] == '1' ) {
		$payPal = 'RewriteCond %{HTTP_HOST} !^paypal.com$' . "\n";
	} else {
		$payPal = '';
	}
	
	if ( isset($PFW_options['bps_pfw_google']) && $PFW_options['bps_pfw_google'] == '1' ) {
		$google = 'RewriteCond %{HTTP_HOST} !^google.com$' . "\n";
	} else {
		$google = '';
	}

	if ( isset($PFW_options['bps_pfw_amazon']) && $PFW_options['bps_pfw_amazon'] == '1' ) {
		$amazon = 'RewriteCond %{HTTP_HOST} !^amazon.com$' . "\n";
	} else {
		$amazon = '';
	}

	if ( isset($PFW_options['bps_pfw_authorizenet']) && $PFW_options['bps_pfw_authorizenet'] == '1' ) {
		$authorizeNet = 'RewriteCond %{HTTP_HOST} !^authorize.net$' . "\n";
	} else {
		$authorizeNet = '';
	}

	if ( file_exists($PluginsHtaccessMaster) ) {

		$bps_js_scripts = array( "/bulletproof-security/admin/js/bulletproof-security-admin-5.js, ", "/bulletproof-security/admin/js/bulletproof-security-admin-4.js, ","/bulletproof-security/admin/js/bulletproof-security-admin-3.js, ", "/bulletproof-security/admin/js/bulletproof-security-admin-2.js, ", "/bulletproof-security/admin/js/bulletproof-security-admin.js, ", "/bulletproof-security/admin/js/bps-tabs.js, ", "/bulletproof-security/admin/js/bps-accordion.js, ", "/bulletproof-security/admin/js/bps-dialog.js, " );		
		
		$bps_pfw_whitelist = array_filter( explode( ', ', str_replace( $bps_js_scripts, "", trim( $PFW_options['bps_pfw_whitelist'], ", \t\n\r") ) ) );	
		
		if ( empty($bps_pfw_whitelist) ) {
			file_put_contents($pluginsHtaccessMasterTXT, "");
		
			if ( esc_html($_SERVER['QUERY_STRING']) == 'page=bulletproof-security/admin/wizard/wizard.php' ) {
				echo $successTextBegin.__('Plugin Firewall Whitelist Rules created or updated - no whitelist rules were found.', 'bulletproof-security').$successTextEnd;
			}

		} else {

			$whiteList = array();

			foreach ( $bps_pfw_whitelist as $Key => $Value ) {
				
				$Value = preg_replace( '/\//', "^", $Value, 1 );
				$whiteList[] = 'RewriteRule ' . $Value . ' - [L]' . "\n";				
				$uniqueRules = array_unique($whiteList);				
				
				if ( esc_html($_SERVER['QUERY_STRING']) == 'page=bulletproof-security/admin/wizard/wizard.php' ) {
					echo $successTextBegin.'RewriteRule '.$Value.' - [L]'.__(' - Plugin Firewall Whitelist Rule created or updated Successfully!', 'bulletproof-security').$successTextEnd;
				}
			
				foreach ( $uniqueRules as $uniqueRule ) {

					if ( $uniqueRule != '' ) {
						file_put_contents($pluginsHtaccessMasterTXT, $uniqueRules);
					}			
				}
			}
		}
		
		$whiteListMaster = @file_get_contents($pluginsHtaccessMasterTXT);
		$PluginsHtaccessMaster_contents = @file_get_contents($PluginsHtaccessMaster);				

		$stringReplace = preg_replace('/BEGIN\sWHITELIST(.*)#\sEND\sPUBLIC\sIP/s', "BEGIN WHITELIST: Frontend Loading Website Plugin scripts/files\nRewriteRule ^bulletproof-security/400.php - [L]\nRewriteRule ^bulletproof-security/403.php - [L]\nRewriteRule ^bulletproof-security/405.php - [L]\nRewriteRule ^bulletproof-security/410.php - [L]\nRewriteRule ^bulletproof-security/isl-logout.php - [L]\n" . $whiteListMaster . "# END WHITELIST\n#\n# FORBID REMOTE ACCESS TO THESE PLUGIN FILE TYPES FROM ANYONE EXCEPT YOU\nRewriteCond %{REQUEST_URI} ^.*\.(7z|as|bat|bin|cgi|chm|chml|class|cmd|com|command|dat|db|db2|db3|dba|dll|DS_Store|exe|gz|hta|htaccess|htc|htm|html|html5|htx|ico|idc|ini|ins|isp|jar|jav|java|js|jse|jsfl|json|jsp|jsx|lib|lnk|out|php|phps|php5|php4|php3|phtml|phpt|pl|py|pyd|pyc|pyo|rar|shtm|shtml|sql|swf|sys|tar|taz|tgz|tpl|txt|vb|vbe|vbs|war|ws|wsf|xhtml|z|zip)\$ [NC]\n$payPal$google$amazon$authorizeNet# BEGIN PUBLIC IP\nRewriteCond %{REMOTE_ADDR} !^" . $bps_get_public_ip . "\$\n# END PUBLIC IP", $PluginsHtaccessMaster_contents);

		file_put_contents($PluginsHtaccessMaster, $stringReplace);

		/** Allow from Whitelist Rules **/
		$Allow_options = get_option('bulletproof_security_options_pfirewall_allow');
		$pluginsAllowFromTXT = WP_PLUGIN_DIR . '/bulletproof-security/admin/htaccess/plugins-allow-from.txt';
		$pluginsAllowFromTXTARQ = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/bulletproof-security/admin/htaccess/plugins-allow-from.txt';
		
		$pfw_allow_from = array_filter( explode( ', ', str_replace( array( "Allow from ", "allow from " ), "", trim( $Allow_options['bps_pfw_allow_from'], ", \t\n\r") ) ) );

		if ( empty($pfw_allow_from) ) {
			
			file_put_contents($pluginsAllowFromTXT, "");
		
		} else {
	
			$allow_whiteList = array();
			
			foreach ( $pfw_allow_from as $allow_Key => $allow_Value ) {
				
				if ( preg_match( '/[a-zA-Z]/', $allow_Value, $matches ) && ! preg_match( '/[:]/', $allow_Value, $matches ) ) {	
				
					$allow_whiteList[] = 'RewriteCond %{HTTP_HOST} !^' . $allow_Value . '$' . "\n";
				
				} else {
					
					$allow_whiteList[] .= 'RewriteCond %{REMOTE_ADDR} !^' . $allow_Value . '$' . "\n";

				}
				
				file_put_contents($pluginsAllowFromTXT, $allow_whiteList);
			}
		}
			
		// This is for DB value cleanup. The cleanup above is for file rule writing cleanup.
		$rule_cleanup = str_replace( array( "Allow from ", "allow from " ), "", trim( $Allow_options['bps_pfw_allow_from'], ", \t\n\r") );

			$Allow_Cleanup = array( 'bps_pfw_allow_from' => $rule_cleanup );

			foreach( $Allow_Cleanup as $key => $value ) {
				update_option('bulletproof_security_options_pfirewall_allow', $Allow_Cleanup);
			}

		// Get new updated DB option values again here
		$Allow_options = get_option('bulletproof_security_options_pfirewall_allow');

		$AllowFromRules = file_get_contents($pluginsAllowFromTXT);
		$stringReplace = file_get_contents($PluginsHtaccessMaster);
					
		if ( isset($Allow_options['bps_pfw_allow_from']) && $Allow_options['bps_pfw_allow_from'] == '' ) {
			
			$stringReplace = preg_replace( '/(#\sBEGIN\sADDITIONAL\sALLOW\sFROM\sRULES(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sADDITIONAL\sALLOW\sFROM\sRULES(.*\s*)){1,}/', "", $stringReplace );			

		} else {

			if ( preg_match( '/(#\sBEGIN\sADDITIONAL\sALLOW\sFROM\sRULES(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sADDITIONAL\sALLOW\sFROM\sRULES(.*\s*)){1,}/', $stringReplace, $matches) ) {
				// 11.8: Remove duplicate blocks of Allow From Rules code. Matches 1 or multiple blocks of code. newline at END...RULES is critical.
				$stringReplace = preg_replace( '/(#\sBEGIN\sADDITIONAL\sALLOW\sFROM\sRULES(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sADDITIONAL\sALLOW\sFROM\sRULES(.*\s*)){1,}/', "# BEGIN ADDITIONAL ALLOW FROM RULES\n" . $AllowFromRules . "# END ADDITIONAL ALLOW FROM RULES\n", $stringReplace );

			} else {
			
				$stringReplace = preg_replace( '/#\sEND\sPUBLIC\sIP/', "# END PUBLIC IP\n# BEGIN ADDITIONAL ALLOW FROM RULES\n" . $AllowFromRules . "# END ADDITIONAL ALLOW FROM RULES\n", $stringReplace );
				
			}
		}
			
		// Clean up - replace multiple newlines with 1 newline
		if ( preg_match('/(\n\n|\n\n\n|\n\n\n\n)/', $stringReplace, $matches) ) {			
			$stringReplace = preg_replace("/(\n\n|\n\n\n|\n\n\n\n)/", "\n", $stringReplace);
		}
			
		// Clean up - remove extra whitespaces before last RewriteRule
		if ( preg_match( '/\s{1,}RewriteRule\s\^\(\.\*\)\$\s\-\s\[F\]/', $stringReplace, $matches ) ) {
			$stringReplace = preg_replace('/\s{1,}RewriteRule\s\^\(\.\*\)\$\s\-\s\[F\]/s', "\nRewriteRule ^(.*)$ - [F]", $stringReplace);
		}

		// This function does everything on each Setup Wizard run except create the plugins htaccess file if PFW is Off
		// When someone turns PFW On the Master file is copied to /plugins/ so it needs to be made and ready for every case.
		$PFW_OnOff = get_option('bulletproof_security_options_pfw');
		
		if ( file_put_contents($PluginsHtaccessMaster, $stringReplace) ) {
			
			if ( ! isset($PFW_OnOff['bps_pfw_on_off']) || isset($PFW_OnOff['bps_pfw_on_off']) && $PFW_OnOff['bps_pfw_on_off'] == 'On' ) {
				@copy($PluginsHtaccessMaster, $PluginsHtaccess);
				
				$BPS_PFW_OnOff = array( 'bps_pfw_on_off' => 'On' );		
			
				foreach( $BPS_PFW_OnOff as $key => $value ) {
					update_option('bulletproof_security_options_pfw', $BPS_PFW_OnOff);
				}
				
				if ( esc_html($_SERVER['QUERY_STRING']) == 'page=bulletproof-security/admin/wizard/wizard.php' ) {
					echo $successTextBegin.__(' Plugin Firewall Activation, Copy & Backup to ARQ Successful!', 'bulletproof-security').$successTextEnd;
				}			
			}
			
			if ( isset($PFW_OnOff['bps_pfw_on_off']) && $PFW_OnOff['bps_pfw_on_off'] == 'Off' ) {
				echo '<strong><font color="blue">'.__('The Plugin Firewall is currently Turned Off.', 'bulletproof-security').'</font></strong><br>';
			}
			
			// DO NOT do a dir check on this file copy or the PFW new install feature will break			
			@copy($PluginsHtaccessMaster, $PluginsHtaccessARQplugins);

			if ( is_dir( WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/bulletproof-security/admin/htaccess' ) ) {
				@copy($PluginsHtaccessMaster, $PluginsHtaccessARQ);
				@copy($pluginsHtaccessMasterTXT, $pluginsHtaccessMasterTXTARQ);
				@copy($pluginsAllowFromTXT, $pluginsAllowFromTXTARQ);
			}
		}
	}	
	}
	}
}

// Setup Wizard - DB Backup is setup in admin.php on BPS Pro installation & upgrades
// but if someone uninstalls BPS Pro and runs the setup wizard again then the db options need to be updated
// with the db backup folder and db backup download URL
function bpsSetupWizard_dbbackup_folder_check() {
$successTextBegin = '<font color="green"><strong>';
$dbb_successMessage = __(' DB Option created or updated Successfully!', 'bulletproof-security');
$successMessage2 = __(' Folder created Successfully!', 'bulletproof-security');
$successTextEnd = '</strong></font><br>';
$failTextBegin = '<font color="#fb0101"><strong>';
$failTextEnd = '</strong></font><br>';

	if ( current_user_can('manage_options') ) {

		$DBBoptions = get_option('bulletproof_security_options_db_backup');
	
	if ( isset($DBBoptions['bps_db_backup_folder']) && $DBBoptions['bps_db_backup_folder'] != '' ) {	
		
		$DBB_Options = array(
		'bps_db_backup' 						=> $DBBoptions['bps_db_backup'], 
		'bps_db_backup_description' 			=> $DBBoptions['bps_db_backup_description'], 
		'bps_db_backup_folder' 					=> $DBBoptions['bps_db_backup_folder'], 
		'bps_db_backup_download_link' 			=> $DBBoptions['bps_db_backup_download_link'], 
		'bps_db_backup_job_type' 				=> $DBBoptions['bps_db_backup_job_type'], 
		'bps_db_backup_frequency' 				=> $DBBoptions['bps_db_backup_frequency'], 
		'bps_db_backup_start_time_hour' 		=> $DBBoptions['bps_db_backup_start_time_hour'], 
		'bps_db_backup_start_time_weekday' 		=> $DBBoptions['bps_db_backup_start_time_weekday'],  
		'bps_db_backup_start_time_month_date' 	=> $DBBoptions['bps_db_backup_start_time_month_date'], 
		'bps_db_backup_email_zip' 				=> $DBBoptions['bps_db_backup_email_zip'], 
		'bps_db_backup_delete' 					=> $DBBoptions['bps_db_backup_delete'], 
		'bps_db_backup_status_display' 			=> $DBBoptions['bps_db_backup_status_display'] 
		);
		
		echo $successTextBegin.$DBBoptions['bps_db_backup_folder'].$successMessage2.$successTextEnd;	
		
		foreach( $DBB_Options as $key => $value ) {
			update_option('bulletproof_security_options_db_backup', $DBB_Options);
			echo $successTextBegin.$key.$dbb_successMessage.$successTextEnd;	
		}		
	
	} else {

		$source = WP_CONTENT_DIR . '/bps-backup';

		if ( is_dir($source) ) {
		
			$iterator = new DirectoryIterator($source);
			
			foreach ( $iterator as $folder ) {
			
				if ( $folder->isDir() && ! $folder->isDot() && preg_match( '/backups_[a-zA-Z0-9]/', $folder ) ) {

					$bps_db_backup_folder = addslashes($source.DIRECTORY_SEPARATOR.$folder);
					$bps_db_backup_download_link = content_url( '/bps-backup/' ) . $folder . '/';
			
					$DBB_Options = array(
					'bps_db_backup' 						=> 'On', 
					'bps_db_backup_description' 			=> '', 
					'bps_db_backup_folder' 					=> $bps_db_backup_folder, 
					'bps_db_backup_download_link' 			=> $bps_db_backup_download_link, 
					'bps_db_backup_job_type' 				=> '', 
					'bps_db_backup_frequency' 				=> '', 		 
					'bps_db_backup_start_time_hour' 		=> '', 
					'bps_db_backup_start_time_weekday' 		=> '', 
					'bps_db_backup_start_time_month_date' 	=> '', 
					'bps_db_backup_email_zip' 				=> '', 
					'bps_db_backup_delete' 					=> '', 
					'bps_db_backup_status_display' 			=> 'No DB Backups' 
					);

					echo $successTextBegin.$bps_db_backup_folder.$successMessage2.$successTextEnd;

					foreach( $DBB_Options as $key => $value ) {
						update_option('bulletproof_security_options_db_backup', $DBB_Options);
						echo $successTextBegin.$key.$dbb_successMessage.$successTextEnd;	
					}			
				}
			}
		}
	}
	}
}

// Setup Wizard - Create/Recreate the User Agent filters in the 403.php file
function bpsSetupWizard_autoupdate_useragent_filters() {		
global $wpdb;
$table_name = $wpdb->prefix . "bpspro_seclog_ignore";
$blankFile = WP_PLUGIN_DIR . '/bulletproof-security/admin/htaccess/blank.txt';
$userAgentMaster = WP_CONTENT_DIR . '/bps-backup/master-backups/UserAgentMaster.txt';
$bps403File = WP_PLUGIN_DIR . '/bulletproof-security/403.php';
$bps403FileARQ = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/bulletproof-security/403.php';
$ARQdir = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/bulletproof-security/';
$search = '';		

	if ( ! file_exists($bps403File) ) {
		return;
	}
	
	if ( file_exists($blankFile) ) {
		copy($blankFile, $userAgentMaster);
	}

	$getSecLogTable = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $table_name WHERE user_agent_bot LIKE %s", "%$search%" ) );
	$UserAgentRules = array();
	
	if ( $wpdb->num_rows == 0 ) {
		$text = '<strong><font color="green">'.__('Security Log User Agent Filter Check Successful! 0 User Agent Filters to update.', 'bulletproof-security').'</font></strong><br>';
		echo $text;	
	}
	
	if ( $wpdb->num_rows != 0 ) {

		foreach ( $getSecLogTable as $row ) {
			$UserAgentRules[] = "(.*)".$row->user_agent_bot."(.*)|";
			file_put_contents($userAgentMaster, $UserAgentRules);
		
			$text = '<strong><font color="green">'.__('Security Log User Agent Filter ', 'bulletproof-security').$row->user_agent_bot.__(' created or updated Successfully!', 'bulletproof-security').'</font></strong><br>';
			echo $text;
		}
	
	$UserAgentRulesT = file_get_contents($userAgentMaster);
	$stringReplace = file_get_contents($bps403File);

	$stringReplace = preg_replace('/# BEGIN USERAGENT FILTER(.*)# END USERAGENT FILTER/s', "# BEGIN USERAGENT FILTER\nif ( @!preg_match('/".trim($UserAgentRulesT, "|")."/', \$_SERVER['HTTP_USER_AGENT']) ) {\n# END USERAGENT FILTER", $stringReplace);
		
	file_put_contents($bps403File, $stringReplace);
		
	if ( is_dir($ARQdir) ) {
		copy($bps403File, $bps403FileARQ);
	}
	}
}

// Setup Wizard - Create ARQ Exclude rules for sitemap.xml and sitemap.xml.gz if they exist
function bpsSetupWizardExcludeSitemap() {
global $wpdb;
$sitemap = ABSPATH . 'sitemap.xml';
$sitemapgz = ABSPATH . 'sitemap.xml.gz';
$sitemapDB = 'sitemap.xml';
$successTextBegin = '<font color="green"><strong>';
$successTextEnd = '</strong></font><br>';
$Etable_name = $wpdb->prefix . "bpspro_arq_exclude";
$getExcludeRows = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $Etable_name WHERE arq_exclude_source LIKE %s", "%$sitemapDB%") );	

	foreach ( $getExcludeRows as $row ) {
		if ( $row->arq_exclude_source == $sitemap || $row->arq_exclude_source == $sitemapgz ) {		
			echo $successTextBegin.__('AutoRestore|Quarantine Sitemap Exclude Rule already exists.', 'bulletproof-security').$successTextEnd;	
			return;
		}
	}

	if ( file_exists($sitemap) || file_exists($sitemapgz) ) {	
	
		if ( $ExcludeSitemap = $wpdb->insert( $Etable_name, array( 'time' => current_time('mysql'), 'arq_exclude_source' => $sitemap ) ) ) {
			echo $successTextBegin.__('AutoRestore|Quarantine Exclude Rule created Successfully for sitemap file: ', 'bulletproof-security').ABSPATH . 'sitemap.xml'.$successTextEnd;	
		}
		if ( $ExcludeSitemapgz = $wpdb->insert( $Etable_name, array( 'time' => current_time('mysql'), 'arq_exclude_source' => $sitemapgz ) ) ) {
			echo $successTextBegin.__('AutoRestore|Quarantine Exclude Rule created Successfully for sitemap file: ', 'bulletproof-security').ABSPATH . 'sitemap.xml.gz'.$successTextEnd;			
		}
	}
}

// Setup Wizard - Create ARQ Exclude rule for WPEngine mysql.sql file if it exists
function bpsSetupWizardExcludeWPEnginesql() {
global $wpdb;
$wpenginesql = WP_CONTENT_DIR . '/mysql.sql';
$wpenginedir = WP_CONTENT_DIR . '/mu-plugins/wpengine-common';
$wpengineDB = 'mysql.sql';
$successTextBegin = '<font color="green"><strong>';
$successTextEnd = '</strong></font><br>';
$Etable_name = $wpdb->prefix . "bpspro_arq_exclude";
$getExcludeRows = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $Etable_name WHERE arq_exclude_source LIKE %s", "%$wpengineDB%") );			
	
	if ( is_dir( $wpenginedir ) && file_exists($wpenginesql) ) {

		foreach ( $getExcludeRows as $row ) {
			if ( $row->arq_exclude_source == $wpenginesql ) {		
				echo $successTextBegin.__('AutoRestore|Quarantine WPEngine mysql.sql Exclude Rule already exists.', 'bulletproof-security').$successTextEnd;	
				return;
			}
		}

		if ( $ExcludeWpenginesql = $wpdb->insert( $Etable_name, array( 'time' => current_time('mysql'), 'arq_exclude_source' => $wpenginesql ) ) ) {
			echo $successTextBegin.__('AutoRestore|Quarantine Exclude Rule created Successfully for WPEngine file: ', 'bulletproof-security').$wpenginesql.$successTextEnd;	
		}
	}
}

// Setup Wizard: Create ARQ Exclude rules for advanced-cache.php file if it exists
function bpsSetupWizardExcludeAdvancedCacheFile() {
global $wpdb;
$advanced_cache = WP_CONTENT_DIR . '/advanced-cache.php';
$advanced_cacheDB = 'advanced-cache.php';
$successTextBegin = '<font color="green"><strong>';
$successTextEnd = '</strong></font><br>';
$Etable_name = $wpdb->prefix . "bpspro_arq_exclude";
$getExcludeRows = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $Etable_name WHERE arq_exclude_source LIKE %s", "%$advanced_cacheDB%") );	

	if ( file_exists($advanced_cache) ) {

		foreach ( $getExcludeRows as $row ) {
			if ( $row->arq_exclude_source == $advanced_cache ) {		
				echo $successTextBegin.__('AutoRestore|Quarantine advanced-cache.php Exclude Rule already exists.', 'bulletproof-security').$successTextEnd;
				return;
			}
		}
	
		if ( $Exclude_advanced_cache = $wpdb->insert( $Etable_name, array( 'time' => current_time('mysql'), 'arq_exclude_source' => $advanced_cache ) ) ) {
			echo $successTextBegin.__('AutoRestore|Quarantine Exclude Rule created Successfully for the advanced-cache.php file: ', 'bulletproof-security').$advanced_cache.$successTextEnd;	
		}	
	}
}

// Setup Wizard: Create ARQ Exclude rules for wp-cache-config.php file if it exists
function bpsSetupWizardExcludeWpCacheConfigFile() {
global $wpdb;
$wp_cache_config = WP_CONTENT_DIR . '/wp-cache-config.php';
$wp_cache_configDB = 'wp-cache-config.php';
$successTextBegin = '<font color="green"><strong>';
$successTextEnd = '</strong></font><br>';
$Etable_name = $wpdb->prefix . "bpspro_arq_exclude";
$getExcludeRows = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $Etable_name WHERE arq_exclude_source LIKE %s", "%$wp_cache_configDB%") );	

	if ( file_exists($wp_cache_config) ) {

		foreach ( $getExcludeRows as $row ) {
			if ( $row->arq_exclude_source == $wp_cache_config ) {		
				echo $successTextBegin.__('AutoRestore|Quarantine wp-cache-config.php Exclude Rule already exists.', 'bulletproof-security').$successTextEnd;
				return;
			}
		}
	
		if ( $Exclude_wp_cache_config = $wpdb->insert( $Etable_name, array( 'time' => current_time('mysql'), 'arq_exclude_source' => $wp_cache_config ) ) ) {
			echo $successTextBegin.__('AutoRestore|Quarantine Exclude Rule created Successfully for the wp-cache-config.php file: ', 'bulletproof-security').$wp_cache_config.$successTextEnd;	
		}	
	}
}

// Setup Wizard: Create ARQ Exclude rules for object-cache.php file if it exists
function bpsSetupWizardExcludeObjectCacheFile() {
global $wpdb;
$object_cache = WP_CONTENT_DIR . '/object-cache.php';
$object_cacheDB = 'object-cache.php';
$successTextBegin = '<font color="green"><strong>';
$successTextEnd = '</strong></font><br>';
$Etable_name = $wpdb->prefix . "bpspro_arq_exclude";
$getExcludeRows = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $Etable_name WHERE arq_exclude_source LIKE %s", "%$object_cacheDB%") );	

	if ( file_exists($object_cache) ) {

		foreach ( $getExcludeRows as $row ) {
			if ( $row->arq_exclude_source == $object_cache ) {		
				echo $successTextBegin.__('AutoRestore|Quarantine object-cache.php Exclude Rule already exists.', 'bulletproof-security').$successTextEnd;
				return;
			}
		}
	
		if ( $Exclude_wp_cache_config = $wpdb->insert( $Etable_name, array( 'time' => current_time('mysql'), 'arq_exclude_source' => $object_cache ) ) ) {
			echo $successTextBegin.__('AutoRestore|Quarantine Exclude Rule created Successfully for the object-cache.php file: ', 'bulletproof-security').$object_cache.$successTextEnd;	
		}	
	}
}

// Setup Wizard: Create ARQ Exclude rules for db.php file if it exists
function bpsSetupWizardExcludeDBCacheFile() {
global $wpdb;
$db_php = WP_CONTENT_DIR . '/db.php';
$db_phpDB = 'db.php';
$successTextBegin = '<font color="green"><strong>';
$successTextEnd = '</strong></font><br>';
$Etable_name = $wpdb->prefix . "bpspro_arq_exclude";
$getExcludeRows = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $Etable_name WHERE arq_exclude_source LIKE %s", "%$db_phpDB%") );	

	if ( file_exists($db_php) ) {

		foreach ( $getExcludeRows as $row ) {
			if ( $row->arq_exclude_source == $db_php ) {		
				echo $successTextBegin.__('AutoRestore|Quarantine db.php Exclude Rule already exists.', 'bulletproof-security').$successTextEnd;
				return;
			}
		}
	
		if ( $Exclude_wp_cache_config = $wpdb->insert( $Etable_name, array( 'time' => current_time('mysql'), 'arq_exclude_source' => $db_php ) ) ) {
			echo $successTextBegin.__('AutoRestore|Quarantine Exclude Rule created Successfully for the db.php file: ', 'bulletproof-security').$db_php.$successTextEnd;	
		}	
	}
}

// Setup Wizard: Get the Current / Last Modifed Date of the Login Security Reset File
function bps_SWLoginSecurityResetFileLastMod() {
$filename = WP_CONTENT_DIR . '/bps-backup/master-backups/Login-Security-Alert-Reset.txt';
$gmt_offset = get_option( 'gmt_offset' ) * 3600;

if ( file_exists($filename) ) {
	$last_modified = date("F d Y H:i:s", filemtime($filename) + $gmt_offset );
	return $last_modified;
	}
}

// Setup Wizard: Get the Current / Last Modifed Date of the Folder Lock Reset File
function bps_SWFolderLockResetFileLastMod() {
$filename = WP_CONTENT_DIR . '/bps-backup/master-backups/Folder-Lock-Alert-Reset.txt';
$gmt_offset = get_option( 'gmt_offset' ) * 3600;

if ( file_exists($filename) ) {
	$last_modified = date("F d Y H:i:s", filemtime($filename) + $gmt_offset );
	return $last_modified;
	}
}

// Setup Wizard: pre-save Custom Code DB options for Custom Code Export|Import features if they do not exist
function bpsSetupWizardCustomCodePresave() {
				
	$bps_Root_CC_Options = 'bulletproof_security_options_customcode';

	if ( ! is_multisite() ) {

		$Root_CC_Options = array(
		'bps_customcode_one' 				=> '', 
		'bps_customcode_server_signature' 	=> '', 
		'bps_customcode_directory_index' 	=> '', 
		'bps_customcode_server_protocol' 	=> '', 
		'bps_customcode_error_logging' 		=> '', 
		'bps_customcode_deny_dot_folders' 	=> '', 
		'bps_customcode_admin_includes' 	=> '', 
		'bps_customcode_wp_rewrite_start' 	=> '', 
		'bps_customcode_request_methods' 	=> '', 
		'bps_customcode_two' 				=> '', 
		'bps_customcode_timthumb_misc' 		=> '', 
		'bps_customcode_bpsqse' 			=> '', 
		'bps_customcode_deny_files' 		=> '', 
		'bps_customcode_three' 				=> ''
		);
				
	} else {
					
		$Root_CC_Options = array(
		'bps_customcode_one' 				=> '', 
		'bps_customcode_server_signature' 	=> '', 
		'bps_customcode_directory_index' 	=> '', 
		'bps_customcode_server_protocol' 	=> '', 
		'bps_customcode_error_logging' 		=> '', 
		'bps_customcode_deny_dot_folders' 	=> '', 
		'bps_customcode_admin_includes' 	=> '', 
		'bps_customcode_wp_rewrite_start' 	=> '', 
		'bps_customcode_request_methods' 	=> '', 
		'bps_customcode_two' 				=> '', 
		'bps_customcode_timthumb_misc' 		=> '', 
		'bps_customcode_bpsqse' 			=> '', 
		'bps_customcode_wp_rewrite_end' 	=> '', 
		'bps_customcode_deny_files' 		=> '', 
		'bps_customcode_three' 				=> ''
		);					
	}

	if ( ! get_option( $bps_Root_CC_Options ) ) {			

		foreach( $Root_CC_Options as $key => $value ) {
			update_option('bulletproof_security_options_customcode', $Root_CC_Options);
		}
	}

	$bps_wpadmin_CC_Options = 'bulletproof_security_options_customcode_WPA';			

	$wpadmin_CC_Options = array(
	'bps_customcode_deny_files_wpa' => '', 
	'bps_customcode_one_wpa' 		=> '', 
	'bps_customcode_two_wpa' 		=> '', 
	'bps_customcode_bpsqse_wpa' 	=> ''
	);
			
	if ( ! get_option( $bps_wpadmin_CC_Options ) ) {			
		
		foreach( $wpadmin_CC_Options as $key => $value ) {
			update_option('bulletproof_security_options_customcode_WPA', $wpadmin_CC_Options);
		}
	}

	$bps_uaeg_CC_Options = 'bulletproof_security_options_customcode_UAEG';			

	$uaeg_CC_Options = array( 'bps_customcode_uaeg' => '' );
			
	if ( ! get_option( $bps_uaeg_CC_Options ) ) {			
		
		foreach( $uaeg_CC_Options as $key => $value ) {
			update_option('bulletproof_security_options_customcode_UAEG', $uaeg_CC_Options);
		}
	}
}

?>