<commit_before><?php

/**
* @package   s9e\WebServices
* @copyright Copyright (c) 2015-2016 The s9e Authors
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace s9e\WebServices\Minifier;

use Exception;
use s9e\TextFormatter\Configurator\JavaScript\Minifiers\FirstAvailable;

class Minifier
{
	/**
	* @var string Path to cache dir
	*/
	public $cacheDir = __DIR__ . '/../www/cache/';

	/**
	* @var integer Compression level at which minified code is stored/sent
	*/
	public $gzLevel = 9;

	/**
	* @var integer Max request payload
	*/
	public $maxPayload = 300000;

	/**
	* @var array
	*/
	public $minifiers = [
		'ClosureCompilerApplication' => [
			'closureCompilerBin' => __DIR__ . '/../bin/compiler.jar'
		],
		'ClosureCompilerService' => []
	];

	/**
	* @var string If set, the unminified code must contain this string
	*/
	public $mustContain;

	/**
	* Handle the current request
	*
	* @return void
	*/
	public function handleRequest()
	{
		// Capture the output in case anything goes wrong and display_errors is on
		ob_start();

		try
		{
			if (isset($_GET['hash']))
			{
				$this->processCacheRequest();
			}
			else
			{
				$this->processMinifierRequest();
			}
			throw new Exception('An unspecified error occured');
		}
		catch (Exception $e)
		{
			$this->sendResponse(500, $e->getMessage());
		}
	}

	/**
	* Return whether the request's client supports gzip
	*
	* @return bool
	*/
	protected function clientSupportsGzip()
	{
		return (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false);
	}

	/**
	* Process the current cache request
	*
	* @return void
	*/
	protected function processCacheRequest()
	{
		if (!preg_match('(^[-\\w]{48}$)D', $_GET['hash']))
		{
			$this->sendResponse(400, 'Bad cache ID');
		}

		$filepath = $this->cacheDir . $_GET['hash'] . '.gz';
		if (!file_exists($filepath))
		{
			$this->sendResponse(404, 'Not in cache');
		}

		$content = file_get_contents($filepath);
		if ($this->clientSupportsGzip())
		{
			header('Content-Encoding: gzip');
			header('Vary: Accept-Encoding');
		}
		else
		{
			$content = gzdecode($content);
		}

		$this->sendResponse(200, $content);
	}

	/**
	* Process the current minifier request
	*
	* @return void
	*/
	protected function processMinifierRequest()
	{
		// Prepare a 500 header in case anything goes wrong
		header('Content-Type: application/octet-stream', true, 500);

		$minifiedCode   = null;
		$compressedCode = null;

		$code = $this->getRequestBody();
		$hash = $this->getHash($code);

		$cacheFile = $this->cacheDir . $hash . '.gz';
		if (file_exists($cacheFile))
		{
			$compressedCode = file_get_contents($cacheFile);
		}
		else
		{
			ignore_user_abort(true);

			$minifiedCode   = $this->getMinifier()->minify($code);
			$compressedCode = gzencode($minifiedCode, $this->gzLevel);

			file_put_contents($cacheFile, $compressedCode);
		}

		if ($this->clientSupportsGzip())
		{<commit_msg>Send a Content-Type header with cache responses<commit_after><?php

/**
* @package   s9e\WebServices
* @copyright Copyright (c) 2015-2016 The s9e Authors
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace s9e\WebServices\Minifier;

use Exception;
use s9e\TextFormatter\Configurator\JavaScript\Minifiers\FirstAvailable;

class Minifier
{
	/**
	* @var string Path to cache dir
	*/
	public $cacheDir = __DIR__ . '/../www/cache/';

	/**
	* @var integer Compression level at which minified code is stored/sent
	*/
	public $gzLevel = 9;

	/**
	* @var integer Max request payload
	*/
	public $maxPayload = 300000;

	/**
	* @var array
	*/
	public $minifiers = [
		'ClosureCompilerApplication' => [
			'closureCompilerBin' => __DIR__ . '/../bin/compiler.jar'
		],
		'ClosureCompilerService' => []
	];

	/**
	* @var string If set, the unminified code must contain this string
	*/
	public $mustContain;

	/**
	* Handle the current request
	*
	* @return void
	*/
	public function handleRequest()
	{
		// Capture the output and prepare a 500 header in case anything goes wrong
		ob_start();
		header('Content-Type: application/octet-stream', true, 500);

		try
		{
			if (isset($_GET['hash']))
			{
				$this->processCacheRequest();
			}
			else
			{
				$this->processMinifierRequest();
			}
			throw new Exception('An unspecified error occured');
		}
		catch (Exception $e)
		{
			$this->sendResponse(500, $e->getMessage());
		}
	}

	/**
	* Return whether the request's client supports gzip
	*
	* @return bool
	*/
	protected function clientSupportsGzip()
	{
		return (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false);
	}

	/**
	* Process the current cache request
	*
	* @return void
	*/
	protected function processCacheRequest()
	{
		if (!preg_match('(^[-\\w]{48}$)D', $_GET['hash']))
		{
			$this->sendResponse(400, 'Bad cache ID');
		}

		$filepath = $this->cacheDir . $_GET['hash'] . '.gz';
		if (!file_exists($filepath))
		{
			$this->sendResponse(404, 'Not in cache');
		}

		$content = file_get_contents($filepath);
		if ($this->clientSupportsGzip())
		{
			header('Content-Encoding: gzip');
			header('Vary: Accept-Encoding');
		}
		else
		{
			$content = gzdecode($content);
		}

		$this->sendResponse(200, $content);
	}

	/**
	* Process the current minifier request
	*
	* @return void
	*/
	protected function processMinifierRequest()
	{
		$minifiedCode   = null;
		$compressedCode = null;

		$code = $this->getRequestBody();
		$hash = $this->getHash($code);

		$cacheFile = $this->cacheDir . $hash . '.gz';
		if (file_exists($cacheFile))
		{
			$compressedCode = file_get_contents($cacheFile);
		}
		else
		{
			ignore_user_abort(true);

			$minifiedCode   = $this->getMinifier()->minify($code);
			$compressedCode = gzencode($minifiedCode, $this->gzLevel);

			file_put_contents($cacheFile, $compressedCode);
		}

		if ($this->clientSupportsGzip())
		{
{'fraction_non_alphanumeric': 0.16043956043956045, 'fraction_numerical': 0.013186813186813187, 'mean_word_length': 3.650943396226415, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3169472', 'n_tokens_mistral': 2295, 'n_tokens_neox': 2018, 'n_words': 442}