Initial commit: Atomaste website
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
Copyright (c) 2012 Matthias Mullie
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,841 @@
|
||||
<?php
|
||||
// phpcs:ignoreFile
|
||||
/**
|
||||
* css.cls.php - modified PHP implementation of Matthias Mullie's CSS minifier
|
||||
*
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
namespace LiteSpeed\Lib\CSS_JS_MIN\Minify;
|
||||
|
||||
use LiteSpeed\Lib\CSS_JS_MIN\Minify\Minify;
|
||||
use LiteSpeed\Lib\CSS_JS_MIN\Minify\Exception\FileImportException;
|
||||
use LiteSpeed\Lib\CSS_JS_MIN\PathConverter\Converter;
|
||||
use LiteSpeed\Lib\CSS_JS_MIN\PathConverter\ConverterInterface;
|
||||
|
||||
defined( 'WPINC' ) || exit;
|
||||
|
||||
class CSS extends Minify {
|
||||
|
||||
/**
|
||||
* @var int maximum import size in kB
|
||||
*/
|
||||
protected $maxImportSize = 5;
|
||||
|
||||
/**
|
||||
* @var string[] valid import extensions
|
||||
*/
|
||||
protected $importExtensions = array(
|
||||
'gif' => 'data:image/gif',
|
||||
'png' => 'data:image/png',
|
||||
'jpe' => 'data:image/jpeg',
|
||||
'jpg' => 'data:image/jpeg',
|
||||
'jpeg' => 'data:image/jpeg',
|
||||
'svg' => 'data:image/svg+xml',
|
||||
'woff' => 'data:application/x-font-woff',
|
||||
'woff2' => 'data:application/x-font-woff2',
|
||||
'avif' => 'data:image/avif',
|
||||
'apng' => 'data:image/apng',
|
||||
'webp' => 'data:image/webp',
|
||||
'tif' => 'image/tiff',
|
||||
'tiff' => 'image/tiff',
|
||||
'xbm' => 'image/x-xbitmap',
|
||||
);
|
||||
|
||||
/**
|
||||
* Set the maximum size if files to be imported.
|
||||
*
|
||||
* Files larger than this size (in kB) will not be imported into the CSS.
|
||||
* Importing files into the CSS as data-uri will save you some connections,
|
||||
* but we should only import relatively small decorative images so that our
|
||||
* CSS file doesn't get too bulky.
|
||||
*
|
||||
* @param int $size Size in kB
|
||||
*/
|
||||
public function setMaxImportSize( $size ) {
|
||||
$this->maxImportSize = $size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the type of extensions to be imported into the CSS (to save network
|
||||
* connections).
|
||||
* Keys of the array should be the file extensions & respective values
|
||||
* should be the data type.
|
||||
*
|
||||
* @param string[] $extensions Array of file extensions
|
||||
*/
|
||||
public function setImportExtensions( array $extensions ) {
|
||||
$this->importExtensions = $extensions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move any import statements to the top.
|
||||
*
|
||||
* @param string $content Nearly finished CSS content
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function moveImportsToTop( $content ) {
|
||||
if ( preg_match_all( '/(;?)(@import (?<url>url\()?(?P<quotes>["\']?).+?(?P=quotes)(?(url)\)));?/', $content, $matches ) ) {
|
||||
// remove from content
|
||||
foreach ( $matches[0] as $import ) {
|
||||
$content = str_replace( $import, '', $content );
|
||||
}
|
||||
|
||||
// add to top
|
||||
$content = implode( ';', $matches[2] ) . ';' . trim( $content, ';' );
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine CSS from import statements.
|
||||
*
|
||||
* \@import's will be loaded and their content merged into the original file,
|
||||
* to save HTTP requests.
|
||||
*
|
||||
* @param string $source The file to combine imports for
|
||||
* @param string $content The CSS content to combine imports for
|
||||
* @param string[] $parents Parent paths, for circular reference checks
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws FileImportException
|
||||
*/
|
||||
protected function combineImports( $source, $content, $parents ) {
|
||||
$importRegexes = array(
|
||||
// @import url(xxx)
|
||||
'/
|
||||
# import statement
|
||||
@import
|
||||
|
||||
# whitespace
|
||||
\s+
|
||||
|
||||
# open url()
|
||||
url\(
|
||||
|
||||
# (optional) open path enclosure
|
||||
(?P<quotes>["\']?)
|
||||
|
||||
# fetch path
|
||||
(?P<path>.+?)
|
||||
|
||||
# (optional) close path enclosure
|
||||
(?P=quotes)
|
||||
|
||||
# close url()
|
||||
\)
|
||||
|
||||
# (optional) trailing whitespace
|
||||
\s*
|
||||
|
||||
# (optional) media statement(s)
|
||||
(?P<media>[^;]*)
|
||||
|
||||
# (optional) trailing whitespace
|
||||
\s*
|
||||
|
||||
# (optional) closing semi-colon
|
||||
;?
|
||||
|
||||
/ix',
|
||||
|
||||
// @import 'xxx'
|
||||
'/
|
||||
|
||||
# import statement
|
||||
@import
|
||||
|
||||
# whitespace
|
||||
\s+
|
||||
|
||||
# open path enclosure
|
||||
(?P<quotes>["\'])
|
||||
|
||||
# fetch path
|
||||
(?P<path>.+?)
|
||||
|
||||
# close path enclosure
|
||||
(?P=quotes)
|
||||
|
||||
# (optional) trailing whitespace
|
||||
\s*
|
||||
|
||||
# (optional) media statement(s)
|
||||
(?P<media>[^;]*)
|
||||
|
||||
# (optional) trailing whitespace
|
||||
\s*
|
||||
|
||||
# (optional) closing semi-colon
|
||||
;?
|
||||
|
||||
/ix',
|
||||
);
|
||||
|
||||
// find all relative imports in css
|
||||
$matches = array();
|
||||
foreach ( $importRegexes as $importRegex ) {
|
||||
if ( preg_match_all( $importRegex, $content, $regexMatches, PREG_SET_ORDER ) ) {
|
||||
$matches = array_merge( $matches, $regexMatches );
|
||||
}
|
||||
}
|
||||
|
||||
$search = array();
|
||||
$replace = array();
|
||||
|
||||
// loop the matches
|
||||
foreach ( $matches as $match ) {
|
||||
// get the path for the file that will be imported
|
||||
$importPath = dirname( $source ) . '/' . $match['path'];
|
||||
|
||||
// only replace the import with the content if we can grab the
|
||||
// content of the file
|
||||
if ( ! $this->canImportByPath( $match['path'] ) || ! $this->canImportFile( $importPath ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// check if current file was not imported previously in the same
|
||||
// import chain.
|
||||
if ( in_array( $importPath, $parents ) ) {
|
||||
throw new FileImportException( 'Failed to import file "' . $importPath . '": circular reference detected.' );
|
||||
}
|
||||
|
||||
// grab referenced file & minify it (which may include importing
|
||||
// yet other @import statements recursively)
|
||||
$minifier = new self( $importPath );
|
||||
$minifier->setMaxImportSize( $this->maxImportSize );
|
||||
$minifier->setImportExtensions( $this->importExtensions );
|
||||
$importContent = $minifier->execute( $source, $parents );
|
||||
|
||||
// check if this is only valid for certain media
|
||||
if ( ! empty( $match['media'] ) ) {
|
||||
$importContent = '@media ' . $match['media'] . '{' . $importContent . '}';
|
||||
}
|
||||
|
||||
// add to replacement array
|
||||
$search[] = $match[0];
|
||||
$replace[] = $importContent;
|
||||
}
|
||||
|
||||
// replace the import statements
|
||||
return str_replace( $search, $replace, $content );
|
||||
}
|
||||
|
||||
/**
|
||||
* Import files into the CSS, base64 encoded.
|
||||
*
|
||||
* Included images @url(image.jpg) will be loaded and their content merged into the
|
||||
* original file, to save HTTP requests.
|
||||
*
|
||||
* @param string $source The file to import files for
|
||||
* @param string $content The CSS content to import files for
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function importFiles( $source, $content ) {
|
||||
$regex = '/url\((["\']?)(.+?)\\1\)/i';
|
||||
if ( $this->importExtensions && preg_match_all( $regex, $content, $matches, PREG_SET_ORDER ) ) {
|
||||
$search = array();
|
||||
$replace = array();
|
||||
|
||||
// loop the matches
|
||||
foreach ( $matches as $match ) {
|
||||
$extension = substr( strrchr( $match[2], '.' ), 1 );
|
||||
if ( $extension && ! array_key_exists( $extension, $this->importExtensions ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// get the path for the file that will be imported
|
||||
$path = $match[2];
|
||||
$path = dirname( $source ) . '/' . $path;
|
||||
|
||||
// only replace the import with the content if we're able to get
|
||||
// the content of the file, and it's relatively small
|
||||
if ( $this->canImportFile( $path ) && $this->canImportBySize( $path ) ) {
|
||||
// grab content && base64-ize
|
||||
$importContent = $this->load( $path );
|
||||
$importContent = base64_encode( $importContent );
|
||||
|
||||
// build replacement
|
||||
$search[] = $match[0];
|
||||
$replace[] = 'url(' . $this->importExtensions[ $extension ] . ';base64,' . $importContent . ')';
|
||||
}
|
||||
}
|
||||
|
||||
// replace the import statements
|
||||
$content = str_replace( $search, $replace, $content );
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minify the data.
|
||||
* Perform CSS optimizations.
|
||||
*
|
||||
* @param string[optional] $path Path to write the data to
|
||||
* @param string[] $parents Parent paths, for circular reference checks
|
||||
*
|
||||
* @return string The minified data
|
||||
*/
|
||||
public function execute( $path = null, $parents = array() ) {
|
||||
$content = '';
|
||||
|
||||
// loop CSS data (raw data and files)
|
||||
foreach ( $this->data as $source => $css ) {
|
||||
/*
|
||||
* Let's first take out strings & comments, since we can't just
|
||||
* remove whitespace anywhere. If whitespace occurs inside a string,
|
||||
* we should leave it alone. E.g.:
|
||||
* p { content: "a test" }
|
||||
*/
|
||||
$this->extractStrings();
|
||||
$this->stripComments();
|
||||
$this->extractMath();
|
||||
$this->extractCustomProperties();
|
||||
$css = $this->replace( $css );
|
||||
|
||||
$css = $this->stripWhitespace( $css );
|
||||
$css = $this->convertLegacyColors( $css );
|
||||
$css = $this->cleanupModernColors( $css );
|
||||
$css = $this->shortenHEXColors( $css );
|
||||
$css = $this->shortenZeroes( $css );
|
||||
$css = $this->shortenFontWeights( $css );
|
||||
$css = $this->stripEmptyTags( $css );
|
||||
|
||||
// restore the string we've extracted earlier
|
||||
$css = $this->restoreExtractedData( $css );
|
||||
|
||||
$source = is_int( $source ) ? '' : $source;
|
||||
$parents = $source ? array_merge( $parents, array( $source ) ) : $parents;
|
||||
$css = $this->combineImports( $source, $css, $parents );
|
||||
$css = $this->importFiles( $source, $css );
|
||||
|
||||
/*
|
||||
* If we'll save to a new path, we'll have to fix the relative paths
|
||||
* to be relative no longer to the source file, but to the new path.
|
||||
* If we don't write to a file, fall back to same path so no
|
||||
* conversion happens (because we still want it to go through most
|
||||
* of the move code, which also addresses url() & @import syntax...)
|
||||
*/
|
||||
$converter = $this->getPathConverter( $source, $path ?: $source );
|
||||
$css = $this->move( $converter, $css );
|
||||
|
||||
// combine css
|
||||
$content .= $css;
|
||||
}
|
||||
|
||||
$content = $this->moveImportsToTop( $content );
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moving a css file should update all relative urls.
|
||||
* Relative references (e.g. ../images/image.gif) in a certain css file,
|
||||
* will have to be updated when a file is being saved at another location
|
||||
* (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
|
||||
*
|
||||
* @param ConverterInterface $converter Relative path converter
|
||||
* @param string $content The CSS content to update relative urls for
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function move( ConverterInterface $converter, $content ) {
|
||||
/*
|
||||
* Relative path references will usually be enclosed by url(). @import
|
||||
* is an exception, where url() is not necessary around the path (but is
|
||||
* allowed).
|
||||
* This *could* be 1 regular expression, where both regular expressions
|
||||
* in this array are on different sides of a |. But we're using named
|
||||
* patterns in both regexes, the same name on both regexes. This is only
|
||||
* possible with a (?J) modifier, but that only works after a fairly
|
||||
* recent PCRE version. That's why I'm doing 2 separate regular
|
||||
* expressions & combining the matches after executing of both.
|
||||
*/
|
||||
$relativeRegexes = array(
|
||||
// url(xxx)
|
||||
'/
|
||||
# open url()
|
||||
url\(
|
||||
|
||||
\s*
|
||||
|
||||
# open path enclosure
|
||||
(?P<quotes>["\'])?
|
||||
|
||||
# fetch path
|
||||
(?P<path>.+?)
|
||||
|
||||
# close path enclosure
|
||||
(?(quotes)(?P=quotes))
|
||||
|
||||
\s*
|
||||
|
||||
# close url()
|
||||
\)
|
||||
|
||||
/ix',
|
||||
|
||||
// @import "xxx"
|
||||
'/
|
||||
# import statement
|
||||
@import
|
||||
|
||||
# whitespace
|
||||
\s+
|
||||
|
||||
# we don\'t have to check for @import url(), because the
|
||||
# condition above will already catch these
|
||||
|
||||
# open path enclosure
|
||||
(?P<quotes>["\'])
|
||||
|
||||
# fetch path
|
||||
(?P<path>.+?)
|
||||
|
||||
# close path enclosure
|
||||
(?P=quotes)
|
||||
|
||||
/ix',
|
||||
);
|
||||
|
||||
// find all relative urls in css
|
||||
$matches = array();
|
||||
foreach ( $relativeRegexes as $relativeRegex ) {
|
||||
if ( preg_match_all( $relativeRegex, $content, $regexMatches, PREG_SET_ORDER ) ) {
|
||||
$matches = array_merge( $matches, $regexMatches );
|
||||
}
|
||||
}
|
||||
|
||||
$search = array();
|
||||
$replace = array();
|
||||
|
||||
// loop all urls
|
||||
foreach ( $matches as $match ) {
|
||||
// determine if it's a url() or an @import match
|
||||
$type = ( strpos( $match[0], '@import' ) === 0 ? 'import' : 'url' );
|
||||
|
||||
$url = $match['path'];
|
||||
if ( $this->canImportByPath( $url ) ) {
|
||||
// attempting to interpret GET-params makes no sense, so let's discard them for awhile
|
||||
$params = strrchr( $url, '?' );
|
||||
$url = $params ? substr( $url, 0, -strlen( $params ) ) : $url;
|
||||
|
||||
// fix relative url
|
||||
$url = $converter->convert( $url );
|
||||
|
||||
// now that the path has been converted, re-apply GET-params
|
||||
$url .= $params;
|
||||
}
|
||||
|
||||
/*
|
||||
* Urls with control characters above 0x7e should be quoted.
|
||||
* According to Mozilla's parser, whitespace is only allowed at the
|
||||
* end of unquoted urls.
|
||||
* Urls with `)` (as could happen with data: uris) should also be
|
||||
* quoted to avoid being confused for the url() closing parentheses.
|
||||
* And urls with a # have also been reported to cause issues.
|
||||
* Urls with quotes inside should also remain escaped.
|
||||
*
|
||||
* @see https://developer.mozilla.org/nl/docs/Web/CSS/url#The_url()_functional_notation
|
||||
* @see https://hg.mozilla.org/mozilla-central/rev/14abca4e7378
|
||||
* @see https://github.com/matthiasmullie/minify/issues/193
|
||||
*/
|
||||
$url = trim( $url );
|
||||
if ( preg_match( '/[\s\)\'"#\x{7f}-\x{9f}]/u', $url ) ) {
|
||||
$url = $match['quotes'] . $url . $match['quotes'];
|
||||
}
|
||||
|
||||
// build replacement
|
||||
$search[] = $match[0];
|
||||
if ( $type === 'url' ) {
|
||||
$replace[] = 'url(' . $url . ')';
|
||||
} elseif ( $type === 'import' ) {
|
||||
$replace[] = '@import "' . $url . '"';
|
||||
}
|
||||
}
|
||||
|
||||
// replace urls
|
||||
return str_replace( $search, $replace, $content );
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand HEX color codes.
|
||||
* #FF0000FF -> #f00 -> red
|
||||
* #FF00FF00 -> transparent.
|
||||
*
|
||||
* @param string $content The CSS content to shorten the HEX color codes for
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function shortenHexColors( $content ) {
|
||||
// shorten repeating patterns within HEX ..
|
||||
$content = preg_replace( '/(?<=[: ])#([0-9a-f])\\1([0-9a-f])\\2([0-9a-f])\\3(?:([0-9a-f])\\4)?(?=[; }])/i', '#$1$2$3$4', $content );
|
||||
|
||||
// remove alpha channel if it's pointless ..
|
||||
$content = preg_replace( '/(?<=[: ])#([0-9a-f]{6})ff(?=[; }])/i', '#$1', $content );
|
||||
$content = preg_replace( '/(?<=[: ])#([0-9a-f]{3})f(?=[; }])/i', '#$1', $content );
|
||||
|
||||
// replace `transparent` with shortcut ..
|
||||
$content = preg_replace( '/(?<=[: ])#[0-9a-f]{6}00(?=[; }])/i', '#fff0', $content );
|
||||
|
||||
$colors = array(
|
||||
// make these more readable
|
||||
'#00f' => 'blue',
|
||||
'#dc143c' => 'crimson',
|
||||
'#0ff' => 'cyan',
|
||||
'#8b0000' => 'darkred',
|
||||
'#696969' => 'dimgray',
|
||||
'#ff69b4' => 'hotpink',
|
||||
'#0f0' => 'lime',
|
||||
'#fdf5e6' => 'oldlace',
|
||||
'#87ceeb' => 'skyblue',
|
||||
'#d8bfd8' => 'thistle',
|
||||
// we can shorten some even more by replacing them with their color name
|
||||
'#f0ffff' => 'azure',
|
||||
'#f5f5dc' => 'beige',
|
||||
'#ffe4c4' => 'bisque',
|
||||
'#a52a2a' => 'brown',
|
||||
'#ff7f50' => 'coral',
|
||||
'#ffd700' => 'gold',
|
||||
'#808080' => 'gray',
|
||||
'#008000' => 'green',
|
||||
'#4b0082' => 'indigo',
|
||||
'#fffff0' => 'ivory',
|
||||
'#f0e68c' => 'khaki',
|
||||
'#faf0e6' => 'linen',
|
||||
'#800000' => 'maroon',
|
||||
'#000080' => 'navy',
|
||||
'#808000' => 'olive',
|
||||
'#ffa500' => 'orange',
|
||||
'#da70d6' => 'orchid',
|
||||
'#cd853f' => 'peru',
|
||||
'#ffc0cb' => 'pink',
|
||||
'#dda0dd' => 'plum',
|
||||
'#800080' => 'purple',
|
||||
'#f00' => 'red',
|
||||
'#fa8072' => 'salmon',
|
||||
'#a0522d' => 'sienna',
|
||||
'#c0c0c0' => 'silver',
|
||||
'#fffafa' => 'snow',
|
||||
'#d2b48c' => 'tan',
|
||||
'#008080' => 'teal',
|
||||
'#ff6347' => 'tomato',
|
||||
'#ee82ee' => 'violet',
|
||||
'#f5deb3' => 'wheat',
|
||||
// or the other way around
|
||||
'black' => '#000',
|
||||
'fuchsia' => '#f0f',
|
||||
'magenta' => '#f0f',
|
||||
'white' => '#fff',
|
||||
'yellow' => '#ff0',
|
||||
// and also `transparent`
|
||||
'transparent' => '#fff0',
|
||||
);
|
||||
|
||||
return preg_replace_callback(
|
||||
'/(?<=[: ])(' . implode( '|', array_keys( $colors ) ) . ')(?=[; }])/i',
|
||||
function ( $match ) use ( $colors ) {
|
||||
return $colors[ strtolower( $match[0] ) ];
|
||||
},
|
||||
$content
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert RGB|HSL color codes.
|
||||
* rgb(255,0,0,.5) -> rgb(255 0 0 / .5).
|
||||
* rgb(255,0,0) -> #f00.
|
||||
*
|
||||
* @param string $content The CSS content to shorten the RGB color codes for
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function convertLegacyColors( $content ) {
|
||||
/*
|
||||
https://drafts.csswg.org/css-color/#color-syntax-legacy
|
||||
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/rgb
|
||||
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/hsl
|
||||
*/
|
||||
|
||||
// convert legacy color syntax
|
||||
$content = preg_replace( '/(rgb)a?\(\s*([0-9]{1,3}%?)\s*,\s*([0-9]{1,3}%?)\s*,\s*([0-9]{1,3}%?)\s*,\s*([0,1]?(?:\.[0-9]*)?)\s*\)/i', '$1($2 $3 $4 / $5)', $content );
|
||||
$content = preg_replace( '/(rgb)a?\(\s*([0-9]{1,3}%?)\s*,\s*([0-9]{1,3}%?)\s*,\s*([0-9]{1,3}%?)\s*\)/i', '$1($2 $3 $4)', $content );
|
||||
$content = preg_replace( '/(hsl)a?\(\s*([0-9]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9]{1,3}%)\s*,\s*([0-9]{1,3}%)\s*,\s*([0,1]?(?:\.[0-9]*)?)\s*\)/i', '$1($2 $3 $4 / $5)', $content );
|
||||
$content = preg_replace( '/(hsl)a?\(\s*([0-9]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9]{1,3}%)\s*,\s*([0-9]{1,3}%)\s*\)/i', '$1($2 $3 $4)', $content );
|
||||
|
||||
// convert `rgb` to `hex`
|
||||
$dec = '([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])';
|
||||
return preg_replace_callback(
|
||||
"/rgb\($dec $dec $dec\)/i",
|
||||
function ( $match ) {
|
||||
return sprintf( '#%02x%02x%02x', $match[1], $match[2], $match[3] );
|
||||
},
|
||||
$content
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup RGB|HSL|HWB|LCH|LAB
|
||||
* rgb(255 0 0 / 1) -> rgb(255 0 0).
|
||||
* rgb(255 0 0 / 0) -> transparent.
|
||||
*
|
||||
* @param string $content The CSS content to cleanup HSL|HWB|LCH|LAB
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function cleanupModernColors( $content ) {
|
||||
/*
|
||||
https://drafts.csswg.org/css-color/#color-syntax-modern
|
||||
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/hwb
|
||||
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/lch
|
||||
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/lab
|
||||
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklch
|
||||
https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklab
|
||||
*/
|
||||
$tag = '(rgb|hsl|hwb|(?:(?:ok)?(?:lch|lab)))';
|
||||
|
||||
// remove alpha channel if it's pointless ..
|
||||
$content = preg_replace( '/' . $tag . '\(\s*([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+\/\s+1(?:(?:\.\d?)*|00%)?\s*\)/i', '$1($2 $3 $4)', $content );
|
||||
|
||||
// replace `transparent` with shortcut ..
|
||||
$content = preg_replace( '/' . $tag . '\(\s*[^\s]+\s+[^\s]+\s+[^\s]+\s+\/\s+0(?:[\.0%]*)?\s*\)/i', '#fff0', $content );
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorten CSS font weights.
|
||||
*
|
||||
* @param string $content The CSS content to shorten the font weights for
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function shortenFontWeights( $content ) {
|
||||
$weights = array(
|
||||
'normal' => 400,
|
||||
'bold' => 700,
|
||||
);
|
||||
|
||||
$callback = function ( $match ) use ( $weights ) {
|
||||
return $match[1] . $weights[ $match[2] ];
|
||||
};
|
||||
|
||||
return preg_replace_callback( '/(font-weight\s*:\s*)(' . implode( '|', array_keys( $weights ) ) . ')(?=[;}])/', $callback, $content );
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand 0 values to plain 0, instead of e.g. -0em.
|
||||
*
|
||||
* @param string $content The CSS content to shorten the zero values for
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function shortenZeroes( $content ) {
|
||||
// we don't want to strip units in `calc()` expressions:
|
||||
// `5px - 0px` is valid, but `5px - 0` is not
|
||||
// `10px * 0` is valid (equates to 0), and so is `10 * 0px`, but
|
||||
// `10 * 0` is invalid
|
||||
// we've extracted calcs earlier, so we don't need to worry about this
|
||||
|
||||
// reusable bits of code throughout these regexes:
|
||||
// before & after are used to make sure we don't match lose unintended
|
||||
// 0-like values (e.g. in #000, or in http://url/1.0)
|
||||
// units can be stripped from 0 values, or used to recognize non 0
|
||||
// values (where wa may be able to strip a .0 suffix)
|
||||
$before = '(?<=[:(, ])';
|
||||
$after = '(?=[ ,);}])';
|
||||
$units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
|
||||
|
||||
// strip units after zeroes (0px -> 0)
|
||||
// NOTE: it should be safe to remove all units for a 0 value, but in
|
||||
// practice, Webkit (especially Safari) seems to stumble over at least
|
||||
// 0%, potentially other units as well. Only stripping 'px' for now.
|
||||
// @see https://github.com/matthiasmullie/minify/issues/60
|
||||
$content = preg_replace( '/' . $before . '(-?0*(\.0+)?)(?<=0)px' . $after . '/', '\\1', $content );
|
||||
|
||||
// strip 0-digits (.0 -> 0)
|
||||
$content = preg_replace( '/' . $before . '\.0+' . $units . '?' . $after . '/', '0\\1', $content );
|
||||
// strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
|
||||
$content = preg_replace( '/' . $before . '(-?[0-9]+\.[0-9]+)0+' . $units . '?' . $after . '/', '\\1\\2', $content );
|
||||
// strip trailing 0: 50.00 -> 50, 50.00px -> 50px
|
||||
$content = preg_replace( '/' . $before . '(-?[0-9]+)\.0+' . $units . '?' . $after . '/', '\\1\\2', $content );
|
||||
// strip leading 0: 0.1 -> .1, 01.1 -> 1.1
|
||||
$content = preg_replace( '/' . $before . '(-?)0+([0-9]*\.[0-9]+)' . $units . '?' . $after . '/', '\\1\\2\\3', $content );
|
||||
|
||||
// strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
|
||||
$content = preg_replace( '/' . $before . '-?0+' . $units . '?' . $after . '/', '0\\1', $content );
|
||||
|
||||
// IE doesn't seem to understand a unitless flex-basis value (correct -
|
||||
// it goes against the spec), so let's add it in again (make it `%`,
|
||||
// which is only 1 char: 0%, 0px, 0 anything, it's all just the same)
|
||||
// @see https://developer.mozilla.org/nl/docs/Web/CSS/flex
|
||||
$content = preg_replace( '/flex:([0-9]+\s[0-9]+\s)0([;\}])/', 'flex:${1}0%${2}', $content );
|
||||
$content = preg_replace( '/flex-basis:0([;\}])/', 'flex-basis:0%${1}', $content );
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip empty tags from source code.
|
||||
*
|
||||
* @param string $content
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function stripEmptyTags( $content ) {
|
||||
$content = preg_replace( '/(?<=^)[^\{\};]+\{\s*\}/', '', $content );
|
||||
$content = preg_replace( '/(?<=(\}|;))[^\{\};]+\{\s*\}/', '', $content );
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip comments from source code.
|
||||
*/
|
||||
protected function stripComments() {
|
||||
$this->stripMultilineComments();
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip whitespace.
|
||||
*
|
||||
* @param string $content The CSS content to strip the whitespace for
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function stripWhitespace( $content ) {
|
||||
// remove leading & trailing whitespace
|
||||
$content = preg_replace( '/^\s*/m', '', $content );
|
||||
$content = preg_replace( '/\s*$/m', '', $content );
|
||||
|
||||
// replace newlines with a single space
|
||||
$content = preg_replace( '/\s+/', ' ', $content );
|
||||
|
||||
// remove whitespace around meta characters
|
||||
// inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
|
||||
$content = preg_replace( '/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content );
|
||||
$content = preg_replace( '/([\[(:>\+])\s+/', '$1', $content );
|
||||
$content = preg_replace( '/\s+([\]\)>\+])/', '$1', $content );
|
||||
$content = preg_replace( '/\s+(:)(?![^\}]*\{)/', '$1', $content );
|
||||
|
||||
// whitespace around + and - can only be stripped inside some pseudo-
|
||||
// classes, like `:nth-child(3+2n)`
|
||||
// not in things like `calc(3px + 2px)`, shorthands like `3px -2px`, or
|
||||
// selectors like `div.weird- p`
|
||||
$pseudos = array( 'nth-child', 'nth-last-child', 'nth-last-of-type', 'nth-of-type' );
|
||||
$content = preg_replace( '/:(' . implode( '|', $pseudos ) . ')\(\s*([+-]?)\s*(.+?)\s*([+-]?)\s*(.*?)\s*\)/', ':$1($2$3$4$5)', $content );
|
||||
|
||||
// remove semicolon/whitespace followed by closing bracket
|
||||
$content = str_replace( ';}', '}', $content );
|
||||
|
||||
return trim( $content );
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace all occurrences of functions that may contain math, where
|
||||
* whitespace around operators needs to be preserved (e.g. calc, clamp).
|
||||
*/
|
||||
protected function extractMath() {
|
||||
$functions = array( 'calc', 'clamp', 'min', 'max' );
|
||||
$pattern = '/\b(' . implode( '|', $functions ) . ')(\(.+?)(?=$|;|})/m';
|
||||
|
||||
// PHP only supports $this inside anonymous functions since 5.4
|
||||
$minifier = $this;
|
||||
$callback = function ( $match ) use ( $minifier, $pattern, &$callback ) {
|
||||
$function = $match[1];
|
||||
$length = strlen( $match[2] );
|
||||
$expr = '';
|
||||
$opened = 0;
|
||||
|
||||
// the regular expression for extracting math has 1 significant problem:
|
||||
// it can't determine the correct closing parenthesis...
|
||||
// instead, it'll match a larger portion of code to where it's certain that
|
||||
// the calc() musts have ended, and we'll figure out which is the correct
|
||||
// closing parenthesis here, by counting how many have opened
|
||||
for ( $i = 0; $i < $length; ++$i ) {
|
||||
$char = $match[2][ $i ];
|
||||
$expr .= $char;
|
||||
if ( $char === '(' ) {
|
||||
++$opened;
|
||||
} elseif ( $char === ')' && --$opened === 0 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// now that we've figured out where the calc() starts and ends, extract it
|
||||
$count = count( $minifier->extracted );
|
||||
$placeholder = 'math(' . $count . ')';
|
||||
$minifier->extracted[ $placeholder ] = $function . '(' . trim( substr( $expr, 1, -1 ) ) . ')';
|
||||
|
||||
// and since we've captured more code than required, we may have some leftover
|
||||
// calc() in here too - go recursive on the remaining but of code to go figure
|
||||
// that out and extract what is needed
|
||||
$rest = $minifier->str_replace_first( $function . $expr, '', $match[0] );
|
||||
$rest = preg_replace_callback( $pattern, $callback, $rest );
|
||||
|
||||
return $placeholder . $rest;
|
||||
};
|
||||
|
||||
$this->registerPattern( $pattern, $callback );
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace custom properties, whose values may be used in scenarios where
|
||||
* we wouldn't want them to be minified (e.g. inside calc).
|
||||
*/
|
||||
protected function extractCustomProperties() {
|
||||
// PHP only supports $this inside anonymous functions since 5.4
|
||||
$minifier = $this;
|
||||
$this->registerPattern(
|
||||
'/(?<=^|[;}{])\s*(--[^:;{}"\'\s]+)\s*:([^;{}]+)/m',
|
||||
function ( $match ) use ( $minifier ) {
|
||||
$placeholder = '--custom-' . count( $minifier->extracted ) . ':0';
|
||||
$minifier->extracted[ $placeholder ] = $match[1] . ':' . trim( $match[2] );
|
||||
|
||||
return $placeholder;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file is small enough to be imported.
|
||||
*
|
||||
* @param string $path The path to the file
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function canImportBySize( $path ) {
|
||||
return ( $size = @filesize( $path ) ) && $size <= $this->maxImportSize * 1024;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file a file can be imported, going by the path.
|
||||
*
|
||||
* @param string $path
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function canImportByPath( $path ) {
|
||||
return preg_match( '/^(data:|https?:|\\/)/', $path ) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a converter to update relative paths to be relative to the new
|
||||
* destination.
|
||||
*
|
||||
* @param string $source
|
||||
* @param string $target
|
||||
*
|
||||
* @return ConverterInterface
|
||||
*/
|
||||
protected function getPathConverter( $source, $target ) {
|
||||
return new Converter( $source, $target );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
in
|
||||
public
|
||||
extends
|
||||
private
|
||||
protected
|
||||
implements
|
||||
instanceof
|
||||
@@ -0,0 +1,26 @@
|
||||
do
|
||||
in
|
||||
let
|
||||
new
|
||||
var
|
||||
case
|
||||
else
|
||||
enum
|
||||
void
|
||||
with
|
||||
class
|
||||
const
|
||||
yield
|
||||
delete
|
||||
export
|
||||
import
|
||||
public
|
||||
static
|
||||
typeof
|
||||
extends
|
||||
package
|
||||
private
|
||||
function
|
||||
protected
|
||||
implements
|
||||
instanceof
|
||||
@@ -0,0 +1,63 @@
|
||||
do
|
||||
if
|
||||
in
|
||||
for
|
||||
let
|
||||
new
|
||||
try
|
||||
var
|
||||
case
|
||||
else
|
||||
enum
|
||||
eval
|
||||
null
|
||||
this
|
||||
true
|
||||
void
|
||||
with
|
||||
break
|
||||
catch
|
||||
class
|
||||
const
|
||||
false
|
||||
super
|
||||
throw
|
||||
while
|
||||
yield
|
||||
delete
|
||||
export
|
||||
import
|
||||
public
|
||||
return
|
||||
static
|
||||
switch
|
||||
typeof
|
||||
default
|
||||
extends
|
||||
finally
|
||||
package
|
||||
private
|
||||
continue
|
||||
debugger
|
||||
function
|
||||
arguments
|
||||
interface
|
||||
protected
|
||||
implements
|
||||
instanceof
|
||||
abstract
|
||||
boolean
|
||||
byte
|
||||
char
|
||||
double
|
||||
final
|
||||
float
|
||||
goto
|
||||
int
|
||||
long
|
||||
native
|
||||
short
|
||||
synchronized
|
||||
throws
|
||||
transient
|
||||
volatile
|
||||
@@ -0,0 +1,46 @@
|
||||
+
|
||||
-
|
||||
*
|
||||
/
|
||||
%
|
||||
=
|
||||
+=
|
||||
-=
|
||||
*=
|
||||
/=
|
||||
%=
|
||||
<<=
|
||||
>>=
|
||||
>>>=
|
||||
&=
|
||||
^=
|
||||
|=
|
||||
&
|
||||
|
|
||||
^
|
||||
~
|
||||
<<
|
||||
>>
|
||||
>>>
|
||||
==
|
||||
===
|
||||
!=
|
||||
!==
|
||||
>
|
||||
<
|
||||
>=
|
||||
<=
|
||||
&&
|
||||
||
|
||||
!
|
||||
.
|
||||
[
|
||||
]
|
||||
?
|
||||
:
|
||||
,
|
||||
;
|
||||
(
|
||||
)
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
+
|
||||
-
|
||||
*
|
||||
/
|
||||
%
|
||||
=
|
||||
+=
|
||||
-=
|
||||
*=
|
||||
/=
|
||||
%=
|
||||
<<=
|
||||
>>=
|
||||
>>>=
|
||||
&=
|
||||
^=
|
||||
|=
|
||||
&
|
||||
|
|
||||
^
|
||||
<<
|
||||
>>
|
||||
>>>
|
||||
==
|
||||
===
|
||||
!=
|
||||
!==
|
||||
>
|
||||
<
|
||||
>=
|
||||
<=
|
||||
&&
|
||||
||
|
||||
.
|
||||
[
|
||||
]
|
||||
?
|
||||
:
|
||||
,
|
||||
;
|
||||
(
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
+
|
||||
-
|
||||
*
|
||||
/
|
||||
%
|
||||
=
|
||||
+=
|
||||
-=
|
||||
*=
|
||||
/=
|
||||
%=
|
||||
<<=
|
||||
>>=
|
||||
>>>=
|
||||
&=
|
||||
^=
|
||||
|=
|
||||
&
|
||||
|
|
||||
^
|
||||
~
|
||||
<<
|
||||
>>
|
||||
>>>
|
||||
==
|
||||
===
|
||||
!=
|
||||
!==
|
||||
>
|
||||
<
|
||||
>=
|
||||
<=
|
||||
&&
|
||||
||
|
||||
!
|
||||
.
|
||||
[
|
||||
?
|
||||
:
|
||||
,
|
||||
;
|
||||
(
|
||||
{
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
// phpcs:ignoreFile
|
||||
/**
|
||||
* exception.cls.php - modified PHP implementation of Matthias Mullie's Exceptions Classes.
|
||||
*
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
*/
|
||||
|
||||
namespace LiteSpeed\Lib\CSS_JS_MIN\Minify\Exception;
|
||||
|
||||
defined( 'WPINC' ) || exit;
|
||||
|
||||
abstract class Exception extends \Exception {
|
||||
|
||||
}
|
||||
|
||||
abstract class BasicException extends Exception {
|
||||
|
||||
}
|
||||
|
||||
class FileImportException extends BasicException {
|
||||
|
||||
}
|
||||
|
||||
class IOException extends BasicException {
|
||||
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,522 @@
|
||||
<?php
|
||||
// phpcs:ignoreFile
|
||||
/**
|
||||
* modified PHP implementation of Matthias Mullie's Abstract minifier class.
|
||||
*
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
namespace LiteSpeed\Lib\CSS_JS_MIN\Minify;
|
||||
|
||||
use LiteSpeed\Lib\CSS_JS_MIN\Minify\Exception\IOException;
|
||||
|
||||
defined( 'WPINC' ) || exit;
|
||||
|
||||
abstract class Minify {
|
||||
|
||||
/**
|
||||
* The data to be minified.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $data = array();
|
||||
|
||||
/**
|
||||
* Array of patterns to match.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $patterns = array();
|
||||
|
||||
/**
|
||||
* This array will hold content of strings and regular expressions that have
|
||||
* been extracted from the JS source code, so we can reliably match "code",
|
||||
* without having to worry about potential "code-like" characters inside.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
public $extracted = array();
|
||||
|
||||
/**
|
||||
* Init the minify class - optionally, code may be passed along already.
|
||||
*/
|
||||
public function __construct( /* $data = null, ... */ ) {
|
||||
// it's possible to add the source through the constructor as well ;)
|
||||
if ( func_num_args() ) {
|
||||
call_user_func_array( array( $this, 'add' ), func_get_args() );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a file or straight-up code to be minified.
|
||||
*
|
||||
* @param string|string[] $data
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public function add( $data /* $data = null, ... */ ) {
|
||||
// bogus "usage" of parameter $data: scrutinizer warns this variable is
|
||||
// not used (we're using func_get_args instead to support overloading),
|
||||
// but it still needs to be defined because it makes no sense to have
|
||||
// this function without argument :)
|
||||
$args = array( $data ) + func_get_args();
|
||||
|
||||
// this method can be overloaded
|
||||
foreach ( $args as $data ) {
|
||||
if ( is_array( $data ) ) {
|
||||
call_user_func_array( array( $this, 'add' ), $data );
|
||||
continue;
|
||||
}
|
||||
|
||||
// redefine var
|
||||
$data = (string) $data;
|
||||
|
||||
// load data
|
||||
$value = $this->load( $data );
|
||||
$key = ( $data != $value ) ? $data : count( $this->data );
|
||||
|
||||
// replace CR linefeeds etc.
|
||||
// @see https://github.com/matthiasmullie/minify/pull/139
|
||||
$value = str_replace( array( "\r\n", "\r" ), "\n", $value );
|
||||
|
||||
// store data
|
||||
$this->data[ $key ] = $value;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a file to be minified.
|
||||
*
|
||||
* @param string|string[] $data
|
||||
*
|
||||
* @return static
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
public function addFile( $data /* $data = null, ... */ ) {
|
||||
// bogus "usage" of parameter $data: scrutinizer warns this variable is
|
||||
// not used (we're using func_get_args instead to support overloading),
|
||||
// but it still needs to be defined because it makes no sense to have
|
||||
// this function without argument :)
|
||||
$args = array( $data ) + func_get_args();
|
||||
|
||||
// this method can be overloaded
|
||||
foreach ( $args as $path ) {
|
||||
if ( is_array( $path ) ) {
|
||||
call_user_func_array( array( $this, 'addFile' ), $path );
|
||||
continue;
|
||||
}
|
||||
|
||||
// redefine var
|
||||
$path = (string) $path;
|
||||
|
||||
// check if we can read the file
|
||||
if ( ! $this->canImportFile( $path ) ) {
|
||||
throw new IOException( 'The file "' . $path . '" could not be opened for reading. Check if PHP has enough permissions.' );
|
||||
}
|
||||
|
||||
$this->add( $path );
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minify the data & (optionally) saves it to a file.
|
||||
*
|
||||
* @param string[optional] $path Path to write the data to
|
||||
*
|
||||
* @return string The minified data
|
||||
*/
|
||||
public function minify( $path = null ) {
|
||||
$content = $this->execute( $path );
|
||||
|
||||
// save to path
|
||||
if ( $path !== null ) {
|
||||
$this->save( $content, $path );
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minify & gzip the data & (optionally) saves it to a file.
|
||||
*
|
||||
* @param string[optional] $path Path to write the data to
|
||||
* @param int[optional] $level Compression level, from 0 to 9
|
||||
*
|
||||
* @return string The minified & gzipped data
|
||||
*/
|
||||
public function gzip( $path = null, $level = 9 ) {
|
||||
$content = $this->execute( $path );
|
||||
$content = gzencode( $content, $level, FORCE_GZIP );
|
||||
|
||||
// save to path
|
||||
if ( $path !== null ) {
|
||||
$this->save( $content, $path );
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Minify the data.
|
||||
*
|
||||
* @param string[optional] $path Path to write the data to
|
||||
*
|
||||
* @return string The minified data
|
||||
*/
|
||||
abstract public function execute( $path = null );
|
||||
|
||||
/**
|
||||
* Load data.
|
||||
*
|
||||
* @param string $data Either a path to a file or the content itself
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function load( $data ) {
|
||||
// check if the data is a file
|
||||
if ( $this->canImportFile( $data ) ) {
|
||||
$data = file_get_contents( $data );
|
||||
|
||||
// strip BOM, if any
|
||||
if ( substr( $data, 0, 3 ) == "\xef\xbb\xbf" ) {
|
||||
$data = substr( $data, 3 );
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save to file.
|
||||
*
|
||||
* @param string $content The minified data
|
||||
* @param string $path The path to save the minified data to
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
protected function save( $content, $path ) {
|
||||
$handler = $this->openFileForWriting( $path );
|
||||
|
||||
$this->writeToFile( $handler, $content );
|
||||
|
||||
@fclose( $handler );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a pattern to execute against the source content.
|
||||
*
|
||||
* If $replacement is a string, it must be plain text. Placeholders like $1 or \2 don't work.
|
||||
* If you need that functionality, use a callback instead.
|
||||
*
|
||||
* @param string $pattern PCRE pattern
|
||||
* @param string|callable $replacement Replacement value for matched pattern
|
||||
*/
|
||||
protected function registerPattern( $pattern, $replacement = '' ) {
|
||||
// study the pattern, we'll execute it more than once
|
||||
$pattern .= 'S';
|
||||
|
||||
$this->patterns[] = array( $pattern, $replacement );
|
||||
}
|
||||
|
||||
/**
|
||||
* Both JS and CSS use the same form of multi-line comment, so putting the common code here.
|
||||
*/
|
||||
protected function stripMultilineComments() {
|
||||
// First extract comments we want to keep, so they can be restored later
|
||||
// PHP only supports $this inside anonymous functions since 5.4
|
||||
$minifier = $this;
|
||||
$callback = function ( $match ) use ( $minifier ) {
|
||||
$count = count( $minifier->extracted );
|
||||
$placeholder = '/*' . $count . '*/';
|
||||
$minifier->extracted[ $placeholder ] = $match[0];
|
||||
|
||||
return $placeholder;
|
||||
};
|
||||
$this->registerPattern(
|
||||
'/
|
||||
# optional newline
|
||||
\n?
|
||||
|
||||
# start comment
|
||||
\/\*
|
||||
|
||||
# comment content
|
||||
(?:
|
||||
# either starts with an !
|
||||
!
|
||||
|
|
||||
# or, after some number of characters which do not end the comment
|
||||
(?:(?!\*\/).)*?
|
||||
|
||||
# there is either a @license or @preserve tag
|
||||
@(?:license|preserve)
|
||||
)
|
||||
|
||||
# then match to the end of the comment
|
||||
.*?\*\/\n?
|
||||
|
||||
/ixs',
|
||||
$callback
|
||||
);
|
||||
|
||||
// Then strip all other comments
|
||||
$this->registerPattern( '/\/\*.*?\*\//s', '' );
|
||||
}
|
||||
|
||||
/**
|
||||
* We can't "just" run some regular expressions against JavaScript: it's a
|
||||
* complex language. E.g. having an occurrence of // xyz would be a comment,
|
||||
* unless it's used within a string. Of you could have something that looks
|
||||
* like a 'string', but inside a comment.
|
||||
* The only way to accurately replace these pieces is to traverse the JS one
|
||||
* character at a time and try to find whatever starts first.
|
||||
*
|
||||
* @param string $content The content to replace patterns in
|
||||
*
|
||||
* @return string The (manipulated) content
|
||||
*/
|
||||
protected function replace( $content ) {
|
||||
$contentLength = strlen( $content );
|
||||
$output = '';
|
||||
$processedOffset = 0;
|
||||
$positions = array_fill( 0, count( $this->patterns ), -1 );
|
||||
$matches = array();
|
||||
|
||||
while ( $processedOffset < $contentLength ) {
|
||||
// find first match for all patterns
|
||||
foreach ( $this->patterns as $i => $pattern ) {
|
||||
list($pattern, $replacement) = $pattern;
|
||||
|
||||
// we can safely ignore patterns for positions we've unset earlier,
|
||||
// because we know these won't show up anymore
|
||||
if ( array_key_exists( $i, $positions ) == false ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// no need to re-run matches that are still in the part of the
|
||||
// content that hasn't been processed
|
||||
if ( $positions[ $i ] >= $processedOffset ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$match = null;
|
||||
if ( preg_match( $pattern, $content, $match, PREG_OFFSET_CAPTURE, $processedOffset ) ) {
|
||||
$matches[ $i ] = $match;
|
||||
|
||||
// we'll store the match position as well; that way, we
|
||||
// don't have to redo all preg_matches after changing only
|
||||
// the first (we'll still know where those others are)
|
||||
$positions[ $i ] = $match[0][1];
|
||||
} else {
|
||||
// if the pattern couldn't be matched, there's no point in
|
||||
// executing it again in later runs on this same content;
|
||||
// ignore this one until we reach end of content
|
||||
unset( $matches[ $i ], $positions[ $i ] );
|
||||
}
|
||||
}
|
||||
|
||||
// no more matches to find: everything's been processed, break out
|
||||
if ( ! $matches ) {
|
||||
// output the remaining content
|
||||
$output .= substr( $content, $processedOffset );
|
||||
break;
|
||||
}
|
||||
|
||||
// see which of the patterns actually found the first thing (we'll
|
||||
// only want to execute that one, since we're unsure if what the
|
||||
// other found was not inside what the first found)
|
||||
$matchOffset = min( $positions );
|
||||
$firstPattern = array_search( $matchOffset, $positions );
|
||||
$match = $matches[ $firstPattern ];
|
||||
|
||||
// execute the pattern that matches earliest in the content string
|
||||
list(, $replacement) = $this->patterns[ $firstPattern ];
|
||||
|
||||
// add the part of the input between $processedOffset and the first match;
|
||||
// that content wasn't matched by anything
|
||||
$output .= substr( $content, $processedOffset, $matchOffset - $processedOffset );
|
||||
// add the replacement for the match
|
||||
$output .= $this->executeReplacement( $replacement, $match );
|
||||
// advance $processedOffset past the match
|
||||
$processedOffset = $matchOffset + strlen( $match[0][0] );
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* If $replacement is a callback, execute it, passing in the match data.
|
||||
* If it's a string, just pass it through.
|
||||
*
|
||||
* @param string|callable $replacement Replacement value
|
||||
* @param array $match Match data, in PREG_OFFSET_CAPTURE form
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function executeReplacement( $replacement, $match ) {
|
||||
if ( ! is_callable( $replacement ) ) {
|
||||
return $replacement;
|
||||
}
|
||||
// convert $match from the PREG_OFFSET_CAPTURE form to the form the callback expects
|
||||
foreach ( $match as &$matchItem ) {
|
||||
$matchItem = $matchItem[0];
|
||||
}
|
||||
|
||||
return $replacement( $match );
|
||||
}
|
||||
|
||||
/**
|
||||
* Strings are a pattern we need to match, in order to ignore potential
|
||||
* code-like content inside them, but we just want all of the string
|
||||
* content to remain untouched.
|
||||
*
|
||||
* This method will replace all string content with simple STRING#
|
||||
* placeholder text, so we've rid all strings from characters that may be
|
||||
* misinterpreted. Original string content will be saved in $this->extracted
|
||||
* and after doing all other minifying, we can restore the original content
|
||||
* via restoreStrings().
|
||||
*
|
||||
* @param string[optional] $chars
|
||||
* @param string[optional] $placeholderPrefix
|
||||
*/
|
||||
protected function extractStrings( $chars = '\'"', $placeholderPrefix = '' ) {
|
||||
// PHP only supports $this inside anonymous functions since 5.4
|
||||
$minifier = $this;
|
||||
$callback = function ( $match ) use ( $minifier, $placeholderPrefix ) {
|
||||
// check the second index here, because the first always contains a quote
|
||||
if ( $match[2] === '' ) {
|
||||
/*
|
||||
* Empty strings need no placeholder; they can't be confused for
|
||||
* anything else anyway.
|
||||
* But we still needed to match them, for the extraction routine
|
||||
* to skip over this particular string.
|
||||
*/
|
||||
return $match[0];
|
||||
}
|
||||
|
||||
$count = count( $minifier->extracted );
|
||||
$placeholder = $match[1] . $placeholderPrefix . $count . $match[1];
|
||||
$minifier->extracted[ $placeholder ] = $match[1] . $match[2] . $match[1];
|
||||
|
||||
return $placeholder;
|
||||
};
|
||||
|
||||
/*
|
||||
* The \\ messiness explained:
|
||||
* * Don't count ' or " as end-of-string if it's escaped (has backslash
|
||||
* in front of it)
|
||||
* * Unless... that backslash itself is escaped (another leading slash),
|
||||
* in which case it's no longer escaping the ' or "
|
||||
* * So there can be either no backslash, or an even number
|
||||
* * multiply all of that times 4, to account for the escaping that has
|
||||
* to be done to pass the backslash into the PHP string without it being
|
||||
* considered as escape-char (times 2) and to get it in the regex,
|
||||
* escaped (times 2)
|
||||
*/
|
||||
$this->registerPattern( '/([' . $chars . '])(.*?(?<!\\\\)(\\\\\\\\)*+)\\1/s', $callback );
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will restore all extracted data (strings, regexes) that were
|
||||
* replaced with placeholder text in extract*(). The original content was
|
||||
* saved in $this->extracted.
|
||||
*
|
||||
* @param string $content
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function restoreExtractedData( $content ) {
|
||||
if ( ! $this->extracted ) {
|
||||
// nothing was extracted, nothing to restore
|
||||
return $content;
|
||||
}
|
||||
|
||||
$content = strtr( $content, $this->extracted );
|
||||
|
||||
$this->extracted = array();
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the path is a regular file and can be read.
|
||||
*
|
||||
* @param string $path
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function canImportFile( $path ) {
|
||||
$parsed = parse_url( $path );
|
||||
if (
|
||||
// file is elsewhere
|
||||
isset( $parsed['host'] )
|
||||
// file responds to queries (may change, or need to bypass cache)
|
||||
|| isset( $parsed['query'] )
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return strlen( $path ) < PHP_MAXPATHLEN && @is_file( $path ) && is_readable( $path );
|
||||
}
|
||||
// catch openbasedir exceptions which are not caught by @ on is_file()
|
||||
catch ( \Exception $e ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to open file specified by $path for writing.
|
||||
*
|
||||
* @param string $path The path to the file
|
||||
*
|
||||
* @return resource Specifier for the target file
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
protected function openFileForWriting( $path ) {
|
||||
if ( $path === '' || ( $handler = @fopen( $path, 'w' ) ) === false ) {
|
||||
throw new IOException( 'The file "' . $path . '" could not be opened for writing. Check if PHP has enough permissions.' );
|
||||
}
|
||||
|
||||
return $handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to write $content to the file specified by $handler. $path is used for printing exceptions.
|
||||
*
|
||||
* @param resource $handler The resource to write to
|
||||
* @param string $content The content to write
|
||||
* @param string $path The path to the file (for exception printing only)
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
protected function writeToFile( $handler, $content, $path = '' ) {
|
||||
if (
|
||||
! is_resource( $handler )
|
||||
|| ( $result = @fwrite( $handler, $content ) ) === false
|
||||
|| ( $result < strlen( $content ) )
|
||||
) {
|
||||
throw new IOException( 'The file "' . $path . '" could not be written to. Check your disk space and file permissions.' );
|
||||
}
|
||||
}
|
||||
|
||||
protected static function str_replace_first( $search, $replace, $subject ) {
|
||||
$pos = strpos( $subject, $search );
|
||||
if ( $pos !== false ) {
|
||||
return substr_replace( $subject, $replace, $pos, strlen( $search ) );
|
||||
}
|
||||
|
||||
return $subject;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
Copyright (c) 2015 Matthias Mullie
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,223 @@
|
||||
<?php
|
||||
// phpcs:ignoreFile
|
||||
/**
|
||||
* modified PHP implementation of Matthias Mullie's convert path class
|
||||
* Convert paths relative from 1 file to another.
|
||||
*
|
||||
* E.g.
|
||||
* ../../images/icon.jpg relative to /css/imports/icons.css
|
||||
* becomes
|
||||
* ../images/icon.jpg relative to /css/minified.css
|
||||
*
|
||||
* @author Matthias Mullie <pathconverter@mullie.eu>
|
||||
* @copyright Copyright (c) 2015, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
namespace LiteSpeed\Lib\CSS_JS_MIN\PathConverter;
|
||||
|
||||
defined( 'WPINC' ) || exit;
|
||||
|
||||
interface ConverterInterface {
|
||||
|
||||
/**
|
||||
* Convert file paths.
|
||||
*
|
||||
* @param string $path The path to be converted
|
||||
*
|
||||
* @return string The new path
|
||||
*/
|
||||
public function convert( $path );
|
||||
}
|
||||
|
||||
class Converter implements ConverterInterface {
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $from;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $to;
|
||||
|
||||
/**
|
||||
* @param string $from The original base path (directory, not file!)
|
||||
* @param string $to The new base path (directory, not file!)
|
||||
* @param string $root Root directory (defaults to `getcwd`)
|
||||
*/
|
||||
public function __construct( $from, $to, $root = '' ) {
|
||||
$shared = $this->shared( $from, $to );
|
||||
if ( $shared === '' ) {
|
||||
// when both paths have nothing in common, one of them is probably
|
||||
// absolute while the other is relative
|
||||
$root = $root ?: getcwd();
|
||||
$from = strpos( $from, $root ) === 0 ? $from : preg_replace( '/\/+/', '/', $root . '/' . $from );
|
||||
$to = strpos( $to, $root ) === 0 ? $to : preg_replace( '/\/+/', '/', $root . '/' . $to );
|
||||
|
||||
// or traveling the tree via `..`
|
||||
// attempt to resolve path, or assume it's fine if it doesn't exist
|
||||
$from = @realpath( $from ) ?: $from;
|
||||
$to = @realpath( $to ) ?: $to;
|
||||
}
|
||||
|
||||
$from = $this->dirname( $from );
|
||||
$to = $this->dirname( $to );
|
||||
|
||||
$from = $this->normalize( $from );
|
||||
$to = $this->normalize( $to );
|
||||
|
||||
$this->from = $from;
|
||||
$this->to = $to;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize path.
|
||||
*
|
||||
* @param string $path
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function normalize( $path ) {
|
||||
// deal with different operating systems' directory structure
|
||||
$path = rtrim( str_replace( DIRECTORY_SEPARATOR, '/', $path ), '/' );
|
||||
|
||||
// remove leading current directory.
|
||||
if ( substr( $path, 0, 2 ) === './' ) {
|
||||
$path = substr( $path, 2 );
|
||||
}
|
||||
|
||||
// remove references to current directory in the path.
|
||||
$path = str_replace( '/./', '/', $path );
|
||||
|
||||
/*
|
||||
* Example:
|
||||
* /home/forkcms/frontend/cache/compiled_templates/../../core/layout/css/../images/img.gif
|
||||
* to
|
||||
* /home/forkcms/frontend/core/layout/images/img.gif
|
||||
*/
|
||||
do {
|
||||
$path = preg_replace( '/[^\/]+(?<!\.\.)\/\.\.\//', '', $path, -1, $count );
|
||||
} while ( $count );
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Figure out the shared path of 2 locations.
|
||||
*
|
||||
* Example:
|
||||
* /home/forkcms/frontend/core/layout/images/img.gif
|
||||
* and
|
||||
* /home/forkcms/frontend/cache/minified_css
|
||||
* share
|
||||
* /home/forkcms/frontend
|
||||
*
|
||||
* @param string $path1
|
||||
* @param string $path2
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function shared( $path1, $path2 ) {
|
||||
// $path could theoretically be empty (e.g. no path is given), in which
|
||||
// case it shouldn't expand to array(''), which would compare to one's
|
||||
// root /
|
||||
$path1 = $path1 ? explode( '/', $path1 ) : array();
|
||||
$path2 = $path2 ? explode( '/', $path2 ) : array();
|
||||
|
||||
$shared = array();
|
||||
|
||||
// compare paths & strip identical ancestors
|
||||
foreach ( $path1 as $i => $chunk ) {
|
||||
if ( isset( $path2[ $i ] ) && $path1[ $i ] == $path2[ $i ] ) {
|
||||
$shared[] = $chunk;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return implode( '/', $shared );
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert paths relative from 1 file to another.
|
||||
*
|
||||
* E.g.
|
||||
* ../images/img.gif relative to /home/forkcms/frontend/core/layout/css
|
||||
* should become:
|
||||
* ../../core/layout/images/img.gif relative to
|
||||
* /home/forkcms/frontend/cache/minified_css
|
||||
*
|
||||
* @param string $path The relative path that needs to be converted
|
||||
*
|
||||
* @return string The new relative path
|
||||
*/
|
||||
public function convert( $path ) {
|
||||
// quit early if conversion makes no sense
|
||||
if ( $this->from === $this->to ) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
$path = $this->normalize( $path );
|
||||
// if we're not dealing with a relative path, just return absolute
|
||||
if ( strpos( $path, '/' ) === 0 ) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
// normalize paths
|
||||
$path = $this->normalize( $this->from . '/' . $path );
|
||||
|
||||
// strip shared ancestor paths
|
||||
$shared = $this->shared( $path, $this->to );
|
||||
$path = mb_substr( $path, mb_strlen( $shared ) );
|
||||
$to = mb_substr( $this->to, mb_strlen( $shared ) );
|
||||
|
||||
// add .. for every directory that needs to be traversed to new path
|
||||
$to = str_repeat( '../', count( array_filter( explode( '/', $to ) ) ) );
|
||||
|
||||
return $to . ltrim( $path, '/' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to get the directory name from a path.
|
||||
*
|
||||
* @param string $path
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function dirname( $path ) {
|
||||
if ( @is_file( $path ) ) {
|
||||
return dirname( $path );
|
||||
}
|
||||
|
||||
if ( @is_dir( $path ) ) {
|
||||
return rtrim( $path, '/' );
|
||||
}
|
||||
|
||||
// no known file/dir, start making assumptions
|
||||
|
||||
// ends in / = dir
|
||||
if ( mb_substr( $path, -1 ) === '/' ) {
|
||||
return rtrim( $path, '/' );
|
||||
}
|
||||
|
||||
// has a dot in the name, likely a file
|
||||
if ( preg_match( '/.*\..*$/', basename( $path ) ) !== 0 ) {
|
||||
return dirname( $path );
|
||||
}
|
||||
|
||||
// you're on your own here!
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
|
||||
class NoConverter implements ConverterInterface {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function convert( $path ) {
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
<?php
|
||||
// phpcs:ignoreFile
|
||||
|
||||
namespace LiteSpeed\Lib;
|
||||
|
||||
/**
|
||||
* Update guest vary
|
||||
*
|
||||
* @since 4.1
|
||||
*/
|
||||
class Guest {
|
||||
|
||||
const CONF_FILE = '.litespeed_conf.dat';
|
||||
const HASH = 'hash'; // Not set-able
|
||||
const O_CACHE_LOGIN_COOKIE = 'cache-login_cookie';
|
||||
const O_DEBUG = 'debug';
|
||||
const O_DEBUG_IPS = 'debug-ips';
|
||||
const O_UTIL_NO_HTTPS_VARY = 'util-no_https_vary';
|
||||
const O_GUEST_UAS = 'guest_uas';
|
||||
const O_GUEST_IPS = 'guest_ips';
|
||||
|
||||
private static $_ip;
|
||||
private static $_vary_name = '_lscache_vary'; // this default vary cookie is used for logged in status check
|
||||
private $_conf = false;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @since 4.1
|
||||
*/
|
||||
public function __construct() {
|
||||
! defined( 'LSCWP_CONTENT_FOLDER' ) && define( 'LSCWP_CONTENT_FOLDER', dirname( __DIR__, 3 ) );
|
||||
// Load config
|
||||
$this->_conf = file_get_contents( LSCWP_CONTENT_FOLDER . '/' . self::CONF_FILE );
|
||||
if ( $this->_conf ) {
|
||||
$this->_conf = json_decode( $this->_conf, true );
|
||||
}
|
||||
|
||||
if ( ! empty( $this->_conf[ self::O_CACHE_LOGIN_COOKIE ] ) ) {
|
||||
self::$_vary_name = $this->_conf[ self::O_CACHE_LOGIN_COOKIE ];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Guest vary
|
||||
*
|
||||
* @since 4.0
|
||||
*/
|
||||
public function update_guest_vary() {
|
||||
// This process must not be cached
|
||||
/**
|
||||
* @reference https://wordpress.org/support/topic/soft-404-from-google-search-on-litespeed-cache-guest-vary-php/#post-16838583
|
||||
*/
|
||||
header( 'X-Robots-Tag: noindex' );
|
||||
header( 'X-LiteSpeed-Cache-Control: no-cache' );
|
||||
|
||||
if ( $this->always_guest() ) {
|
||||
echo '[]';
|
||||
exit;
|
||||
}
|
||||
|
||||
// If contains vary already, don't reload to avoid infinite loop when parent page having browser cache
|
||||
if ( $this->_conf && self::has_vary() ) {
|
||||
echo '[]';
|
||||
exit;
|
||||
}
|
||||
|
||||
// Send vary cookie
|
||||
$vary = 'guest_mode:1';
|
||||
if ( $this->_conf && empty( $this->_conf[ self::O_DEBUG ] ) ) {
|
||||
$vary = md5( $this->_conf[ self::HASH ] . $vary );
|
||||
}
|
||||
|
||||
$expire = time() + 2 * 86400;
|
||||
$is_ssl = ! empty( $this->_conf[ self::O_UTIL_NO_HTTPS_VARY ] ) ? false : $this->is_ssl();
|
||||
setcookie( self::$_vary_name, $vary, $expire, '/', false, $is_ssl, true );
|
||||
|
||||
// return json
|
||||
echo json_encode( array( 'reload' => 'yes' ) );
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* WP's is_ssl() func
|
||||
*
|
||||
* @since 4.1
|
||||
*/
|
||||
private function is_ssl() {
|
||||
if ( isset( $_SERVER['HTTPS'] ) ) {
|
||||
if ( 'on' === strtolower( $_SERVER['HTTPS'] ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( '1' == $_SERVER['HTTPS'] ) {
|
||||
return true;
|
||||
}
|
||||
} elseif ( isset( $_SERVER['SERVER_PORT'] ) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if default vary has a value
|
||||
*
|
||||
* @since 1.1.3
|
||||
* @access public
|
||||
*/
|
||||
public static function has_vary() {
|
||||
if ( empty( $_COOKIE[ self::$_vary_name ] ) ) {
|
||||
return false;
|
||||
}
|
||||
return $_COOKIE[ self::$_vary_name ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect if is a guest visitor or not
|
||||
*
|
||||
* @since 4.0
|
||||
*/
|
||||
public function always_guest() {
|
||||
if ( empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( $this->_conf[ self::O_GUEST_UAS ] ) {
|
||||
$quoted_uas = array();
|
||||
foreach ( $this->_conf[ self::O_GUEST_UAS ] as $v ) {
|
||||
$quoted_uas[] = preg_quote( $v, '#' );
|
||||
}
|
||||
$match = preg_match( '#' . implode( '|', $quoted_uas ) . '#i', $_SERVER['HTTP_USER_AGENT'] );
|
||||
if ( $match ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if ( $this->ip_access( $this->_conf[ self::O_GUEST_IPS ] ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the ip is in the range
|
||||
*
|
||||
* @since 1.1.0
|
||||
* @access public
|
||||
*/
|
||||
public function ip_access( $ip_list ) {
|
||||
if ( ! $ip_list ) {
|
||||
return false;
|
||||
}
|
||||
if ( ! isset( self::$_ip ) ) {
|
||||
self::$_ip = self::get_ip();
|
||||
}
|
||||
// $uip = explode('.', $_ip);
|
||||
// if(empty($uip) || count($uip) != 4) Return false;
|
||||
// foreach($ip_list as $key => $ip) $ip_list[$key] = explode('.', trim($ip));
|
||||
// foreach($ip_list as $key => $ip) {
|
||||
// if(count($ip) != 4) continue;
|
||||
// for($i = 0; $i <= 3; $i++) if($ip[$i] == '*') $ip_list[$key][$i] = $uip[$i];
|
||||
// }
|
||||
return in_array( self::$_ip, $ip_list );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get client ip
|
||||
*
|
||||
* @since 1.1.0
|
||||
* @since 1.6.5 changed to public
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public static function get_ip() {
|
||||
$_ip = '';
|
||||
if ( function_exists( 'apache_request_headers' ) ) {
|
||||
$apache_headers = apache_request_headers();
|
||||
$_ip = ! empty( $apache_headers['True-Client-IP'] ) ? $apache_headers['True-Client-IP'] : false;
|
||||
if ( ! $_ip ) {
|
||||
$_ip = ! empty( $apache_headers['X-Forwarded-For'] ) ? $apache_headers['X-Forwarded-For'] : false;
|
||||
$_ip = explode( ',', $_ip );
|
||||
$_ip = $_ip[0];
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! $_ip ) {
|
||||
$_ip = ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : false;
|
||||
}
|
||||
return $_ip;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
<?php
|
||||
// phpcs:ignoreFile
|
||||
/**
|
||||
* Compress HTML
|
||||
*
|
||||
* This is a heavy regex-based removal of whitespace, unnecessary comments and
|
||||
* tokens. IE conditional comments are preserved. There are also options to have
|
||||
* STYLE and SCRIPT blocks compressed by callback functions.
|
||||
*
|
||||
* A test suite is available.
|
||||
*
|
||||
* @package Minify
|
||||
* @author Stephen Clay <steve@mrclay.org>
|
||||
*/
|
||||
namespace LiteSpeed\Lib;
|
||||
|
||||
defined( 'WPINC' ) || exit;
|
||||
|
||||
class HTML_MIN {
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $_html = '';
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
*/
|
||||
protected $_jsCleanComments = true;
|
||||
protected $_skipComments = array();
|
||||
|
||||
/**
|
||||
* "Minify" an HTML page
|
||||
*
|
||||
* @param string $html
|
||||
*
|
||||
* @param array $options
|
||||
*
|
||||
* 'cssMinifier' : (optional) callback function to process content of STYLE
|
||||
* elements.
|
||||
*
|
||||
* 'jsMinifier' : (optional) callback function to process content of SCRIPT
|
||||
* elements. Note: the type attribute is ignored.
|
||||
*
|
||||
* 'xhtml' : (optional boolean) should content be treated as XHTML1.0? If
|
||||
* unset, minify will sniff for an XHTML doctype.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function minify( $html, $options = array() ) {
|
||||
$min = new self( $html, $options );
|
||||
|
||||
return $min->process();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a minifier object
|
||||
*
|
||||
* @param string $html
|
||||
*
|
||||
* @param array $options
|
||||
*
|
||||
* 'cssMinifier' : (optional) callback function to process content of STYLE
|
||||
* elements.
|
||||
*
|
||||
* 'jsMinifier' : (optional) callback function to process content of SCRIPT
|
||||
* elements. Note: the type attribute is ignored.
|
||||
*
|
||||
* 'jsCleanComments' : (optional) whether to remove HTML comments beginning and end of script block
|
||||
*
|
||||
* 'xhtml' : (optional boolean) should content be treated as XHTML1.0? If
|
||||
* unset, minify will sniff for an XHTML doctype.
|
||||
*/
|
||||
public function __construct( $html, $options = array() ) {
|
||||
$this->_html = str_replace( "\r\n", "\n", trim( $html ) );
|
||||
if ( isset( $options['xhtml'] ) ) {
|
||||
$this->_isXhtml = (bool) $options['xhtml'];
|
||||
}
|
||||
if ( isset( $options['cssMinifier'] ) ) {
|
||||
$this->_cssMinifier = $options['cssMinifier'];
|
||||
}
|
||||
if ( isset( $options['jsMinifier'] ) ) {
|
||||
$this->_jsMinifier = $options['jsMinifier'];
|
||||
}
|
||||
if ( isset( $options['jsCleanComments'] ) ) {
|
||||
$this->_jsCleanComments = (bool) $options['jsCleanComments'];
|
||||
}
|
||||
if ( isset( $options['skipComments'] ) ) {
|
||||
$this->_skipComments = $options['skipComments'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Minify the markeup given in the constructor
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function process() {
|
||||
if ( $this->_isXhtml === null ) {
|
||||
$this->_isXhtml = ( false !== strpos( $this->_html, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML' ) );
|
||||
}
|
||||
|
||||
$this->_replacementHash = 'MINIFYHTML' . md5( $_SERVER['REQUEST_TIME'] );
|
||||
$this->_placeholders = array();
|
||||
|
||||
// replace SCRIPTs (and minify) with placeholders
|
||||
$this->_html = preg_replace_callback(
|
||||
'/(\\s*)<script(\\b[^>]*?>)([\\s\\S]*?)<\\/script>(\\s*)/i',
|
||||
array( $this, '_removeScriptCB' ),
|
||||
$this->_html
|
||||
);
|
||||
|
||||
// replace STYLEs (and minify) with placeholders
|
||||
$this->_html = preg_replace_callback(
|
||||
'/\\s*<style(\\b[^>]*>)([\\s\\S]*?)<\\/style>\\s*/i',
|
||||
array( $this, '_removeStyleCB' ),
|
||||
$this->_html
|
||||
);
|
||||
|
||||
// remove HTML comments (not containing IE conditional comments).
|
||||
$this->_html = preg_replace_callback(
|
||||
'/<!--([\\s\\S]*?)-->/',
|
||||
array( $this, '_commentCB' ),
|
||||
$this->_html
|
||||
);
|
||||
|
||||
// replace PREs with placeholders
|
||||
$this->_html = preg_replace_callback(
|
||||
'/\\s*<pre(\\b[^>]*?>[\\s\\S]*?<\\/pre>)\\s*/i',
|
||||
array( $this, '_removePreCB' ),
|
||||
$this->_html
|
||||
);
|
||||
|
||||
// replace TEXTAREAs with placeholders
|
||||
$this->_html = preg_replace_callback(
|
||||
'/\\s*<textarea(\\b[^>]*?>[\\s\\S]*?<\\/textarea>)\\s*/i',
|
||||
array( $this, '_removeTextareaCB' ),
|
||||
$this->_html
|
||||
);
|
||||
|
||||
// trim each line.
|
||||
// @todo take into account attribute values that span multiple lines.
|
||||
$this->_html = preg_replace( '/^\\s+|\\s+$/m', '', $this->_html );
|
||||
|
||||
// remove ws around block/undisplayed elements
|
||||
$this->_html = preg_replace(
|
||||
'/\\s+(<\\/?(?:area|article|aside|base(?:font)?|blockquote|body'
|
||||
. '|canvas|caption|center|col(?:group)?|dd|dir|div|dl|dt|fieldset|figcaption|figure|footer|form'
|
||||
. '|frame(?:set)?|h[1-6]|head|header|hgroup|hr|html|legend|li|link|main|map|menu|meta|nav'
|
||||
. '|ol|opt(?:group|ion)|output|p|param|section|t(?:able|body|head|d|h||r|foot|itle)'
|
||||
. '|ul|video)\\b[^>]*>)/i',
|
||||
'$1',
|
||||
$this->_html
|
||||
);
|
||||
|
||||
// remove ws outside of all elements
|
||||
$this->_html = preg_replace(
|
||||
'/>(\\s(?:\\s*))?([^<]+)(\\s(?:\s*))?</',
|
||||
'>$1$2$3<',
|
||||
$this->_html
|
||||
);
|
||||
|
||||
// use newlines before 1st attribute in open tags (to limit line lengths)
|
||||
// $this->_html = preg_replace('/(<[a-z\\-]+)\\s+([^>]+>)/i', "$1\n$2", $this->_html);
|
||||
|
||||
// fill placeholders
|
||||
$this->_html = str_replace(
|
||||
array_keys( $this->_placeholders ),
|
||||
array_values( $this->_placeholders ),
|
||||
$this->_html
|
||||
);
|
||||
// issue 229: multi-pass to catch scripts that didn't get replaced in textareas
|
||||
$this->_html = str_replace(
|
||||
array_keys( $this->_placeholders ),
|
||||
array_values( $this->_placeholders ),
|
||||
$this->_html
|
||||
);
|
||||
|
||||
return $this->_html;
|
||||
}
|
||||
|
||||
/**
|
||||
* From LSCWP 6.2: Changed the function to test for special comments that will be skipped. See: https://github.com/litespeedtech/lscache_wp/pull/622
|
||||
*/
|
||||
protected function _commentCB( $m ) {
|
||||
// If is IE conditional comment return it.
|
||||
if ( 0 === strpos( $m[1], '[' ) || false !== strpos( $m[1], '<![' ) ) {
|
||||
return $m[0];
|
||||
}
|
||||
|
||||
// Check if comment text is present in Page Optimization -> HTML Settings -> HTML Keep comments
|
||||
if ( count( $this->_skipComments ) > 0 ) {
|
||||
foreach ( $this->_skipComments as $comment ) {
|
||||
if ( $comment && strpos( $m[1], $comment ) !== false ) {
|
||||
return $m[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Comment can be removed.
|
||||
return '';
|
||||
}
|
||||
|
||||
protected function _reservePlace( $content ) {
|
||||
$placeholder = '%' . $this->_replacementHash . count( $this->_placeholders ) . '%';
|
||||
$this->_placeholders[ $placeholder ] = $content;
|
||||
|
||||
return $placeholder;
|
||||
}
|
||||
|
||||
protected $_isXhtml = null;
|
||||
protected $_replacementHash = null;
|
||||
protected $_placeholders = array();
|
||||
protected $_cssMinifier = null;
|
||||
protected $_jsMinifier = null;
|
||||
|
||||
protected function _removePreCB( $m ) {
|
||||
return $this->_reservePlace( "<pre{$m[1]}" );
|
||||
}
|
||||
|
||||
protected function _removeTextareaCB( $m ) {
|
||||
return $this->_reservePlace( "<textarea{$m[1]}" );
|
||||
}
|
||||
|
||||
protected function _removeStyleCB( $m ) {
|
||||
$openStyle = "<style{$m[1]}";
|
||||
$css = $m[2];
|
||||
// remove HTML comments
|
||||
$css = preg_replace( '/(?:^\\s*<!--|-->\\s*$)/', '', $css );
|
||||
|
||||
// remove CDATA section markers
|
||||
$css = $this->_removeCdata( $css );
|
||||
|
||||
// minify
|
||||
$minifier = $this->_cssMinifier
|
||||
? $this->_cssMinifier
|
||||
: 'trim';
|
||||
$css = call_user_func( $minifier, $css );
|
||||
|
||||
return $this->_reservePlace(
|
||||
$this->_needsCdata( $css )
|
||||
? "{$openStyle}/*<![CDATA[*/{$css}/*]]>*/</style>"
|
||||
: "{$openStyle}{$css}</style>"
|
||||
);
|
||||
}
|
||||
|
||||
protected function _removeScriptCB( $m ) {
|
||||
$openScript = "<script{$m[2]}";
|
||||
$js = $m[3];
|
||||
|
||||
// whitespace surrounding? preserve at least one space
|
||||
$ws1 = ( $m[1] === '' ) ? '' : ' ';
|
||||
$ws2 = ( $m[4] === '' ) ? '' : ' ';
|
||||
|
||||
// remove HTML comments (and ending "//" if present)
|
||||
if ( $this->_jsCleanComments ) {
|
||||
$js = preg_replace( '/(?:^\\s*<!--\\s*|\\s*(?:\\/\\/)?\\s*-->\\s*$)/', '', $js );
|
||||
}
|
||||
|
||||
// remove CDATA section markers
|
||||
$js = $this->_removeCdata( $js );
|
||||
|
||||
// minify
|
||||
/**
|
||||
* Added 2nd param by LiteSpeed
|
||||
*
|
||||
* @since 2.2.3
|
||||
*/
|
||||
if ( $this->_jsMinifier ) {
|
||||
$js = call_user_func( $this->_jsMinifier, $js, trim( $m[2] ) );
|
||||
} else {
|
||||
$js = trim( $js );
|
||||
}
|
||||
|
||||
return $this->_reservePlace(
|
||||
$this->_needsCdata( $js )
|
||||
? "{$ws1}{$openScript}/*<![CDATA[*/{$js}/*]]>*/</script>{$ws2}"
|
||||
: "{$ws1}{$openScript}{$js}</script>{$ws2}"
|
||||
);
|
||||
}
|
||||
|
||||
protected function _removeCdata( $str ) {
|
||||
return ( false !== strpos( $str, '<![CDATA[' ) )
|
||||
? str_replace( array( '<![CDATA[', ']]>' ), '', $str )
|
||||
: $str;
|
||||
}
|
||||
|
||||
protected function _needsCdata( $str ) {
|
||||
return ( $this->_isXhtml && preg_match( '/(?:[<&]|\\-\\-|\\]\\]>)/', $str ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
// phpcs:ignoreFile
|
||||
|
||||
/**
|
||||
* Plugin Name: LiteSpeed Cache - Object Cache (Drop-in)
|
||||
* Plugin URI: https://www.litespeedtech.com/products/cache-plugins/wordpress-acceleration
|
||||
* Description: High-performance page caching and site optimization from LiteSpeed.
|
||||
* Author: LiteSpeed Technologies
|
||||
* Author URI: https://www.litespeedtech.com
|
||||
*/
|
||||
|
||||
defined( 'WPINC' ) || exit;
|
||||
/**
|
||||
* LiteSpeed Object Cache
|
||||
*
|
||||
* @since 1.8
|
||||
*/
|
||||
|
||||
! defined( 'LSCWP_OBJECT_CACHE' ) && define( 'LSCWP_OBJECT_CACHE', true );
|
||||
|
||||
// Initialize const `LSCWP_DIR` and locate LSCWP plugin folder
|
||||
$lscwp_dir = ( defined( 'WP_PLUGIN_DIR' ) ? WP_PLUGIN_DIR : WP_CONTENT_DIR . '/plugins' ) . '/litespeed-cache/';
|
||||
|
||||
// Use plugin as higher priority than MU plugin
|
||||
if ( ! file_exists( $lscwp_dir . 'litespeed-cache.php' ) ) {
|
||||
// Check if is mu plugin or not
|
||||
$lscwp_dir = ( defined( 'WPMU_PLUGIN_DIR' ) ? WPMU_PLUGIN_DIR : WP_CONTENT_DIR . '/mu-plugins' ) . '/litespeed-cache/';
|
||||
if ( ! file_exists( $lscwp_dir . 'litespeed-cache.php' ) ) {
|
||||
$lscwp_dir = '';
|
||||
}
|
||||
}
|
||||
|
||||
$data_file = WP_CONTENT_DIR . '/.litespeed_conf.dat';
|
||||
$lib_file = $lscwp_dir . 'src/object.lib.php';
|
||||
|
||||
// Can't find LSCWP location, terminate object cache process
|
||||
if ( ! $lscwp_dir || ! file_exists( $data_file ) || ( ! file_exists( $lib_file ) ) ) {
|
||||
if ( ! is_admin() ) { // Bypass object cache for frontend
|
||||
require_once ABSPATH . WPINC . '/cache.php';
|
||||
} else {
|
||||
$err = 'Can NOT find LSCWP path for object cache initialization in ' . __FILE__;
|
||||
error_log( $err );
|
||||
add_action(
|
||||
is_network_admin() ? 'network_admin_notices' : 'admin_notices',
|
||||
function () use ( &$err ) {
|
||||
echo $err;
|
||||
}
|
||||
);
|
||||
}
|
||||
} elseif ( ! LSCWP_OBJECT_CACHE ) {
|
||||
// Disable cache
|
||||
wp_using_ext_object_cache( false );
|
||||
}
|
||||
// Init object cache & LSCWP
|
||||
elseif ( file_exists( $lib_file ) ) {
|
||||
require_once $lib_file;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
<?php
|
||||
// phpcs:ignoreFile
|
||||
/**
|
||||
* LiteSpeed PHP compatibility functions for lower PHP version
|
||||
*
|
||||
* @since 1.1.3
|
||||
* @package LiteSpeed
|
||||
* @subpackage LiteSpeed_Cache/lib
|
||||
*/
|
||||
|
||||
defined( 'WPINC' ) || exit;
|
||||
|
||||
|
||||
/**
|
||||
* http_build_url() compatibility
|
||||
*/
|
||||
if ( ! function_exists( 'http_build_url' ) ) {
|
||||
if ( ! defined( 'HTTP_URL_REPLACE' ) ) {
|
||||
define( 'HTTP_URL_REPLACE', 1 ); // Replace every part of the first URL when there's one of the second URL
|
||||
}
|
||||
if ( ! defined( 'HTTP_URL_JOIN_PATH' ) ) {
|
||||
define( 'HTTP_URL_JOIN_PATH', 2 ); // Join relative paths
|
||||
}
|
||||
if ( ! defined( 'HTTP_URL_JOIN_QUERY' ) ) {
|
||||
define( 'HTTP_URL_JOIN_QUERY', 4 ); // Join query strings
|
||||
}
|
||||
if ( ! defined( 'HTTP_URL_STRIP_USER' ) ) {
|
||||
define( 'HTTP_URL_STRIP_USER', 8 ); // Strip any user authentication information
|
||||
}
|
||||
if ( ! defined( 'HTTP_URL_STRIP_PASS' ) ) {
|
||||
define( 'HTTP_URL_STRIP_PASS', 16 ); // Strip any password authentication information
|
||||
}
|
||||
if ( ! defined( 'HTTP_URL_STRIP_AUTH' ) ) {
|
||||
define( 'HTTP_URL_STRIP_AUTH', 32 ); // Strip any authentication information
|
||||
}
|
||||
if ( ! defined( 'HTTP_URL_STRIP_PORT' ) ) {
|
||||
define( 'HTTP_URL_STRIP_PORT', 64 ); // Strip explicit port numbers
|
||||
}
|
||||
if ( ! defined( 'HTTP_URL_STRIP_PATH' ) ) {
|
||||
define( 'HTTP_URL_STRIP_PATH', 128 ); // Strip complete path
|
||||
}
|
||||
if ( ! defined( 'HTTP_URL_STRIP_QUERY' ) ) {
|
||||
define( 'HTTP_URL_STRIP_QUERY', 256 ); // Strip query string
|
||||
}
|
||||
if ( ! defined( 'HTTP_URL_STRIP_FRAGMENT' ) ) {
|
||||
define( 'HTTP_URL_STRIP_FRAGMENT', 512 ); // Strip any fragments (#identifier)
|
||||
}
|
||||
if ( ! defined( 'HTTP_URL_STRIP_ALL' ) ) {
|
||||
define( 'HTTP_URL_STRIP_ALL', 1024 ); // Strip anything but scheme and host
|
||||
}
|
||||
|
||||
// Build an URL
|
||||
// The parts of the second URL will be merged into the first according to the flags argument.
|
||||
//
|
||||
// @param mixed (Part(s) of) an URL in form of a string or associative array like parse_url() returns
|
||||
// @param mixed Same as the first argument
|
||||
// @param int A bitmask of binary or'ed HTTP_URL constants (Optional)HTTP_URL_REPLACE is the default
|
||||
// @param array If set, it will be filled with the parts of the composed url like parse_url() would return
|
||||
function http_build_url( $url, $parts = array(), $flags = HTTP_URL_REPLACE, &$new_url = false ) {
|
||||
$keys = array( 'user', 'pass', 'port', 'path', 'query', 'fragment' );
|
||||
|
||||
// HTTP_URL_STRIP_ALL becomes all the HTTP_URL_STRIP_Xs
|
||||
if ( $flags & HTTP_URL_STRIP_ALL ) {
|
||||
$flags |= HTTP_URL_STRIP_USER;
|
||||
$flags |= HTTP_URL_STRIP_PASS;
|
||||
$flags |= HTTP_URL_STRIP_PORT;
|
||||
$flags |= HTTP_URL_STRIP_PATH;
|
||||
$flags |= HTTP_URL_STRIP_QUERY;
|
||||
$flags |= HTTP_URL_STRIP_FRAGMENT;
|
||||
}
|
||||
// HTTP_URL_STRIP_AUTH becomes HTTP_URL_STRIP_USER and HTTP_URL_STRIP_PASS
|
||||
elseif ( $flags & HTTP_URL_STRIP_AUTH ) {
|
||||
$flags |= HTTP_URL_STRIP_USER;
|
||||
$flags |= HTTP_URL_STRIP_PASS;
|
||||
}
|
||||
|
||||
// Parse the original URL
|
||||
// - Suggestion by Sayed Ahad Abbas
|
||||
// In case you send a parse_url array as input
|
||||
$parse_url = ! is_array( $url ) ? parse_url( $url ) : $url;
|
||||
|
||||
// Scheme and Host are always replaced
|
||||
if ( isset( $parts['scheme'] ) ) {
|
||||
$parse_url['scheme'] = $parts['scheme'];
|
||||
}
|
||||
if ( isset( $parts['host'] ) ) {
|
||||
$parse_url['host'] = $parts['host'];
|
||||
}
|
||||
|
||||
// (If applicable) Replace the original URL with it's new parts
|
||||
if ( $flags & HTTP_URL_REPLACE ) {
|
||||
foreach ( $keys as $key ) {
|
||||
if ( isset( $parts[ $key ] ) ) {
|
||||
$parse_url[ $key ] = $parts[ $key ];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Join the original URL path with the new path
|
||||
if ( isset( $parts['path'] ) && ( $flags & HTTP_URL_JOIN_PATH ) ) {
|
||||
if ( isset( $parse_url['path'] ) ) {
|
||||
$parse_url['path'] = rtrim( str_replace( basename( $parse_url['path'] ), '', $parse_url['path'] ), '/' ) . '/' . ltrim( $parts['path'], '/' );
|
||||
} else {
|
||||
$parse_url['path'] = $parts['path'];
|
||||
}
|
||||
}
|
||||
|
||||
// Join the original query string with the new query string
|
||||
if ( isset( $parts['query'] ) && ( $flags & HTTP_URL_JOIN_QUERY ) ) {
|
||||
if ( isset( $parse_url['query'] ) ) {
|
||||
$parse_url['query'] .= '&' . $parts['query'];
|
||||
} else {
|
||||
$parse_url['query'] = $parts['query'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Strips all the applicable sections of the URL
|
||||
// Note: Scheme and Host are never stripped
|
||||
foreach ( $keys as $key ) {
|
||||
if ( $flags & (int) constant( 'HTTP_URL_STRIP_' . strtoupper( $key ) ) ) {
|
||||
unset( $parse_url[ $key ] );
|
||||
}
|
||||
}
|
||||
|
||||
$new_url = $parse_url;
|
||||
|
||||
return ( isset( $parse_url['scheme'] ) ? $parse_url['scheme'] . '://' : '' )
|
||||
. ( isset( $parse_url['user'] ) ? $parse_url['user'] . ( isset( $parse_url['pass'] ) ? ':' . $parse_url['pass'] : '' ) . '@' : '' )
|
||||
. ( isset( $parse_url['host'] ) ? $parse_url['host'] : '' )
|
||||
. ( isset( $parse_url['port'] ) ? ':' . $parse_url['port'] : '' )
|
||||
. ( isset( $parse_url['path'] ) ? $parse_url['path'] : '' )
|
||||
. ( isset( $parse_url['query'] ) ? '?' . $parse_url['query'] : '' )
|
||||
. ( isset( $parse_url['fragment'] ) ? '#' . $parse_url['fragment'] : '' );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if ( ! function_exists( 'array_key_first' ) ) {
|
||||
function array_key_first( array $arr ) {
|
||||
foreach ( $arr as $k => $unused ) {
|
||||
return $k;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! function_exists( 'array_column' ) ) {
|
||||
function array_column( $array, $column_name ) {
|
||||
return array_map(
|
||||
function ( $element ) use ( $column_name ) {
|
||||
return $element[ $column_name ];
|
||||
},
|
||||
$array
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
<?php
|
||||
// phpcs:ignoreFile
|
||||
/**
|
||||
* Rewrite file-relative URIs as root-relative in CSS files
|
||||
*
|
||||
* @package Minify
|
||||
* @author Stephen Clay <steve@mrclay.org>
|
||||
*/
|
||||
|
||||
namespace LiteSpeed\Lib;
|
||||
|
||||
defined( 'WPINC' ) || exit;
|
||||
|
||||
class UriRewriter {
|
||||
|
||||
|
||||
/**
|
||||
* rewrite() and rewriteRelative() append debugging information here
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public static $debugText = '';
|
||||
|
||||
/**
|
||||
* In CSS content, rewrite file relative URIs as root relative
|
||||
*
|
||||
* @param string $css
|
||||
*
|
||||
* @param string $currentDir The directory of the current CSS file.
|
||||
*
|
||||
* @param string $docRoot The document root of the web site in which
|
||||
* the CSS file resides (default = $_SERVER['DOCUMENT_ROOT']).
|
||||
*
|
||||
* @param array $symlinks (default = array()) If the CSS file is stored in
|
||||
* a symlink-ed directory, provide an array of link paths to
|
||||
* target paths, where the link paths are within the document root. Because
|
||||
* paths need to be normalized for this to work, use "//" to substitute
|
||||
* the doc root in the link paths (the array keys). E.g.:
|
||||
* <code>
|
||||
* array('//symlink' => '/real/target/path') // unix
|
||||
* array('//static' => 'D:\\staticStorage') // Windows
|
||||
* </code>
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function rewrite( $css, $currentDir, $docRoot = null, $symlinks = array() ) {
|
||||
self::$_docRoot = self::_realpath(
|
||||
$docRoot ? $docRoot : $_SERVER['DOCUMENT_ROOT']
|
||||
);
|
||||
self::$_currentDir = self::_realpath( $currentDir );
|
||||
self::$_symlinks = array();
|
||||
|
||||
// normalize symlinks in order to map to link
|
||||
foreach ( $symlinks as $link => $target ) {
|
||||
$link = ( $link === '//' ) ? self::$_docRoot : str_replace( '//', self::$_docRoot . '/', $link );
|
||||
$link = strtr( $link, '/', DIRECTORY_SEPARATOR );
|
||||
|
||||
self::$_symlinks[ $link ] = self::_realpath( $target );
|
||||
}
|
||||
|
||||
self::$debugText .= 'docRoot : ' . self::$_docRoot . "\n"
|
||||
. 'currentDir : ' . self::$_currentDir . "\n";
|
||||
if ( self::$_symlinks ) {
|
||||
self::$debugText .= 'symlinks : ' . var_export( self::$_symlinks, 1 ) . "\n";
|
||||
}
|
||||
self::$debugText .= "\n";
|
||||
|
||||
$css = self::_trimUrls( $css );
|
||||
|
||||
$css = self::_owlifySvgPaths( $css );
|
||||
|
||||
// rewrite
|
||||
$pattern = '/@import\\s+([\'"])(.*?)[\'"]/';
|
||||
$css = preg_replace_callback( $pattern, __CLASS__ . '::_processUriCB', $css );
|
||||
|
||||
$pattern = '/url\\(\\s*([\'"](.*?)[\'"]|[^\\)\\s]+)\\s*\\)/';
|
||||
$css = preg_replace_callback( $pattern, __CLASS__ . '::_processUriCB', $css );
|
||||
|
||||
$css = self::_unOwlify( $css );
|
||||
|
||||
return $css;
|
||||
}
|
||||
|
||||
/**
|
||||
* In CSS content, prepend a path to relative URIs
|
||||
*
|
||||
* @param string $css
|
||||
*
|
||||
* @param string $path The path to prepend.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function prepend( $css, $path ) {
|
||||
self::$_prependPath = $path;
|
||||
|
||||
$css = self::_trimUrls( $css );
|
||||
|
||||
$css = self::_owlifySvgPaths( $css );
|
||||
|
||||
// append
|
||||
$pattern = '/@import\\s+([\'"])(.*?)[\'"]/';
|
||||
$css = preg_replace_callback( $pattern, __CLASS__ . '::_processUriCB', $css );
|
||||
|
||||
$pattern = '/url\\(\\s*([\'"](.*?)[\'"]|[^\\)\\s]+)\\s*\\)/';
|
||||
$css = preg_replace_callback( $pattern, __CLASS__ . '::_processUriCB', $css );
|
||||
|
||||
$css = self::_unOwlify( $css );
|
||||
|
||||
self::$_prependPath = null;
|
||||
|
||||
return $css;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a root relative URI from a file relative URI
|
||||
*
|
||||
* <code>
|
||||
* UriRewriter::rewriteRelative(
|
||||
* '../img/hello.gif'
|
||||
* , '/home/user/www/css' // path of CSS file
|
||||
* , '/home/user/www' // doc root
|
||||
* );
|
||||
* // returns '/img/hello.gif'
|
||||
*
|
||||
* // example where static files are stored in a symlinked directory
|
||||
* UriRewriter::rewriteRelative(
|
||||
* 'hello.gif'
|
||||
* , '/var/staticFiles/theme'
|
||||
* , '/home/user/www'
|
||||
* , array('/home/user/www/static' => '/var/staticFiles')
|
||||
* );
|
||||
* // returns '/static/theme/hello.gif'
|
||||
* </code>
|
||||
*
|
||||
* @param string $uri file relative URI
|
||||
*
|
||||
* @param string $realCurrentDir realpath of the current file's directory.
|
||||
*
|
||||
* @param string $realDocRoot realpath of the site document root.
|
||||
*
|
||||
* @param array $symlinks (default = array()) If the file is stored in
|
||||
* a symlink-ed directory, provide an array of link paths to
|
||||
* real target paths, where the link paths "appear" to be within the document
|
||||
* root. E.g.:
|
||||
* <code>
|
||||
* array('/home/foo/www/not/real/path' => '/real/target/path') // unix
|
||||
* array('C:\\htdocs\\not\\real' => 'D:\\real\\target\\path') // Windows
|
||||
* </code>
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function rewriteRelative( $uri, $realCurrentDir, $realDocRoot, $symlinks = array() ) {
|
||||
// prepend path with current dir separator (OS-independent)
|
||||
$path = strtr( $realCurrentDir, '/', DIRECTORY_SEPARATOR );
|
||||
$path .= DIRECTORY_SEPARATOR . strtr( $uri, '/', DIRECTORY_SEPARATOR );
|
||||
|
||||
self::$debugText .= "file-relative URI : {$uri}\n"
|
||||
. "path prepended : {$path}\n";
|
||||
|
||||
// "unresolve" a symlink back to doc root
|
||||
foreach ( $symlinks as $link => $target ) {
|
||||
if ( 0 === strpos( $path, $target ) ) {
|
||||
// replace $target with $link
|
||||
$path = $link . substr( $path, strlen( $target ) );
|
||||
|
||||
self::$debugText .= "symlink unresolved : {$path}\n";
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
// strip doc root
|
||||
$path = substr( $path, strlen( $realDocRoot ) );
|
||||
|
||||
self::$debugText .= "docroot stripped : {$path}\n";
|
||||
|
||||
// fix to root-relative URI
|
||||
$uri = strtr( $path, '/\\', '//' );
|
||||
$uri = self::removeDots( $uri );
|
||||
|
||||
self::$debugText .= "traversals removed : {$uri}\n\n";
|
||||
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove instances of "./" and "../" where possible from a root-relative URI
|
||||
*
|
||||
* @param string $uri
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function removeDots( $uri ) {
|
||||
$uri = str_replace( '/./', '/', $uri );
|
||||
// inspired by patch from Oleg Cherniy
|
||||
do {
|
||||
$uri = preg_replace( '@/[^/]+/\\.\\./@', '/', $uri, 1, $changed );
|
||||
} while ( $changed );
|
||||
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get realpath with any trailing slash removed. If realpath() fails,
|
||||
* just remove the trailing slash.
|
||||
*
|
||||
* @param string $path
|
||||
*
|
||||
* @return mixed path with no trailing slash
|
||||
*/
|
||||
protected static function _realpath( $path ) {
|
||||
$realPath = realpath( $path );
|
||||
if ( $realPath !== false ) {
|
||||
$path = $realPath;
|
||||
}
|
||||
|
||||
return rtrim( $path, '/\\' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Directory of this stylesheet
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private static $_currentDir = '';
|
||||
|
||||
/**
|
||||
* DOC_ROOT
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private static $_docRoot = '';
|
||||
|
||||
/**
|
||||
* directory replacements to map symlink targets back to their
|
||||
* source (within the document root) E.g. '/var/www/symlink' => '/var/realpath'
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private static $_symlinks = array();
|
||||
|
||||
/**
|
||||
* Path to prepend
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private static $_prependPath = null;
|
||||
|
||||
/**
|
||||
* @param string $css
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private static function _trimUrls( $css ) {
|
||||
$pattern = '/
|
||||
url\\( # url(
|
||||
\\s*
|
||||
([^\\)]+?) # 1 = URI (assuming does not contain ")")
|
||||
\\s*
|
||||
\\) # )
|
||||
/x';
|
||||
|
||||
return preg_replace( $pattern, 'url($1)', $css );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $m
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private static function _processUriCB( $m ) {
|
||||
// $m matched either '/@import\\s+([\'"])(.*?)[\'"]/' or '/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
|
||||
$isImport = ( $m[0][0] === '@' );
|
||||
// determine URI and the quote character (if any)
|
||||
if ( $isImport ) {
|
||||
$quoteChar = $m[1];
|
||||
$uri = $m[2];
|
||||
} else {
|
||||
// $m[1] is either quoted or not
|
||||
$quoteChar = ( $m[1][0] === "'" || $m[1][0] === '"' ) ? $m[1][0] : '';
|
||||
|
||||
$uri = ( $quoteChar === '' ) ? $m[1] : substr( $m[1], 1, strlen( $m[1] ) - 2 );
|
||||
}
|
||||
|
||||
if ( $uri === '' ) {
|
||||
return $m[0];
|
||||
}
|
||||
|
||||
// if not anchor id, not root/scheme relative, and not starts with scheme
|
||||
if ( ! preg_match( '~^(#|/|[a-z]+\:)~', $uri ) ) {
|
||||
// URI is file-relative: rewrite depending on options
|
||||
if ( self::$_prependPath === null ) {
|
||||
$uri = self::rewriteRelative( $uri, self::$_currentDir, self::$_docRoot, self::$_symlinks );
|
||||
} else {
|
||||
$uri = self::$_prependPath . $uri;
|
||||
if ( $uri[0] === '/' ) {
|
||||
$root = '';
|
||||
$rootRelative = $uri;
|
||||
$uri = $root . self::removeDots( $rootRelative );
|
||||
} elseif ( preg_match( '@^((https?\:)?//([^/]+))/@', $uri, $m ) && ( false !== strpos( $m[3], '.' ) ) ) {
|
||||
$root = $m[1];
|
||||
$rootRelative = substr( $uri, strlen( $root ) );
|
||||
$uri = $root . self::removeDots( $rootRelative );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( $isImport ) {
|
||||
return "@import {$quoteChar}{$uri}{$quoteChar}";
|
||||
} else {
|
||||
return "url({$quoteChar}{$uri}{$quoteChar})";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mungs some inline SVG URL declarations so they won't be touched
|
||||
*
|
||||
* @link https://github.com/mrclay/minify/issues/517
|
||||
* @see _unOwlify
|
||||
*
|
||||
* @param string $css
|
||||
* @return string
|
||||
*/
|
||||
private static function _owlifySvgPaths( $css ) {
|
||||
$pattern = '~\b((?:clip-path|mask|-webkit-mask)\s*\:\s*)url(\(\s*#\w+\s*\))~';
|
||||
|
||||
return preg_replace( $pattern, '$1owl$2', $css );
|
||||
}
|
||||
|
||||
/**
|
||||
* Undo work of _owlify
|
||||
*
|
||||
* @see _owlifySvgPaths
|
||||
*
|
||||
* @param string $css
|
||||
* @return string
|
||||
*/
|
||||
private static function _unOwlify( $css ) {
|
||||
$pattern = '~\b((?:clip-path|mask|-webkit-mask)\s*\:\s*)owl~';
|
||||
|
||||
return preg_replace( $pattern, '$1url', $css );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user