<?php
	// Content Protection

add_action('wp_head', 'wpfresh5_wccp_main_settings');
add_action('wp_head', 'wpfresh5_right_click_premium_settings');
// add_action('wp_head', 'wpfresh5_wccp_css_settings');
// add_action('wp_footer', 'wpfresh5_alert_message');
// add_filter('body_class', 'wpfresh5_wccp_class_names');

function wpfresh5_wccp_main_settings()
{
	$disable_select = wpfresh5_get_settings( array( 'security', 'content', 'disable_select' ) );
	if( /*!current_user_can( 'manage_options' ) || (current_user_can( 'manage_options' ) && $wccp_settings['exclude_admin_from_protection'] == 'No')*/ $disable_select){
			if (((is_home() || is_front_page() || is_archive() || is_post_type_archive() ||  is_404() || is_attachment() || is_author() || is_category() || is_feed() || is_search()) /*&& $wccp_settings['home_page_protection'] == 'Enabled'*/))
			{
				wpfresh5_disable_selection();
				return;
			}
			if (is_single() /*&& $wccp_settings['single_posts_protection'] == 'Enabled'*/)
			{
				wpfresh5_disable_selection();
				return;
			}
			if (is_page() && !is_front_page()/* && $wccp_settings['page_protection'] == 'Enabled'*/)
			{
				wpfresh5_disable_selection();
				return;
			}
	}
}

function wpfresh5_right_click_premium_settings()
{
	$disable_right = wpfresh5_get_settings( array( 'security', 'content', 'disable_right' ) );
	if(/*!current_user_can( 'manage_options' ) || (current_user_can( 'manage_options' ) && $wccp_settings['exclude_admin_from_protection'] == 'No')*/ $disable_right ){
			if (((is_home() || is_front_page() || is_archive() || is_post_type_archive() ||  is_404() || is_attachment() || is_author() || is_category() || is_feed()) /*&& $wccp_settings['right_click_protection_homepage'] == 'checked'*/))
			{
				wpfresh5_disable_right_click();
				return;
			}
		if (is_single() /*&& $wccp_settings['right_click_protection_posts'] == 'checked'*/)
			{
				wpfresh5_disable_right_click();
				return;
			}
		if (is_page() && !is_front_page() /*&& $wccp_settings['right_click_protection_posts'] == 'checked'*/)
			{
				wpfresh5_disable_right_click();
				return;
			}
	}
}

function wpfresh5_wccp_class_names()
{
	global $wccp_settings;
	if(!current_user_can( 'manage_options' ) || (current_user_can( 'manage_options' ) && $wccp_settings['exclude_admin_from_protection'] == 'No')){
		if (((is_home() || is_front_page() || is_archive() || is_post_type_archive() ||  is_404() || is_attachment() || is_author() || is_category() || is_feed()) && $wccp_settings['home_css_protection'] == 'Enabled'))
		{
			wpfresh5_css_script();
			return;
		}
		if (is_single() && $wccp_settings['posts_css_protection'] == 'Enabled')
		{
			wpfresh5_css_script();
			return;
		}
		if (is_page() && !is_front_page() && $wccp_settings['pages_css_protection'] == 'Enabled')
		{
			wpfresh5_css_script();
			return;
		}
	}
}

// Add specific CSS class by filter
function wpfresh5_class_names($classes) {
global  $wccp_settings;
if(!current_user_can( 'manage_options' ) || (current_user_can( 'manage_options' ) && $wccp_settings['exclude_admin_from_protection'] == 'No'))
	{
			if ($wccp_settings['home_css_protection'] == 'Enabled' || $wccp_settings['posts_css_protection'] == 'Enabled' ||  $wccp_settings['pages_css_protection'] == 'Enabled')
			{
				$classes[] = 'unselectable';
				return $classes;
			}
			else
			{
				$classes[] = 'none';
				return $classes;
			}
	}else
	{
		$classes[] = 'none';
		return $classes;
	}
}

//////////////////////////////////////////////////////////////////////////////////////

function wpfresh5_disable_right_click()
{
global $wccp_settings;
?>
	<script id="wpcp_disable_Right_Click" type="text/javascript">
	//<![CDATA[
	document.ondragstart = function() { return false;}
	    function nocontext(e) {
	       return false;
	    }
	    document.oncontextmenu = nocontext;
	//]]>
	</script>
<?php
}
function wpfresh5_disable_selection()
{
global $wccp_settings;
?>
<script id="wpcp_disable_selection" type="text/javascript">
//<![CDATA[
var image_save_msg='You Can Not Save images!';
	var no_menu_msg='Context Menu disabled!';
	var smessage = "Not alowed";

function disableEnterKey(e)
{
	if (e.ctrlKey){
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox (97)
    //if (key != 17) alert(key);
     if (key == 97 || key == 65 || key == 67 || key == 99 || key == 88 || key == 120 || key == 26 || key == 85  || key == 86 || key == 83 || key == 43)
     {
          wpfresh5_show_msg('You are not allowed to copy content or view source');
          return false;
     }else
     	return true;
     }
}

function disable_copy(e)
{
	var elemtype = e.target.nodeName;
	var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
	elemtype = elemtype.toUpperCase();
	var checker_IMG = '<?php echo $wccp_settings['img'];?>';
	if (elemtype == "IMG" && checker_IMG == 'checked' && e.detail >= 2) {wpfresh5_show_msg(alertMsg_IMG);return false;}
	if (elemtype != "TEXT" && elemtype != "TEXTAREA" && elemtype != "INPUT" && elemtype != "PASSWORD" && elemtype != "SELECT" && elemtype != "OPTION" && elemtype != "EMBED")
	{
		if (smessage !== "" && e.detail == 2)
			wpfresh5_show_msg(smessage);

		if (isSafari)
			return true;
		else
			return false;
	}
}
function disable_copy_ie()
{
	var elemtype = window.event.srcElement.nodeName;
	elemtype = elemtype.toUpperCase();
	if (elemtype == "IMG") {wpfresh5_show_msg(alertMsg_IMG);return false;}
	if (elemtype != "TEXT" && elemtype != "TEXTAREA" && elemtype != "INPUT" && elemtype != "PASSWORD" && elemtype != "SELECT" && elemtype != "OPTION" && elemtype != "EMBED")
	{
		//alert(navigator.userAgent.indexOf('MSIE'));
			//if (smessage !== "") wpfresh5_show_msg(smessage);
		return false;
	}
}
function reEnable()
{
	return true;
}
document.onkeydown = disableEnterKey;
document.onselectstart = disable_copy_ie;
if(navigator.userAgent.indexOf('MSIE')==-1)
{
	document.onmousedown = disable_copy;
	document.onclick = reEnable;
}
function disableSelection(target)
{
    //For IE This code will work
    if (typeof target.onselectstart!="undefined")
    target.onselectstart = disable_copy_ie;

    //For Firefox This code will work
    else if (typeof target.style.MozUserSelect!="undefined")
    {target.style.MozUserSelect="none";}

    //All other  (ie: Opera) This code will work
    else
    target.onmousedown=function(){return false}
    target.style.cursor = "default";
}
//Calling the JS function directly just after body load
window.onload = function(){disableSelection(document.body);};
//]]>
</script>
<?php
}

function wpfresh5_css_script()
{
?>
<style>
.unselectable
{
-moz-user-select:none;
-webkit-user-select:none;
cursor: default;
}
html
{
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
</style>
<script id="wpcp_css_disable_selection" type="text/javascript">
var e = document.getElementsByTagName('body')[0];
if(e)
{
	e.setAttribute('unselectable',on);
}

function wpfresh5_show_msg( message ) {
	console.log(message)
}
</script>
<?php
}


// Hotlink protection

global $wpfresh5_hotlink_protection_file;
global $wpfresh5_hotlink_protection_file_hlp;


$url = strtolower( get_bloginfo( 'url' ) );
$url = str_replace( 'https://','',$url );
$url = str_replace( 'http://','',$url );
$url = str_replace( 'www.','',$url );
/*$wpfresh5_hotlink_protection_file_hlp = "
# Hotlink Protection START #

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http( s )?://( www\. )?".$url." [NC]
RewriteCond %{HTTP_REFERER} !^http( s )?://( www\. )?google.com [NC]
RewriteRule \.( jpg|jpeg|png|gif )$ - [NC,F,L]

# Hotlink Protection END #
";*/

$wpfresh5_hotlink_protection_file_hlp = "
# Hotlink Protection START #

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?".$url." [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

# Hotlink Protection END #
";

$upload_dir   = wp_upload_dir();

$wpfresh5_hotlink_protection_file = $upload_dir['basedir'] . '/.htaccess';

// on activate
function wpfresh5_hotlink_activate() {
	global $wpfresh5_hotlink_protection_file;
	global $wpfresh5_hotlink_protection_file_hlp;

	if ( file_exists( $wpfresh5_hotlink_protection_file ) ) {
		$fh = fopen( $wpfresh5_hotlink_protection_file, 'r' );
		$fsize = filesize( $wpfresh5_hotlink_protection_file );
		if( $fsize && ( $fsize > 0 ) )
			$htaccess = fread( $fh, $fsize );
		fclose( $fh );
		if( !$fsize || ( $fsize < 0 ) )
			return;
	}
	else
		$htaccess = '';

	$fh = fopen( $wpfresh5_hotlink_protection_file, 'w' ) or die( "can't open file" );
	fwrite( $fh, $htaccess.$wpfresh5_hotlink_protection_file_hlp );
	fclose( $fh );
}
// register_activation_hook( __FILE__, 'wpfresh5_wpaihp_active' );


// on deactivate
function wpfresh5_hotlink_deactivate() {
	global $wpfresh5_hotlink_protection_file;
	global $wpfresh5_hotlink_protection_file_hlp;

	if ( file_exists( $wpfresh5_hotlink_protection_file ) ) {

		$fh = fopen( $wpfresh5_hotlink_protection_file, 'r' );
		/*$htaccess = fread( $fh, filesize( $wpfresh5_hotlink_protection_file ) );
		fclose( $fh );*/
		$fsize = filesize( $wpfresh5_hotlink_protection_file );
		if( $fsize && ( $fsize > 0 ) )
			$htaccess = fread( $fh, $fsize );
		fclose( $fh );

		$htaccess = str_replace( $wpfresh5_hotlink_protection_file_hlp,"",$htaccess );

		$fh = fopen( $wpfresh5_hotlink_protection_file, 'w' ) or die( "can't open file" );
		fwrite( $fh, $htaccess );
		fclose( $fh );
	}

}
// register_deactivation_hook( __FILE__, 'wpfresh5_wpaihp_deactivate' );

// Hide WP

/*
	Change plugins path
	Change theme path
	Change css style file
	Change uploads path
	Hide wp root files
	Hide generator
*/

function wpfresh5_write_htaccess() {
    wpfresh5_flush_rewrite_rules_hard();
}

function wpfresh5_get_htaccess_lines() {
	$text = array();

	$hide_wp = wpfresh5_get_settings( array( 'security', 'hacker', 'hide_wp' ) );
	if( !$hide_wp )
		return array();
	$settings = wpfresh5_get_settings( array( 'security', 'hacker' ) );
/*	'hacker' => array(
	    'hide_wp' => $hide_wp,
	    'plugins_path' => $plugins_path,
	    'theme_path' => $theme_path,
	    'style_path' => $style_path,
	    'uploads_path' => $uploads_path,
	    'hide_root' => $hide_root,
	    'block_spam' => $block_spam,
	    'limit_logins' => $limit_logins,
	    'logins_num' => $logins_num,
	    'ch_login_url' => $ch_login_url,
	    'login_url' => $login_url
	),*/

	$default_vars = wpfresh5_get_default_variables();
	$default_variables = $default_vars[0];
	$templates_data = $default_vars[1];
	$wpfresh5_urls_replacement = array();

	if( isset($settings['plugins_path']) && !empty( $settings['plugins_path'] ) ) {
		// plugins path
		// global $wpfresh5_urls_replacement;
		$new_plugin_path        =   wpfresh5_untrailingslashit_all(    $settings['plugins_path']  );
		$new_plugin_path        =   trailingslashit(    home_url()  )   . untrailingslashit(  $new_plugin_path    );
		// wpfresh5_add_replacement( WP_PLUGIN_URL, $new_plugin_path );
		$wpfresh5_urls_replacement[] = array( WP_PLUGIN_URL, $new_plugin_path );
		$rewrite                            =  '';
		$plugin_path =   wpfresh5_get_url_path( WP_PLUGIN_URL );
		$path           =   '';

		if(!empty($settings['plugins_path']))
		    $path           .=  trailingslashit(   $settings['plugins_path']   );

		$rewrite_to     =   wpfresh5_get_rewrite_to_base( $plugin_path );
        $text[]  .= "\nRewriteRule ^"    .   trailingslashit(   $path   )   .   '(.+) '. $rewrite_to .'$1 [L,QSA]';

	}

	if( isset($settings['theme_path']) && !empty( $settings['theme_path'] ) ) {
		// plugins path
		// global $wpfresh5_urls_replacement;
		$wpfresh5_urls_replacement[] = array( trailingslashit( $default_variables['template_url']), trailingslashit( trailingslashit(    home_url()  )   .   $settings['theme_path'] ) );

        $theme_path =   wpfresh5_get_url_path( $templates_data['themes_url'] . $templates_data['main']['folder_name']    );

        $path           =   '';
        $path           .=  trailingslashit(   $settings['theme_path']   );

        $theme_path = str_replace(' ', '%20', $theme_path);
        $rewrite_to     =   wpfresh5_get_rewrite_to_base( $theme_path );

        // if($this->wph->server_htaccess_config   === TRUE)
        $text[] = "\nRewriteRule ^"    .   $path   .   '(.+) '. $rewrite_to .'$1 [L,QSA]';
	}

	if( isset($settings['style_path']) && !empty( $settings['style_path'] ) ) {
		// stylesheet path
		// TO-DO
	}

	if( isset($settings['uploads_path']) && !empty( $settings['uploads_path'] ) ) {
		// wp-uploads path

		//add_filter('upload_dir',            array( $this, 'upload_dir' ), 999);
		//add default plugin path replacement
		$new_upload_path        =   wpfresh5_untrailingslashit_all(    $settings['uploads_path']  );
		$new_url                =   trailingslashit(    site_url()  )   . $new_upload_path;
		$wpfresh5_urls_replacement[] = array( $default_variables['upload_url'], $new_url );

		$wp_upload_dir  =   wp_upload_dir();
		$uploads_path =   wpfresh5_get_url_path(   $wp_upload_dir['baseurl']   );

		$path           =   '';
		if(!empty($default_variables['wordpress_directory']))
		    $path           =   trailingslashit($default_variables['wordpress_directory']);
		$path           .=  trailingslashit(   $settings['uploads_path']   );

		$rewrite_base   =   wpfresh5_get_rewrite_base( $settings['uploads_path'], FALSE );
		$rewrite_to     =   wpfresh5_get_rewrite_to_base( $uploads_path );

		// if($this->wph->server_htaccess_config   === TRUE)
	    $text[] = "\nRewriteRule ^"    .   $rewrite_base   .   '(.+) '. $rewrite_to .'$1 [L,QSA]';
	}

	if( isset($settings['content_path']) && !empty( $settings['content_path'] ) ) {
		// wp-content path
		$content_directory  =   /*$default_variables['content_directory']*/untrailingslashit(    site_url()  )   . untrailingslashit(  $default_variables['content_directory'] );
		//add default plugin path replacement
		$new_content_path   =   trailingslashit(    site_url()  )   . untrailingslashit(  $settings['content_path'] );
		$wpfresh5_urls_replacement[] = array( $content_directory, $new_content_path );

		$content_path   =   wpfresh5_get_url_path( trailingslashit(   WP_CONTENT_URL   ));
		$rewrite_base   =   wpfresh5_get_rewrite_base( $settings['content_path'], FALSE);
		$rewrite_to     =   wpfresh5_get_rewrite_to_base( $content_path );
        $text[] = "\nRewriteRule ^"    .   $rewrite_base   .   '(.+) '. $rewrite_to .'$1 [L,QSA]';
	}

	if( isset($settings['includes_path']) && !empty( $settings['includes_path'] ) ) {
		// wp-includes path

		$new_include_path   =   wpfresh5_untrailingslashit_all(    $settings['includes_path']  );
		$new_include_path   =   trailingslashit(    site_url()  )   . untrailingslashit(  $new_include_path    );
		$wpfresh5_urls_replacement[] = array( trailingslashit(    site_url()  ) . 'wp-includes', $new_include_path );

		$include_path   =   wpfresh5_get_url_path( trailingslashit(site_url()) . WPINC    );

		$path           =   '';
		if(!empty($default_variables['wordpress_directory']))
		    $path           =   trailingslashit($default_variables['wordpress_directory']);
		$path           .=  trailingslashit(  $settings['includes_path']   );

		$rewrite_base   =   wpfresh5_get_rewrite_base( $settings['includes_path'], FALSE );
		$rewrite_to     =   wpfresh5_get_rewrite_to_base( $include_path );

		// if($this->wph->server_htaccess_config   === TRUE)
	    $text[] = "\nRewriteRule ^"    .   $rewrite_base   .   '(.+) '. $rewrite_to .'$1 [L,QSA]';

	}

	if( isset($settings['hide_root']) && $settings['hide_root'] ) {
		// readme.html
		$rewrite_base   =   wpfresh5_get_rewrite_base( 'readme.html', FALSE, FALSE );
		$rewrite_to     =   wpfresh5_get_rewrite_to_base( 'index.php', TRUE, FALSE, 'site_path' );
	    $text[]   =   "RewriteCond %{ENV:REDIRECT_STATUS} ^$\n";
	    $text[] =   "RewriteRule ^" . $rewrite_base ." ".  $rewrite_to ."?wpfresh5-throw-404 [L]";

    	// license
    	$rewrite_base   =   wpfresh5_get_rewrite_base( 'license.txt', FALSE, FALSE );
    	$rewrite_to     =   wpfresh5_get_rewrite_to_base( 'index.php', TRUE, FALSE, 'site_path' );
        $text[]   =   "RewriteCond %{ENV:REDIRECT_STATUS} ^$\n";
        $text[] =   "RewriteRule ^" . $rewrite_base ." ".  $rewrite_to ."?wpfresh5-throw-404 [L]";
	}
	update_option( 'wpfresh5_urls_replacement', $wpfresh5_urls_replacement );
    return $text;
}

add_action( 'init', 'wpfresh5_init_generator' );
function wpfresh5_init_generator() {
	$hide_wp = wpfresh5_get_settings( array( 'security', 'hacker', 'hide_wp' ) );
	if( $hide_wp ) {
		add_filter('the_generator', create_function('', 'return "";'));
		remove_action( 'wp_head',  'wp_generator' );
	}
}
/**
* Return rewrite base
*
*/
function wpfresh5_get_rewrite_base( $saved_field_data, $left_slash   =   TRUE, $right_slash  =   TRUE )
{
    global $blog_id;
    $default_vars = wpfresh5_get_default_variables();
    $default_variables = $default_vars[0];
    $templates_data = $default_vars[1];

    $saved_field_data   =   wpfresh5_untrailingslashit_all($saved_field_data);

    $path           =   !empty($default_variables['wordpress_directory']) ? trailingslashit( $default_variables['wordpress_directory'] )  :   '';

    $rewrite_base   =   !empty($path) ? trailingslashit( $path ) . $saved_field_data : ( !empty($saved_field_data) ?  '/' .$saved_field_data : '' );
    if( !empty($rewrite_base))
        {
            $rewrite_base   =   wpfresh5_untrailingslashit_all( $rewrite_base );

            if( $left_slash === TRUE )
                $rewrite_base   =   '/' .   $rewrite_base;

            if( $right_slash === TRUE )
                $rewrite_base   =   $rewrite_base . '/';

        }

    return $rewrite_base;

}

/**
* Return rewrite to base
*
*/
function wpfresh5_get_rewrite_to_base( $field_data, $left_slash   =   TRUE, $right_slash  =   TRUE, $append_path =   '')
{
	$default_vars = wpfresh5_get_default_variables();
	$default_variables = $default_vars[0];
	$templates_data = $default_vars[1];

    $field_data         =   wpfresh5_untrailingslashit_all( $field_data );

    $path               =   '';
    switch($append_path)
        {
            case 'site_path'    :
                                    $path               =   !empty($default_variables['site_relative_path']) ? trailingslashit( $default_variables['site_relative_path'] )  :   '';
                                    break;

            case 'wp_path'    :
                                    $path              .=   !empty($default_variables['wordpress_directory']) ? trailingslashit( $default_variables['wordpress_directory'] )  :   '';
                                    break;
            case 'full_path'    :
                                    $path               =   !empty($default_variables['site_relative_path']) ? trailingslashit( $default_variables['site_relative_path'] )  :   '';
                                    $path              .=   !empty($default_variables['wordpress_directory']) ? trailingslashit( $default_variables['wordpress_directory'] )  :   '';
                                    break;
        }

    $rewrite_to_base    =   !empty($path) ? trailingslashit( $path ) . $field_data : ( !empty( $field_data ) ?  '/' . $field_data : '' );
    if( !empty($rewrite_to_base))
        {
            $rewrite_to_base   =   wpfresh5_untrailingslashit_all( $rewrite_to_base );

            if( $left_slash === TRUE )
                $rewrite_to_base   =   '/' .   $rewrite_to_base;

            if( $right_slash === TRUE )
                $rewrite_to_base   =   $rewrite_to_base . '/';

        }

    return $rewrite_to_base;

}

function wpfresh5_untrailingslashit_all($value)
{
    $value  =   ltrim(rtrim($value, "/"),  "/");
    return $value;
}


function wpfresh5_get_default_variables()
    {
    	$default_variables = array();
        $default_variables['include_url']         =   trailingslashit(    site_url()  )  . WPINC;

        $default_variables['template_url']        =   get_bloginfo('template_url');
        $default_variables['stylesheet_uri']      =   get_stylesheet_directory_uri();

        $default_variables['plugins_url']         =   plugins_url();

        $wp_upload_dir  =   wp_upload_dir();
        $default_variables['upload_url']          =   $wp_upload_dir['baseurl'];

        //catch the absolute siteurl in case wp folder is different than domain root
        $default_variables['wordpress_directory']    =   '';
        $default_variables['content_directory']      =   '';

        //content_directory
        $content_directory   =   str_replace(ABSPATH, "", WP_CONTENT_DIR);
        $content_directory   =   str_replace( '\\', '/', $content_directory );
        $content_directory   =   trim($content_directory, '/ ');
        $default_variables['content_directory']   =   '/' .   $content_directory;

        $home_url   =   defined('WP_HOME')  ?   WP_HOME         :   get_option('home');
        $home_url   =   untrailingslashit($home_url);

        $siteurl    =   defined('WP_HOME')  ?   WP_SITEURL      :   get_option('siteurl');
        $siteurl    =   untrailingslashit($siteurl);

        $wp_directory   =   str_replace($home_url, "" , $siteurl);
        $wp_directory   =   trim(trim($wp_directory), '/');

        if($wp_directory    !=  '')
            {
                $default_variables['wordpress_directory'] =   '/' . trim($wp_directory, '/');

                /*
                $domain_ABSPATH         =   str_replace('/' . $wp_directory .'/' , "", trailingslashit( str_replace('\\', '/', realpath( ABSPATH ))));

                $content_directory      = str_replace($domain_ABSPATH, "" , untrailingslashit( str_replace('\\', '/', realpath( WP_CONTENT_DIR ))));
                $content_directory      =   trim($content_directory, '/ ');
                $default_variables['content_directory']   =   '/' . $content_directory;
                */
            }

        //used across modules
        $home_root = parse_url(home_url());
        if ( isset( $home_root['path'] ) )
                $home_root_path = trailingslashit($home_root['path']);
            else
                $home_root_path = '/';
        $default_variables['site_relative_path']  =   $home_root_path;
        //$default_variables['site_relative_path']  =   rtrim ( $this->functions->get_url_path( rtrim(    $siteurl, '/'  ), FALSE, FALSE), '/' );
        if ( empty ( $default_variables['site_relative_path'] ) )
            $default_variables['site_relative_path']  =   '/';

        //themes url
        $templates_data['themes_url']                 =   trailingslashit(    get_theme_root_uri()    );

        $all_templates  =   wpfresh5_get_themes();
        $all_templates  =   wpfresh5_parse_themes_headers($all_templates);

        $stylesheet     =   get_option( 'stylesheet' );

        $templates_data['use_child_theme']            =   wpfresh5_is_child_theme($stylesheet, $all_templates);

        $main_theme_directory                               =   wpfresh5_get_main_theme_directory($stylesheet, $all_templates);
        $templates_data['main']                       =   array();
        $templates_data['main']['folder_name']        =   $main_theme_directory;
        $templates_data['_template_' .  $main_theme_directory]    =   'main';

        if($templates_data['use_child_theme'])
            {
                $templates_data['child']         =   array();
                $templates_data['child']['folder_name']  =   $stylesheet;
                $templates_data['_template_' .  $stylesheet]    =   'child';
            }
        return array( $default_variables, $templates_data );
    }

    function wpfresh5_is_child_theme($theme_slug, $all_themes)
        {

            $theme_data =   $all_themes[$theme_slug];

            if( isset($theme_data['headers']['Template']) &&  !empty($theme_data['headers']['Template']))
                return TRUE;

            return FALSE;

        }

        function wpfresh5_get_main_theme_directory($theme_slug, $all_themes)
            {

                $theme_data         =   $all_themes[$theme_slug];
                $theme_directory    =   $theme_slug;

                if( isset($theme_data['headers']['Template']) &&  !empty($theme_data['headers']['Template']))
                    {
                        $theme_directory    =   $theme_data['headers']['Template'];
                    }

                return $theme_directory;

            }

            function wpfresh5_get_themes( $args = array() )
                {
                    global $wp_theme_directories;

                    $defaults = array( 'errors' => false, 'allowed' => null, 'blog_id' => 0 );
                    $args = wp_parse_args( $args, $defaults );


                    // Register the default theme directory root
                    if ( count( $wp_theme_directories ) < 1  )
                        register_theme_directory( get_theme_root() );

                    $theme_directories = search_theme_directories();

                    if ( count( $wp_theme_directories ) > 1 ) {
                        // Make sure the current theme wins out, in case search_theme_directories() picks the wrong
                        // one in the case of a conflict. (Normally, last registered theme root wins.)
                        $current_theme = get_stylesheet();
                        if ( isset( $theme_directories[ $current_theme ] ) ) {
                            $root_of_current_theme = get_raw_theme_root( $current_theme );
                            if ( ! in_array( $root_of_current_theme, $wp_theme_directories ) )
                                $root_of_current_theme = WP_CONTENT_DIR . $root_of_current_theme;
                            $theme_directories[ $current_theme ]['theme_root'] = $root_of_current_theme;
                        }
                    }

                    if ( empty( $theme_directories ) )
                        return array();

                    if ( is_multisite() && null !== $args['allowed'] ) {
                        $allowed = $args['allowed'];
                        if ( 'network' === $allowed )
                            $theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed_on_network() );
                        elseif ( 'site' === $allowed )
                            $theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed_on_site( $args['blog_id'] ) );
                        elseif ( $allowed )
                            $theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed( $args['blog_id'] ) );
                        else
                            $theme_directories = array_diff_key( $theme_directories, WP_Theme::get_allowed( $args['blog_id'] ) );
                    }

                    return $theme_directories;

                }


            /**
            * Parse available themes headers
            *
            */
            function wpfresh5_parse_themes_headers( $all_templates )
                {
                    foreach( $all_templates as  $directory  =>  $theme_data)
                        {

                            $theme_headers  =   wpfresh5_get_theme_headers( trailingslashit( $theme_data['theme_root']) . $theme_data['theme_file']);
                            $all_templates[$directory]['headers']   =  $theme_headers;

                        }

                    return $all_templates;

                }


            function wpfresh5_get_theme_headers($stylesheet_path)
                {

                    $file_headers = array(
                                            'Name'        => 'Theme Name',
                                            'ThemeURI'    => 'Theme URI',
                                            'Description' => 'Description',
                                            'Author'      => 'Author',
                                            'AuthorURI'   => 'Author URI',
                                            'Version'     => 'Version',
                                            'Template'    => 'Template',
                                            'Status'      => 'Status',
                                            'Tags'        => 'Tags',
                                            'TextDomain'  => 'Text Domain',
                                            'DomainPath'  => 'Domain Path',
                                        );

                    $theme_headers = get_file_data( $stylesheet_path, $file_headers, 'theme' );

                    return $theme_headers;

                }

function wpfresh5_flush_rewrite_rules_hard( $continue = false )
    {
        $home_path      = wpfresh5_get_home_path();
        $htaccess_file  = $home_path . DIRECTORY_SEPARATOR . '.htaccess';

        //check if .htaccess file exists and is writable
        if( ! wpfresh5_is_writable_htaccess_config_file( $htaccess_file ))
            return TRUE;

        $rules          =   wpfresh5_get_rewrite_rules();
        // if( !$rules )
        // 	return;
        //check if there's a  # BEGIN WordPress    and   # END WordPress    markers or create those to ensude plugin rules are put on top of Wordpress ones
        $file_content = file( $htaccess_file );

        if( count( preg_grep("/.*# BEGIN WordPress.*/i", $file_content) )   <   1 &&  count( preg_grep("/.*# END WordPress.*/i", $file_content) )   <   1 )
            {
                wpfresh5_insert_with_markers_on_top( $htaccess_file, 'WordPress', '' );
            }


        wpfresh5_insert_with_markers_on_top( $htaccess_file, 'WP Freshtart 4', $rules, 'top' );

        return TRUE;

    }

function wpfresh5_insert_with_markers_on_top( $filename, $marker, $insertion)
    {

        if ( ! file_exists( $filename ) ) {
            if ( ! is_writable( dirname( $filename ) ) ) {
                return false;
            }
            if ( ! touch( $filename ) ) {
                return false;
            }
        } elseif ( ! is_writeable( $filename ) ) {
            return false;
        }

        if ( ! is_array( $insertion ) ) {
            $insertion = explode( "\n", $insertion );
        }

        $start_marker = "# BEGIN {$marker}";
        $end_marker   = "# END {$marker}";

        $fp = fopen( $filename, 'r+' );
        if ( ! $fp ) {
            return false;
        }

        // Attempt to get a lock. If the filesystem supports locking, this will block until the lock is acquired.
        flock( $fp, LOCK_EX );

        $lines = array();
        while ( ! feof( $fp ) ) {
            $lines[] = rtrim( fgets( $fp ), "\r\n" );
        }

        // Split out the existing file into the preceding lines, and those that appear after the marker
        $pre_lines = $post_lines = $existing_lines = array();
        $found_marker = $found_end_marker = false;
        foreach ( $lines as $line ) {
            if ( ! $found_marker && false !== strpos( $line, $start_marker ) ) {
                $found_marker = true;
                continue;
            } elseif ( ! $found_end_marker && false !== strpos( $line, $end_marker ) ) {
                $found_end_marker = true;
                continue;
            }
            if ( ! $found_marker ) {
                $pre_lines[] = $line;
            } elseif ( $found_marker && $found_end_marker ) {
                $post_lines[] = $line;
            } else {
                $existing_lines[] = $line;
            }
        }

        // Check to see if there was a change
        if ( $existing_lines === $insertion ) {
            flock( $fp, LOCK_UN );
            fclose( $fp );

            return true;
        }


        // Generate the new file data
        if($found_marker && $found_end_marker)
            {
                $new_file_data = implode( "\n", array_merge(
                    $pre_lines,
                    array( $start_marker ),
                    $insertion,
                    array( $end_marker ),
                    $post_lines
                ) );
            }
            else
            {

                $new_file_data = implode( "\n", array_merge(
                    array( $start_marker ),
                    $insertion,
                    array( $end_marker ),
                    $pre_lines
                ) );

            }

        // Write to the start of the file, and truncate it to that length
        fseek( $fp, 0 );
        $bytes = fwrite( $fp, $new_file_data );
        if ( $bytes ) {
            ftruncate( $fp, ftell( $fp ) );
        }
        fflush( $fp );
        flock( $fp, LOCK_UN );
        fclose( $fp );

        return (bool) $bytes;


    }

    function wpfresh5_get_rewrite_rules( )
        {

            $rules  =   "";
            $uninstall = false;
            if($uninstall === TRUE)
                return $rules;

            //$processing_data    =   $this->get_components_rules();
            $htaccess_lines = wpfresh5_get_htaccess_lines();
            //post-process the htaccess data
            $_rewrite_data =   array();
            $_page_refresh  =   FALSE;
/*            foreach($processing_data    as  $response)
                {
                    if(isset($response['rewrite']) &&  !empty($response['rewrite']))
                        {
                            $_rewrite_data[]   =   $response['rewrite'];
                        }

                    if(isset($response['page_refresh']) &&  $response['page_refresh']   === TRUE)
                        $_page_refresh  =   TRUE;
                }
*/
            $write_check_string  =   time() . '_' . mt_rand(100, 99999);
            /*$this->settings['write_check_string']   =   $write_check_string;
            $this->functions->update_settings($this->settings);*/


            $rules  .=  "#WriteCheckString:" . $write_check_string . "\n";
            $rules  .=  "RewriteRule .* - [E=HTTP_MOD_REWRITE:On]";
/*
            if(count($_rewrite_data)   >   0)
                {
                    foreach($_rewrite_data as  $_htaccess_data_line)
                        {
                            $rules .=   "\n"    .   $_htaccess_data_line;
                        }
                }
*/
            if( !empty( $htaccess_lines ) ) {
            	foreach ( $htaccess_lines as $line )
                    $rules .=   "\n"    .   $line;
            }
            $rules      =   apply_filters('wp-hide/mod_rewrite_rules', $rules);


            $home_root = parse_url(home_url());
            if ( isset( $home_root['path'] ) )
                    $home_root = trailingslashit($home_root['path']);
                else
                    $home_root = '/';

            $rules  =   "<IfModule mod_rewrite.c> \n"
                        . "RewriteEngine On \n"
                        . "RewriteBase ". $home_root ." \n"
                        . $rules
                        . "\n"
                        . "</IfModule> \n";

            return $rules;

        }

function wpfresh5_is_writable_htaccess_config_file()
    {
        $home_path      = wpfresh5_get_home_path();
        $htaccess_file  = $home_path . DIRECTORY_SEPARATOR . '.htaccess';

        if ((!file_exists($htaccess_file)  && $this->is_permalink_enabled()) || is_writable($htaccess_file))
            return TRUE;

        return FALSE;

    }

    function wpfresh5_get_home_path()
        {

            $home    = set_url_scheme( get_option( 'home' ), 'http' );
            $siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' );
            if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) )
                    {
                        $wp_path_rel_to_home    = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */
                        $pos                    = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) );

                        if($pos !== FALSE)
                            {
                                $home_path              = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos );
                                $home_path              =   trim( $home_path , '/\\') . DIRECTORY_SEPARATOR;;
                            }
                            else
                            {
                                $wp_path_rel_to_home    =   DIRECTORY_SEPARATOR . trim($wp_path_rel_to_home, '/\\') . DIRECTORY_SEPARATOR;

                                $real_apth              =   realpath(ABSPATH) . DIRECTORY_SEPARATOR ;

                                $pos                    =   strpos( $real_apth, $wp_path_rel_to_home);
                                $home_path              =   substr( $real_apth, 0, $pos );
                                $home_path              =   trim( $home_path , '/\\') . DIRECTORY_SEPARATOR;
                            }
                    }
                else
                    {
                        $home_path = ABSPATH;
                    }


            $home_path      =   trim($home_path, '\\/ ');

            //not for windows
            if ( DIRECTORY_SEPARATOR    !=  '\\')
                $home_path      =   DIRECTORY_SEPARATOR . $home_path;

            return $home_path;

        }

        add_action('init',  'wpfresh5_check_for_404');

        function wpfresh5_check_for_404()
            {
                if(!isset($_GET['wpfresh5-throw-404']))
                    return;

                global $wp_query;

                $wp_query->set_404();
                status_header(404);

                add_action('request',               'wpfresh5_change_request', 999);
                add_action('parse_request',         'wpfresh5_change_parse_request', 999);

                remove_action( 'template_redirect', 'redirect_canonical' );
                remove_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );

            }

            function wpfresh5_change_request($query_vars)
                {

                    return array();

                }

            function wpfresh5_change_parse_request( $object )
                {

                    $object->request            =   NULL;
                    $object->matched_rule       =   NULL;
                    $object->matched_query      =   NULL;

                    $object->query_vars['error']    =   404;

                }

                function wpfresh5_get_url_path($url, $is_file_path   =   FALSE, $relative_to_wordpress_directory    =   FALSE)
                    {
                        if(!$is_file_path)
                            $url            =   trailingslashit(    $url    );

                        $url_parse      =   parse_url(  $url   );

                        $path           =   $url_parse['path'];
                        if( $relative_to_wordpress_directory   === TRUE &&  $this->wph->default_variables['wordpress_directory']    !=  '/')
                            {
                                $path   =   $this->string_left_replacement( $path , trailingslashit ( $this->wph->default_variables['wordpress_directory'] )) ;
                            }

                        if(!$is_file_path)
                            $path           =   trailingslashit(    $path   );

                        if($path    !=  '/' && strlen($path) > 1)
                            {
                                $path   =   ltrim($path, '/');
                                $path   =   '/' .   $path;
                            }

                        if(isset($url_parse['query']))
                            $path   .=  '?' .   $url_parse['query'];

                        $path   =   str_replace( '\\', '/', $path);

                        return $path;

                    }

// $wpfresh5_urls_replacement = array();

add_action( 'init', 'wpfresh5_on_init', 0 );

function wpfresh5_on_init() {
	$hide_wp = wpfresh5_get_settings( array( 'security', 'hacker', 'hide_wp' ) );
	if( !$hide_wp )
		return;
	ob_start();
	add_action('shutdown', 'wpfresh5_on_shutdown', 0 );
	add_filter('wpfresh5_final_output', 'wpfresh5_do_final_check' );
}

function wpfresh5_on_shutdown() {
    $final = '';

    // We'll need to get the number of ob levels we're in, so that we can iterate over each, collecting
    // that buffer's output into the final output.
    $levels = ob_get_level();

    for ($i = 0; $i < $levels; $i++) {
        $final .= ob_get_clean();
    }

    // Apply any filters to the final output
    echo apply_filters( 'wpfresh5_final_output', $final );
}


function wpfresh5_do_final_check($output) {
	// global $wpfresh5_urls_replacement;
	$hide_wp = wpfresh5_get_settings( array( 'security', 'hacker', 'hide_wp' ) );
	if( !$hide_wp )
		return $output;
	$wpfresh5_urls_replacement = get_option( 'wpfresh5_urls_replacement' );
	if( !$wpfresh5_urls_replacement )
		return $output;
	$from = array();
	$to = array();
	foreach( $wpfresh5_urls_replacement as $replacement ) {
		$from[] = $replacement[0];
		$to[] = $replacement[1];
	}
	// var_dump($from);
	// var_dump($to);
	// return '';
    return str_replace( $from, $to, $output);
};

// Rename WP Login

add_action( 'init', 'wpfresh5_change_login_fn', -10 );
function wpfresh5_change_login_fn() {
	if( !wpfresh5_is_custom_login() )
		return;
// die('bb');

	// add_action( 'plugins_loaded', 'wpfresh5_plugins_loaded', 1 );
	add_action( 'wp_loaded', 'wpfresh5_plugins_loaded', 1 );
	add_action( 'wp_loaded', 'wpfresh5_wp_loaded' );
	add_filter( 'site_url', 'wpfresh5_site_url', 10, 4 );
	add_filter( 'network_site_url', 'wpfresh5_network_site_url', 10, 3 );
	add_filter( 'wp_redirect', 'wpfresh5_wp_redirect', 10, 2 );
	add_filter( 'site_option_welcome_email', 'wpfresh5_welcome_email' );
	remove_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );
}

$wpfresh5_login_php = false;

function wpfresh5_is_custom_login() {
	$ch_login_url = wpfresh5_get_settings( array( 'security', 'hacker', 'ch_login_url' ) );
	$login_url = wpfresh5_get_settings( array( 'security', 'hacker', 'login_url' ) );
	// var_dump($ch_login_url);
	// var_dump($login_url);
	// die('aaa');
	return ( $ch_login_url && ! empty( $login_url ) );
}

function wpfresh5_plugins_loaded() {
	// die('ff');
	global $pagenow;
	global $wpfresh5_login_php;
	// load_plugin_textdomain( 'rename-wp-login' );

// die('aa');
	if( !wpfresh5_is_custom_login() )
		return;
	if (
		! is_multisite() && (
			strpos( $_SERVER['REQUEST_URI'], 'wp-signup' ) !== false ||
			strpos( $_SERVER['REQUEST_URI'], 'wp-activate' ) !== false
		)
	) {
		wp_die( __( 'This feature is not enabled.', 'rename-wp-login' ) );
	}

	$request = parse_url( $_SERVER['REQUEST_URI'] );

	if ( (
			strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ||
			untrailingslashit( $request['path'] ) === site_url( 'wp-login', 'relative' )
		) &&
		! is_admin()
	) {
		$wpfresh5_login_php = true;
		$_SERVER['REQUEST_URI'] = wpfresh5_user_trailingslashit( '/' . str_repeat( '-/', 10 ) );
		$pagenow = 'index.php';
	} elseif (
		untrailingslashit( $request['path'] ) === home_url( wpfresh5_new_login_slug(), 'relative' ) || (
			! get_option( 'permalink_structure' ) &&
			isset( $_GET[wpfresh5_new_login_slug()] ) &&
			empty( $_GET[wpfresh5_new_login_slug()] )
	) ) {
		$pagenow = 'wp-login.php';
	}
}

function wpfresh5_wp_loaded() {
	global $pagenow;
	global $wpfresh5_login_php;

	if( !wpfresh5_is_custom_login() )
		return;

	if ( is_admin() && ! is_user_logged_in() && ! defined( 'DOING_AJAX' ) ) {
		wp_die( __( 'You must log in to access the admin area.', 'rename-wp-login' ) );
	}

	$request = parse_url( $_SERVER['REQUEST_URI'] );

	if (
		$pagenow === 'wp-login.php' &&
		$request['path'] !== wpfresh5_user_trailingslashit( $request['path'] ) &&
		get_option( 'permalink_structure' )
	) {
		wp_safe_redirect( wpfresh5_user_trailingslashit(wpfresh5_new_login_url() ) . ( ! empty( $_SERVER['QUERY_STRING'] ) ? '?' . $_SERVER['QUERY_STRING'] : '' ) );
		die;
	} elseif ( $wpfresh5_login_php ) {
		if (
			( $referer = wp_get_referer() ) &&
			strpos( $referer, 'wp-activate.php' ) !== false &&
			( $referer = parse_url( $referer ) ) &&
			! empty( $referer['query'] )
		) {
			parse_str( $referer['query'], $referer );

			if (
				! empty( $referer['key'] ) &&
				( $result = wpmu_activate_signup( $referer['key'] ) ) &&
				is_wp_error( $result ) && (
					$result->get_error_code() === 'already_active' ||
					$result->get_error_code() === 'blog_taken'
			) ) {
				wp_safe_redirect( $wpfresh5_new_login_url() . ( ! empty( $_SERVER['QUERY_STRING'] ) ? '?' . $_SERVER['QUERY_STRING'] : '' ) );
				die;
			}
		}

		wpfresh5_wp_template_loader();
	} elseif ( $pagenow === 'wp-login.php' ) {
		global $error, $interim_login, $action, $user_login;

		@require_once ABSPATH . 'wp-login.php';

		die;
	}
}

function wpfresh5_site_url( $url, $path, $scheme, $blog_id ) {
	return wpfresh5_filter_wp_login_php( $url, $scheme );
}

function wpfresh5_network_site_url( $url, $path, $scheme ) {
	return wpfresh5_filter_wp_login_php( $url, $scheme );
}

function wpfresh5_wp_redirect( $location, $status ) {
	if( !wpfresh5_is_custom_login() )
		return $location;
	return wpfresh5_filter_wp_login_php( $location );
}

function wpfresh5_filter_wp_login_php( $url, $scheme = null ) {
	if( !wpfresh5_is_custom_login() )
		return $url;
	if ( strpos( $url, 'wp-login.php' ) !== false ) {
		if ( is_ssl() ) {
			$scheme = 'https';
		}

		$args = explode( '?', $url );

		if ( isset( $args[1] ) ) {
			parse_str( $args[1], $args );
			$url = add_query_arg( $args, wpfresh5_new_login_url( $scheme ) );
		} else {
			$url = wpfresh5_new_login_url( $scheme );
		}
	}

	return $url;
}

function wpfresh5_welcome_email( $value ) {
	$ch_login_url = wpfresh5_get_settings( array( 'security', 'hacker', 'ch_login_url' ) );
	$login_url = wpfresh5_get_settings( array( 'security', 'hacker', 'login_url' ) );
	if( $ch_login_url && $login_url )
		return $value = str_replace( 'wp-login.php', trailingslashit( $login_url ), $value );
	return $value;
}

function wpfresh5_forbidden_slugs() {
	$wp = new WP;
	return array_merge( $wp->public_query_vars, $wp->private_query_vars );
}

function wpfresh5_new_login_slug() {
	$ch_login_url = wpfresh5_get_settings( array( 'security', 'hacker', 'ch_login_url' ) );
	$login_url = wpfresh5_get_settings( array( 'security', 'hacker', 'login_url' ) );

	if (
		( ( $slug = $login_url ) && $ch_login_url ) || (
			is_multisite() &&
			is_plugin_active_for_network( $this->basename() ) &&
			( $slug = $login_url )
		) ||
		( $slug = 'login' )
	) {
		return $slug;
	}
}

function wpfresh5_new_login_url( $scheme = null ) {
	if ( get_option( 'permalink_structure' ) ) {
		return wpfresh5_user_trailingslashit( home_url( '/', $scheme ) . wpfresh5_new_login_slug() );
	} else {
		return home_url( '/', $scheme ) . '?' . wpfresh5_new_login_slug();
	}
}

function wpfresh5_use_trailing_slashes() {
	return '/' === substr( get_option( 'permalink_structure' ), -1, 1 );
}

function wpfresh5_user_trailingslashit( $string ) {
	return wpfresh5_use_trailing_slashes() ? trailingslashit( $string ) : untrailingslashit( $string );
}

function wpfresh5_wp_template_loader() {
	global $pagenow;

	$pagenow = 'index.php';

	if ( ! defined( 'WP_USE_THEMES' ) ) {
		define( 'WP_USE_THEMES', true );
	}

	wp();

	if ( $_SERVER['REQUEST_URI'] === wpfresh5_user_trailingslashit( str_repeat( '-/', 10 ) ) ) {
		$_SERVER['REQUEST_URI'] = wpfresh5_user_trailingslashit( '/wp-login-php/' );
	}

	require_once( ABSPATH . WPINC . '/template-loader.php' );

	die;
}

// Limit Logins

/* Different ways to get remote address: direct & behind proxy */
define('WPF5_LIMIT_LOGIN_DIRECT_ADDR', 'REMOTE_ADDR');
define('WPF5_LIMIT_LOGIN_PROXY_ADDR', 'HTTP_X_FORWARDED_FOR');

/* Notify value checked against these in limit_login_sanitize_variables() */
//define('LIMIT_LOGIN_LOCKOUT_NOTIFY_ALLOWED', 'log,email');

/*
 * Startup
 */

add_action('plugins_loaded', 'wpfresh5_limit_login_setup', 99999);


/*
 * Functions start here
 */

/* Get options and setup filters & actions */
function wpfresh5_limit_login_setup() {
	$limit_logins = wpfresh5_get_settings( array( 'security', 'hacker', 'limit_logins' ) );
	$logins_num = wpfresh5_get_settings( array( 'security', 'hacker', 'logins_num' ) );
	if( !$limit_logins || !$logins_num )
		return;
	// limit_login_setup_options();

	/* Filters and actions */
	add_action('wp_login_failed', 'wpfresh5_limit_login_failed');
	/*if ( wpfresh5_limit_login_option('cookies') ) {
		limit_login_handle_cookies();
		add_action('auth_cookie_bad_username', 'wpfresh5_limit_login_failed_cookie');

		global $wp_version;

		if (version_compare($wp_version, '3.0', '>=')) {
			add_action('auth_cookie_bad_hash', 'limit_login_failed_cookie_hash');
			add_action('auth_cookie_valid', 'limit_login_valid_cookie', 10, 2);
		} else {
			add_action('auth_cookie_bad_hash', 'limit_login_failed_cookie');
		}
	}*/
	add_filter('wp_authenticate_user', 'wpfresh5_limit_login_wp_authenticate_user', 99999, 2);
	add_filter('shake_error_codes', 'wpfresh5_limit_login_failure_shake');
	add_action('login_head', 'wpfresh5_limit_login_add_error_message');
	add_action('login_errors', 'wpfresh5_limit_login_fixup_error_messages');
	// add_action('admin_menu', 'limit_login_admin_menu');

	/*
	 * This action should really be changed to the 'authenticate' filter as
	 * it will probably be deprecated. That is however only available in
	 * later versions of WP.
	 */
	add_action('wp_authenticate', 'wpfresh5_limit_login_track_credentials', 10, 2);
}



/*
 * Action when login attempt failed
 *
 * Increase nr of retries (if necessary). Reset valid value. Setup
 * lockout if nr of retries are above threshold. And more!
 *
 * A note on external whitelist: retries and statistics are still counted and
 * notifications done as usual, but no lockout is done.
 */
function wpfresh5_limit_login_failed($username) {
	$ip = wpfresh5_limit_login_get_address();

	/* if currently locked-out, do not add to retries */
	$lockouts = get_option('wpfs5_ll_lockouts');
	if (!is_array($lockouts)) {
		$lockouts = array();
	}
	if(isset($lockouts[$ip]) && time() < $lockouts[$ip]) {
		return;
	}

	/* Get the arrays with retries and retries-valid information */
	$retries = get_option('wpfs5_ll_retries');
	$valid = get_option('wpfs5_ll_retries_valid');
	if (!is_array($retries)) {
		$retries = array();
		add_option('wpfs5_ll_retries', $retries, '', 'no');
	}
	if (!is_array($valid)) {
		$valid = array();
		add_option('wpfs5_ll_retries_valid', $valid, '', 'no');
	}

	/* Check validity and add one to retries */
	if (isset($retries[$ip]) && isset($valid[$ip]) && time() < $valid[$ip]) {
		$retries[$ip] ++;
	} else {
		$retries[$ip] = 1;
	}
	$valid[$ip] = time() + wpfresh5_limit_login_option('valid_duration');

	/* lockout? */
	if($retries[$ip] % wpfresh5_limit_login_option('allowed_retries') != 0) {
		/*
		 * Not lockout (yet!)
		 * Do housecleaning (which also saves retry/valid values).
		 */
		wpfresh5_limit_login_cleanup($retries, null, $valid);
		return;
	}

	/* lockout! */

	$whitelisted = wpfresh5_is_limit_login_ip_whitelisted($ip);

	$retries_long = wpfresh5_limit_login_option('allowed_retries')
		* wpfresh5_limit_login_option('allowed_lockouts');

	/*
	 * Note that retries and statistics are still counted and notifications
	 * done as usual for whitelisted ips , but no lockout is done.
	 */
	if ($whitelisted) {
		if ($retries[$ip] >= $retries_long) {
			unset($retries[$ip]);
			unset($valid[$ip]);
		}
	} else {
		global $limit_login_just_lockedout;
		$limit_login_just_lockedout = true;

		/* setup lockout, reset retries as needed */
		if ($retries[$ip] >= $retries_long) {
			/* long lockout */
			$lockouts[$ip] = time() + wpfresh5_limit_login_option('long_duration');
			unset($retries[$ip]);
			unset($valid[$ip]);
		} else {
			/* normal lockout */
			$lockouts[$ip] = time() + wpfresh5_limit_login_option('lockout_duration');
		}
	}

	/* do housecleaning and save values */
	wpfresh5_limit_login_cleanup($retries, $lockouts, $valid);

	/* do any notification */
//	wpfresh5_limit_login_notify($username);

	/* increase statistics */
	$total = get_option('wpfs5_ll_lockouts_total');
	if ($total === false || !is_numeric($total)) {
		add_option('wpfs5_ll_lockouts_total', 1, '', 'no');
	} else {
		update_option('wpfs5_ll_lockouts_total', $total + 1);
	}
}


/* Clean up old lockouts and retries, and save supplied arrays */
function wpfresh5_limit_login_cleanup($retries = null, $lockouts = null, $valid = null) {
	$now = time();
	$lockouts = !is_null($lockouts) ? $lockouts : get_option('wpfs5_ll_lockouts');

	/* remove old lockouts */
	if (is_array($lockouts)) {
		foreach ($lockouts as $ip => $lockout) {
			if ($lockout < $now) {
				unset($lockouts[$ip]);
			}
		}
		update_option('wpfs5_ll_lockouts', $lockouts);
	}

	/* remove retries that are no longer valid */
	$valid = !is_null($valid) ? $valid : get_option('wpfs5_ll_retries_valid');
	$retries = !is_null($retries) ? $retries : get_option('wpfs5_ll_retries');
	if (!is_array($valid) || !is_array($retries)) {
		return;
	}

	foreach ($valid as $ip => $lockout) {
		if ($lockout < $now) {
			unset($valid[$ip]);
			unset($retries[$ip]);
		}
	}

	/* go through retries directly, if for some reason they've gone out of sync */
	foreach ($retries as $ip => $retry) {
		if (!isset($valid[$ip])) {
			unset($retries[$ip]);
		}
	}

	update_option('wpfs5_ll_retries', $retries);
	update_option('wpfs5_ll_retries_valid', $valid);
}



/* Filter: allow login attempt? (called from wp_authenticate()) */
function wpfresh5_limit_login_wp_authenticate_user($user, $password) {
	if (is_wp_error($user) || wpfresh5_is_limit_login_ok() ) {
		return $user;
	}

	global $limit_login_my_error_shown;
	$limit_login_my_error_shown = true;

	$error = new WP_Error();
	// This error should be the same as in "shake it" filter below
	$error->add('too_many_retries', wpfresh5_limit_login_error_msg());
	return $error;
}

/* Construct informative error message */
function wpfresh5_limit_login_error_msg() {
	// $ip = limit_login_get_address();
	// $lockouts = get_option('limit_login_lockouts');

	$msg = __('<strong>ERROR</strong>: Too many failed login attempts.', 'limit-login-attempts') . ' ';

	/*if (!is_array($lockouts) || !isset($lockouts[$ip]) || time() >= $lockouts[$ip]) {
		$msg .=  __('Please try again later.', 'limit-login-attempts');
		return $msg;
	}

	$when = ceil(($lockouts[$ip] - time()) / 60);
	if ($when > 60) {
		$when = ceil($when / 60);
		$msg .= sprintf(_n('Please try again in %d hour.', 'Please try again in %d hours.', $when, 'limit-login-attempts'), $when);
	} else {
		$msg .= sprintf(_n('Please try again in %d minute.', 'Please try again in %d minutes.', $when, 'limit-login-attempts'), $when);
	}*/

	return $msg;
}

/* Filter: add this failure to login page "Shake it!" */
function wpfresh5_limit_login_failure_shake($error_codes) {
	$error_codes[] = 'too_many_retries';
	return $error_codes;
}


/* Should we show errors and messages on this page? */
function wpfresh5_should_limit_login_show_msg() {
	if (isset($_GET['key'])) {
		/* reset password */
		return false;
	}

	$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';

	return ( $action != 'lostpassword' && $action != 'retrievepassword'
			 && $action != 'resetpass' && $action != 'rp'
			 && $action != 'register' );
}

/* Construct retries remaining message */
function wpfresh5_limit_login_retries_remaining_msg() {
	$ip = wpfresh5_limit_login_get_address();
	$retries = get_option('wpfs5_ll_retries');
	$valid = get_option('wpfs5_ll_retries_valid');

	/* Should we show retries remaining? */

	if (!is_array($retries) || !is_array($valid)) {
		/* no retries at all */
		return '';
	}
	if (!isset($retries[$ip]) || !isset($valid[$ip]) || time() > $valid[$ip]) {
		/* no: no valid retries */
		return '';
	}
	if (($retries[$ip] % wpfresh5_limit_login_option('allowed_retries')) == 0 ) {
		/* no: already been locked out for these retries */
		return '';
	}

	$remaining = max((wpfresh5_limit_login_option('allowed_retries') - ($retries[$ip] % wpfresh5_limit_login_option('allowed_retries'))), 0);
	return sprintf(_n("<strong>%d</strong> attempt remaining.", "<strong>%d</strong> attempts remaining.", $remaining, 'limit-login-attempts'), $remaining);
}

/* Return current (error) message to show, if any */
function wpfresh5_limit_login_get_message() {
	/* Check external whitelist */
	if (wpfresh5_is_limit_login_ip_whitelisted()) {
		return '';
	}

	/* Is lockout in effect? */
	if (!wpfresh5_is_limit_login_ok()) {
		return wpfresh5_limit_login_error_msg();
	}

	return wpfresh5_limit_login_retries_remaining_msg();
}

/* Add a message to login page when necessary */
function wpfresh5_limit_login_add_error_message() {
	global $error, $limit_login_my_error_shown;

	if (!wpfresh5_should_limit_login_show_msg() || $limit_login_my_error_shown) {
		return;
	}

	$msg = wpfresh5_limit_login_get_message();

	if ($msg != '') {
		$limit_login_my_error_shown = true;
		$error .= $msg;
	}

	return;
}

/* Fix up the error message before showing it */
function wpfresh5_limit_login_fixup_error_messages($content) {
	global $limit_login_just_lockedout, $limit_login_nonempty_credentials, $limit_login_my_error_shown;

	if (!wpfresh5_should_limit_login_show_msg()) {
		return $content;
	}

	/*
	 * During lockout we do not want to show any other error messages (like
	 * unknown user or empty password).
	 */
	if (!wpfresh5_is_limit_login_ok() && !$limit_login_just_lockedout) {
		return wpfresh5_limit_login_error_msg();
	}

	/*
	 * We want to filter the messages 'Invalid username' and
	 * 'Invalid password' as that is an information leak regarding user
	 * account names (prior to WP 2.9?).
	 *
	 * Also, if more than one error message, put an extra <br /> tag between
	 * them.
	 */
	$msgs = explode("<br />\n", $content);

	if (strlen(end($msgs)) == 0) {
		/* remove last entry empty string */
		array_pop($msgs);
	}

	$count = count($msgs);
	$my_warn_count = $limit_login_my_error_shown ? 1 : 0;

	if ($limit_login_nonempty_credentials && $count > $my_warn_count) {
		/* Replace error message, including ours if necessary */
		$content = __('<strong>ERROR</strong>: Incorrect username or password.', 'limit-login-attempts') . "<br />\n";
		if ($limit_login_my_error_shown) {
			$content .= "<br />\n" . wpfresh5_limit_login_get_message() . "<br />\n";
		}
		return $content;
	} elseif ($count <= 1) {
		return $content;
	}

	$new = '';
	while ($count-- > 0) {
		$new .= array_shift($msgs) . "<br />\n";
		if ($count > 0) {
			$new .= "<br />\n";
		}
	}

	return $new;
}


/* Keep track of if user or password are empty, to filter errors correctly */
function wpfresh5_limit_login_track_credentials($user, $password) {
	global $limit_login_nonempty_credentials;

	$limit_login_nonempty_credentials = (!empty($user) && !empty($password));
}

function wpfresh5_is_limit_login_ip_whitelisted($ip = null) {
	if (is_null($ip)) {
		$ip = wpfresh5_limit_login_get_address();
	}
	$whitelisted = apply_filters('limit_login_whitelist_ip', false, $ip);

	return ($whitelisted === true);
}

/* Get correct remote address */
function wpfresh5_limit_login_get_address($type_name = '') {
	$type = $type_name;
	if (empty($type)) {
		$type = wpfresh5_limit_login_option('client_type');
	}

	if (isset($_SERVER[$type])) {
		return $_SERVER[$type];
	}

	/*
	 * Not found. Did we get proxy type from option?
	 * If so, try to fall back to direct address.
	 */
	if ( empty($type_name) && $type == WPF5_LIMIT_LOGIN_PROXY_ADDR
		 && isset($_SERVER[WPF5_LIMIT_LOGIN_DIRECT_ADDR])) {

		/*
		 * NOTE: Even though we fall back to direct address -- meaning you
		 * can get a mostly working plugin when set to PROXY mode while in
		 * fact directly connected to Internet it is not safe!
		 *
		 * Client can itself send HTTP_X_FORWARDED_FOR header fooling us
		 * regarding which IP should be banned.
		 */

		return $_SERVER[WPF5_LIMIT_LOGIN_DIRECT_ADDR];
	}

	return '';
}

/* Get current option value */
function wpfresh5_limit_login_option($option_name) {
	global $wpfresh5_limit_login_options;
	$limit_logins = wpfresh5_get_settings( array( 'security', 'hacker', 'limit_logins' ) );
	$logins_num = wpfresh5_get_settings( array( 'security', 'hacker', 'logins_num' ) );
	if( $option_name == 'allowed_retries')
		return $logins_num;
	else if( $option_name == 'lockout_duration')
		return 1200;
	else if( $option_name == 'allowed_lockouts')
		return 4;
	else if( $option_name == 'long_duration')
		return 86400;
	else if( $option_name == 'valid_duration')
		return 43200;
	else if( $option_name == 'cookies')
		return false;
/*
	}
	$valid[$ip] = time() + wpfresh5_limit_login_option('valid_duration');

	if($retries[$ip] % wpfresh5_limit_login_option('allowed_retries') != 0) {
		limit_login_cleanup($retries, null, $valid);
		return;
	}


	$whitelisted = wpfresh5_is_limit_login_ip_whitelisted($ip);

	$retries_long = wpfresh5_limit_login_option('allowed_retries')
		* wpfresh5_limit_login_option('allowed_lockouts');

		*/

	if (isset($wpfresh5_limit_login_options[$option_name])) {
		return $wpfresh5_limit_login_options[$option_name];
	} else {
		return null;
	}
}

/* Check if it is ok to login */
function wpfresh5_is_limit_login_ok() {
	$ip = wpfresh5_limit_login_get_address();

	/* Check external whitelist filter */
	if (wpfresh5_is_limit_login_ip_whitelisted($ip)) {
		return true;
	}

	/* lockout active? */
	$lockouts = get_option('wpfs5_ll_lockouts');
	return (!is_array($lockouts) || !isset($lockouts[$ip]) || time() >= $lockouts[$ip]);
}

// Backup
add_action( 'wp_ajax_wpfresh5_db_backup_now', 'wpfresh5_db_backup_now');

function wpfresh5_db_backup_now() {
	try
	{
		$host = DB_HOST;
		$name = DB_NAME;
		$user = DB_USER;
		$pass = DB_PASSWORD;
		$tables = '*';

		$path_info = wp_upload_dir();
		$mainDir=$path_info['basedir'].'/wp-freshstart5';
		if (!file_exists($mainDir))
		      wp_mkdir_p($mainDir);

		$sqlfile  =$mainDir . '/'.DB_NAME.'.sql';
		if (file_exists(sqlfile))
		      unlink($sqlfile);

		$filename=DB_NAME.'.sql';

		$handle = fopen($path_info['basedir'].'/wp-freshstart5/'.$filename,'w+');
	 	$con = mysql_connect($host,$user,$pass);
		mysql_select_db($name,$con);

			//get all of the tables
			if($tables == '*')
			{
				$tables = array();
				$result = mysql_query('SHOW TABLES');
				while($row = mysql_fetch_row($result))
				{
					$tables[] = $row[0];
				}
			}
			else
			{
				$tables = is_array($tables) ? $tables : explode(',',$tables);
			}
			$return = "";

			//cycle through
			foreach($tables as $table)
			{

				$result = mysql_query('SELECT * FROM '.$table);
				$num_fields = mysql_num_fields($result);
				//$return.= 'DROP TABLE '.$table.';';
				$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
				$return.= "\n\n".$row2[1].";\n\n";
				while($row = mysql_fetch_row($result))
				{
					$return.= 'INSERT INTO '.$table.' VALUES(';
					for($j=0; $j<$num_fields; $j++)
					{
						$row[$j] = mysql_real_escape_string($row[$j]);
						$return .= (isset($row[$j])) ? '"'.$row[$j].'"'	: '""';
						if ($j<($num_fields-1)) {
							$return .= ',';
						}
					}
					$return.= ");\n";
				}
				$return.="\n";
			}
			fwrite($handle,$return);
			fclose($handle);

			// Uploading File to upload directory
			$upload_path = array(
						'filename' => ($filename),
						'dir' => ($path_info['basedir'].'/wp-freshstart5/'.$filename),
						'url' => ($path_info['baseurl'].'/wp-freshstart5/'.$filename),
						'size' => 0
					);
			$upload_path['size']=filesize($upload_path['dir']);

		        $fullDownloadPath=$path_info['baseurl'].'/wp-freshstart5/'.$filename;

			echo json_encode(array('Success'=>true, 'FullDownloadPath'=>$fullDownloadPath));
			wp_die();
	}
	catch(Exception $e)
	{
	    $GLOBALS['errors'][] = $e;
	}


}
/// Backup kill switch

add_action( 'init', 'wpfresh5_disable_all_security' );

function wpfresh5_disable_all_security() {
	if( isset( $_GET['wpfresh5_dis_sec'] ) ) {
    	$settings = wpfresh5_get_plugin_settings();
    	$settings['security']['hacker']['hide_wp'] = 0;
    	$settings['security']['hacker']['ch_login_url'] = 0;
    	$settings['security']['hacker']['login_url'] = '';
    	$settings['security']['hacker']['block_spam'] = 0;
    	$settings['security']['hacker']['limit_logins'] = 0;

    	$settings['security']['recaptcha']['login'] = 0;
    	$settings['security']['recaptcha']['comments'] = 0;


    	delete_option( 'wpfs5_ll_retries' );
    	delete_option( 'wpfs5_ll_retries_valid' );

    	$settings['security']['content']['disable_hotlink'] = 0;
        wpfresh5_hotlink_deactivate();

    	$settings['others']['optimize']['minimize_html'] = 0;
    	$settings['others']['optimize']['minimize_js'] = 0;
    	$settings['others']['optimize']['minimize_css'] = 0;
    	wpfresh5_minify( 0, 0, 0, '', '' );

    	wpfresh5_save_plugin_settings( $settings );
    	// wpfresh5_hotlink_deactivate();
	}
}

function wpfs5_plugin_deactivated()
{
	wpfresh5_disable_all_security();
}


// Recaptcha

function frontend_wpfresh5_script() {
	$settings = wpfresh5_get_settings( array( 'security', 'captcha' ) );
	if( empty( $settings ) )
		return;
	$key = isset( $settings['key'] ) ? trim( $settings['key'] ) : false;
	$secret = isset( $settings['secret'] ) ? trim( $settings['secret'] ) : false;
	$login = isset( $settings['login'] ) ? intval( $settings['login'] ) : false;
	$comments = isset( $settings['comments'] ) ? trim( $settings['comments'] ) : false;


	if( empty( $key ) || empty( $secret ) )
		return;

	if( !$login && !$comments )
		return;
	// $wpfresh5_site_key = filter_var(get_option("wpfresh5_site_key"), FILTER_SANITIZE_FULL_SPECIAL_CHARS);

	$wpfresh5_display_list = array();
	$wpfresh5_comments = array("comment_form_after_fields");
	$wpfresh5_login = array("login_form", "register_form", "lost_password", "lostpassword_form", "retrieve_password", "resetpass_form", "woocommerce_login_form", "woocommerce_register_form", "woocommerce_lostpassword_form", "woocommerce_after_order_notes", "bp_after_signup_profile_fields");

	if( $comments )
		$wpfresh5_display_list = $wpfresh5_comments;

	if( $login )
		$wpfresh5_display_list = array_merge( $wpfresh5_display_list, $wpfresh5_login );
	wp_register_script("wpfresh5_recaptcha_main", WPFRESH5_URL . '/js/front/recaptcha.js',   array( 'jquery' ), WPFRESH5_VERSION);
	wp_enqueue_script("wpfresh5_recaptcha_main");
	wp_localize_script("wpfresh5_recaptcha_main", "wpfresh5_recaptchav", array("site_key" => $key));

	wp_register_script("wpfresh5_recaptcha", "https://www.google.com/recaptcha/api.js?hl=".get_locale()."&onload=wpfresh5_recaptcha&render=explicit");
	wp_enqueue_script("wpfresh5_recaptcha");

	wp_register_style( 'wpfresh5_recaptcha', WPFRESH5_URL . '/css/recaptcha.css', array(), WPFRESH5_VERSION );
	wp_enqueue_style( 'wpfresh5_recaptcha' );

	foreach($wpfresh5_display_list as $wpfresh5_display) {
		add_action( $wpfresh5_display, "wpfresh5_display" );
	}
}

function wpfresh5_display() {
	echo "<div class=\"g-recaptcha\"></div>";
}

function wpfresh5_verify($input) {
	$settings = wpfresh5_get_settings( array( 'security', 'captcha' ) );
	if( empty( $settings ) )
		return $input;
	$key = isset( $settings['key'] ) ? trim( $settings['key'] ) : false;
	$secret = isset( $settings['secret'] ) ? trim( $settings['secret'] ) : false;

	if( empty( $key ) || empty( $secret ) )
		return $input;

	if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["g-recaptcha-response"])) {
		$wpfresh5_secret_key = filter_var($key, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		$recaptcha_response = filter_input(INPUT_POST, "g-recaptcha-response", FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		$response = wp_remote_get("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$recaptcha_response}");
		$response = json_decode($response["body"], 1);

		if ($response["success"]) {
			return $input;
		} else {
			wp_die("<p><strong>".__("ERROR:", "wpfreshstart5")."</strong> ".__("Google reCAPTCHA verification failed.", "wpfreshstart5")."</p>\n\n<p><a href=".wp_get_referer().">&laquo; ".__("Back", "wpfreshstart5")."</a>", "", 403);
			return null;
		}
	} else {
		wp_die("<p><strong>".__("ERROR:", "wpfreshstart5")."</strong> ".__("Google reCAPTCHA verification failed.", "wpfreshstart5")." ".__("Do you have JavaScript enabled?", "wpfreshstart5")."</p>\n\n<p><a href=".wp_get_referer().">&laquo; ".__("Back", "simple-google-recaptcha")."</a>", "", 403);
		return null;
	}
}

function wpfresh5_recaptcha_check() {
	$settings = wpfresh5_get_settings( array( 'security', 'captcha' ) );
	if( empty( $settings ) )
		return;
	$key = isset( $settings['key'] ) ? trim( $settings['key'] ) : false;
	$secret = isset( $settings['secret'] ) ? trim( $settings['secret'] ) : false;
	$login = isset( $settings['login'] ) ? intval( $settings['login'] ) : false;
	$comments = isset( $settings['comments'] ) ? trim( $settings['comments'] ) : false;
// var_dump($settings);
// die('a');
	if( empty( $key ) || empty( $secret ) )
		return;

	if ( $key && $secret && !is_user_logged_in()) {
		add_action("login_enqueue_scripts", "frontend_wpfresh5_script");
		add_action("wp_enqueue_scripts", "frontend_wpfresh5_script");

		$wpfresh5_comments = array("preprocess_comment");
		$wpfresh5_login = array("wp_authenticate_user", "registration_errors", "lostpassword_post", "resetpass_post", "bp_signup_validate", "woocommerce_register_post");

		if( $comments )
			$wpfresh5_verify_list = $wpfresh5_comments;

		if( $login )
			$wpfresh5_verify_list = array_merge( $wpfresh5_verify_list, $wpfresh5_login );

		// $wpfresh5_verify_list = array("", );
		if( !empty( $wpfresh5_verify_list ) ) {
			foreach($wpfresh5_verify_list as $wpfresh5_verify) {
				add_action($wpfresh5_verify, "wpfresh5_verify");
			}
		}
	}
}

add_action("init", "wpfresh5_recaptcha_check");
?>