Your IP : 216.73.216.43


Current Path : /var/www/www.indacotrentino.com/www/vendor/iubenda/module-cookiesolution/Helper/
Upload File :
Current File : //var/www/www.indacotrentino.com/www/vendor/iubenda/module-cookiesolution/Helper/AutoBlocking.php

<?php

namespace Iubenda\CookieSolution\Helper;

/**
 * Class AutoBlocking
 *
 * Helper class for AutoBlocking functionalities.
 */
class AutoBlocking {

	/**
	 * Include HTTP client functionalities from HttpClientTrait.
	 * Provides methods for making HTTP requests.
	 */
	use HttpClientTrait;

	/**
	 * @var string Format for an autoblocking script.
	 */
	private $autoblockingScriptFormat = '<script type="text/javascript" src="https://cs.iubenda.com/autoblocking/%d.js" charset="UTF-8"></script>';

	/**
	 * @var string Format for sync script.
	 */
	private $syncScriptFormat = '<script type="text/javascript" src="//cs.iubenda.com/sync/%d.js" charset="UTF-8"></script>';

	/**
	 * @var string Format for autoblocking URL.
	 */
	private $autoblockingUrlFormat = 'https://cs.iubenda.com/autoblocking/%d.js';

	/**
	 * @var string Pattern to identify autoblocking scripts.
	 */
	private $autoblockingPattern = "/<script\b[^>]*src=['\"][^'\"]*iubenda\.com\/autoblocking[^'\"]*['\"][^>]*><\/script>/";

	/**
	 * @var string Pattern to identify sync scripts.
	 */
	private $syncPattern = "/<script\b[^>]*src=['\"][^'\"]*iubenda\.com\/sync[^'\"]*['\"][^>]*><\/script>/";

	/**
	 * @var string Default configuration script.
	 * Initializes the _iub global variable and ensures that the
	 * csConfiguration object is defined.
	 */
	private $defaultCsConfigurationScript = '<script>
window._iub = window._iub || [];
_iub.csConfiguration = _iub.csConfiguration || {};
</script>';

	/**
	 * Process the given code.
	 *
	 * @param   string  $code  The code to process.
	 *
	 * @return string The processed code.
	 */
	public function processCode( $code ) {
		/**
		 * Attempt to retrieve the site ID from the provided code.
		 * If unsuccessful, do nothing and continue to the next iteration.
		 */
		$siteId = $this->getSiteIdFromCsCode( $code );
		if ( empty( $siteId ) || ! (int) $siteId ) {
			return $code;
		}

		/**
		 * Check if the autoblocking feature is available for the site.
		 * Remove existing autoblocking and sync scripts if present.
		 */
		$autoblockingStatus = $this->isAutoblockingFeatureAvailable( $siteId );
		$code               = $this->removeExistingScripts( $code );

		/**
		 * If the autoblocking feature is available,
		 * insert the autoblocking script.
		 * Otherwise, insert the sync script.
		 */
		if ( $autoblockingStatus ) {
			$code = $this->insertAutoblockingScript( $code, $siteId );
		} else {
			$code = $this->insertSyncScript( $code, $siteId );
		}

		return $code;
	}

	/**
	 * Parses the provided script and extracts the site ID.
	 *
	 * @param   string  $code  The script to parse.
	 *
	 * @return  string  The extracted site ID.
	 */
	public function getSiteIdFromCsCode( $code ) {
		if ( empty( $code ) ) {
			return '';
		}

		// Removing slashes from the code.
		$code = stripslashes( $code );

		// Parsing configuration using regular expressions.
		$parsedConfiguration = $this->parseConfigurationByRegex( $code );

		// Returning the site ID if found in the parsed configuration.
		if ( isset( $parsedConfiguration['siteId'] ) ) {
			return $parsedConfiguration['siteId'];
		}

		// Return empty string if no site ID found.
		return '';
	}

	/**
	 * Checks whether the autoblocking feature is available for the given site ID.
	 *
	 * @param   string  $siteId  The site ID to check.
	 *
	 * @return  bool    True if the autoblocking feature is available; otherwise, false.
	 */
	public function isAutoblockingFeatureAvailable( $siteId ) {
		$url = sprintf( $this->autoblockingUrlFormat, $siteId );

		try {
			$response = $this->httpGet( $url );
		} catch ( \Exception $e ) {
			return false;
		}

		return strlen( $response ) > 150 && strpos( $response, "Autoblocking not enabled" ) === false;
	}

	/**
	 * Extracts configuration data from an iubenda code using regex.
	 *
	 * @param   string  $code  The iubenda code.
	 *
	 * @return  array   Extracted configuration data.
	 */
	public function parseConfigurationByRegex( $code ) {
		$result = [];
		$code   = stripslashes( $code );

		// Extract 'siteId'.
		if ( preg_match( '/siteId([\s\S]*?)(?:,|})/', $code, $matches ) ) {
			$result['siteId'] = trim( preg_replace( "/(?:'|\"|}|:)/", ' ', $matches[1] ) );
		}

		// Extract 'cookiePolicyId'.
		if ( preg_match( '/cookiePolicyId([\s\S]*?)(?:,|})/', $code, $matches ) ) {
			$result['cookiePolicyId'] = trim( preg_replace( "/(?:'|\"|}|:)/", ' ', $matches[1] ) );
		}

		return $result;
	}

	/**
	 * Removes existing autoblocking and sync scripts from the given code if found.
	 *
	 * This function searches for script tags within the given HTML code where the src attribute
	 * includes either "iubenda.com/autoblocking" or "iubenda.com/sync", and removes them if found.
	 *
	 * @param   string  $code  The HTML code to clean.
	 *
	 * @return  string  The cleaned HTML code, without autoblocking and sync scripts if found.
	 */
	public function removeExistingScripts( $code ) {
		// Remove the autoblocking scripts if found.
		$code = preg_replace( $this->autoblockingPattern, '', $code );

		// Remove the sync scripts if found.
		$code = preg_replace( $this->syncPattern, '', $code );

		// Trim and return the cleaned code.
		return trim( $code );
	}

	/**
	 * Inserts the autoblocking script after the _iub.csConfiguration script block.
	 *
	 * This function inserts autoblocking script URL after the _iub.csConfiguration in provided code,
	 * ensuring that the script is loaded after the _iub.csConfiguration code content.
	 *
	 * @param   string  $code     The existing code content to which the script will be inserted.
	 * @param   string  $site_id  The site ID used to generate the autoblocking script URL.
	 *
	 * @return  string  The modified code with the autoblocking script inserted.
	 */
	public function insertAutoblockingScript( $code, $site_id ) {
		$autoblockingScriptUrl = sprintf(
			$this->autoblockingScriptFormat,
			$site_id
		);

		return $this->insertScriptAfterCsConfiguration( $code, $autoblockingScriptUrl );
	}

	/**
	 * Inserts the sync script after the _iub.csConfiguration script block.
	 *
	 * This function inserts sync script URL after the _iub.csConfiguration in provided code,
	 * ensuring that the script is loaded after the _iub.csConfiguration code content.
	 *
	 * @param   string  $code     The existing code content to which the script will be inserted.
	 * @param   string  $site_id  The site ID used to generate the sync script URL.
	 *
	 * @return  string  The modified code with the sync script inserted.
	 */
	public function insertSyncScript( $code, $site_id ) {
		$syncScriptUrl = sprintf(
			$this->syncScriptFormat,
			$site_id
		);

		return $this->insertScriptAfterCsConfiguration( $code, $syncScriptUrl );
	}

	/**
	 * Inserts a script immediately after the _iub.csConfiguration script block.
	 *
	 * This method inserts a script immediately after the _iub.csConfiguration script block within the provided code.
	 * It searches for the _iub.csConfiguration script block and determines its position in the code.
	 * Then, it finds the position of closing </script> tag following the _iub.csConfiguration block and inserts the script after it.
	 * If _iub.csConfiguration or </script> is not found, it adds the necessary script tags and then inserts the custom script.
	 *
	 * @param   string  $code    The original code containing the _iub.csConfiguration script.
	 * @param   string  $script  The script to insert.
	 *
	 * @return string The modified code with the script inserted.
	 */
	private function insertScriptAfterCsConfiguration( $code, $script ) {
		// Detect the position of _iub.csConfiguration.
		$CsConfigurationPos = strpos( $code, '_iub.csConfiguration' );

		if ( $CsConfigurationPos !== false ) {
			// Detect the position of </script> after _iub.csConfiguration.
			$CsConfigurationScriptEndPos = strpos( $code, '</script>', $CsConfigurationPos );

			if ( $CsConfigurationScriptEndPos !== false ) {
				// Insert the custom script after the </script> tag.
				$CsConfigurationScriptEndPos += 9; // Length of '</script>'

				// Extract the substring before and after the </script> tag.
				$beforeCsConfigurationScript = substr( $code, 0, $CsConfigurationScriptEndPos );
				$afterCsConfigurationScript  = substr( $code, $CsConfigurationScriptEndPos );

				// Trim both substrings and then add the custom script.
				$beforeCsConfigurationScript = trim( $beforeCsConfigurationScript );
				$afterCsConfigurationScript  = trim( $afterCsConfigurationScript );

				return $beforeCsConfigurationScript . PHP_EOL . $script . PHP_EOL . $afterCsConfigurationScript;
			}
		}

		// If _iub.csConfiguration or </script> is not found, prepend the necessary script tags and the custom script.
		return $this->defaultCsConfigurationScript . PHP_EOL . $script . PHP_EOL . $code;
	}

}