Archived
1
0

Minify CSS and JS

This commit is contained in:
KingOfDog 2018-11-01 11:19:02 +01:00 committed by Marcel
parent c07b714a0d
commit f168cf6863

View File

@ -1,253 +1,256 @@
<?php <?php
$cache = true; $cache = true;
$cachedir = dirname(__FILE__) . '/assets/cache'; $cachedir = dirname(__FILE__) . '/assets/cache';
$cssdir = dirname(__FILE__) . '/assets/css'; $cssdir = dirname(__FILE__) . '/assets/css';
$jsdir = dirname(__FILE__) . '/assets/js'; $jsdir = dirname(__FILE__) . '/assets/js';
// Determine the directory and type we should use // Determine the directory and type we should use
switch ($_GET['type']) { switch ($_GET['type']) {
case 'css': case 'css':
$base = realpath($cssdir); $base = realpath($cssdir);
break; break;
case 'javascript': case 'javascript':
$base = realpath($jsdir); $base = realpath($jsdir);
break; break;
default: default:
header("HTTP/1.0 503 Not Implemented"); header("HTTP/1.0 503 Not Implemented");
exit; exit;
}; };
$type = $_GET['type']; $type = $_GET['type'];
$elements = explode(',', $_GET['files']); $elements = explode(',', $_GET['files']);
// Determine last modification date of the files // Determine last modification date of the files
$lastmodified = 0; $lastmodified = 0;
while (list(, $element) = each($elements)) {
$path = realpath($base . '/' . $element);
if (($type == 'javascript' && substr($path, -3) != '.js') ||
($type == 'css' && substr($path, -4) != '.css')) {
header("HTTP/1.0 403 Forbidden");
exit;
}
if (substr($path, 0, strlen($base)) != $base || !file_exists($path)) {
header("HTTP/1.0 404 Not Found");
exit;
}
$lastmodified = max($lastmodified, filemtime($path));
}
// Send Etag hash
$hash = $lastmodified . '-' . md5($_GET['files']);
header("Etag: \"" . $hash . "\"");
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) == '"' . $hash . '"') {
// Return visit and no modifications, so do not send anything
header("HTTP/1.0 304 Not Modified");
header('Content-Length: 0');
} else {
// First time visit or files were modified
if ($cache) {
// Determine supported compression method
$gzip = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
$deflate = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate');
// Determine used compression method
$encoding = $gzip ? 'gzip' : ($deflate ? 'deflate' : 'none');
// Check for buggy versions of Internet Explorer
if (!strstr($_SERVER['HTTP_USER_AGENT'], 'Opera') &&
preg_match('/^Mozilla\/4\.0 \(compatible; MSIE ([0-9]\.[0-9])/i', $_SERVER['HTTP_USER_AGENT'], $matches)) {
$version = floatval($matches[1]);
if ($version < 6)
$encoding = 'none';
if ($version == 6 && !strstr($_SERVER['HTTP_USER_AGENT'], 'EV1'))
$encoding = 'none';
}
// Try the cache first to see if the combined files were already generated
$cachefile = 'cache-' . $hash . '.' . $type . ($encoding != 'none' ? '.' . $encoding : '');
if (file_exists($cachedir . '/' . $cachefile)) {
if ($fp = fopen($cachedir . '/' . $cachefile, 'rb')) {
if ($encoding != 'none') {
header("Content-Encoding: " . $encoding);
}
header("Content-Type: text/" . $type);
header("Content-Length: " . filesize($cachedir . '/' . $cachefile));
fpassthru($fp);
fclose($fp);
exit;
}
}
}
// Get contents of the files
$contents = '';
reset($elements);
while (list(, $element) = each($elements)) { while (list(, $element) = each($elements)) {
$path = realpath($base . '/' . $element); $path = realpath($base . '/' . $element);
$contents .= "\n\n" . file_get_contents($path);
// $contents = fn_minify_css($contents); if (($type == 'javascript' && substr($path, -3) != '.js') ||
($type == 'css' && substr($path, -4) != '.css')) {
header("HTTP/1.0 403 Forbidden");
exit;
}
if (substr($path, 0, strlen($base)) != $base || !file_exists($path)) {
header("HTTP/1.0 404 Not Found");
exit;
}
$lastmodified = max($lastmodified, filemtime($path));
} }
// Send Content-Type // Send Etag hash
header("Content-Type: text/" . $type); $hash = $lastmodified . '-' . md5($_GET['files']);
header("Etag: \"" . $hash . "\"");
if (isset($encoding) && $encoding != 'none') { if (isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
// Send compressed contents stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) == '"' . $hash . '"') {
$contents = gzencode($contents, 9, $gzip ? FORCE_GZIP : FORCE_DEFLATE); // Return visit and no modifications, so do not send anything
header("Content-Encoding: " . $encoding); header("HTTP/1.0 304 Not Modified");
header('Content-Length: ' . strlen($contents)); header('Content-Length: 0');
echo $contents;
} else { } else {
// Send regular contents // First time visit or files were modified
header('Content-Length: ' . strlen($contents)); if ($cache) {
echo $contents; // Determine supported compression method
} $gzip = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
echo strlen($contents); $deflate = strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate');
// Store cache // Determine used compression method
if ($cache) { $encoding = $gzip ? 'gzip' : ($deflate ? 'deflate' : 'none');
if ($fp = fopen($cachedir . '/' . $cachefile, 'wb')) {
fwrite($fp, $contents);
fclose($fp);
}
}
}
define('MINIFY_STRING', '"(?:[^"\\\]|\\\.)*"|\'(?:[^\'\\\]|\\\.)*\''); // Check for buggy versions of Internet Explorer
define('MINIFY_COMMENT_CSS', '/\*[\s\S]*?\*/'); if (!strstr($_SERVER['HTTP_USER_AGENT'], 'Opera') &&
define('MINIFY_COMMENT_HTML', '<!\-{2}[\s\S]*?\-{2}>'); preg_match('/^Mozilla\/4\.0 \(compatible; MSIE ([0-9]\.[0-9])/i', $_SERVER['HTTP_USER_AGENT'], $matches)) {
define('X', "\x1A"); $version = floatval($matches[1]);
function n($s) if ($version < 6)
{ $encoding = 'none';
return str_replace(["\r\n", "\r"], "\n", $s);
}
function t($a, $b) if ($version == 6 && !strstr($_SERVER['HTTP_USER_AGENT'], 'EV1'))
{ $encoding = 'none';
if ($a && strpos($a, $b) === 0 && substr($a, -strlen($b)) === $b) {
return substr(substr($a, strlen($b)), 0, -strlen($b));
}
return $a;
}
function fn_minify($pattern, $input)
{
return preg_split('#(' . implode('|', $pattern) . ')#', $input, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
}
function fn_minify_css($input, $comment = 2, $quote = 2)
{
if (!is_string($input) || !$input = n(trim($input))) return $input;
$output = $prev = "";
foreach (fn_minify([MINIFY_COMMENT_CSS, MINIFY_STRING], $input) as $part) {
if (trim($part) === "") continue;
if ($comment !== 1 && strpos($part, '/*') === 0 && substr($part, -2) === '*/') {
if (
$comment === 2 && (
// Detect special comment(s) from the third character. It should be a `!` or `*` → `/*! keep */` or `/** keep */`
strpos('*!', $part[2]) !== false ||
// Detect license comment(s) from the content. It should contains character(s) like `@license`
stripos($part, '@licence') !== false || // noun
stripos($part, '@license') !== false || // verb
stripos($part, '@preserve') !== false
)
) {
$output .= $part;
} }
continue;
} // Try the cache first to see if the combined files were already generated
if ($part[0] === '"' && substr($part, -1) === '"' || $part[0] === "'" && substr($part, -1) === "'") { $cachefile = 'cache-' . $hash . '.' . $type . ($encoding != 'none' ? '.' . $encoding : '');
// Remove quote(s) where possible …
$q = $part[0]; if (file_exists($cachedir . '/' . $cachefile)) {
if ( if ($fp = fopen($cachedir . '/' . $cachefile, 'rb')) {
$quote !== 1 && (
// <https://www.w3.org/TR/CSS2/syndata.html#uri> if ($encoding != 'none') {
substr($prev, -4) === 'url(' && preg_match('#\burl\($#', $prev) || header("Content-Encoding: " . $encoding);
// <https://www.w3.org/TR/CSS2/syndata.html#characters> }
substr($prev, -1) === '=' && preg_match('#^' . $q . '[a-zA-Z_][\w-]*?' . $q . '$#', $part)
) header("Content-Type: text/" . $type);
) { header("Content-Length: " . filesize($cachedir . '/' . $cachefile));
$part = t($part, $q); // trim quote(s)
fpassthru($fp);
fclose($fp);
exit;
}
} }
$output .= $part; }
// Get contents of the files
$contents = '';
reset($elements);
while (list(, $element) = each($elements)) {
$path = realpath($base . '/' . $element);
$contents .= "\n\n" . file_get_contents($path);
$contents = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $contents);
$contents = str_replace(': ', ':', $contents);
$contents = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $contents);
// $contents = fn_minify_css($contents);
}
// Send Content-Type
header("Content-Type: text/" . $type);
if (isset($encoding) && $encoding != 'none') {
// Send compressed contents
$contents = gzencode($contents, 9, $gzip ? FORCE_GZIP : FORCE_DEFLATE);
header("Content-Encoding: " . $encoding);
header('Content-Length: ' . strlen($contents));
echo $contents;
} else { } else {
$output .= fn_minify_css_union($part); // Send regular contents
header('Content-Length: ' . strlen($contents));
echo $contents;
} }
$prev = $part; echo strlen($contents);
}
return trim($output);
}
function fn_minify_css_union($input) // Store cache
{ if ($cache) {
if (stripos($input, 'calc(') !== false) { if ($fp = fopen($cachedir . '/' . $cachefile, 'wb')) {
// Keep important whitespace(s) in `calc()` fwrite($fp, $contents);
$input = preg_replace_callback('#\b(calc\()\s*(.*?)\s*\)#i', function ($m) { fclose($fp);
return $m[1] . preg_replace('#\s+#', X, $m[2]) . ')'; }
}, $input); }
} }
$input = preg_replace([
// Fix case for `#foo<space>[bar="baz"]`, `#foo<space>*` and `#foo<space>:first-child` [^1] define('MINIFY_STRING', '"(?:[^"\\\]|\\\.)*"|\'(?:[^\'\\\]|\\\.)*\'');
'#(?<=[\w])\s+(\*|\[|:[\w-]+)#', define('MINIFY_COMMENT_CSS', '/\*[\s\S]*?\*/');
// Fix case for `[bar="baz"]<space>.foo`, `*<space>.foo`, `:nth-child(2)<space>.foo` and `@media<space>(foo: bar)<space>and<space>(baz: qux)` [^2] define('MINIFY_COMMENT_HTML', '<!\-{2}[\s\S]*?\-{2}>');
'#([*\]\)])\s+(?=[\w\#.])#', '#\b\s+\(#', '#\)\s+\b#', define('X', "\x1A");
// Minify HEX color code … [^3]
'#\#([a-f\d])\1([a-f\d])\2([a-f\d])\3\b#i', function n($s)
// Remove whitespace(s) around punctuation(s) [^4] {
'#\s*([~!@*\(\)+=\{\}\[\]:;,>\/])\s*#', return str_replace(["\r\n", "\r"], "\n", $s);
// Replace zero unit(s) with `0` [^5] }
'#\b(?<!\d\.)(?:0+\.)?0+(?:[a-z]+\b)#i',
// Replace `0.6` with `.6` [^6] function t($a, $b)
'#\b0+\.(\d+)#', {
// Replace `:0 0`, `:0 0 0` and `:0 0 0 0` with `:0` [^7] if ($a && strpos($a, $b) === 0 && substr($a, -strlen($b)) === $b) {
'#:(0\s+){0,3}0(?=[!,;\)\}]|$)#', return substr(substr($a, strlen($b)), 0, -strlen($b));
// Replace `background(?:-position)?:(0|none)` with `background$1:0 0` [^8] }
'#\b(background(?:-position)?):(?:0|none)([;,\}])#i', return $a;
// Replace `(border(?:-radius)?|outline):none` with `$1:0` [^9] }
'#\b(border(?:-radius)?|outline):none\b#i',
// Remove empty selector(s) [^10] function fn_minify($pattern, $input)
'#(^|[\{\}])(?:[^\{\}]+)\{\}#', {
// Remove the last semicolon and replace multiple semicolon(s) with a semicolon [^11] return preg_split('#(' . implode('|', $pattern) . ')#', $input, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
'#;+([;\}])#', }
// Replace multiple whitespace(s) with a space [^12]
'#\s+#' function fn_minify_css($input, $comment = 2, $quote = 2)
], [ {
// [^1] if (!is_string($input) || !$input = n(trim($input))) return $input;
X . '$1', $output = $prev = "";
// [^2] foreach (fn_minify([MINIFY_COMMENT_CSS, MINIFY_STRING], $input) as $part) {
'$1' . X, X . '(', ')' . X, if (trim($part) === "") continue;
// [^3] if ($comment !== 1 && strpos($part, '/*') === 0 && substr($part, -2) === '*/') {
'#$1$2$3', if (
// [^4] $comment === 2 && (
'$1', // Detect special comment(s) from the third character. It should be a `!` or `*` → `/*! keep */` or `/** keep */`
// [^5] strpos('*!', $part[2]) !== false ||
'0', // Detect license comment(s) from the content. It should contains character(s) like `@license`
// [^6] stripos($part, '@licence') !== false || // noun
'.$1', stripos($part, '@license') !== false || // verb
// [^7] stripos($part, '@preserve') !== false
':0', )
// [^8] ) {
'$1:0 0$2', $output .= $part;
// [^9] }
'$1:0', continue;
// [^10] }
'$1', if ($part[0] === '"' && substr($part, -1) === '"' || $part[0] === "'" && substr($part, -1) === "'") {
// [^11] // Remove quote(s) where possible …
'$1', $q = $part[0];
// [^12] if (
' ' $quote !== 1 && (
], $input); // <https://www.w3.org/TR/CSS2/syndata.html#uri>
return trim(str_replace(X, ' ', $input)); substr($prev, -4) === 'url(' && preg_match('#\burl\($#', $prev) ||
} // <https://www.w3.org/TR/CSS2/syndata.html#characters>
substr($prev, -1) === '=' && preg_match('#^' . $q . '[a-zA-Z_][\w-]*?' . $q . '$#', $part)
)
) {
$part = t($part, $q); // trim quote(s)
}
$output .= $part;
} else {
$output .= fn_minify_css_union($part);
}
$prev = $part;
}
return trim($output);
}
function fn_minify_css_union($input)
{
if (stripos($input, 'calc(') !== false) {
// Keep important whitespace(s) in `calc()`
$input = preg_replace_callback('#\b(calc\()\s*(.*?)\s*\)#i', function ($m) {
return $m[1] . preg_replace('#\s+#', X, $m[2]) . ')';
}, $input);
}
$input = preg_replace([
// Fix case for `#foo<space>[bar="baz"]`, `#foo<space>*` and `#foo<space>:first-child` [^1]
'#(?<=[\w])\s+(\*|\[|:[\w-]+)#',
// Fix case for `[bar="baz"]<space>.foo`, `*<space>.foo`, `:nth-child(2)<space>.foo` and `@media<space>(foo: bar)<space>and<space>(baz: qux)` [^2]
'#([*\]\)])\s+(?=[\w\#.])#', '#\b\s+\(#', '#\)\s+\b#',
// Minify HEX color code … [^3]
'#\#([a-f\d])\1([a-f\d])\2([a-f\d])\3\b#i',
// Remove whitespace(s) around punctuation(s) [^4]
'#\s*([~!@*\(\)+=\{\}\[\]:;,>\/])\s*#',
// Replace zero unit(s) with `0` [^5]
'#\b(?<!\d\.)(?:0+\.)?0+(?:[a-z]+\b)#i',
// Replace `0.6` with `.6` [^6]
'#\b0+\.(\d+)#',
// Replace `:0 0`, `:0 0 0` and `:0 0 0 0` with `:0` [^7]
'#:(0\s+){0,3}0(?=[!,;\)\}]|$)#',
// Replace `background(?:-position)?:(0|none)` with `background$1:0 0` [^8]
'#\b(background(?:-position)?):(?:0|none)([;,\}])#i',
// Replace `(border(?:-radius)?|outline):none` with `$1:0` [^9]
'#\b(border(?:-radius)?|outline):none\b#i',
// Remove empty selector(s) [^10]
'#(^|[\{\}])(?:[^\{\}]+)\{\}#',
// Remove the last semicolon and replace multiple semicolon(s) with a semicolon [^11]
'#;+([;\}])#',
// Replace multiple whitespace(s) with a space [^12]
'#\s+#'
], [
// [^1]
X . '$1',
// [^2]
'$1' . X, X . '(', ')' . X,
// [^3]
'#$1$2$3',
// [^4]
'$1',
// [^5]
'0',
// [^6]
'.$1',
// [^7]
':0',
// [^8]
'$1:0 0$2',
// [^9]
'$1:0',
// [^10]
'$1',
// [^11]
'$1',
// [^12]
' '
], $input);
return trim(str_replace(X, ' ', $input));
}