<?php
/**
 * @package   admintoolswp
 * @copyright Copyright (c)2017-2026 Nicholas K. Dionysopoulos / Akeeba Ltd
 * @license   GNU GPL version 3 or later
 */

use Akeeba\AdminTools\Admin\Helper\Wordpress;

defined('ADMINTOOLSINC') or die;

class AtsystemFeatureMuashield extends AtsystemFeatureAbstract
{
	protected $loadOrder = 305;

	/**
	 * Is this feature enabled?
	 *
	 * @return bool
	 */
	public function isEnabled()
	{
		if (Wordpress::is_admin() && !Wordpress::is_ajax())
		{
			return false;
		}

		if ($this->skipFiltering)
		{
			return false;
		}

		return ($this->cparams->getValue('muashield', 1) == 1);
	}

	/**
	 * Protects against malicious User Agent strings and forged forwarding
	 * headers that contain PHP code or serialised object injection payloads.
	 */
	public function onSystem()
	{
		if (!isset($_SERVER) || !is_array($_SERVER))
		{
			return;
		}

		$this->blockUserAgent();
		$this->blockForwardHeader();
	}

	private function blockUserAgent()
	{
		if (!array_key_exists('HTTP_USER_AGENT', $_SERVER))
		{
			return;
		}

		$mua = trim($_SERVER['HTTP_USER_AGENT']);

		// PHP code in the User Agent string
		if (strstr($mua, '<?'))
		{
			$this->exceptionsHandler->blockRequest('muashield');
		}

		// Serialised data / object injection in the User Agent string
		$patterns = [
			'@"feed_url@',
			'@}__(.*)|O:@',
			'@J?Simple(p|P)ie(Factory)?@',
		];

		foreach ($patterns as $pattern)
		{
			if (preg_match($pattern, $mua) == 1)
			{
				$_SERVER['HTTP_USER_AGENT'] = 'HACKING ATTEMPT DETECTED';

				$this->exceptionsHandler->blockRequest('muashield');
			}
		}
	}

	private function blockForwardHeader()
	{
		$headers = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_SUCURI_CLIENTIP'];

		foreach ($headers as $headerName)
		{
			if (!isset($_SERVER[$headerName]))
			{
				continue;
			}

			$header = trim($_SERVER[$headerName]);

			$patterns = [
				'@"feed_url@',
				'@}__(.*)|O:@',
				'@"J?Simple(p|P)ie(Factory)?"@',
			];

			foreach ($patterns as $pattern)
			{
				if (preg_match($pattern, $header))
				{
					$_SERVER[$headerName] = 'HACKING ATTEMPT DETECTED';

					$this->exceptionsHandler->blockRequest('muashield');
				}
			}
		}
	}
}
