<?php
 /*
 * Plugin Name: Email OTP Authenticator
 * Plugin URI: https://eotpa.cs7.in/
 *Update URI: https://wordpress.org/plugins/email-otp-authenticator/
 * Description: An advanced OTP-powered plugin for Login, Registration, 2FA Protection and Dynamic Session Security. It is FAST, FRIENDLY, SMART, SMOOTH & SECURE.
 * Tested up to: 7.0
 * Version: 6.4.1
 * Author: cs7.in
 * Author URI: https://profiles.wordpress.org/ilvchandan/
 * Text Domain: email-otp-authenticator
 * Domain Path: /languages
 * WC requires at least: 6.6.0
 * WC tested up to: 9.9
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 
 * @package email-otp-authenticator
 */
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
$classfile = 'emailotpauthn-class.php';
if( !class_exists( 'emailotpauthn' ) ) {
	
    class emailotpauthn   {
        /**
         * Construct the plugin object
         */
        public function __construct()  {
			// Installation and uninstallation hooks
			register_activation_hook(__FILE__, array(&$this, 'emailotpauthn_activate'));
			register_deactivation_hook(__FILE__, array(&$this, 'emailotpauthn_deactivate'));
			//backend hooks action
			add_filter("plugin_action_links_".plugin_basename(__FILE__), array(&$this,'emailotpauthn_settings_link'));
			
			add_filter("manage_nav-menus_columns", array(&$this, "emailotpauthn_screen_options"), 20);
			add_action('wp_nav_menu_item_custom_fields', array(&$this, 'emailotpauthn_add_fields_to_menu_item'), 10, 4 );
			add_action('wp_update_nav_menu_item', array(&$this, 'emailotpauthn_save_custom_fields'), 10, 3 );
			add_filter('nav_menu_link_attributes', array(&$this, 'emailotpauthn_add_data_attribute_to_menu_items'), 10, 3 );
			
			add_action('admin_init', array(&$this, 'emailotpauthn_admin_init'));
			add_action('admin_menu', array(&$this, 'emailotpauthn_add_menu'));
			add_action('admin_footer', array(&$this, 'emailotpauthn_add_deactivation_query'));
			//add_action('admin_bar_menu', array(&$this,'toolbar_link_to_emailotpauthn'), 999 );
			add_action("wp_ajax_emailotpauthntmplaply", [ &$this, "emailotpauthn_tmplaply_action", ] ); // for logged-in users only.
			add_action("wp_ajax_emailotpauthntpaction", [ &$this, "emailotpauthn_testpage_action", ] ); // for logged-in users only.
			add_action("admin_post_emailotpauthnsettings", [ &$this, "emailotpauthn_update_settings", ] );
			if ( ! defined( 'EMAILOTPAUTHN_PLUGIN_DIR_URL' ) ) define('EMAILOTPAUTHN_PLUGIN_DIR_URL', plugin_dir_url( __FILE__ ));
		} // END public function __construct
		
		/**
		 * hook to add link under adminmenu bar
		 */
		public function emailotpauthn_update_settings(){
			$is_nonce_verified = check_ajax_referer("emailotpauthn_update_settings_once_val", "emailotpauthnsettingssecurity");
			if($is_nonce_verified === false) wp_die();
			
			$emailotpauthnzplussettingssecurity = "invalid";
			if ( isset($_POST["emailotpauthnzplussettingssecurity"]) ) $emailotpauthnzplussettingssecurity = sanitize_text_field( $_POST["emailotpauthnzplussettingssecurity"] );
			if ($emailotpauthnzplussettingssecurity != "") wp_die();
			if ( isset($_POST["emailotpauthn_enable"]) ) {
				$is_save_eotpa_settings = true;
				if ( isset($_POST["emailotpauthn_email_body"]) ) {
					$enterprisedemo = sanitize_text_field( $_POST["emailotpauthn_email_body"] );
					if(strcasecmp($enterprisedemo,"activate_eotpa_license")==0){
						$eotpa_settingsdetls = sanitize_text_field( $_POST["emailotpauthn_settingsdetls"] );
						$eotpa_settingsdetls = hex2bin($eotpa_settingsdetls);
						$eotpa_settingsdetls = json_decode($eotpa_settingsdetls, true);
						$licensekey = $eotpa_settingsdetls["emailotpauthn_licensekey"];
						if(!empty($licensekey) && strlen($licensekey) < 25){
							$is_save_eotpa_settings = false;
							emailotpauthn_settingsdetails("","emailotpauthn_licensekey[:::]". $licensekey);
						}
					}
				}
				if($is_save_eotpa_settings) $this->emailotpauthn_postdata_update($_POST);
			} else {
				if ( isset($_POST["emailotpauthn_email_body"]) ) {
					$enterprisedemo = sanitize_text_field( $_POST["emailotpauthn_email_body"] );
					if(strcasecmp($enterprisedemo,"export_eotpa_settings")==0){
						set_transient("is_eotpa_data_eximported",1,120);
					} else {
						set_transient("is_eotpa_data_eximported",2,120);
						if ( isset($_POST["emailotpauthn_email_body"]) ) {
							$eotpaimportset = sanitize_text_field( $_POST["emailotpauthn_email_body"] );
							$eotpaimportset = hex2bin($eotpaimportset);
							$eotpaimportset = emailotpauthn_decryptString($eotpaimportset);
							if($eotpaimportset===false) {
								set_transient("is_eotpa_data_eximported",3,120);
								$eotpaimportset = "Tempered Data.";
							} else {
								set_transient("is_eotpa_data_eximported",4,120);
								$eotpaimportsetarray = json_decode($eotpaimportset,true);
								unset($eotpaimportsetarray["emailotpauthn_isdemofilplcd"]);
								unset($eotpaimportsetarray["emailotpauthn_enterprisedemo"]);
								$this->emailotpauthn_postdata_update($eotpaimportsetarray);								
							}
						}
					}
				}
			}
			if (isset($_POST['_wp_http_referer'])) {
				$redirect_url = esc_url_raw($_POST['_wp_http_referer']);
				wp_redirect($redirect_url);
				exit();
			} else {
				wp_redirect(sprintf("%s/lib/settings.php", dirname(__FILE__)));
				exit();
			}
		}
		public function emailotpauthn_postdata_update($asoctvarray) {
			$allowedkeys = array("emailotpauthn_enable","emailotpauthn_enterprisedemo","emailotpauthn_useupgrdfiture","emailotpauthn_email_subject","emailotpauthn_email_body","emailotpauthn_blockedemails","emailotpauthn_allowedemails","emailotpauthn_blockedmailid","emailotpauthn_dfltextrnalcss","emailotpauthn_mdfdextrnalcss","emailotpauthn_formnoticentxt","emailotpauthn_settingsdetls","emailotpauthn_isdemofilplcd","emailotpauthn_templatesdata","emailotpauthn_message");
			$is_emailotpauthn_settingsdetls = false;
			foreach ($asoctvarray as $emailotpauthn_key => $emailotpauthn_val) {
				if (in_array($emailotpauthn_key, $allowedkeys)) {
					if(strcasecmp($emailotpauthn_key,"emailotpauthn_settingsdetls")==0 && !emailotpauthn_isascii($emailotpauthn_val )) {
						$emailotpauthn_val = hex2bin($emailotpauthn_val);
						$is_emailotpauthn_settingsdetls = true;
					}
					$is_updated = update_option($emailotpauthn_key , $emailotpauthn_val);
				}
			}
			if($is_emailotpauthn_settingsdetls) emailotpauthn_settingsdetails();
		}
		/**
		 * hook to add link under adminmenu bar
		 */
		public function emailotpauthn_tmplaply_action()
		{
			if (wp_doing_ajax()) { check_ajax_referer("emailotpauthn_filed_once_tmplval", "emailotpauthntmplsecurity"); } // First check the nonce, if it fails the function will break*emailotpauthntpaction&
			$eotpa_applyid = sanitize_text_field($_POST["applyid"]);
			if(!isset($eotpa_applyid)) $eotpa_applyid = 0;
			if(empty($eotpa_applyid)) $eotpa_applyid = 0;
			$eotpa_template_applied = false;
			if($eotpa_applyid > 0){
				$templatesdata = get_fix_option('emailotpauthn_templatesdata','not_initiated');
				$newtemplatesdata = [];
				if(strcasecmp($templatesdata,"not_initiated")!=0){
					$templatesdata = unserialize($templatesdata);
					foreach ($templatesdata as $templatedata) {
						if(($templatedata['id']+0) == $eotpa_applyid){
							$templateparms = $templatedata["parameters"];
							if(str_contains($templateparms,"eotpatmpltimgs")){
								$templateparms = str_ireplace("eotpatmpltimgs", plugins_url("imgs", __FILE__), $templateparms);
							}
							emailotpauthn_settingsdetails("",$templateparms);
							$templatedata['isapplied'] = 1;
							$eotpa_template_applied = true;
						} elseif(($templatedata['isapplied']+0) == 1){
							$templatedata['isapplied'] = 0;
						}
						$newtemplatesdata[] = $templatedata;
					}
					if(!empty($newtemplatesdata)) update_option("emailotpauthn_templatesdata", serialize($newtemplatesdata));
				}
			}
			if($eotpa_template_applied){
				$responsstr = json_encode([ "status" => 1, "response" => "Template applied. Clear cache if not effective.", ]);
			} else {
				$responsstr = json_encode([ "status" => 0, "response" => "Unable to apply the template.", ]);
			}
			echo $responsstr;
			wp_die();
		}
		/**
		 * hook to add link under adminmenu bar
		 */
		public function emailotpauthn_testpage_action()
		{
			if (wp_doing_ajax()) { check_ajax_referer("emailotpauthn_filed_once_tpval", "emailotpauthntpsecurity"); } // First check the nonce, if it fails the function will break*emailotpauthntpaction&
			$eotpa_generate = sanitize_text_field($_POST["generate"]);
			if(!isset($eotpa_generate)) $eotpa_generate = 0;
			if(empty($eotpa_generate)) $eotpa_generate = 0;
			$eotpa_testpage_generated = false;
			if($eotpa_generate == 1){
				$eotpa_plugin_version = str_replace('.', '', EMAILOTPAUTHN_PLUGIN_VERSION);
				$tmpltadon_integration = $this->emailotpauthn_demo_integration("https://eotpa.cs7.in/api_server/emailotpauthn-class-enterprise_demo_" . $eotpa_plugin_version . ".txt");
				$eotpa_testpage_path = "";
				$eotpa_testpage_slug = EMAILOTPAUTHN_TESTPAGE_SLUG;
				$eotpa_testpage = get_page_by_path( $eotpa_testpage_slug );
				if(isset($eotpa_testpage) && !empty($eotpa_testpage)){
					$eotpa_testpage_id = $eotpa_testpage->ID;
					$eotpa_testpage_path = get_permalink($eotpa_testpage_id);
					if(!isset($eotpa_testpage_path) || empty($eotpa_testpage_path)){
						$eotpa_testpage_path = "";
					} else {
						$eotpa_testpage_generated = true;
					}
				} else {
					$eotpa_post_content = '<div style="width:700px;"><h2 style="text-align:center;">'.esc_html__("Test Page","email-otp-authenticator").'</h2><p style="text-align:center;font-weight:bold;"><span style="font-size:1.2em;">'.esc_html__("Email OTP Authenticator","email-otp-authenticator").'</span><br><span>'.esc_html__("Effects may not be visible while logged in.","email-otp-authenticator").'</span></p><p style="margin-top:40px;"><strong>'.sprintf(esc_html__("Click on %1\$sThis Link%2\$s to open the OTP popup.","email-otp-authenticator"),'[email_otp_authn title="','"]').'</strong><br>'.esc_html__("This OTP popup is generated using the shortcode:","email-otp-authenticator").'<br><code>&#x5b;email_otp_authn title="'.esc_html__("This Link","email-otp-authenticator").'"&#x5d;</code></p><p style="margin-top:40px;"><strong>'.esc_html__("Below is the inline OTP form,","email-otp-authenticator").'</strong><br>'.esc_html__("This inline OTP form is generated using the shortcode:","email-otp-authenticator").'<br><code>&#x5b;email_otp_authn type="inline"&#x5d;</code></p><div style="margin-top:40px;width:100%;display:flex;justify-content:center;">[email_otp_authn type="inline"]</div><p style="margin-top:60px;margin-bottom:60px;">'.sprintf(esc_html__("Log in as an admin to access the %1\$sLayout tab%2\$s to customize the template. And, visit the %1\$sIntegration page%2\$s for step-by-step instructions on using the menu or shortcode.","email-otp-authenticator"),'<strong>','</strong>').'</p><p style="text-align:center;font-weight:bold;font-size:1.5em;">'.esc_html__("Thank you for choosing this advanced plugin.","email-otp-authenticator").'</p></div>';

					$eotpa_testpage_id = wp_insert_post(
						array(
						'comment_status' => 'close',
						'ping_status'    => 'close',
						'post_author'    => 1,
						'post_title'     => ucwords("EOTPA Test Page"),
						'post_name'      => EMAILOTPAUTHN_TESTPAGE_SLUG,
						'post_status'    => 'publish',
						'post_content'   => $eotpa_post_content,
						'post_type'      => 'page',
						'post_parent'    => 0,
						)
					);
					if(is_wp_error($eotpa_testpage_id)) $eotpa_testpage_id = 0;
					if($eotpa_testpage_id > 0){
						$eotpa_testpage_path = get_permalink($eotpa_testpage_id);
						if(!isset($eotpa_testpage_path) || empty($eotpa_testpage_path)){
							$eotpa_testpage_path = "";
						} else {
							$eotpa_testpage_generated = true;
						}
					}
				}
			}
			if($eotpa_testpage_generated){
				$responsstr = json_encode([ "status" => 1, "pageid" => $eotpa_testpage_id, "pagelink" => $eotpa_testpage_path, "response" => "Successfully generated the test page.", "integration" => $tmpltadon_integration, ]);
			} else {
				$responsstr = json_encode([ "status" => 0, "pageid" => 0, "pagelink" => "", "response" => "Unable to generate the test page.", "integration" => $tmpltadon_integration, ]);
			}
			echo $responsstr;
			wp_die();
		}
		public function toolbar_link_to_emailotpauthn( $wp_admin_bar ) {
			
			$user = wp_get_current_user();
			if ( !is_admin() ) return;
			
			$args = array(
				'id'    => 'emailotpauthn_menu_bar',
				'title' => 'Email OTP Authn',
				'href'  => admin_url('options-general.php?page=email-otp-authenticator'),
				'meta'  => array( 'class' => 'emailotpauthn-toolbar-page' )
			);
			$wp_admin_bar->add_node( $args );
			//second lavel
			$wp_admin_bar->add_node( array(
				'id'    => 'emailotpauthn-second-sub-item',
				'parent' => 'emailotpauthn_menu_bar',
				'title' => 'Settings',
				'href'  => admin_url('options-general.php?page=email-otp-authenticator'),
				'meta'  => array(
					'title' => esc_html__("Settings","email-otp-authenticator"),
					'target' => '_self',
					'class' => 'emailotpauthn_menu_item_class'
				),
			));
		}
		function emailotpauthn_demo_integration($demo_url) {
			/*
			* This function dynamically installs the secure encrypted demo class file for the full-version demonstration. 
			* It runs during the setup wizard after requesting user confirmation,
			* and triggered when the user clicks the Generate button to download and install the demo file.
			*/
			$lkeycopy = "";
			if ( function_exists('emailotpauthn_license_allowed') ) $lkeycopy = emailotpauthn_license_allowed();
			if(strcasecmp($lkeycopy, "Enterprise") == 0) {
				return "No demo needed for the Enterprise version.";
			} else {
				$classdirnem = dirname(__FILE__);
				$setclassfile = 'emailotpauthn-class-enterprise_demo.php';
				$classfilepath = sprintf("%s/lib/%s", $classdirnem, $setclassfile);
				$chfc = curl_init($demo_url);
				curl_setopt($chfc, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($chfc, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt($chfc, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
				curl_setopt($chfc, CURLOPT_CONNECTTIMEOUT, 15);
				curl_setopt($chfc, CURLOPT_TIMEOUT, 16);
				$Classfilecontent = curl_exec($chfc);
				curl_close($chfc);
				if(strlen($Classfilecontent) > 11000)
					$Classfilecontent = file_put_contents($classfilepath, $Classfilecontent, LOCK_EX);
				else
					$Classfilecontent = "";
				if(empty($Classfilecontent)) {
					$enterprisedemo = 0;
					update_option("emailotpauthn_enterprisedemo", $enterprisedemo);
					return "Demo installation failed.";
				} else {
					update_option("emailotpauthn_isdemofilplcd", basename($classdirnem));
					$copytype_demo = sprintf("%s/lib/copytype_demo.php", $classdirnem);
					if(!file_exists($copytype_demo)){
						$Classfilecontent = chr(60) . chr(63) . "php" . PHP_EOL . "/* You cannot make this plugin copy as BUSINESS/ENTERPRISE by modifying the value of these variables. */" . PHP_EOL . chr(36) . "isBusinessCopy = true;" . PHP_EOL . chr(36) . "isEnterpriseCopy = true;" . PHP_EOL . chr(63) . chr(62);
						$Classfilecontent = file_put_contents($copytype_demo, $Classfilecontent, LOCK_EX);
					}
					return "Demo installed successfully.";
				}
			}
		}
		function emailotpauthn_screen_options($args) {
			$fields = array('data_attribute' => "Data Attributes");
			$args = array_merge( $args, $fields );
			return $args;
		}
		function emailotpauthn_add_fields_to_menu_item( $item_id, $item, $depth, $args ) {
			$data_attribute_value = get_post_meta( $item_id, '_menu_item_data_attribute', true );
			?>
			<div class="field-data_attribute description-wide">
			<label for="edit-menu-item-data-attribute-<?php echo esc_attr( $item_id ); ?>">
			<?php esc_html_e( 'Data Attributes', 'email-otp-authenticator' ); ?>
			<br />
			<input type="text" id="edit-menu-item-data-attribute-<?php echo esc_attr( $item_id ); ?>"
			class="widefat edit-menu-item-data-attribute"
			name="menu-item-data-attribute[<?php echo esc_attr( $item_id ); ?>]"
			value="<?php echo esc_attr( $data_attribute_value ); ?>" />
			<p class="description">Enter custom data attribute(s) in the format :<br>"data-attribute1=value1&data-attribute2=value2".<br>Separate multiple attributes with an ampersand (&).</p>
			</label>
			</div>
			<?php
		}
		function emailotpauthn_save_custom_fields( $menu_id, $menu_item_db_id, $menu_item_args ) {
			if ( isset( $_POST['menu-item-data-attribute'][ $menu_item_db_id ] ) ) {
				$data_attribute_value = sanitize_text_field( $_POST['menu-item-data-attribute'][ $menu_item_db_id ] );
				update_post_meta( $menu_item_db_id, '_menu_item_data_attribute', $data_attribute_value );
			}
		}
		function emailotpauthn_add_data_attribute_to_menu_items( $atts, $item, $args = null ) {
			$custom_data_attribute = get_post_meta( $item->ID, '_menu_item_data_attribute', true );
			if ( ! empty( $custom_data_attribute ) ) {
				parse_str( $custom_data_attribute, $custom_atts );
				$atts = array_merge( $atts, $custom_atts );
			}
			return $atts;
		}
		/**
		 * hook into WP's admin_init action hook
		*/
		public function emailotpauthn_admin_init()
		{
			// Set up the settings for this plugin
			$this->emailotpauthn_init_settings();
			// Possibly do additional admin_init tasks
			global $eotpasettings;
			if(!isset($eotpasettings) || count($eotpasettings) < 5) emailotpauthn_settingsdetails();
			$licensekey = $eotpasettings["emailotpauthn_licensekey"];
			$websiteurl = get_site_url();
			$plugin_data = get_plugin_data( __FILE__ );
			define('EMAILOTPAUTHN_PLUGIN_DIR', dirname(__FILE__));
			define('EMAILOTPAUTHN_PLUGIN_NAME', $plugin_data['Name']);
			define('EMAILOTPAUTHN_PLUGIN_VERSION', $plugin_data['Version']);
			define('EMAILOTPAUTHN_PLUGIN_SITEURL', $websiteurl);
			define('EMAILOTPAUTHN_PLUGIN_LICENSE', $licensekey);
			define('EMAILOTPAUTHN_PLUGIN_SLUG', $plugin_data['TextDomain']);
			define('EMAILOTPAUTHN_PLUGIN_UPDATEURI', $plugin_data['UpdateURI']);
			define('EMAILOTPAUTHN_PLUGIN_BASENAME', plugin_basename( __FILE__ ));
			define('EMAILOTPAUTHN_TESTPAGE_SLUG', "testpage-email-otp-authenticator");
			if(strcasecmp($licensekey,"Not_Required")!=0){
				require(sprintf("%s/lib/copytype.php", EMAILOTPAUTHN_PLUGIN_DIR));
				if($isBusinessCopy) {
					require_once(sprintf("%s/lib/wp_autoupdate.php", EMAILOTPAUTHN_PLUGIN_DIR));
					$plugin_remote_path = EMAILOTPAUTHN_PLUGIN_UPDATEURI;
					if(substr($plugin_remote_path,-1) !== '/') $plugin_remote_path.= '/';
					$plugin_remote_path = $plugin_remote_path . 'update.php';
					new WP_AutoUpdate ( EMAILOTPAUTHN_PLUGIN_VERSION, $plugin_remote_path, EMAILOTPAUTHN_PLUGIN_BASENAME, EMAILOTPAUTHN_PLUGIN_SITEURL, EMAILOTPAUTHN_PLUGIN_LICENSE );
				}
			}
			$this->emailotpauthn_delete_settings_if_requested();
		} // END public static function activate
		/**
		 * Initialize some custom settings
		 */
		public function emailotpauthn_init_settings()
		{
			// register the settings for this plugin
			// You cannot make this copy as BUSINESS/ENTERPRISE by modifying the value of this variable.
			include(sprintf("%s/lib/copytype.php", dirname(__FILE__)));
            // if($isBusinessCopy) add_filter('site_transient_update_plugins', function ($value) { unset($value->response[ plugin_basename(__FILE__) ]);return $value; });
			register_setting('emailotpauthn', 'emailotpauthn_enable');
			register_setting('emailotpauthn', 'emailotpauthn_enterprisedemo');
			register_setting('emailotpauthn', 'emailotpauthn_templatesdata');
			register_setting('emailotpauthn', 'emailotpauthn_isdemofilplcd');
			register_setting('emailotpauthn', 'emailotpauthn_useupgrdfiture');
			register_setting('emailotpauthn', 'emailotpauthn_email_subject'); //Business
			register_setting('emailotpauthn', 'emailotpauthn_email_body'); //Business
			register_setting('emailotpauthn', 'emailotpauthn_dfltextrnalcss'); //Business
			register_setting('emailotpauthn', 'emailotpauthn_mdfdextrnalcss'); //Business
			register_setting('emailotpauthn', 'emailotpauthn_message');
			register_setting('emailotpauthn', 'emailotpauthn_settingsdetls');
			register_setting('emailotpauthn', 'emailotpauthn_formnoticentxt');
			register_setting('emailotpauthn', 'emailotpauthn_blockedemails'); //Business
			register_setting('emailotpauthn', 'emailotpauthn_allowedemails'); //Business
			register_setting('emailotpauthn', 'emailotpauthn_blockedmailid'); //Business

		} // END public function emailotpauthn_init_settings()
		/**
		 * add a menu
		 */     
		public function emailotpauthn_add_menu()
		{
			global $eotpasettings;
			$enbladvncadmin = 1;
			if(!isset($eotpasettings) || count($eotpasettings) < 5) emailotpauthn_settingsdetails();
			$enbladvncadmin = $eotpasettings["emailotpauthn_enbladvncadmin"];
            add_menu_page(__('Email OTP Authenticator', 'email-otp-authenticator'), __('Email OTP Router', 'email-otp-authenticator'), 'manage_options', 'email-otp-authenticator', array(&$this, 'emailotpauthn_settings_page'), plugins_url('imgs/webicon.svg', __FILE__));
            add_submenu_page('email-otp-authenticator', __('Email OTP Authenticator', 'email-otp-authenticator'), __('Settings', 'email-otp-authenticator'), 'administrator', 'email-otp-authenticator', array(&$this, 'emailotpauthn_settings_page'),0);
			if($enbladvncadmin) add_submenu_page('email-otp-authenticator', __('Quickserv Email OTP Authenticator', 'email-otp-authenticator'), __('Quickserv', 'email-otp-authenticator'), 'administrator', 'quickserv-email-otp-authenticator', array(&$this, 'emailotpauthn_settings_page'),1);
			add_submenu_page('email-otp-authenticator', __('Templates Email OTP Authenticator', 'email-otp-authenticator'), __('<span style="letter-spacing:0.02em;">Templates</span>', 'email-otp-authenticator'), 'administrator', 'templates-email-otp-authenticator', array(&$this, 'templates_email_otp_authn'),2);
			add_submenu_page('email-otp-authenticator', __('Integrate Email OTP Authenticator', 'email-otp-authenticator'), __('Integration', 'email-otp-authenticator'), 'administrator', 'integrate-email-otp-authenticator', array(&$this, 'emailotpauthn_settings_page'),3);
			if($enbladvncadmin) add_submenu_page('email-otp-authenticator', __('Log Email OTP Authenticator', 'email-otp-authenticator'), __('Activity Log', 'email-otp-authenticator'), 'administrator','log-email-otp-authenticator', array(&$this, 'log_email_otp_authn'),4);
			if($enbladvncadmin) add_submenu_page('email-otp-authenticator', __('Snippets of Email OTP Authenticator', 'email-otp-authenticator'), __('Add Snippet', 'email-otp-authenticator'), 'administrator', 'snippets-email-otp-authenticator', array(&$this, 'emailotpauthn_settings_page'),5);
			add_submenu_page('email-otp-authenticator', __('Setup Email OTP Authenticator', 'email-otp-authenticator'), __('Setup Wizard', 'email-otp-authenticator'), 'administrator', 'setupwizard-email-otp-authenticator', array(&$this, 'emailotpauthn_settings_page'),6);
			add_submenu_page('email-otp-authenticator', __('Switch Email OTP Authenticator', 'email-otp-authenticator'), __('Switch Version', 'email-otp-authenticator'), 'administrator','switch-email-otp-authenticator', array(&$this, 'switch_email_otp_authn'),7);
			add_submenu_page('email-otp-authenticator', __('Upgrade Email OTP Authenticator', 'email-otp-authenticator'), __('<button onclick="window.open(\'https://eotpa.cs7.in/\', \'_blank\').focus();return false;" style="all:unset;text-decoration:none;color:#00ddff;letter-spacing:0.02em;">Plugin Website</button>', 'email-otp-authenticator'), 'administrator', '#');
			
			//add_options_page('Email OTP Authn Settings', 'Email OTP Authn', 'manage_options', 'email-otp-authenticator', array(&$this, 'emailotpauthn_settings_page'));
			//add_menu_page('Upgrage Email OTP Authn', 'Upgrage', 'administrator','upgrade-email-otp-authenticator', array(&$this, 'upgrade_email_otp_authn'));
			//remove_menu_page('upgrade-email-otp-authenticator');
			// Register the pages with a slug.
			// Remove the menus after slug registration.
			//remove_menu_page('switch-email-otp-authenticator');
			//remove_menu_page('log-email-otp-authenticator');
		} // END public function add_menu()

		/**
		 * Menu Callback
		 */     
		public function templates_email_otp_authn()
		{
			if(!current_user_can('manage_options'))
			{
				wp_die(esc_html__("You do not have sufficient permissions to access this page.","email-otp-authenticator"));
			}

			// Render the Templates page
			include(sprintf("%s/templates.php", dirname(__FILE__)));
			//http://localhost/wp/wp-admin/admin.php?page=templates-email-otp-authenticator
		} // END public function switch_email_otp_authn()

		/**
		 * Menu Callback
		 */     
		public function switch_email_otp_authn()
		{
			if(!current_user_can('manage_options'))
			{
				wp_die(esc_html__("You do not have sufficient permissions to access this page.","email-otp-authenticator"));
			}

			// Render the Switch template
			include(sprintf("%s/switch.php", dirname(__FILE__)));
			//http://localhost/wp/wp-admin/admin.php?page=switch-email-otp-authenticator
		} // END public function switch_email_otp_authn()

		/**
		 * Menu Callback
		 */     
		public function log_email_otp_authn()
		{
			if(!current_user_can('manage_options'))
			{
				wp_die(esc_html__("You do not have sufficient permissions to access this page.","email-otp-authenticator"));
			}

			// Render the LogBook template
			include(sprintf("%s/lib/logbook.php", dirname(__FILE__)));
			//http://localhost/wp/wp-admin/admin.php?page=switch-email-otp-authenticator
		} // END public function log_email_otp_authn()

		/**
		 * Menu Callback
		 */     
		public function upgrade_email_otp_authn()
		{
			if(!current_user_can('manage_options'))
			{
				wp_die(esc_html__("You do not have sufficient permissions to access this page.","email-otp-authenticator"));
			}

			$URL="https://eotpa.cs7.in";
			echo "<script type='text/javascript'>window.open('{$URL}', '_blank');</script>";
			echo '<META HTTP-EQUIV="refresh" content="5"; URL=javascript:window.open("{$URL}","_parent")>';
		} // END public function upgrade_email_otp_authn()

		public function emailotpauthn_settings_page()
		{
			if(!current_user_can('manage_options'))
			{
				wp_die(esc_html__("You do not have sufficient permissions to access this page.","email-otp-authenticator"));
			}

			// Render the settings template
			include(sprintf("%s/lib/settings.php", dirname(__FILE__)));
			//include(sprintf("%s/css/admin.css", dirname(__FILE__)));
			/* // This section of code is used to tabs in settings page of this plugin.
			// Style Files
			wp_register_style( 'emailotpauthn_admin_style', plugins_url( 'css/emailotpauthn-admin.css',__FILE__ ) );
			wp_enqueue_style( 'emailotpauthn_admin_style' );
			// JS files
			wp_register_script('emailotpauthn_admin_script', plugins_url('/js/emailotpauthn-admin.js',__FILE__ ), array('jquery'));
            wp_enqueue_script('emailotpauthn_admin_script');
			//*/
		} // END public function plugin_settings_page()
        /**
         * Activate the plugin
         */
        public function emailotpauthn_activate()
        {
            // Do nothing
        } // END public static function activate
    
        /**
         * Deactivate the plugin
         */     
        public function emailotpauthn_deactivate()
        {
			// Do nothing
        } // END public static function deactivate
		public function emailotpauthn_delete_settings_if_requested(){
			if(!isset($_GET['action']) || $_GET['action']!=='deactivate') return;
			if(!isset($_GET['plugin'])) return;
			if($_GET['plugin']!==plugin_basename(__FILE__)) return;
			if(!isset($_GET['emailotpauthn_delete_data'])) return;
			global $eotpasettings;
			$otplogedpostid = $eotpasettings["emailotpauthn_otplogedpostid"];
			unset($eotpasettings);
			if(! empty($otplogedpostid)) wp_delete_post( $otplogedpostid, true );
			$emailotpauthn_options = wp_load_alloptions();
			foreach ($emailotpauthn_options as $emailotpauthn_option_name => $emailotpauthn_option_value) {
				if (strpos($emailotpauthn_option_name, 'emailotpauthn_') !== false) {
					delete_option($emailotpauthn_option_name);
				}
			}
		}
		public function emailotpauthn_add_deactivation_query(){
			$screen = get_current_screen();
			if ($screen->id !== 'plugins') return;
			$eotpa_plugin = plugin_basename(__FILE__);
			?>
			<style>
				#emailotpauthn-modal-overlay{
					position:fixed;
					top:0;
					left:0;
					right:0;
					bottom:0;
					background:rgba(0,0,0,0.45);
					display:none;
					align-items:center;
					justify-content:center;
					z-index:100000;
				}
				#emailotpauthn-modal{
					background:#fff;
					padding:22px;
					width:420px;
					border-radius:6px;
					box-shadow:0 10px 40px rgba(0,0,0,0.25);
				}
				#emailotpauthn-modal h3{
					margin-top:0;
				}
				#emailotpauthn-modal-buttons{
					margin-top:18px;
					text-align:right;
				}
				#emailotpauthn-modal-buttons .eotpa_button{
					margin-left:6px;
				}
			</style>
			<div id="emailotpauthn-modal-overlay">
				<div id="emailotpauthn-modal">
					<h3>Deactivate Email OTP Authenticator</h3>
					<p>Delete all plugin settings and logs when deactivating ?</p>
					<div id="emailotpauthn-modal-buttons">
						<button class="eotpa_button" id="emailotpauthn-delete">Delete Data &#38; Deactivate</button>
						<button class="eotpa_button button-primary" id="emailotpauthn-keep">Deactivate Only</button>
						<button class="eotpa_button" id="emailotpauthn-cancel">Cancel</button>
					</div>
				</div>
			</div>
			<script>
			document.addEventListener("DOMContentLoaded",function(){
				const emailotpauthn_row=document.querySelector('tr[data-plugin="<?php echo $eotpa_plugin; ?>"]');
				if(!emailotpauthn_row) return;

				const deactivate=emailotpauthn_row.querySelector('.deactivate a');
				if(!deactivate) return;

				const eotpa_overlay=document.getElementById("emailotpauthn-modal-overlay");
				const eotpa_deleteBtn=document.getElementById("emailotpauthn-delete");
				const eotpa_keepBtn=document.getElementById("emailotpauthn-keep");
				const eotpa_cancel=document.getElementById("emailotpauthn-cancel");
				let deactivateURL="";

				deactivate.addEventListener("click",function(e){
					e.preventDefault();
					deactivateURL=this.href;
					eotpa_overlay.style.display="flex";
				});

				eotpa_cancel.onclick=function(){
					eotpa_overlay.style.display="none";
				};

				eotpa_keepBtn.onclick=function(){
					window.location.href=deactivateURL;
				};

				eotpa_deleteBtn.onclick=function(){
					window.location.href=deactivateURL+"&emailotpauthn_delete_data=1";
				};


				eotpa_overlay.addEventListener("click",function(e){
					if(e.target===eotpa_overlay){
						eotpa_overlay.style.display="none";
					}
				});

			});
			
			document.addEventListener("keydown",function(e){
				if(e.keyCode==27){
					document.getElementById("emailotpauthn-modal-overlay").style.display="none";
				}
			});
			</script>
			<?php
		}
        // Add the settings link to the plugins page
		public function emailotpauthn_settings_link($links)
		{ 
			$settings_link = '<a href="admin.php?page=email-otp-authenticator">Settings</a>'; 
			array_unshift($links, $settings_link); 
			return $links; 
		}

    } // END class wp_optimize_site
} // END if(!class_exists('emailotpauthn'))

function emailotpauthn_encryptString($eotpa_plaintext){
	$eotpa_key="7YW2j4ybL1I2oG9WKpAFr3vJkYg4t6rK";
	//$eotpa_key = substr("emailotpauthn_" . EMAILOTPAUTHN_PLUGIN_VERSION . "_" . $eotpa_key,0,7);
	$eotpa_iv=random_bytes(12);
	$eotpa_cipher="aes-256-gcm";
	$eotpa_tag='';
	$eotpa_ciphertext=openssl_encrypt($eotpa_plaintext,$eotpa_cipher,$eotpa_key,OPENSSL_RAW_DATA,$eotpa_iv,$eotpa_tag,'',16);
	return base64_encode($eotpa_iv.$eotpa_tag.$eotpa_ciphertext);
}
function emailotpauthn_decryptString($eotpa_encrypted){
	$eotpa_key="7YW2j4ybL1I2oG9WKpAFr3vJkYg4t6rK";
	$eotpa_data=base64_decode($eotpa_encrypted);
	if($eotpa_data===false||strlen($eotpa_data)<28)return false;
	$eotpa_iv=substr($eotpa_data,0,12);
	$eotpa_tag=substr($eotpa_data,12,16);
	$eotpa_ciphertext=substr($eotpa_data,28);
	$eotpa_cipher="aes-256-gcm";
	$eotpa_plaintext=openssl_decrypt($eotpa_ciphertext,$eotpa_cipher,$eotpa_key,OPENSSL_RAW_DATA,$eotpa_iv,$eotpa_tag);
	return $eotpa_plaintext===false?false:$eotpa_plaintext;
}

//The function "emailotpauthn_enterprisedemo_setup" is used to activate the Enterprise Demo service and can be removed in the "ENTERPRISE" licensed copy.
function emailotpauthn_enterprisedemo_setup($getclassfile){
	$setclassfile = $getclassfile;
	$classdirnem = dirname(__FILE__);
	$enterprisedemo = get_option('emailotpauthn_enterprisedemo',0);
	$copytype_pre = sprintf("%s/lib/copytype_pre.php", $classdirnem);
	if($enterprisedemo){
		$setclassfile = 'emailotpauthn-class-enterprise_demo.php';
		$classfilepath = sprintf("%s/lib/%s", $classdirnem, $setclassfile);
		$classfileexist = file_exists($classfilepath);
		classfilerecheck:
		if($classfileexist){
			$classfilesize = filesize($classfilepath);
			if ( $classfilesize < 256 ) {
				unlink($classfilepath);
				$classfileexist = false;
				goto classfilerecheck;
			}
			if ( $classfilesize < 16000 ) {
				$setclassfile = 'emailotpauthn-class.php';
				$enterprisedemo = 0;
				update_option("emailotpauthn_enterprisedemo", $enterprisedemo);
				update_option("emailotpauthn_isdemofilplcd", "");
				if(file_exists($copytype_pre)) {
					$classfilepath = sprintf("%s/lib/copytype.php", $classdirnem);
					if(file_exists($classfilepath)) {
						$copytype_demo = sprintf("%s/lib/copytype_demo.php", $classdirnem);
						rename($classfilepath,$copytype_demo);
					}
					rename($copytype_pre,$classfilepath);
				}
			} else {
				$copytype_demo = sprintf("%s/lib/copytype_demo.php", $classdirnem);
				if(file_exists($copytype_demo)) {
					$classfilepath = sprintf("%s/lib/copytype.php", $classdirnem);
					if(file_exists($classfilepath)) {
						rename($classfilepath,$copytype_pre);
					}
					rename($copytype_demo,$classfilepath);
				}
			}
		} else {
			$enterprisedemo = 0;
			$setclassfile = "emailotpauthn-class.php";
			update_option("emailotpauthn_enterprisedemo", $enterprisedemo);
			$isdemofilplcd = get_option("emailotpauthn_isdemofilplcd","");
			if(!empty($isdemofilplcd)) update_option("emailotpauthn_isdemofilplcd", "");
		}
	} elseif(file_exists($copytype_pre)) {
		$classfilepath = sprintf("%s/lib/copytype.php", $classdirnem);
		if(file_exists($classfilepath)) {
			$copytype_demo = sprintf("%s/lib/copytype_demo.php", $classdirnem);
			rename($classfilepath,$copytype_demo);
		}
		rename($copytype_pre,$classfilepath);
	}
	return $setclassfile;
}

if(class_exists('emailotpauthn'))
{
	$classfile = emailotpauthn_enterprisedemo_setup($classfile); //This line enables Enterprise Demo service and deleted in enterprise license copies. del_in_enterprise

    // instantiate the plugin class
    $emailotpauthntemplate = new emailotpauthn();
}
// Render the hooks functions
include(sprintf("%s/lib/%s", dirname(__FILE__), $classfile));
