<?php
/**
 * @package AOW - Security Plugin
 */
/*
Plugin Name: AOW - Security Plugin
Plugin URI: http://aheadoftheweb.com
Description: This custom plugin provides login page protection for AOW clients.
Version: 1.1.2
Author: Ahead of the Web
Author URI: http://aheadoftheweb.com
License: GPLv2 or later
*/

/**
 * Setup native automatic theme update functionality
 */
require 'update-checker/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
	'https://updates.aheadoftheweb.com/?action=get_metadata&slug=aow_security',
	__FILE__,
	'aow_security'
);

if (!function_exists('aow')):
function aow()
{
	$plugin_base = get_home_path()."wp-content/plugins/";

	echo "<h2>Ahead of the Web Plugins</h2>
	<hr />";
?>
	<ul>
    <li>AOW - Central Author Plugin - <?php if (is_plugin_active('aow_author/aow_author.php')): ?> <strong>Active</strong> <?php elseif (is_plugin_inactive('aow_author/aow_author.php') && is_dir($plugin_base."aow_author")): ?> <strong>Inactive</strong> <?php else: ?><strong>Not installed</strong> <?php endif; ?></li>
    <li>AOW - Hours of Business Plugin - <?php if (is_plugin_active('aow_contentshare-child/aow_contentshare-child.php')): ?> <strong>Active</strong> <?php elseif (is_plugin_inactive('aow_contentshare-child/aow_contentshare-child.php') && is_dir($plugin_base."aow_contentshare-child")): ?> <strong>Inactive</strong> <?php else: ?><strong>Not installed</strong> <?php endif; ?> </li>
    <li>AOW - Links Plugin - <?php if (is_plugin_active('aow_hub_links/aow_hub_links.php')): ?> <strong>Active</strong> <?php elseif (is_plugin_inactive('aow_hub_links/aow_hub_links.php') && is_dir($plugin_base."aow_hub_links")): ?> <strong>Inactive</strong> <?php else: ?><strong>Not installed</strong> <?php endif; ?></li>
    <li>AOW - Promotion Plugin - <?php if (is_plugin_active('aow_hub_promo/aow_hub_promo.php')): ?> <strong>Active</strong> <?php elseif (is_plugin_inactive('aow_hub_promo/aow_hub_promo.php') && is_dir($plugin_base."aow_hub_promo")): ?> <strong>Inactive</strong> <?php else: ?><strong>Not installed</strong> <?php endif; ?> </li>
    <li>AOW - Referral Promotion Plugin - <?php if (is_plugin_active('aow_referral_promotion/aow_referral_promotion.php')): ?> <strong>Active</strong> <?php elseif (is_plugin_inactive('aow_referral_promotion/aow_referral_promotion.php') && is_dir($plugin_base."aow_referral_promotion")): ?> <strong>Inactive</strong> <?php else: ?><strong>Not installed</strong> <?php endif; ?></li>
    <li>AOW - Security Plugin - <?php if (is_plugin_active('aow_security/aow_security.php')): ?> <strong>Active</strong> <?php elseif (is_plugin_inactive('aow_security/aow_security.php') && is_dir($plugin_base."aow_security")): ?> <strong>Inactive</strong> <?php else: ?><strong>Not installed</strong> <?php endif; ?></li>
    <li>AOW - Testimonials Plugin - <?php if (is_plugin_active('aow_testimonial/aow_testimonial.php')): ?> <strong>Active</strong> <?php elseif (is_plugin_inactive('aow_testimonial/aow_testimonial.php') && is_dir($plugin_base."aow_testimonial")): ?> <strong>Inactive</strong> <?php else: ?><strong>Not installed</strong> <?php endif; ?></li>
    </ul>
<?php
}
endif;

function aow_security_menu()
{
		if (empty($GLOBALS['admin_page_hooks']['aow'])):
			add_menu_page('AOW Plugins', 'AOW Plugins', 'update_plugins', 'aow', 'aow','dashicons-admin-plugins');
		endif;
	add_submenu_page('aow','Security', 'Security', 'update_plugins', 'aow-security', 'aow_security');
	add_submenu_page('aow-security','Security', 'Security', 'update_plugins', 'aow-security-about', 'aow_security_about');

}
add_action('admin_menu', 'aow_security_menu'); // this is the function that is called to add items to the admin menu.

function aow_security_about()
{
	require_once('includes/about.php');
}

function aow_security()
{
	require_once('includes/main_content.php');
}

add_action( 'upgrader_process_complete', 'aow_upgrader_ran', 10, 2 );

function aow_upgrader_ran($upgrader_object, $options)
{
    // inspect $options
		aow_security_activate();
}

function aow_security_activate()
{

			if (!isset($_COOKIE["IamCool"])):
			$month = strtotime("+6 months"); // set to six months
			setcookie("IamCool","yesyouare",$month,"/");
			endif;
			
		$homepath = get_home_path();
		$pluginpath = plugin_dir_path(__FILE__);
		$plugin_forbidden_file = $pluginpath."forbidden.php";
		$plugin_something_file = $pluginpath."alittlesomethingforyou.php";
		$root_forbidden_file = $homepath."forbidden.php";
		$root_something_file = $homepath."alittlesomethingforyou.php";

			if (!file_exists($root_forbidden_file)):
				copy($plugin_forbidden_file,$root_forbidden_file);
			endif;

			if (!file_exists($root_something_file)):
				copy($plugin_something_file,$root_something_file);
			endif;
			
			$htaccess = get_home_path().".htaccess";
			chmod($htaccess,0755);
			
			$root_doc = $_SERVER['DOCUMENT_ROOT'];
			$path_explosion = explode("/",$homepath);
	/* begin modified by jade 
			$root_name = end(explode("/",$root_doc)); 
			commented out original single line and added two new lines below */
			$exploded = explode('/', $root_doc);
			$root_name = end($exploded);
	/* end added by jade */
			$search_dir_key = array_search($root_name,$path_explosion);
			$htaccess_path = "";
			if ($search_dir_key !== false):
				for ($i=$search_dir_key+1;$i<count($path_explosion);$i++):
				if (isset($path_explosion[$i])):
				$htaccess_path .= "/".$path_explosion[$i];
				endif;
				endfor;
			else:
				$htaccess_path = "/";
			endif;

			$lines = array();
			$lines[0] = "RewriteEngine On";
			$lines[1] = "RewriteCond %{REQUEST_URI} ^".$htaccess_path."wp-login.php$";
			$lines[2] = "RewriteCond %{HTTP_COOKIE} !^.*IamCool.*$ [NC]";
			$lines[3] = "RewriteRule . ".$htaccess_path."forbidden.php [NC,L]";
			$lines[4] = "<Files xmlrpc.php>";
			$lines[5] = "Order Allow,Deny";
			$lines[6] = "Deny from all";
			$lines[7] = "</Files>";

			
		$ht_resource = file($htaccess);
		$trimmed_array = array_map('trim',$ht_resource); // trim extra spaces in each line so we can use php to search if the values exist

		$begin_wordpress = array_search("# BEGIN WordPress",$trimmed_array,true);
		$end_wordpress = array_search("# END WordPress",$trimmed_array,true);

		/* Check if the htaccess file contains these rules. If it does not, it will create them. */
		foreach($ht_resource as $k => $line):

			foreach ($lines as $l):
			if (trim($line) == trim($l)): // the line matches one of the items we want to modify.
			
			if ($begin_wordpress !== FALSE && $end_wordpress !== FALSE):
				if ($begin_wordpress < $k && $end_wordpress > $k):
				// don't unset this item since we don't want to get rid of the item in the wordpress modified section.
				else:
					unset($ht_resource[$k]);
				endif;
			else: // else begin_wordpress is false and/or end_wordpress is false
					unset($ht_resource[$k]);
			endif; // endif ($begin_wordpress !== FALSE && $end_wordpress !== FALSE):

			endif; // endif (trim($line) == trime($l))
			endforeach;

		endforeach;

		file_put_contents($htaccess, $ht_resource);
		
			insert_with_markers($htaccess, "Ahead of the Web Security",$lines);
			chmod($htaccess,0644);
}
register_activation_hook(__FILE__,'aow_security_activate');
function aow_security_deactivate()
{
			$homepath = get_home_path();
			$root_forbidden_file = $homepath."forbidden.php";
			$root_something_file = $homepath."alittlesomethingforyou.php";
			$lines = array();
			/*			insert_with_markers($htaccess, "",$lines);*/
			$htaccess = get_home_path().".htaccess";
			chmod($htaccess,0755);
			$root_doc = $_SERVER['DOCUMENT_ROOT'];
			$path_explosion = explode("/",$homepath);
			$root_name = end(explode("/",$root_doc));
			$search_dir_key = array_search($root_name,$path_explosion);
			$htaccess_path = "";
			if ($search_dir_key !== false):
				for ($i=$search_dir_key+1;$i<count($path_explosion);$i++):
				if (isset($path_explosion[$i])):
				$htaccess_path .= "/".$path_explosion[$i];
				endif;
				endfor;
			else:
				$htaccess_path = "/";
			endif;

			$lines = array();
			$lines[0] = "# BEGIN Ahead of the Web Security";
			$lines[1] = "RewriteEngine On";
			$lines[2] = "RewriteCond %{REQUEST_URI} ^".$htaccess_path."wp-login.php$";
			$lines[3] = "RewriteCond %{REQUEST_URI} ^/wp-login.php$"; // allows us to delete the old version as well
			$lines[4] = "RewriteCond %{HTTP_COOKIE} !^.*IamCool.*$ [NC]";
			$lines[5] = "RewriteRule . /forbidden.php [NC,L]"; // allows us to delete the old version as well
			$lines[6] = "RewriteRule . ".$htaccess_path."forbidden.php [NC,L]";
			$lines[7] = "# END Ahead of the Web Security";
		$ht_resource = file($htaccess);
		$trimmed_array = array_map('trim',$ht_resource); // trim extra spaces in each line so we can use php to search if the values exist

		$begin_wordpress = array_search("# BEGIN WordPress",$trimmed_array,true);
		$end_wordpress = array_search("# END WordPress",$trimmed_array,true);
		
		/* Check if the htaccess file contains these rules. If it does not, it will create them. */
		foreach($ht_resource as $k => $line):

			foreach ($lines as $l):
			if (trim($line) == trim($l)): // the line matches one of the items we want to modify.
			
			if ($begin_wordpress !== FALSE && $end_wordpress !== FALSE):
				if ($begin_wordpress < $k && $end_wordpress > $k):
				// don't unset this item since we don't want to get rid of the item in the wordpress modified section.
				else:
					unset($ht_resource[$k]);
				endif;
			else: // else begin_wordpress is false and/or end_wordpress is false
					unset($ht_resource[$k]);
			endif; // endif ($begin_wordpress !== FALSE && $end_wordpress !== FALSE):

			endif; // endif (trim($line) == trime($l))
			endforeach;

		endforeach;

		file_put_contents($htaccess, $ht_resource);
		
			if (file_exists($root_forbidden_file)):
			unlink($root_forbidden_file);
			endif;
			
			if (file_exists($root_something_file)):
			unlink($root_something_file);
			endif;

	if (isset($_COOKIE['IamCool']) && $_COOKIE["IamCool"] == "yesyouare"): setcookie( 'IamCool', "", time() - 3600); endif;
	chmod($htaccess,0644);
}
register_deactivation_hook(__FILE__,'aow_security_deactivate');

function aow_admin_init()
{
			$homepath = get_home_path();

		if (is_admin() && is_user_logged_in() ){
			$month = strtotime("+6 months"); // set to six months
			@setcookie("IamCool","yesyouare",$month,"/");

		}elseif ( defined( 'DOING_AJAX' ) && DOING_AJAX ){
				
		}else{
			setcookie( 'IamCool', "", time() - 3600);
			$siteurl = site_url()."/forbidden.php";
			wp_redirect($siteurl ,"301");
			wp_logout();
			exit;
		}
}
add_action('admin_init', 'aow_admin_init');

function remove_user_cookie()
{
	setcookie( 'IamCool', "", time() - 3600);
	if (isset($_COOKIE['IamCool']) && $_COOKIE["IamCool"] == "yesyouare"): setcookie( 'IamCool', "", time() - 3600); endif;
}

function respond_to_user_logout() {
	setcookie( 'IamCool', "", time() - 3600);
}

add_action('wp_logout', 'respond_to_user_logout');