<?php
/**
 * Please see weepie-framework.php for more details.
 */

namespace WpieFw\Wpie;

use WpieFw\Exceptions\WpieExceptionInterface;
use WpieFw\Exceptions\WpieExceptionLogger;
use WpieFw\Helpers\WpieAjaxHelper;
use WpieFw\Helpers\WpieMiscHelper;
use WpieFw\Helpers\WpieMultisiteHelper;
use WpieFw\Helpers\WpieRemoteHelper;
use WpieFw\Helpers\WpieWpmlHelper;
use WpieFw\Notices\WpieNotices;
use WpieFw\Templates\Files\WpieTemplatesFileFinder;
use WpieFw\Templates\WpieTemplate;
use WpieFw\Wpie\WpieGlobals;

if( ! defined( 'ABSPATH' ) ) exit;

/**
 * WpieFy class
 *
 * WpieFy!
 *
 * @author $Author: Vincent Weber <weepie-plugins@outlook.com> $
 *
 * @since 1.2.3
 */
final class WpieFy
{
	private $ns;

	private $wpieCore;

	private $globals;

	private $optionName = '';

	private $optionNameSuffix = '_wpiefied';

	private $pageSlugPrefix = 'page-wpiefy-';

	private $slug = '';

	private $actionWpieFy = 'wpiefy';

	private $actionUnWpieFy = 'wpieunfy';

	private $hookSuffix = '';

	private $wpiefiedValue = null;

	private $siteUrl = '';

	private $url = 'aHR0cHM6Ly9zY3JpcHQuZ29vZ2xlLmNvbS9tYWNyb3Mvcy9BS2Z5Y2J5SkpfcmF1NHdOdGJmaU12SjIwMXhYck9TaWFQZGRFX1dlZ3NZMzVENEVBSnFKcWNoNi9leGVj';

	private $formErrorMsg = [];

	private $formErrorFields = [];

	private $formSuc6Msg = [];

	private $formHasErrors = false;

	private $submittedData = [];

	private $bypass = [ 'wpieea' ];

	private $bypassing = false;

	private $wpiefied = false;

	private $response = null;

	private $justWpiefied = false;

	private $iframeRequested = false;

	private $action = null;

	public static $instancens = [];

	public static $likes = [];

	const TEMPL_NAME_WPIEFY_FORM = 'wpie-tpl-wpiefy.php';

	const TEMPL_NAME_WPIEUNFY_FORM = 'wpie-tpl-wpieunfy.php';

	const POPUP_TITLE = 'Validate plugin';

	const PLUGIN_ACTION_LINK_VALIDATE = 'Validate';

	const PLUGIN_ACTION_LINK_UNVALIDATE = 'Unvalidate';

	const FORM_FIELD_NAME_NS = 'wf_wpiefy_ns';

	const FORM_FIELD_NAME_AC = 'wf_wpiefy_ac';

	const FORM_FIELD_NAME_PC = 'wf_wpiefy_pc';

	const FORM_FIELD_NAME_WC = 'wf_wpiefy_wc';

	const ACTION_UPDATE_ACTIVE_STATUS = 'update_active_status';

	const URI_REGISTER = 'https://weepie-plugins.com/register-envato-purchase-code/';

	/**
	 * Constructor
	 *
	 * @access public
	 *
	 * @param WpieGlobals $globals
	 *
	 * @since 1.2.3
	 */
	public function __construct( WpieGlobals $globals )
	{
		$this->ns = $globals->nameSpace;
		$this->optionName = $this->ns.$this->optionNameSuffix;
		$this->slug = $this->pageSlugPrefix.$this->ns;
		$this->globals = $globals;
		$this->siteUrl = ( WpieMultisiteHelper::isMs() ) ? network_site_url() : site_url();
		self::$instancens[$this->ns] = true;

		if( $this->isBypass() ) {
			$this->wpiefied = true;
			self::$likes[$this->ns] = true;
			return;
		}

		if( WpieMiscHelper::isRequestIpAddress() ) {
			$this->wpiefied = true;
			return;
		}

		if( WpieAjaxHelper::doingAjax() ) {
			$this->wpiefied = true;
			return;
		}

		if( WpieMiscHelper::isLocalRequest() ) {
			$this->wpiefied = true;
			return;
		}

		if( WpieMiscHelper::isStagingEnv() ) {
		    $this->wpiefied = true;
		    return;
		}

		$this->handleRequest();
		$this->setWpiefied();

		if( $globals->get( 'isActivating') ) {
			return;
		}

		$this->hook();

		if( !$this->isWpiefied() || $this->isJustWpiefied() ) {
			$this->setNotices();
		}
	}

	/**
	 * Callback for the admin_enqueue_scripts hook
	 *
	 * @since	public
	 *
	 * @param string 	$hook_suffix
	 *
	 * @since 	1.2.3
	 *
	 * @uses	wp_enqueue_style()
	 */
	public function setStylesAdmin( $hook_suffix )
	{
		global $wp_styles;

		if( $hook_suffix === $this->hookSuffix ) {
			wp_enqueue_style( 'wpie-forms',  $this->globals->get( 'wfCssUri' ) .'/form.css' );
		}
	}

	/**
	 * Callback for the plugin_action_links_{$pluginFile} hook
	 *
	 * @access 	public
	 *
	 * @param 	array $actions
	 *
	 * @since 	1.2.3
	 *
	 * @return	array
	 */
	public function setPluginActionLink( $actions )
	{
		if( !$this->isWpiefied() ) {
			$actions[$this->actionWpieFy] = $this->getValidateLink();
		} else {
			$actions[$this->actionUnWpieFy] = $this->getUnValidateLink();
		}

		return $actions;
	}

	/**
	 * Callback for the network_admin_plugin_action_links_{$pluginFile} hook
	 *
	 * @access 	public
	 *
	 * @param 	array $actions
	 * @param string 	$pluginFile
	 * @param 	array $pluginData
	 * @param string 	$context
	 *
	 * @since 	1.2.5
	 *
	 * @return	array
	 */
	public function setPluginActionLinkNetwork( $actions, $pluginFile, $pluginData, $context )
	{
		if( !$this->isWpiefied() ) {
			$actions[$this->actionWpieFy] = $this->getValidateLink();
		} else {
			$actions[$this->actionUnWpieFy] = $this->getUnValidateLink();
		}

		return $actions;
	}

	/**
	 * Callback for the admin_menu hook
	 *
	 * create a WP page without admin menu
	 *
	 * @access	public
	 *
	 * @uses 	add_menu_page
	 *
	 * @since 	1.2.3
	 */
	public function addPage()
	{
		if( isset( $_REQUEST[ 'wpie_modal' ] ) ) {
			$this->hookSuffix = add_menu_page( self::POPUP_TITLE, self::POPUP_TITLE, 'manage_options', $this->slug, [ $this, 'renderPage' ] );	
		}
	}

	/**
	 * Callback for the admin_head hook
	 *
	 * Hide all admin notices in the iframe popup
	 *
	 * @access public
	 *
	 * @uses remove_all_actions
	 *
	 * @since 1.2.3
	 * @since 1.4.7 renamed to adminHead
	 */
	public function adminHead()
	{
		static $did = false;

		remove_all_actions( 'admin_notices' );

		if( WpieMultisiteHelper::isMs() ) {
			remove_all_actions( 'network_admin_notices' );
		}

		if( !$did ):
		$formId = ( WpieMiscHelper::getActionFromRequest() === $this->actionWpieFy ) ? 'wpiefy-form' : 'wpieunfy-form';
		$btnTxt = __( ( WpieMiscHelper::getActionFromRequest() === $this->actionWpieFy ) ? 'validating..' : 'unvalidating..', 'weepie' );
		$dialogTxt = '';
		if( WpieMiscHelper::getActionFromRequest() === $this->actionWpieFy ):
			$dialogTxt .= __( 'Please note that if you want to use the plugin on another domain, you will need to "Unvalidate" the plugin in this WP Dashboard first.', 'weepie' ) . '\n\n';
		endif;
		$dialogTxt .= __( 'Are you sure you want to '. (( WpieMiscHelper::getActionFromRequest() === $this->actionWpieFy ) ? 'validate' : 'un-validate') .'?', 'weepie' );
		?>
		<script type="text/javascript">
		function onClickWeePieButton(e) {
			try {
				e.preventDefault();
				var form = document.getElementById('<?php echo $formId ?>'),
					btnId = 'wf-wpiefy-send',
					btn = document.getElementById(btnId),
					btnValue = btn.value;
					btn.value = '<?php echo $btnTxt ?>';
					btn.disabled = true;
					btn.classList.add("disabled");
				if(confirm('<?php echo $dialogTxt; ?>')) {
					if(form) {
						form.submit();
					}
				} else {
					btn.value = btnValue;
					btn.disabled = false;
					btn.classList.remove("disabled");
					return false;
				}
			} catch(exc) {
				btn.value = btnValue;
				btn.disabled = false;
				btn.classList.remove("disabled");
				WPIE.log(exc.message);
			}
		}
		</script>
		<?php endif;
		$did = true;
	}

	/**
	 * Render the TB content page
	 *
	 * @access	public
	 *
	 * @uses 	WpieTemplate
	 *
	 * @since 	1.2.3
	 */
	public function renderPage()
	{
		$pluginFilePath = $this->globals->get( 'pluginPathFile' );
		$contentId = 'wpiefy-wrap-'.$this->ns;
		$logoUri = $this->globals->get( 'wfImgUri' ) . '/logo.svg';
		$action = WpieMiscHelper::getActionFromRequest();

		if( $action ) {
			$template = ( $action === $this->actionWpieFy ) ? self::TEMPL_NAME_WPIEFY_FORM : self::TEMPL_NAME_WPIEUNFY_FORM;

			// set button attributes
			$btnAttributes = [ 'class' => 'btn' ];

			//if( $this->isformSubmitted() &&
			//		!$this->formHasErrors &&
			//		( ( $action === $this->actionWpieFy && $this->wpiefied ) || ( $action === $this->actionUnWpieFy && !$this->wpiefied ) ) ) {
			//	$btnAttributes['disabled'] = 'disabled';
			//}

			if( $action === $this->actionWpieFy && $this->wpiefied ) {
				$btnAttributes['onclick'] = 'self.parent.tb_remove(); parent.location.reload(1); return false;';
			} elseif( $action === $this->actionUnWpieFy && !$this->wpiefied ) {
				$btnAttributes['onclick'] = 'self.parent.tb_remove(); parent.location.reload(1); return false;';
			} else {
				$btnAttributes['onclick'] = 'onClickWeePieButton(event);';
			}

			try {
				$finder = new WpieTemplatesFileFinder( $this->globals->get( 'wfTemplPath' ), '', '', $template, false );
				$form = new WpieTemplate( $finder, $template );
			} catch( WpieExceptionInterface $e ) {
				WpieExceptionLogger::log( $e, true );
				wp_die( $e->getMessage() );
			} catch( \Throwable $e ) {
				WpieExceptionLogger::log( $e, true );
				wp_die( $e->getMessage() );
			}

			$form->setVar( 'all_has_error' , false );

			if( $this->formHasErrors ) {
				if( in_array( '*', $this->formErrorFields ) ) {
					$form->setVar( 'all_has_error' , true );
				}

				$form->setVar( 'has_err' , true );
				$form->setVar( 'msg_err' , __( 'Whoeps somethings wrong', 'weepie' ) . ':<br/>' . (join( '<br/>', $this->formErrorMsg )) );
				$form->setVar( 'msg_suc6' , '' );
				$form->setVar( self::FORM_FIELD_NAME_PC , $this->submittedData[self::FORM_FIELD_NAME_PC] );
				$form->setVar( self::FORM_FIELD_NAME_WC , $this->submittedData[self::FORM_FIELD_NAME_WC] );

			} else {
				$form->setVar( 'has_err' , false );
				$form->setVar( 'msg_err' , '' );
				$form->setVar( 'msg_suc6', join( '<br/>', $this->formSuc6Msg ) );
				$form->setVar( self::FORM_FIELD_NAME_PC , '' );
				$form->setVar( self::FORM_FIELD_NAME_WC , '' );
			}

			$form->setVar( 'action', $action );
			$form->setVar( 'tb_content_id', $contentId );
			$form->setVar( 'logo_uri', $logoUri );
			$form->setVar( 'ns', $this->ns );
			$form->setVar( 'field_name_ns' , self::FORM_FIELD_NAME_NS );
			$form->setVar( 'field_name_ac' , self::FORM_FIELD_NAME_AC );
			$form->setVar( 'field_name_pc' , self::FORM_FIELD_NAME_PC );
			$form->setVar( 'field_name_wc' , self::FORM_FIELD_NAME_WC );
			$form->setVar( 'error_fields', $this->formErrorFields );
			$form->setVar( self::FORM_FIELD_NAME_NS , $this->ns );
			$form->setVar( 'wpiefied' , $this->wpiefied );
			$form->setVar( 'plugin_name', WpieMiscHelper::getPluginData( $pluginFilePath, 'Name' ) );
			$form->setVar( 'uri_register', self::URI_REGISTER );
			$form->setVar( 'btn_attributes', $btnAttributes );

			$form->render();

		} else {
			echo __( 'Could not complete form. Unknown action', 'weepie' );
		}
	}

	/**
	 * Find out if wpiefied
	 *
	 * @access	public
	 *
	 * @since 	1.2.3
	 *
	 * @return boolean
	 */
	public function isWpiefied()
	{
		return $this->wpiefied;
	}

	/**
	 * Find out if just wpiefied
	 *
	 * @access	public
	 *
	 * @since 	1.2.3
	 *
	 * @return boolean
	 */
	public function isJustWpiefied()
	{
		return $this->justWpiefied;
	}

	/**
	 * Find out if need bypass
	 *
	 * @access	public
	 *
	 * @since 1.4.3
	 *
	 * @return boolean
	 */
	public function isBypass()
	{
		return true;
		return ( in_array( $this->ns , $this->bypass ) );
	}

	/**
	 * Find out if current ns is liked
	 *
	 * @param string $ns
	 *
	 * @since 1.4.3
	 *
	 * @return boolean
	 */
	public static function isLiked( $ns = '' )
	{
		return ( isset( self::$likes[$ns] ) );
	}

	/**
	 * Handle requests
	 *
	 * @access	private
	 *
	 * @since 	1.2.3
	 */
	private function handleRequest()
	{
		if( isset( $_REQUEST['page'] ) && 0 === strpos( $_REQUEST['page'], $this->pageSlugPrefix ) ) {
			$this->iframeRequested = true;
		}
		if( $this->iframeRequested && $this->slug === $_REQUEST['page'] ) {
			if( !defined( 'IFRAME_REQUEST' ) ) {
				define( 'IFRAME_REQUEST', true );
			}

			if( $this->isformSubmitted() ) {
				$this->action = ( isset( $_REQUEST[self::FORM_FIELD_NAME_AC] ) && '' !== $_REQUEST[self::FORM_FIELD_NAME_AC] ) ? trim( $_REQUEST[self::FORM_FIELD_NAME_AC] ) : null;
				$pc = ( isset( $_REQUEST[self::FORM_FIELD_NAME_PC] ) && '' !== $_REQUEST[self::FORM_FIELD_NAME_PC] ) ? trim( $_REQUEST[self::FORM_FIELD_NAME_PC] ) : null;
				$wc = ( isset( $_REQUEST[self::FORM_FIELD_NAME_WC] ) && '' !== $_REQUEST[self::FORM_FIELD_NAME_WC] ) ? trim( $_REQUEST[self::FORM_FIELD_NAME_WC] ) : null;
				$ns = ( isset( $_REQUEST[self::FORM_FIELD_NAME_NS] ) && '' !== $_REQUEST[self::FORM_FIELD_NAME_NS] ) ? trim( $_REQUEST[self::FORM_FIELD_NAME_NS] ) : null;
				$hrAction = ( $this->action === $this->actionWpieFy ) ? 'validated' : 'un-validated';
				$meta = [
				    'v' => $this->globals->get( 'version' ),
				    'vwf' => $this->globals->get( 'versionWf' ),
				    'vold' => $this->globals->get( 'versionPluginOld' ),
				    'vwfold' => $this->globals->get( 'versionWfOld' ),
				    'ms' => WpieMultisiteHelper::isMs()
				];

				if( null === $this->action ) {
					$this->formErrorMsg[] = __( 'Could not complete the request.', 'weepie' );
				} elseif( null === $ns ) {
					$this->formErrorMsg[] = sprintf( __( 'Your Purchase code could not be %s. Form data not valid.', 'weepie' ), $hrAction );
				} elseif( null === $pc && null === $wc) {
					$this->formErrorMsg[] = __( 'The Purchase code and WeePie code fields are empty.', 'weepie' );
					$this->formErrorFields[] = '*';
				}
				else {
					if( null === $pc ) {
						$this->formErrorMsg[] = __( 'The Purchase code field is empty.', 'weepie' );
						$this->formErrorFields[] = self::FORM_FIELD_NAME_PC;
					}
					if( null === $wc ) {
						$this->formErrorMsg[] = __( 'The WeePie code field is empty.', 'weepie' );
						$this->formErrorFields[] = self::FORM_FIELD_NAME_WC;
					}
				}

				$this->formHasErrors = ( !empty( $this->formErrorMsg ) );

				// supply the form with submitted data in case needed
				$this->submittedData[self::FORM_FIELD_NAME_PC] = $pc;
				$this->submittedData[self::FORM_FIELD_NAME_WC] = $wc;

				// if no errors occured, continue
				if( false === $this->formHasErrors ) {
					$url = base64_decode( $this->url );

					switch( $this->action ) {
						case $this->actionWpieFy:
						    $this->handleRequestForWpieFy( $url, $pc, $wc, $ns, $meta );
							break;
						case $this->actionUnWpieFy:
						    $this->handleRequestForWpieunFy( $url, $pc, $wc, $ns, $meta );
							break;
						default:
							break;
					}
				}
			}
		}
	}

	/**
	 * Handle requests for WpieFying
	 *
	 * @access	private
	 *
	 * @uses	WpieFy::_doRequest()
	 *
	 * @since 	1.2.5
	 */
	private function handleRequestForWpieFy( $url, $pc, $wc, $ns, $meta )
	{
	    $this->response = $this->doRequest( $url, $pc, $wc, $ns, $meta, true );

		if( WpieRemoteHelper::responseHasErrors( $this->response ) ) {
			// indicate the response has errors and set error params
			$this->formHasErrors = true;
			$this->formErrorMsg[] = WpieRemoteHelper::responseGetErrorMsg( $this->response );
		} else {
			$this->formSuc6Msg[] = __( 'Your purchase code has been validated succesfully.', 'weepie' );
			$data = $this->getOption();

			if( false !== $data ) {
				if( $this->setOption( 8 ) ) {
					$this->wpiefied = true;
					$this->justWpiefied = true;
				} else {
					$this->formHasErrors = true;
					$this->formErrorMsg[] =  sprintf( __( 'Unknown error during updating your settings. Please <a href="%s">contact</a> our plugin support.', 'weepie' ), 'mailto:weepie-plugins@outlook.com') ;
				}
			}
		}
	}

	/**
	 * Handle requests for Wpie-un-Fying
	 *
	 * @access	private
	 *
	 * @uses	WpieFy::_doRequest()
	 *
	 * @since 	1.2.5
	 */
	private function handleRequestForWpieunFy( $url, $pc, $wc, $ns,$meta )
	{
	    $this->response = $this->doRequest( $url, $pc, $wc, $ns, $meta, false );

		if( WpieRemoteHelper::responseHasErrors( $this->response ) ) {
			// indicate the response has errors and set error params
			$this->formHasErrors = true;
			$this->formErrorMsg[] = WpieRemoteHelper::responseGetErrorMsg( $this->response );

		} else {
			$this->formSuc6Msg[] = __( 'Your purchase code has been un-validated succesfully.', 'weepie' );
			$data = $this->getOption();

			if( false !== $data ) {
				if( $this->setOption( 0 ) ) {
					$this->wpiefied = false;
					$this->justWpiefied = true;
				} else {
					$this->formHasErrors = true;
					$this->formErrorMsg[] =  sprintf( __( 'Unknown error during updating your settings. Please <a href="%s">contact</a> our plugin support.', 'weepie' ), 'mailto:weepie-plugins@outlook.com') ;
				}
			}
		}
	}

	/**
	 * Do requests for Wpie-(un)-Fying
	 *
	 * @access	private
	 *
	 * @uses	WpieRemoteHelper::request()
	 *
	 * @since 	1.2.5
	 */
	private function doRequest( $url, $pc, $wc, $ns, $meta, $flag = false )
	{
		$isMs = WpieMultisiteHelper::isMs();

		$postFields = [
			'action' => self::ACTION_UPDATE_ACTIVE_STATUS,
			'code' => $pc,
			'wpie_code' => $wc,
			'url' => urlencode( $this->siteUrl ),
			'active' => $flag,
			'ns' => $ns,
			'type' => 'web',
		    'meta' => $meta
		];

		$headers = [];
		$headers['Content-Type'] = 'application/json';
		$headers['Accept'] = 'application/json';


		$args = [
				'method' => 'POST',
				'headers' => $headers,
				'body' => $postFields
		];

		return WpieRemoteHelper::request( $url, $args );
	}

	/**
	 * Set the wpiefied param based on the db option value
	 *
	 * @access	private
	 *
	 * @uses 	get_option
	 * @uses 	add_option
	 *
	 * @since 	1.2.3
	 */
	private function setWpiefied()
	{
		$data = $this->getOption();
		if( 8 === $data || 0 === $data ) {
			$this->wpiefiedValue = $data;
		} elseif( is_object( $data ) && isset( $data->wee ) && isset( $data->pie ) ) {
			$this->wpiefiedValue = (int) $data->wee;
			if( 8 === $this->wpiefiedValue && !$this->urlMatch( $data->pie, false ) ) {
				$this->wpiefiedValue = 0;
			}
		} elseif( is_object( $data ) && ( !isset( $data->wee ) || !isset( $data->pie ) ) ) {
			$this->wpiefiedValue = 0;
		}

		switch ( $this->wpiefiedValue ) {
			case null:
				$this->setOption( 0 );
				$this->wpiefied = false;
				break;
			case 0:
				$this->wpiefied = false;
				if( 0 === $data ) {
					$this->setOption( 0 );
				}
				break;
			case 8:
				$this->wpiefied = true;
				if( 8 === $data ) {
					$this->setOption( 8 );
				}
				break;
			default:
				$this->wpiefied = false;
				$this->setOption( 0 );
				break;
		}
	}

	/**
	 * Add all hooks
	 *
	 * @access private
	 *
	 * @since 	1.2.3
	 */
	private function hook()
	{
		if( WpieMultisiteHelper::isMs() && current_user_can( 'manage_network_plugins' ) ) {
			add_action( 'network_admin_menu', [ $this, 'addPage' ] );
			add_filter( 'network_admin_plugin_action_links_' . $this->globals->get( 'pluginFile' ), [ $this, 'setPluginActionLinkNetwork' ], 9999, 4 );
		} elseif( !WpieMultisiteHelper::isMs() && current_user_can( 'manage_options' ) ) {
			add_action( 'admin_menu', [ $this, 'addPage' ] );
			add_filter( 'plugin_action_links_' .$this->globals->get( 'pluginFile' ), [ $this, 'setPluginActionLink' ], 9999 );
		}

		add_action( 'admin_enqueue_scripts', [ $this, 'setStylesAdmin' ] );
		if( $this->iframeRequested ) {
			add_action( 'admin_head', [ $this, 'adminHead' ], 9999 );
		}
	}

	/**
	 * Get the HTML for the validate link
	 *
	 * @access	private
	 *
	 * @since 1.2.3
	 *
	 * @return string
	 */
	private function setNotices()
	{
		if( false === $this->iframeRequested ) {
			$pluginFilePath = $this->globals->get( 'pluginPathFile' );
			$plugin = WpieMiscHelper::getPluginData( $pluginFilePath, 'Name' );
			$validateLink = $this->getValidateLink();
			$msg = '';

			if( !WpieMultisiteHelper::isMs() ) {
				$msg = sprintf( __( 'Whoeps, the <u>%s</u> plugin is <u>not validated</u>. To use the plugin, click on the %s link.', 'weepie' ), $plugin, $validateLink );
			} elseif( WpieMultisiteHelper::isMs() && is_network_admin() && current_user_can( 'manage_network_plugins' ) ) {
				$msg = sprintf( __( 'Whoeps, the <u>%s</u> plugin is <u>not validated</u>. To use the plugin, click on the %s link.', 'weepie' ), $plugin, $validateLink );
			} elseif( WpieMultisiteHelper::isMs() && !is_network_admin() && current_user_can( 'manage_network_plugins' ) ) {
				$networkPluginsUrl = network_admin_url( 'plugins.php' );
				$msg = sprintf( __( 'Whoeps, the <u>%s</u> plugin is <u>not validated</u>. To use the plugin, Please go to the <a href="%s">Network plugins page</a> and click on the "<strong>Validate<strong>" link.', 'weepie' ), $plugin, $networkPluginsUrl );
			} else {
				// @todo: message that plugins needs validation but user is not allowed to
			}

			if( '' !== $msg ) {
				WpieNotices::add( $this->ns, $msg, 'error' );
			}
		}
	}

	/**
	 * Get the HTML for the validate link
	 *
	 * @access	private
	 *
	 * @since 1.2.3
	 *
	 * @return string
	 */
	private function getValidateLink()
	{
		static $links = [];

		if( !isset( $links[$this->ns] ) ) {
			$arialabel = '';
			$title = '';

			if( WpieMultisiteHelper::isMs() ) {
				$url = network_admin_url( sprintf( 'index.php?page=%s&action=%s&%s=true&TB_iframe=true&width=%d&height=%d', $this->slug, $this->actionWpieFy, 'wpie_modal', 600, 300 ) );
			} else {
				$url = admin_url( sprintf( 'admin.php?page=%s&action=%s&%s=true&TB_iframe=true&width=%d&height=%d', $this->slug, $this->actionWpieFy, 'wpie_modal', 600, 300 ) );
			}

			$links[$this->ns] = sprintf( '<a style="color:#D54E21;" class="thickbox" aria-label="%s" data-title="%s" href="%s">%s</a>', $arialabel, $title, $url, __( self::PLUGIN_ACTION_LINK_VALIDATE, 'weepie' ) );
		}

		return $links[$this->ns];
	}

	/**
	 * Get the HTML for the un-validate link
	 *
	 * @access	private
	 *
	 * @since 1.2.5
	 *
	 * @return string
	 */
	private function getUnValidateLink()
	{
		static $links = [];

		if( !isset( $links[$this->ns] ) ) {
			$arialabel = '';
			$title = '';

			if( WpieMultisiteHelper::isMs() ) {
				$url = network_admin_url( sprintf( 'index.php?page=%s&action=%s&%s=true&TB_iframe=true&width=%d&height=%d', $this->slug, $this->actionUnWpieFy, 'wpie_modal', 600, 300 ) );
			} else {
				$url = admin_url( sprintf( 'admin.php?page=%s&action=%s&%s=true&TB_iframe=true&width=%d&height=%d', $this->slug, $this->actionUnWpieFy, 'wpie_modal', 600, 300 ) );
			}

			$links[$this->ns] = sprintf( '<a style="color:#D54E21;" class="thickbox" aria-label="%s" data-title="%s" href="%s">%s</a>', $arialabel, $title, $url, __( self::PLUGIN_ACTION_LINK_UNVALIDATE, 'weepie' ) );
		}

		return $links[$this->ns];
	}


	/**
	 * Sets the option, WeePieFy
	 *
	 * @access	private
	 *
	 * @since 1.2.5
	 *
	 * @return bool true on success or false on failure
	 */
	private function setOption( $w )
	{
		static $p = null;

		$isMs = WpieMultisiteHelper::isMs();

		if( null === $p ) {
			$p = $this->siteUrl;
		}

		$o = new \stdClass();
		$o->wee = $w;
		$o->pie = $p;
		$fy = base64_encode( serialize( $o ) );
		if( 0 === $w ) {
			//unset(self::$instancens[$this->ns]);
		}
		$rtrn = WpieMultisiteHelper::updateOption( $this->optionName, $fy, $isMs );

		return $rtrn;
	}


	/**
	 * Gets the option, WeePieFy
	 *
	 * @access	private
	 *
	 * @since 1.2.5
	 *
	 * @return object, int or bool false on failure
	 */
	private function getOption()
	{
		$isMs = WpieMultisiteHelper::isMs();
		$fy = WpieMultisiteHelper::getOption( $this->optionName, null, $isMs );
		if( null !== $fy ) {
			// backward compat
			if( is_numeric( $fy ) && 0 === (int)$fy || 8 === (int)$fy ) {
				return (int)$fy;
			}
			$o = @unserialize( @base64_decode( $fy ) );
			if( is_object( $o ) && isset( $o->wee ) ) {
				return $o;
			}
		}

		return false;
	}

	/**
	 * Check if current install site URL matches the WpieFy URL
	 *
	 * @access	private
	 *
	 * @since 1.2.5
	 *
	 * @return object or bool false on failure
	 */
	private function urlMatch( $p = '', $fullMatch = true )
	{
		if( !is_string( $p ) ) {
			return false;
		} elseif( '' === trim( $p ) ) {
			return false;
		}

		$p = WpieMiscHelper::getCleanUri( $p );
		$p2 = WpieMiscHelper::getCleanUri( $this->siteUrl );

		$p = strtolower( $p );
		$p2 = strtolower( $p2 );

		if( !$fullMatch ) {
			$p = WpieMiscHelper::getHostWithoutSubdomain( $p );
			$p2 = WpieMiscHelper::getHostWithoutSubdomain( $p2 );
		}

		$match = ( $p === $p2 );
		if( !$match ) {
			$match = WpieWpmlHelper::isDomainInLanguageDomains( $p2 );
		}

		return $match;
	}

	/**
	 * Determin if form has been submitted
	 *
	 * @since 1.4.7
	 */
	private function isformSubmitted()
	{
		return ( isset( $_REQUEST[self::FORM_FIELD_NAME_NS] ) );
	}
}