<?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 ( ! function_exists('add_action') ) {
		header('Status: 403 Forbidden');
		header('HTTP/1.1 403 Forbidden');
		exit();
}

// Get IP address for any/all logged in Users - no capabilities restriction
function bpsPro_get_proxy_real_ip_address_pfw_roles() {

	if ( is_admin() ) {
	
		if ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
			$ip = esc_html( $_SERVER['HTTP_CLIENT_IP'] );
			
			if ( ! is_array($ip) ) {
				
				if ( preg_match( '/(\d+\.){3}\d+/', $ip, $matches ) ) {

					return $matches[0];	
				
				} elseif ( preg_match( '/([:\d\w]+\.(\d+\.){2}\d+|[:\d\w]+)/', $ip, $matches ) ) {
				
					return $matches[0];	
		
				} else {
					
					return $ip;
				}
			
			} else {
				
				return current($ip);				
			}
		
		} elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
			$ip = esc_html( $_SERVER['HTTP_X_FORWARDED_FOR'] );
			
			if ( ! is_array($ip) ) {
				
				if ( preg_match( '/(\d+\.){3}\d+/', $ip, $matches ) ) {

					return $matches[0];	
				
				} elseif ( preg_match( '/([:\d\w]+\.(\d+\.){2}\d+|[:\d\w]+)/', $ip, $matches ) ) {
				
					return $matches[0];	
		
				} else {
					
					return $ip;
				}
			
			} else {
				
				return current($ip);				
			}
		
		} elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
			$ip = esc_html( $_SERVER['REMOTE_ADDR'] );
			return $ip;
		}
	}
}	

// Plugin Firewall - Additional Roles IP Addresses added
// XAMPP testing: need to manually change IP address 127.0.0.1 in the plugins .htaccess file to test Roles IP
// Network/MU sites work differently - Additional Roles may not work on MU - pending additional testing
// admin_notices are displayed in the wp-admin area to all users unless you restrict it by Role or Capability
// 11: now using mod_rewrite and not mod_access_compat and mod_authz_core 
// 11.5: Write to both the plugins.htaccess Master file and Live PFW file. Necessary if PFW AutoPilot Mode is on.
// 11.8: AutoFix duplicate or invalid ADDITIONAL ROLES IP lines of code
// 12.4: changed user_level to Roles conditions.
// 12.5: added Custom User Roles
// 12.9: Added Plugin Firewall Test Mode condition
// 14.1: Added PFW On|Off condition
// 15.3: BugFix: the get ip address function was restricted to only admins. created > bpsPro_get_proxy_real_ip_address_pfw_roles()
function bps_pfw_roles() {

	if ( ! get_option('bulletproof_security_options_pfirewall_roles') ) {
		return;
	}

	$PFW_OnOff = get_option('bulletproof_security_options_pfw');

	if ( isset($PFW_OnOff['bps_pfw_on_off']) && $PFW_OnOff['bps_pfw_on_off'] == 'Off' ) {
		return;
	}	

	$HFiles_options = get_option('bulletproof_security_options_htaccess_files');
	
	if ( $HFiles_options['bps_htaccess_files'] == 'disabled' ) {
		return;
	}

	// Plugin Firewall Test Mode: do not create new code in the plugins htaccess file while in test mode
	$PFWTM_options = get_option('bulletproof_security_options_pfw_test_mode');
	
	if ( isset($PFWTM_options['bps_pfw_test_mode']) && $PFWTM_options['bps_pfw_test_mode'] == 'On' ) {
		return;
	}

	$options = get_option('bulletproof_security_options_pfirewall_roles');

	//if ( $options['bps_pfw_administrator'] != '1' && $options['bps_pfw_editor'] != '1' && $options['bps_pfw_author'] != '1' && $options['bps_pfw_contributor'] != '1' ) {
	//	return;		
	//}

	global $current_user, $pagenow;
	$current_user = wp_get_current_user();
	$user_roles = $current_user->roles;
	$user_role = array_shift($user_roles);	

	$PluginsHtaccess = WP_PLUGIN_DIR . '/.htaccess';
	$PluginsHtaccessARQplugins = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/.htaccess';
	$PluginsHtaccessMaster = WP_PLUGIN_DIR . '/bulletproof-security/admin/htaccess/plugins.htaccess';
	$PluginsHtaccessARQ = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/bulletproof-security/admin/htaccess/plugins.htaccess';
	$PluginsHtaccessARQDir = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins';
	$bps_get_public_ip = bpsPro_get_proxy_real_ip_address_pfw_roles();
	
	if ( file_exists($PluginsHtaccess) ) {
		$check_string = @file_get_contents($PluginsHtaccess);	
		$stringReplace = @file_get_contents($PluginsHtaccess);
		$stringReplaceMaster = @file_get_contents($PluginsHtaccessMaster);
		$pattern = '/#\sBEGIN\sADDITIONAL\sROLES\sIP/s';
		//if ( $user_role == 'administrator' || $user_role == 'editor' || $user_role == 'author' || $user_role == 'contributor' ) {
			
			// 11.8: AutoFix duplicate or invalid ADDITIONAL ROLES IP lines of code
			if ( preg_match('/(#\sEND\sADDITIONAL\sROLES\sIP(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sADDITIONAL\sROLES\sIP(.*\s*)){1,}/', $check_string, $matches ) ) {
					
				$stringReplace = preg_replace( '/(#\sEND\sADDITIONAL\sROLES\sIP(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sADDITIONAL\sROLES\sIP(.*\s*)){1,}/', "# END ADDITIONAL ROLES IP\n", $stringReplace );
				
				$stringReplaceMaster = preg_replace( '/(#\sEND\sADDITIONAL\sROLES\sIP(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sADDITIONAL\sROLES\sIP(.*\s*)){1,}/', "# END ADDITIONAL ROLES IP\n", $stringReplaceMaster );			
			
				if ( file_put_contents($PluginsHtaccess, $stringReplace ) ) {
					@copy($PluginsHtaccess, $PluginsHtaccessARQplugins);
				}
				
				if ( file_put_contents($PluginsHtaccessMaster, $stringReplaceMaster ) ) {
					@copy($PluginsHtaccessMaster, $PluginsHtaccessARQ);
				}
			}	
	
		//if ( $current_user->ID != 1 ) {
		
			// If the IP address is blank return, otherwise these invalid lines of code will be created: RewriteCond %{REMOTE_ADDR} !^$
			if ( $bps_get_public_ip == '' ) {
			return;
			}	
			
			if ( $options['bps_pfw_administrator'] == '1' && $user_role == 'administrator' ) {
				$administrator = 'RewriteCond %{REMOTE_ADDR} !^' . $bps_get_public_ip . '$' . "\n";
			} else {
				$administrator = '';
			}
	
			if ( $options['bps_pfw_editor'] == '1' && $user_role == 'editor' ) {
				$editor = 'RewriteCond %{REMOTE_ADDR} !^' . $bps_get_public_ip . '$' . "\n";
			} else {
				$editor = '';
			}
		
			if ( $options['bps_pfw_author'] == '1' && $user_role == 'author' ) {
				$author = 'RewriteCond %{REMOTE_ADDR} !^' . $bps_get_public_ip . '$' . "\n";
			} else {
				$author = '';
			}
	
			if ( $options['bps_pfw_contributor'] == '1' && $user_role == 'contributor' ) {
				$contributor = 'RewriteCond %{REMOTE_ADDR} !^' . $bps_get_public_ip . '$' . "\n";
			} else {
				$contributor = '';
			}
		
			$custom_role = '';
			
			foreach ( $options as $key => $value ) {
		
				if ( $key == 'bps_pfw_custom_roles' && ! is_array($value) ) {
					$custom_role = '';
				}
				
				if ( $key == 'bps_pfw_custom_roles' && is_array($value) ) {
					
					foreach ( $value as $ckey => $cvalue ) {
						
						if ( $user_role == $ckey && $cvalue == '1' ) {
							$custom_role = 'RewriteCond %{REMOTE_ADDR} !^' . $bps_get_public_ip . '$' . "\n";
						} else {
							$custom_role = '';
						}
					}
				}
			}
		}
		
		if ( file_exists($PluginsHtaccess) && ! strpos($check_string, $bps_get_public_ip) && is_dir($PluginsHtaccessARQDir) ) {
			
			if ( ! preg_match($pattern, $check_string, $matches) ) {
				
				// Note: newlines are added in the above code already for each REMOTE_ADDR line of code that is created
				$stringReplace = preg_replace( '/RewriteRule\s\^\(\.\*\)\$\s\-\s\[F\]/', "# BEGIN ADDITIONAL ROLES IP\n$administrator$editor$author$contributor$custom_role# END ADDITIONAL ROLES IP\nRewriteRule ^(.*)\$ - [F]", $stringReplace );
				
				$stringReplaceMaster = preg_replace( '/RewriteRule\s\^\(\.\*\)\$\s\-\s\[F\]/', "# BEGIN ADDITIONAL ROLES IP\n$administrator$editor$author$contributor$custom_role# END ADDITIONAL ROLES IP\nRewriteRule ^(.*)\$ - [F]", $stringReplaceMaster );				
				
			} else { 
				// Adds additional ips and does not replace the entire section of code
				$stringReplace = preg_replace( '/#\sEND\sADDITIONAL\sROLES\sIP/s', "$administrator$editor$author$contributor$custom_role# END ADDITIONAL ROLES IP", $stringReplace );
				$stringReplaceMaster = preg_replace('/#\sEND\sADDITIONAL\sROLES\sIP/s', "$administrator$editor$author$contributor$custom_role# END ADDITIONAL ROLES IP", $stringReplaceMaster );
			}
		
			if ( file_put_contents($PluginsHtaccess, $stringReplace) ) {
				if ( is_dir( WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins' ) ) {				
					copy($PluginsHtaccess, $PluginsHtaccessARQplugins);
				}
			}
			
			if ( file_put_contents($PluginsHtaccessMaster, $stringReplaceMaster) ) {
				if ( is_dir( WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/bulletproof-security/admin/htaccess' ) ) {
					copy($PluginsHtaccessMaster, $PluginsHtaccessARQ);
				}
			}		
		} // end if file exists, ip already exists and ARQ plugin folder exists
	//} // end if ( $current_user->ID != 1 ) { ...
	//}// end if ( $user_role == 'administrator' || ...
}

add_action('admin_notices', 'bps_pfw_roles');

// Plugin Firewall Whitelist Rule checks - Automatically delete the /plugins/.htaccess file if invalid whitelist rules exist
// to prevent website problems until the whitelist rule(s) is corrected
// 12.5: pattern5 removed /plugins/ from the check 
// 12.9: Added Plugin Firewall Test Mode condition
// 14.1: Added PFW On|Off condition
function bpsPro_PFW_auto_delete() {

	if ( current_user_can('manage_options') ) {

		$PFW_OnOff = get_option('bulletproof_security_options_pfw');
	
		if ( isset($PFW_OnOff['bps_pfw_on_off']) && $PFW_OnOff['bps_pfw_on_off'] == 'Off' ) {
			return;
		}		
		
		// Plugin Firewall Test Mode: do not create new code in the plugins htaccess file while in test mode
		$PFWTM_options = get_option('bulletproof_security_options_pfw_test_mode');
	
		if ( isset($PFWTM_options['bps_pfw_test_mode']) && $PFWTM_options['bps_pfw_test_mode'] == 'On' ) {
			return;
		}

		$options = get_option('bulletproof_security_options_pfirewall'); 
		$pattern1 = '/(\/(.*)\s{2}\/|\/(.*)\s{3}\/|\/(.*)\s{4}\/|\/(.*)\s{5}\/|\/(.*),\/|\n|\r)/';		
		//$pattern2 = '/(\bver=\b|\bpage=\b|\bsrc=\b|\bwww\b|\bhttp\b|\bhttps\b|\bhref\b|\b\.com\b|\b\.net\b|\b\.org\b\b\.biz\b|\b\.info\b|\b\.gov\b|\b\.edu\b)/';
		$pattern2 = '/(\bver=\b|\bpage=\b|\bsrc=\b|\bhref\b|\b\.com\b|\b\.net\b|\b\.org\b\b\.biz\b|\b\.info\b|\b\.gov\b|\b\.edu\b)/';
		$pattern3 = '/[\%\"\'\&\;\<\>]/';
		//$pattern4 = '/(\/bulletproof-security\/admin\/js\/\(\.\*\)\.js|\/bulletproof-security\/)/';
		$pattern4 = '/\/bulletproof-security\/admin\/js\/(.*)\.js/';
		//$pattern5 = '/(\/themes\/|\/plugins\/|\/wp-content\/|\/wp-includes\/|\/uploads\/)/';
		$pattern5 = '/(\/wp-content\/|\/wp-includes\/)/';

		$error = '0';

		// additional/extra whitespaces, line breaks/new lines after your whitelist rules or no space after the comma
		if ( preg_match( $pattern1, $options['bps_pfw_whitelist'], $matches ) ) {
			$error = '1';
		}
		// ver=, page=, src=, www, http, https, href, .com, .net, .org, .biz, .info, .gov, .edu
		if ( preg_match( $pattern2, $options['bps_pfw_whitelist'], $matches ) ) {
			$error = '2';
		}
		// invalid characters: %, ", \', &, <, > or ;
		if ( preg_match( $pattern3, $options['bps_pfw_whitelist'], $matches ) ) {
			$error = '3';
		}
		// /bulletproof-security/admin/js/ scripts
		if ( preg_match( $pattern4, $options['bps_pfw_whitelist'], $matches ) ) {
			$error = '4';
		}
		// invalid paths: /plugins/ or /wp-content/ or /wp-includes/
		if ( preg_match( $pattern5, $options['bps_pfw_whitelist'], $matches ) ) {
			$error = '5';
		}
		
		if ( $error != '0' ) {
		
			$PluginsHtaccess = WP_PLUGIN_DIR . '/.htaccess';
			$PluginsHtaccessARQplugins = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/.htaccess';
			@unlink($PluginsHtaccess);
			@unlink($PluginsHtaccessARQplugins);
		
			// Turn off AutoPilot Mode so the Plugin Firewall htaccess file will not be automatically created again.
			// For idiot plugin authors who use the "reserved" WP "plugins" folder name in URI naming conventions: /plugins/plugin-name/js/plugins/something/script-name.js
			// this will cause the Plugin Firewall to deactivate itself. I am not going to compensate for these idiots. They need to learn good coding practices instead.
			// The User will need to create a Regex whitelist rule: /plugin-name/js/(.*).js to compensate for these idiot plugin authors.
			$PFWAP_options = get_option('bulletproof_security_options_pfw_autopilot');
		
			$BPS_PFWAP_Options = array( 
			'bps_pfw_autopilot_cron' 			=> 'Off',  
			'bps_pfw_autopilot_cron_frequency' 	=> $PFWAP_options['bps_pfw_autopilot_cron_frequency'],  	
			'bps_pfw_autopilot_cron_end' 		=> $PFWAP_options['bps_pfw_autopilot_cron_end'] 
			);		
			
			foreach( $BPS_PFWAP_Options as $key => $value ) {
				update_option('bulletproof_security_options_pfw_autopilot', $BPS_PFWAP_Options);
			}
		}
	}
}

// Automated Plugins Folder BulletProof Mode
// This is an Admin Notice and works independently of PFWAP to update the User's IP address in real-time
// Note: if AutoPilot Mode is turned on the Plugin Firewall .htaccess file is automatically recreated on next Cron job.
// Note: if using XAMPP then your Server IP & Public IP will be the same 127.0.0.1 which means
// the strpos check string check will see 127.0.0.1 for Server Address and not change the public ip address
// Since frontloading plugin scripts should be whitelisted already then this should be Admin only.
// Automatically deletes the /plugins/.htaccess file if whitelist rule(s) are invalid
// 10.4: XTF turn off condition added
// 11: now using mod_rewrite and not mod_access_compat and mod_authz_core 
// 11.5: Everyone should be using the new PFW mod_rewrite htaccess file at this point. 
// 11.8: AutoFix blank plugins.htaccess file problem & older versions of PFW htaccess file
// 11.8: htaccess files disabled condition added
// 12.9: Added Plugin Firewall Test Mode condition
// 14.1: Added a PFW On|Off condition
function bps_Plugins_Folder_Lockdown() {

	if ( current_user_can('manage_options') ) {
		
	// New installations - BPS Pro has NOT been activated or S-Monitor Options have not been saved &/or the Setup Wizard has not been run
	if ( ! get_option('bulletproof_security_options_activation') || ! get_option('bulletproof_security_options_monitor') ) {
		return;
	}
	
	$PFW_OnOff = get_option('bulletproof_security_options_pfw');

	if ( isset($PFW_OnOff['bps_pfw_on_off']) && $PFW_OnOff['bps_pfw_on_off'] == 'Off' ) {
		return;
	}

	$HFiles_options = get_option('bulletproof_security_options_htaccess_files');

	if ( isset( $HFiles_options['bps_htaccess_files'] ) && $HFiles_options['bps_htaccess_files'] == 'disabled' ) {
		return;
	}	
	
	// Plugin Firewall Test Mode: do not create new code in the plugins htaccess file while in test mode
	$PFWTM_options = get_option('bulletproof_security_options_pfw_test_mode');
	
	if ( isset($PFWTM_options['bps_pfw_test_mode']) && $PFWTM_options['bps_pfw_test_mode'] == 'On' ) {
		return;
	}

	if ( ! get_option('bulletproof_security_options_pfirewall') ) {
		$text = '<div class="update-nag" style="background-color:#dfecf2;border:1px solid #999;font-size:1em;font-weight:600;padding:2px 5px;margin-top:2px;-moz-border-radius-topleft:3px;-webkit-border-top-left-radius:3px;-khtml-border-top-left-radius:3px;border-top-left-radius:3px;-moz-border-radius-topright:3px;-webkit-border-top-right-radius:3px;-khtml-border-top-right-radius:3px;border-top-right-radius:3px;-webkit-box-shadow: 3px 3px 5px -1px rgba(153,153,153,0.7);-moz-box-shadow: 3px 3px 5px -1px rgba(153,153,153,0.7);box-shadow: 3px 3px 5px -1px rgba(153,153,153,0.7);">'.__('The Plugin Firewall Needs To Be Activated', 'bulletproof-security').'<br><a href="'.admin_url( 'admin.php?page=bulletproof-security/admin/core/core.php#PFWScan-Menu-Link' ).'">'.__('Click Here', 'bulletproof-security').'</a>'.__(' to go to the Plugin Firewall to create your Plugin Firewall Whitelist and then Activate the Plugin Firewall.', 'bulletproof-security').'<br>'.__('If you do not want to setup or use the Plugin Firewall then click the Plugin Firewall Whitelist Tools tab and click the ', 'bulletproof-security').'<font color="blue">'.__('Save Whitelist Data', 'bulletproof-security').'</font>'.__(' button to remove/clear this message/notification.', 'bulletproof-security').'</div>';
		echo $text;
	}

	// Automatically delete the /plugins/.htaccess file if invalid whitelist rules exist
	bpsPro_PFW_auto_delete();

	$bps_get_public_ip = bpsPro_get_proxy_real_ip_address();
	$PluginsHtaccess = WP_PLUGIN_DIR . '/.htaccess';
	if ( file_exists($PluginsHtaccess) ) {
	$check_string = @file_get_contents($PluginsHtaccess);
	}

	// Error Checking display on BPS Pro pages only: affects all site types: Network/Single - display unconditionally
	// Since these checks are done on BPS Pro plugin pages only then resource usage is only impacted while on BPS Pro pages
	if ( @preg_match( '/page=bulletproof-security/', esc_html( $_SERVER['REQUEST_URI'] ) ) ) {		
	
		if ( file_exists($PluginsHtaccess) ) {
			
			$root_htaccess_file = ABSPATH . '.htaccess';
			$root_check_string = @file_get_contents($root_htaccess_file);
			$root_pattern = '/#{1,}(\s|){1,}ErrorDocument\s403(.*)\/bulletproof-security\/403\.php/';
			$pfwap_options = get_option('bulletproof_security_options_pfw_autopilot');

			if ( @file_exists($root_htaccess_file) && preg_match($root_pattern, $root_check_string, $root_matches) && $pfwap_options['bps_pfw_autopilot_cron'] == 'On' ) {
				
				echo '<div id="message" class="updated" style="background-color:#dfecf2;border:1px solid #999;-moz-border-radius-topleft:3px;-webkit-border-top-left-radius:3px;-khtml-border-top-left-radius:3px;border-top-left-radius:3px;-moz-border-radius-topright:3px;-webkit-border-top-right-radius:3px;-khtml-border-top-right-radius:3px;border-top-right-radius:3px;-webkit-box-shadow: 3px 3px 5px -1px rgba(153,153,153,0.7);-moz-box-shadow: 3px 3px 5px -1px rgba(153,153,153,0.7);box-shadow: 3px 3px 5px -1px rgba(153,153,153,0.7);"><p>';				
				$text = '<strong><font color="#fb0101">'.__('Plugin Firewall AutoPilot Mode Alert', 'bulletproof-security').'</font><br>'.__('Security Logging MUST be turned On in order for AutoPilot Mode to work. Either turn On Security Logging or turn Off AutoPilot Mode to make this Alert go away.', 'bulletproof-security').'</strong><br>';
				echo $text;
				echo '</p></div>';			
			}
		
			// 11.8: AutoFix blank plugins.htaccess file problem & older versions of PFW htaccess file
			if ( isset($pfwap_options['bps_pfw_autopilot_cron']) && $pfwap_options['bps_pfw_autopilot_cron'] == 'Off' ) {				

				$PluginsHtaccessMasterBackup = WP_PLUGIN_DIR . '/bulletproof-security/admin/htaccess/plugins.htaccess-backup.txt';
				$PluginsHtaccessMaster = WP_PLUGIN_DIR . '/bulletproof-security/admin/htaccess/plugins.htaccess';
				$PluginsHtaccessMasterARQ = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/bulletproof-security/admin/htaccess/plugins.htaccess';				
				$master_check_string = file_get_contents($PluginsHtaccessMaster);

				if ( ! preg_match( '/[a-zA-Z0-9]/', $master_check_string, $matches ) || ! strpos( $check_string, "BPS Pro 11 mod_rewrite" ) || ! strpos( $check_string, "bulletproof-security/405.php" ) ) {		
					
					if ( copy($PluginsHtaccessMasterBackup, $PluginsHtaccessMaster) ) {
						copy($PluginsHtaccessMaster, $PluginsHtaccessMasterARQ);
	
						require_once ( WP_PLUGIN_DIR . '/bulletproof-security/admin/wizard/swizard-functions.php' );		
						bpsSetupWizardPluginFirewall_File();
					}
				}
			}
		}
	}

	// This rest of this function ONLY applies to BEGIN PUBLIC IP change - Additional Roles are handled separately
	// Network/MU sites work differently - Additional Roles does not work on MU
	// if a user is not a Super Admin return - this is correct because if a Super Admin and an Administrator are logged in
	// then an additional IP address needs to be added using the Whitelist by Hostname (domain name) and IP Address tool or the Roles tool otherwise the 2 admins
	// will be updating/competing for the same Public IP address value at the same time.
	if ( is_multisite() && ! is_super_admin() ) {
		return;
	}

	if ( is_dir( WP_CONTENT_DIR . '/bps-backup/autorestore' ) ) {
		
		if ( ! is_dir( WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins' ) ) {
			@mkdir( WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins', 0755, true );
			@chmod( WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/', 0755 );
		}	
	}

	if ( file_exists($PluginsHtaccess) ) {
	
		//if ( strpos($check_string, $bps_get_public_ip) ) {	
		//	return;
		//}
		
		$PluginsHtaccessARQplugins = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins/.htaccess';
		$PluginsHtaccessARQDir = WP_CONTENT_DIR . '/bps-backup/autorestore/wp-content/plugins';

		//if ( ! strpos( $check_string, $bps_get_public_ip ) && is_dir( $PluginsHtaccessARQDir ) ) {
		if ( is_dir( $PluginsHtaccessARQDir ) ) {
					
			$stringReplace = @file_get_contents($PluginsHtaccess);
			$stringReplace = preg_replace('/BEGIN PUBLIC IP\s*(.*)END PUBLIC IP/s', "BEGIN PUBLIC IP\nRewriteCond %{REMOTE_ADDR} !^" . $bps_get_public_ip . "\$\n# END PUBLIC IP", $stringReplace);			
			
			// comment out both lines below for testing
			file_put_contents($PluginsHtaccess, $stringReplace);
			@copy($PluginsHtaccess, $PluginsHtaccessARQplugins);
		}
	
		// Error Check: Assume that everything has worked: IP address has been updated and the user has a BPS Pro 11 Plugin Firewall htaccess file.
		// Possible checks later if needed: RewriteCond %{REMOTE_ADDR} !^" . $bps_get_public_ip . "\$\n and BPS Pro 11 placeholder text exists. 
		// use the old <pre> code to display the problem visually with manual plugin firewall setup steps. have them email me if the manual steps do not work.
	} 
	}
}

add_action('admin_notices', 'bps_Plugins_Folder_Lockdown');

/*********************************************************/
//  Plugin Firewall AutoPilot - Cron Schedules & Check   //
/*********************************************************/

add_action('bpsPro_PFWAP_check', 'bpsPro_firewall_autopilot_mode');

// Plugin Firewall AutoPilot Cron schedule checks based on DB options saved
// 14.1: Added a PFW On|Off condition
function bpsPro_schedule_PFWAP_check() {
$options = get_option('bulletproof_security_options_pfw_autopilot');
$bpsPFWAPCronCheck = wp_get_schedule('bpsPro_PFWAP_check');
$killit = '';
	
	if ( ! get_option('bulletproof_security_options_pfw_autopilot' ) || ! isset($options['bps_pfw_autopilot_cron']) || $options['bps_pfw_autopilot_cron'] == '' || ! get_option('bulletproof_security_options_pfw_new_install' ) ) {
		return $killit;
	}
	
	$PFW_OnOff = get_option('bulletproof_security_options_pfw');

	if ( isset($PFW_OnOff['bps_pfw_on_off']) && $PFW_OnOff['bps_pfw_on_off'] == 'Off' ) {
		wp_clear_scheduled_hook('bpsPro_PFWAP_check');
		return;
	}

	if ( isset($options['bps_pfw_autopilot_cron']) && $options['bps_pfw_autopilot_cron'] == 'On' ) {
	
		$pfw_new_install_options = get_option('bulletproof_security_options_pfw_new_install'); 

		if ( isset($pfw_new_install_options['bps_pfw_new_install_completed']) && $pfw_new_install_options['bps_pfw_new_install_completed'] == 'No' ) {

			if ( time() > $pfw_new_install_options['bps_pfw_new_install_end'] ) {
				
				$BPS_pfw_new_install = array(
				'bps_pfw_new_install_start' 	=> time(), 
				'bps_pfw_new_install_end' 		=> time(), 
				'bps_pfw_new_install_completed' => 'Yes'
				);
	
				foreach( $BPS_pfw_new_install as $key => $value ) {
					update_option('bulletproof_security_options_pfw_new_install', $BPS_pfw_new_install);
				}
			
				wp_clear_scheduled_hook('bpsPro_PFWAP_check');
				
				if ( ! wp_next_scheduled('bpsPro_PFWAP_check' ) ) {
					wp_schedule_event( time(), 'minutes_10', 'bpsPro_PFWAP_check' );
				}			
			
				$BPS_PFWAP_Options = array( 
				'bps_pfw_autopilot_cron' 			=> 'On', 
				'bps_pfw_autopilot_cron_frequency' 	=> '10',  	
				'bps_pfw_autopilot_cron_end' 		=> time() + 900 
				);		
			
				foreach( $BPS_PFWAP_Options as $key => $value ) {
					update_option('bulletproof_security_options_pfw_autopilot', $BPS_PFWAP_Options);
				}
			}
		
			// Note: The default PFW cron interval time should be 10 minutes, but to avoid any possible problems don't 
			// create a cron frequency db option setting condition and instead just clear and reset the scheduled event to 1 minute.
			// In other words just clear the scheduled event ONCE if the Cron schedule value is not: minutes_1
			if ( time() < $pfw_new_install_options['bps_pfw_new_install_end'] ) {
				
				if ( $bpsPFWAPCronCheck == 'minutes_5' || $bpsPFWAPCronCheck == 'minutes_10' || $bpsPFWAPCronCheck == 'minutes_15' || $bpsPFWAPCronCheck == 'minutes_30' || $bpsPFWAPCronCheck == 'minutes_60' ) {
					wp_clear_scheduled_hook('bpsPro_PFWAP_check');
				}
				
				if ( ! wp_next_scheduled( 'bpsPro_PFWAP_check' ) ) {
					wp_schedule_event( time(), 'minutes_1', 'bpsPro_PFWAP_check');
				}		
			}
		
		} else {

			if ( $options['bps_pfw_autopilot_cron_frequency'] == '1' ) {
				if ( $bpsPFWAPCronCheck == 'minutes_5' || $bpsPFWAPCronCheck == 'minutes_10' || $bpsPFWAPCronCheck == 'minutes_15' || $bpsPFWAPCronCheck == 'minutes_30' || $bpsPFWAPCronCheck == 'minutes_60' ) {
					wp_clear_scheduled_hook('bpsPro_PFWAP_check');
				}
				
				if ( ! wp_next_scheduled( 'bpsPro_PFWAP_check' ) ) {
					wp_schedule_event( time(), 'minutes_1', 'bpsPro_PFWAP_check');
				}
			}
			
			if ( $options['bps_pfw_autopilot_cron_frequency'] == '5' ) {
				if ( $bpsPFWAPCronCheck == 'minutes_1' || $bpsPFWAPCronCheck == 'minutes_10' || $bpsPFWAPCronCheck == 'minutes_15' || $bpsPFWAPCronCheck == 'minutes_30' || $bpsPFWAPCronCheck == 'minutes_60' ) {
					wp_clear_scheduled_hook('bpsPro_PFWAP_check');
				}
				
				if ( ! wp_next_scheduled('bpsPro_PFWAP_check' ) ) {
					wp_schedule_event( time(), 'minutes_5', 'bpsPro_PFWAP_check' );
				}
			}
			
			if ( $options['bps_pfw_autopilot_cron_frequency'] == '10' ) {
				if ( $bpsPFWAPCronCheck == 'minutes_1' || $bpsPFWAPCronCheck == 'minutes_5' || $bpsPFWAPCronCheck == 'minutes_15' || $bpsPFWAPCronCheck == 'minutes_30' || $bpsPFWAPCronCheck == 'minutes_60' ) {
					wp_clear_scheduled_hook('bpsPro_PFWAP_check');
				}
				
				if ( ! wp_next_scheduled('bpsPro_PFWAP_check' ) ) {
					wp_schedule_event( time(), 'minutes_10', 'bpsPro_PFWAP_check' );
				}
			}
			
			if ( $options['bps_pfw_autopilot_cron_frequency'] == '15' ) {
				if ( $bpsPFWAPCronCheck == 'minutes_1' || $bpsPFWAPCronCheck == 'minutes_5' || $bpsPFWAPCronCheck == 'minutes_10' || $bpsPFWAPCronCheck == 'minutes_30' || $bpsPFWAPCronCheck == 'minutes_60' ) {
					wp_clear_scheduled_hook('bpsPro_PFWAP_check');
				}
				
				if ( ! wp_next_scheduled('bpsPro_PFWAP_check' ) ) {
					wp_schedule_event( time(), 'minutes_15', 'bpsPro_PFWAP_check' );
				}
			}
			
			if ( $options['bps_pfw_autopilot_cron_frequency'] == '30' ) {
				if ( $bpsPFWAPCronCheck == 'minutes_1' || $bpsPFWAPCronCheck == 'minutes_5' || $bpsPFWAPCronCheck == 'minutes_10' || $bpsPFWAPCronCheck == 'minutes_15' || $bpsPFWAPCronCheck == 'minutes_60' ) {
					wp_clear_scheduled_hook('bpsPro_PFWAP_check');
				}
				
				if ( ! wp_next_scheduled('bpsPro_PFWAP_check' ) ) {
					wp_schedule_event( time(), 'minutes_30', 'bpsPro_PFWAP_check' );
				}
			}
		
			if ( $options['bps_pfw_autopilot_cron_frequency'] == '60' ) {
				if ( $bpsPFWAPCronCheck == 'minutes_1' || $bpsPFWAPCronCheck == 'minutes_5' || $bpsPFWAPCronCheck == 'minutes_10' || $bpsPFWAPCronCheck == 'minutes_15' || $bpsPFWAPCronCheck == 'minutes_30' ) {
					wp_clear_scheduled_hook('bpsPro_PFWAP_check');
				}
				
				if ( ! wp_next_scheduled('bpsPro_PFWAP_check' ) ) {
					wp_schedule_event( time(), 'minutes_60', 'bpsPro_PFWAP_check' );
				}
			}
		}

	} elseif ( $options['bps_pfw_autopilot_cron'] == 'Off' ) { 
		wp_clear_scheduled_hook('bpsPro_PFWAP_check');
	}
}

add_action('init', 'bpsPro_schedule_PFWAP_check');

// Get Domain Root with prefix: used in autopilot mode function for preg_match_all
function bpsGetDomainRootPrefix() {

	if ( isset( $_SERVER['SERVER_NAME'] ) ) {

		$ServerName = esc_html( $_SERVER['SERVER_NAME'] );
		return $ServerName;		
	
	} else {
		
		$ServerName = esc_html( $_SERVER['HTTP_HOST'] );
		return $ServerName;	
	}
}

// Plugin Firewall AutoPilot Mode Cron with Time Restriction
// Note: AutoPilot Mode will automatically recreate a new Plugin Firewall htaccess file on the next Cron run
// Notes: Gets possible Plugin Firewall whitelist rules from Security Log file contents.
// Checks that the plugin folder & files actually really exist.
// Removes old or bad whitelist rules.
// Does not interfere with custom Regex whitelist rules.
// Does a unique array merge of new whitelist rules	and DB option whitelist rules
// New Plugin Firewall Whitelist rules are logged in the Security Log when detected and created
// 10.8 BugFix: Plugin Firewall AutoPilot Mode: Error: Minor Plugin Firewall Code Correction Needed
// 11: now using mod_rewrite and not mod_access_compat and mod_authz_core 
// 11.5 Change|BugFix: Whitelist by Hostname (domain name) and IP Address tool - previously called Allow from tool.
// 11.5 Change: The Master is written to and copied to Live htaccess file. Previously Master and Live files were written to separately.
// 11.8: New improved code to remove duplicate blocks of Allow From Rules code.
// 11.8: htaccess files disabled condition added
// 12.4.1: AutoPilot Mode bugFix. AutoPilot Mode is not creating new additional whitelist rules if whitelist rules were already created previously.
// Notes: This problem occurred when 2 separate blocks of code were consolidated into only 1 block of code and an old condition was not removed.
// in 9.9 that condition was added to prevent a blank whitelist rule from being written to the Security Log. Later in an newer version the 
// code autopilot was consolidated into 1 condition. Not sure which version that was.
// 12.5: Fix for double slashes // in path - create RegEx whitelist rule & "plugins" folder name used in path - preg_match from wp-content folder.
// 12.9: Conditions added for nuisance log entries: Checks that file actually exists - URI points directly to the root /plugins/example.php folder
// 12.9: Added Plugin Firewall Test Mode conditions
// 14.1: Added PFW On|Off condition
function bpsPro_firewall_autopilot_mode() {
$PFWAP_options = get_option('bulletproof_security_options_pfw_autopilot');
$bpsProLogARQ = WP_CONTENT_DIR . '/bps-backup/logs/http_error_log.txt';

	if ( $PFWAP_options['bps_pfw_autopilot_cron'] == 'Off' || ! get_option('bulletproof_security_options_pfw_autopilot') ) {
		exit();
	}
	
	$HFiles_options = get_option('bulletproof_security_options_htaccess_files');
	
	if ( isset( $HFiles_options['bps_htaccess_files'] ) && $HFiles_options['bps_htaccess_files'] == 'disabled' ) {
		exit();
	}

	$PFW_OnOff = get_option('bulletproof_security_options_pfw');

	if ( isset($PFW_OnOff['bps_pfw_on_off']) && $PFW_OnOff['bps_pfw_on_off'] == 'Off' ) {
		exit();
	}

	if ( time() < $PFWAP_options['bps_pfw_autopilot_cron_end'] ) {
		exit();
	
	} else {
	
		if ( file_exists($bpsProLogARQ) ) {
	
			if ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
				$ip = esc_html( $_SERVER['HTTP_CLIENT_IP'] );
			
				if ( ! is_array($ip) ) {
				
					if ( preg_match( '/(\d+\.){3}\d+/', $ip, $matches ) ) {

						$public_ip = $matches[0];	
				
					} elseif ( preg_match( '/([:\d\w]+\.(\d+\.){2}\d+|[:\d\w]+)/', $ip, $matches ) ) {
				
						$public_ip = $matches[0];	
		
					} else {
					
						$public_ip = $ip;
					}
			
				} else {
				
					$public_ip = current($ip);				
				}
		
			} elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
				$ip = esc_html( $_SERVER['HTTP_X_FORWARDED_FOR'] );
			
				if ( ! is_array($ip) ) {
				
					if ( preg_match( '/(\d+\.){3}\d+/', $ip, $matches ) ) {

						$public_ip = $matches[0];	
				
					} elseif ( preg_match( '/([:\d\w]+\.(\d+\.){2}\d+|[:\d\w]+)/', $ip, $matches ) ) {
				
						$public_ip = $matches[0];	
		
					} else {
					
						$public_ip = $ip;
					}
			
				} else {
				
					$public_ip = current($ip);				
				}
		
			} elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
				$ip = esc_html( $_SERVER['REMOTE_ADDR'] );
				$public_ip = $ip;
			}

			global $bpspro_version, $wp_version;
			$bps_wpcontent_dir = str_replace( ABSPATH, '', WP_CONTENT_DIR );
			$bpsProLogARQ_contents = file_get_contents($bpsProLogARQ);
			$filterPattern1 = '/\/bulletproof-security\/admin\/php\/bps-phpinfo\.php/';
			// 13.2: filter changed to include all BPS .php files - 400.php, 403.php, 404.php, 405.php, 410.php, etc.
			$filterPattern2 = '/\/bulletproof-security\/(.*).php/';
			$filterPattern3 = '/\/bulletproof-security\/admin\/js\/(.*)\.js/';
			$filterPattern4 = '/HTTP_REFERER:\s(.*)\/plugins\/(.*)(\.js|\.php|\.swf)/';
			$filterPattern5 = '/\/bulletproof-security\/isl-logout\.php/';			
			$filterPattern6 = '/\/bulletproof-security\/admin\/htaccess\/bps-maintenance(.*)\.php/';
			
			preg_match_all( '/HTTP_REFERER:\shttps?:\/\/' . bpsGetDomainRootPrefix() . '(.*)\s*REQUEST_URI:(.*)\/'.$bps_wpcontent_dir.'\/plugins\/(.*)(\.js|\.php|\.swf|\.json)/', $bpsProLogARQ_contents, $matches );
			
			$pathValue = array();
		
			foreach ( $matches[0] as $Key => $Value ) {
				// Filters
				if ( ! preg_match( $filterPattern1, $Value ) && ! preg_match( $filterPattern2, $Value ) && ! preg_match( $filterPattern3, $Value ) && ! preg_match( $filterPattern4, $Value ) && ! preg_match( $filterPattern5, $Value ) && ! preg_match( $filterPattern6, $Value ) ) {
								
					$dir_check = preg_replace( '/HTTP_REFERER:\shttps?:\/\/' . bpsGetDomainRootPrefix() . '(.*)\s*REQUEST_URI:(.*)\/'.$bps_wpcontent_dir.'\/plugins/', '', $Value );

					if ( is_dir( WP_PLUGIN_DIR . dirname($dir_check) ) && file_exists( WP_PLUGIN_DIR.dirname($dir_check).DIRECTORY_SEPARATOR.basename($dir_check) ) && dirname($dir_check) != '\\' && dirname($dir_check) != '/' ) {	

						$pathValue[] = preg_replace( '/\/\//', '/(.*)', $dir_check );
						$comma_separated = implode( ', ', $pathValue );	
						$NoDupes = implode( ', ', array_unique( explode( ', ', $comma_separated ) ) );
					}
				}
			}

			$PFW_options = get_option('bulletproof_security_options_pfirewall');

			$string1 = $PFW_options['bps_pfw_whitelist'];
			$string2 = @$NoDupes;
			
			## 13.5: String added and merged for the WordPress Social Login plugin
			$wordpress_social_login = 'wordpress-social-login/wp-social-login.php';
			$wordpress_social_login_active = in_array( $wordpress_social_login, apply_filters('active_plugins', get_option('active_plugins')));
			
			if ( $wordpress_social_login_active == 1 || is_plugin_active_for_network( $wordpress_social_login ) ) {
				$string3 = '/wordpress-social-login/(.*).(js|php)';
				$NoDupes = @$NoDupes . ', ' . $string3;
			} else {
				$string3 = '';
			}
			
			## 14.9: String added and merged for YITH WooCommerce Social Login Premium
			$yith_woocommerce_social_login = WP_PLUGIN_DIR . '/yith-woocommerce-social-login/includes/hybridauth/twitter.php';			
			$yith_woocommerce_social_login_premium = WP_PLUGIN_DIR . '/yith-woocommerce-social-login-premium/includes/hybridauth/twitter.php';
			
			if ( file_exists( $yith_woocommerce_social_login ) || file_exists ( $yith_woocommerce_social_login_premium ) ) {
				$string4 = '/yith-woocommerce-social-login(.*)/includes/hybridauth/(.*).(php)';
				$NoDupes = @$NoDupes . ', ' . $string4;
			} else {
				$string4 = '';
			}				

			$stringMerge = $string1 . ', ' . $string2 . ', ' . $string3 . ', ' . $string4;
			$stringMergeUnique = implode( ', ', array_unique( explode( ', ', trim( $stringMerge, ", \t\n\r" ) ) ) );
			
			$NoDupes_array = explode( ', ', @$NoDupes );
			$pfw_whitelist_array = explode( ', ', $PFW_options['bps_pfw_whitelist'] );
			$result = array_diff($NoDupes_array, $pfw_whitelist_array);
			
			$timeNow = time();
			$gmt_offset = get_option( 'gmt_offset' ) * 3600;
			$timestamp = date_i18n(get_option('date_format'), strtotime("11/15-1976")) . ' - ' . date_i18n(get_option('time_format'), $timeNow + $gmt_offset);
			$bpsSecLog = WP_CONTENT_DIR . '/bps-backup/logs/http_error_log.txt';
			$log_title = "\r\n" . '[Plugin Firewall AutoPilot Mode New Whitelist Rule(s) Created: ' . $timestamp . ']' . "\r\n" . 'BPS Pro: ' . $bpspro_version . "\r\n" . 'WP: ' . $wp_version . "\r\n";
			
			if ( $PFW_options['bps_pfw_paypal'] == '1' ) {
				$payPal = 'RewriteCond %{HTTP_HOST} !^paypal.com$' . "\n";
			} else {
				$payPal = '';
			}
	
			if ( $PFW_options['bps_pfw_google'] == '1' ) {
				$google = 'RewriteCond %{HTTP_HOST} !^google.com$' . "\n";
			} else {
				$google = '';
			}

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

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

			// PFW Create New Whitelist Rules if detected
			// 12.5: condition that was breaking new AutoPilot whitelist rules created on re-runs:  if ( ! empty($result) && $result[0] != '' ) {
			if ( ! empty($result) && $string2 != '' ) {
		
				if ( is_writable( $bpsSecLog ) ) {
				if ( ! $handle = fopen( $bpsSecLog, 'a' ) ) {
        			exit;
    			}
    			if ( fwrite( $handle, $log_title ) === FALSE ) {
        			exit;
    			}
    			fclose($handle);
				}

				foreach ( $result as $key => $value ) {
		
					$log_contents = 'Whitelist Rule: ' . $value . "\r\n";
					
					if ( is_writable( $bpsSecLog ) ) {
					if ( ! $handle = fopen( $bpsSecLog, 'a' ) ) {
         				exit;
    				}
    				if ( fwrite( $handle, $log_contents ) === FALSE ) {
        				exit;
    				}
    				fclose($handle);
					}
				}

				$bps_pfw_whitelist = $stringMergeUnique;

				$BPS_PFW_Options = array(
				'bps_pfw_paypal' 		=> $PFW_options['bps_pfw_paypal'], 
				'bps_pfw_google' 		=> $PFW_options['bps_pfw_google'], 
				'bps_pfw_amazon' 		=> $PFW_options['bps_pfw_amazon'], 
				'bps_pfw_authorizenet' 	=> $PFW_options['bps_pfw_authorizenet'], 
				'bps_pfw_whitelist' 	=> $bps_pfw_whitelist
				);

				foreach( $BPS_PFW_Options as $key => $value ) {
					update_option('bulletproof_security_options_pfirewall', $BPS_PFW_Options);
				}
			
			/* for testing: print_r($stringMergeUnique); */
			$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';
			$PluginsHtaccessMasterBackup = WP_PLUGIN_DIR . '/bulletproof-security/admin/htaccess/plugins.htaccess-backup.txt';
			$master_check_string = file_get_contents($PluginsHtaccessMaster);
			
			if ( file_exists($PluginsHtaccessMaster) ) {
		
				if ( ! preg_match( '/[a-zA-Z0-9]/', $master_check_string, $matches ) ) {		
					
					if ( copy($PluginsHtaccessMasterBackup, $PluginsHtaccessMaster) ) {
						@copy($PluginsHtaccessMaster, $PluginsHtaccessARQ);
					}
				}

				// IMPORTANT! Get the new PFW DB Option values again here
				$PFW_options_new = get_option('bulletproof_security_options_pfirewall');
				$bps_pfw_whitelist_filter = array_filter( explode( ', ', trim( $PFW_options_new['bps_pfw_whitelist'], ", \t\n\r") ) );				
				
				$whiteList = array();
		
				foreach ( $bps_pfw_whitelist_filter as $Key => $Value ) {
				
					$Value_rule = preg_replace( '/\//', "^", $Value, 1 );
					$whiteList[] = 'RewriteRule ' . $Value_rule . ' - [L]' . "\n";
					$uniqueRules = array_unique($whiteList);
						
					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} !^" . $public_ip . "\$\n# END PUBLIC IP", $PluginsHtaccessMaster_contents);

				file_put_contents($PluginsHtaccessMaster, $stringReplace);
		
				/** Whitelist by Hostname (domain name) and IP Address tool. Previously called: 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 ( $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);
				}				

				if ( file_put_contents($PluginsHtaccessMaster, $stringReplace) ) {
					@copy($PluginsHtaccessMaster, $PluginsHtaccess);
					@copy($PluginsHtaccessMaster, $PluginsHtaccessARQ);
					@copy($PluginsHtaccessMaster, $PluginsHtaccessARQplugins);	
					@copy($pluginsHtaccessMasterTXT, $pluginsHtaccessMasterTXTARQ);
					@copy($pluginsAllowFromTXT, $pluginsAllowFromTXTARQ);				
				}
				
				// Plugin Firewall Test Mode: Set the IP address to: 127.0.0.9 for Public IP, Allow From Rules and Additional Roles IP
				$PFWTM_options = get_option('bulletproof_security_options_pfw_test_mode');
	
				if ( $PFWTM_options['bps_pfw_test_mode'] == 'On' ) {
	
					$pattern1 = '/#\sBEGIN\sPUBLIC\sIP(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sPUBLIC\sIP/';
					$pattern2 = '/#\sBEGIN\sADDITIONAL\sALLOW\sFROM\sRULES(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sADDITIONAL\sALLOW\sFROM\sRULES/';
					$pattern3 = '/#\sBEGIN\sADDITIONAL\sROLES\sIP(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sADDITIONAL\sROLES\sIP/';	

					if ( preg_match( $pattern1, $stringReplace, $matches ) ) {
						$stringReplace = preg_replace( $pattern1, "# BEGIN PUBLIC IP\nRewriteCond %{REMOTE_ADDR} !^127.0.0.9$\n# END PUBLIC IP", $stringReplace );
					}
	
					if ( preg_match( $pattern2, $stringReplace, $matches ) ) {
						$stringReplace = preg_replace( $pattern2, "# BEGIN ADDITIONAL ALLOW FROM RULES\nRewriteCond %{REMOTE_ADDR} !^127.0.0.9$\n# END ADDITIONAL ALLOW FROM RULES", $stringReplace );
					}

					if ( preg_match( $pattern3, $stringReplace, $matches ) ) {
						$stringReplace = preg_replace( $pattern3, "# BEGIN ADDITIONAL ROLES IP\nRewriteCond %{REMOTE_ADDR} !^127.0.0.9$\n# END ADDITIONAL ROLES IP", $stringReplace );
					}				
				
					if ( file_put_contents($PluginsHtaccess, $stringReplace ) ) {
						copy($PluginsHtaccess, $PluginsHtaccessARQplugins);
					}
				}
			} // end if ( file_exists($PluginsHtaccessMaster) ) {
			} // end if ( ! empty($result) ) {

			// PFW Whitelist Rule Clean Up: Remove invalid or old/unused whitelist rules
			$PFW_options = get_option('bulletproof_security_options_pfirewall');
			$pfw_whitelist_cleanup = explode( ', ', $PFW_options['bps_pfw_whitelist'] );
			$cfilter1 = '/\/plugins\/[a-zA-Z]{1,}\.php/';	
			$cfilter2 = '/\/bulletproof-security\/(405\.php|includes|admin).*/';
			$wp_plugin_dir_str_replace = str_replace( array( '\\', '//' ), "/", WP_PLUGIN_DIR );
		
			$whiteList_cleanup = array();

			foreach ( $pfw_whitelist_cleanup as $Key => $Value ) {
					
				$whiteList_cleanup[] = $wp_plugin_dir_str_replace . $Value;
				$uniqueRules_cleanup = array_unique($whiteList_cleanup);
			}
			
			$uniqueRule_cleanup_rules_array = array();
				
			foreach ( $uniqueRules_cleanup as $uniqueRule_cleanup ) {
					
				if ( $uniqueRule_cleanup != '' ) {
					// Match Regex characters: ( ) * ^ $ + ? \ [ ] { } | 
					// filter BPS plugin folders and root plugins folder .php files
					if ( ! preg_match( $cfilter1, $uniqueRule_cleanup ) && ! preg_match( $cfilter2, $uniqueRule_cleanup ) ) {
						
						if ( file_exists($uniqueRule_cleanup) || preg_match( '/[\(\)\*\^\$\+\?\\\[\]\{\}\|]/', $uniqueRule_cleanup ) ) {
							
							$uniqueRule_cleanup_rules = str_replace( $wp_plugin_dir_str_replace, "", $uniqueRule_cleanup );
							$uniqueRule_cleanup_rules_array[] = $uniqueRule_cleanup_rules;
							$comma_separated_c = implode( ', ', $uniqueRule_cleanup_rules_array );	
							$NoDupes_cleanup = implode( ', ', array_unique( explode( ', ', $comma_separated_c ) ) );
						}
					}
				}		
			}

			$bps_pfw_whitelist_db = $NoDupes_cleanup;

			$BPS_PFW_Options = array(
			'bps_pfw_paypal' 		=> $PFW_options['bps_pfw_paypal'], 
			'bps_pfw_google' 		=> $PFW_options['bps_pfw_google'], 
			'bps_pfw_amazon' 		=> $PFW_options['bps_pfw_amazon'], 
			'bps_pfw_authorizenet' 	=> $PFW_options['bps_pfw_authorizenet'], 
			'bps_pfw_whitelist' 	=> $bps_pfw_whitelist_db
			);

				foreach( $BPS_PFW_Options as $key => $value ) {
					update_option('bulletproof_security_options_pfirewall', $BPS_PFW_Options);
				}

			$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';
			$PluginsHtaccessMasterBackup = WP_PLUGIN_DIR . '/bulletproof-security/admin/htaccess/plugins.htaccess-backup.txt';
			$master_check_string = file_get_contents($PluginsHtaccessMaster);

			if ( file_exists($PluginsHtaccessMaster) ) {
		
				if ( ! preg_match( '/[a-zA-Z0-9]/', $master_check_string, $matches ) ) {		
					
					if ( copy($PluginsHtaccessMasterBackup, $PluginsHtaccessMaster) ) {
						@copy($PluginsHtaccessMaster, $PluginsHtaccessARQ);
					}
				}

				// IMPORTANT! Get the new PFW DB Option values again here
				$PFW_options_new = get_option('bulletproof_security_options_pfirewall');
				$bps_pfw_whitelist_filter = array_filter( explode( ', ', trim( $PFW_options_new['bps_pfw_whitelist'], ", \t\n\r") ) );				
				
				$whiteList = array();
		
				foreach ( $bps_pfw_whitelist_filter as $Key => $Value ) {
				
					$Value_rule = preg_replace( '/\//', "^", $Value, 1 );
					$whiteList[] = 'RewriteRule ' . $Value_rule . ' - [L]' . "\n";
					$uniqueRules = array_unique($whiteList);
						
					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} !^" . $public_ip . "\$\n# END PUBLIC IP", $PluginsHtaccessMaster_contents);

				file_put_contents($PluginsHtaccessMaster, $stringReplace);
		
				/** Whitelist by Hostname (domain name) and IP Address tool. Previously called: 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 ( $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);
				}

				if ( file_put_contents($PluginsHtaccessMaster, $stringReplace) ) {
					@copy($PluginsHtaccessMaster, $PluginsHtaccess);
					@copy($PluginsHtaccessMaster, $PluginsHtaccessARQ);
					@copy($PluginsHtaccessMaster, $PluginsHtaccessARQplugins);	
					@copy($pluginsHtaccessMasterTXT, $pluginsHtaccessMasterTXTARQ);
					@copy($pluginsAllowFromTXT, $pluginsAllowFromTXTARQ);				
				}

				// Plugin Firewall Test Mode: Set the IP address to: 127.0.0.9 for Public IP, Allow From Rules and Additional Roles IP
				$PFWTM_options = get_option('bulletproof_security_options_pfw_test_mode');
	
				if ( isset($PFWTM_options['bps_pfw_test_mode']) && $PFWTM_options['bps_pfw_test_mode'] == 'On' ) {
	
					$pattern1 = '/#\sBEGIN\sPUBLIC\sIP(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sPUBLIC\sIP/';
					$pattern2 = '/#\sBEGIN\sADDITIONAL\sALLOW\sFROM\sRULES(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sADDITIONAL\sALLOW\sFROM\sRULES/';
					$pattern3 = '/#\sBEGIN\sADDITIONAL\sROLES\sIP(.*\s*)([a-zA-Z0-9].*\s*){1,}#\sEND\sADDITIONAL\sROLES\sIP/';	

					if ( preg_match( $pattern1, $stringReplace, $matches ) ) {
						$stringReplace = preg_replace( $pattern1, "# BEGIN PUBLIC IP\nRewriteCond %{REMOTE_ADDR} !^127.0.0.9$\n# END PUBLIC IP", $stringReplace );
					}
	
					if ( preg_match( $pattern2, $stringReplace, $matches ) ) {
						$stringReplace = preg_replace( $pattern2, "# BEGIN ADDITIONAL ALLOW FROM RULES\nRewriteCond %{REMOTE_ADDR} !^127.0.0.9$\n# END ADDITIONAL ALLOW FROM RULES", $stringReplace );
					}

					if ( preg_match( $pattern3, $stringReplace, $matches ) ) {
						$stringReplace = preg_replace( $pattern3, "# BEGIN ADDITIONAL ROLES IP\nRewriteCond %{REMOTE_ADDR} !^127.0.0.9$\n# END ADDITIONAL ROLES IP", $stringReplace );
					}				
				
					if ( file_put_contents($PluginsHtaccess, $stringReplace ) ) {
						copy($PluginsHtaccess, $PluginsHtaccessARQplugins);
					}
				}
			} // end if ( file_exists($PluginsHtaccessMaster) ) {
		} // end if ( file_exists($bpsProLogARQ) ) {
	}
}

?>