add wp-rocket
This commit is contained in:
752
wp-content/plugins/wp-rocket/inc/Dependencies/Minify/CSS.php
Normal file
752
wp-content/plugins/wp-rocket/inc/Dependencies/Minify/CSS.php
Normal file
@@ -0,0 +1,752 @@
|
||||
<?php
|
||||
/**
|
||||
* CSS Minifier
|
||||
*
|
||||
* Please report bugs on https://github.com/matthiasmullie/minify/issues
|
||||
*
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
namespace WP_Rocket\Dependencies\Minify;
|
||||
|
||||
use WP_Rocket\Dependencies\Minify\Exceptions\FileImportException;
|
||||
use WP_Rocket\Dependencies\PathConverter\ConverterInterface;
|
||||
use WP_Rocket\Dependencies\PathConverter\Converter;
|
||||
|
||||
/**
|
||||
* CSS minifier
|
||||
*
|
||||
* Please report bugs on https://github.com/matthiasmullie/minify/issues
|
||||
*
|
||||
* @package Minify
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
* @author Tijs Verkoyen <minify@verkoyen.eu>
|
||||
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
class CSS extends Minify
|
||||
{
|
||||
/**
|
||||
* @var int maximum inport 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',
|
||||
'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
|
||||
*/
|
||||
protected 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 static($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-ized.
|
||||
*
|
||||
* @url(image.jpg) images 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->extractCalcs();
|
||||
$css = $this->replace($css);
|
||||
|
||||
$css = $this->stripWhitespace($css);
|
||||
$css = $this->shortenColors($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.
|
||||
* #FF0000 -> #F00.
|
||||
*
|
||||
* @param string $content The CSS content to shorten the hex color codes for
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function shortenColors($content)
|
||||
{
|
||||
$content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?:([0-9a-z])\\4)?(?=[; }])/i', '#$1$2$3$4', $content);
|
||||
|
||||
// remove alpha channel if it's pointless...
|
||||
$content = preg_replace('/(?<=[: ])#([0-9a-z]{6})ff?(?=[; }])/i', '#$1', $content);
|
||||
$content = preg_replace('/(?<=[: ])#([0-9a-z]{3})f?(?=[; }])/i', '#$1', $content);
|
||||
|
||||
$colors = array(
|
||||
// we can shorten some even more by replacing them with their color name
|
||||
'#F0FFFF' => 'azure',
|
||||
'#F5F5DC' => 'beige',
|
||||
'#A52A2A' => 'brown',
|
||||
'#FF7F50' => 'coral',
|
||||
'#FFD700' => 'gold',
|
||||
'#808080' => 'gray',
|
||||
'#008000' => 'green',
|
||||
'#4B0082' => 'indigo',
|
||||
'#FFFFF0' => 'ivory',
|
||||
'#F0E68C' => 'khaki',
|
||||
'#FAF0E6' => 'linen',
|
||||
'#800000' => 'maroon',
|
||||
'#000080' => 'navy',
|
||||
'#808000' => 'olive',
|
||||
'#CD853F' => 'peru',
|
||||
'#FFC0CB' => 'pink',
|
||||
'#DDA0DD' => 'plum',
|
||||
'#800080' => 'purple',
|
||||
'#F00' => 'red',
|
||||
'#FA8072' => 'salmon',
|
||||
'#A0522D' => 'sienna',
|
||||
'#C0C0C0' => 'silver',
|
||||
'#FFFAFA' => 'snow',
|
||||
'#D2B48C' => 'tan',
|
||||
'#FF6347' => 'tomato',
|
||||
'#EE82EE' => 'violet',
|
||||
'#F5DEB3' => 'wheat',
|
||||
// or the other way around
|
||||
'WHITE' => '#fff',
|
||||
'BLACK' => '#000',
|
||||
);
|
||||
|
||||
return preg_replace_callback(
|
||||
'/(?<=[: ])('.implode('|', array_keys($colors)).')(?=[; }])/i',
|
||||
function ($match) use ($colors) {
|
||||
return $colors[strtoupper($match[0])];
|
||||
},
|
||||
$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()
|
||||
{
|
||||
// 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('/\n?\/\*(!|.*?@license|.*?@preserve).*?\*\/\n?/s', $callback);
|
||||
|
||||
$this->registerPattern('/\/\*.*?\*\//s', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 `calc()` occurrences.
|
||||
*/
|
||||
protected function extractCalcs()
|
||||
{
|
||||
// PHP only supports $this inside anonymous functions since 5.4
|
||||
$minifier = $this;
|
||||
$callback = function ($match) use ($minifier) {
|
||||
$length = strlen($match[1]);
|
||||
$expr = '';
|
||||
$opened = 0;
|
||||
|
||||
for ($i = 0; $i < $length; $i++) {
|
||||
$char = $match[1][$i];
|
||||
$expr .= $char;
|
||||
if ($char === '(') {
|
||||
$opened++;
|
||||
} elseif ($char === ')' && --$opened === 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$rest = str_replace($expr, '', $match[1]);
|
||||
$expr = trim(substr($expr, 1, -1));
|
||||
|
||||
$count = count($minifier->extracted);
|
||||
$placeholder = 'calc('.$count.')';
|
||||
$minifier->extracted[$placeholder] = 'calc('.$expr.')';
|
||||
|
||||
return $placeholder.$rest;
|
||||
};
|
||||
|
||||
$this->registerPattern('/calc(\(.+?)(?=$|;|}|calc\()/', $callback);
|
||||
$this->registerPattern('/calc(\(.+?)(?=$|;|}|calc\()/m', $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,20 @@
|
||||
<?php
|
||||
/**
|
||||
* Base Exception
|
||||
*
|
||||
* @deprecated Use Exceptions\BasicException instead
|
||||
*
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
*/
|
||||
namespace WP_Rocket\Dependencies\Minify;
|
||||
|
||||
/**
|
||||
* Base Exception Class
|
||||
* @deprecated Use Exceptions\BasicException instead
|
||||
*
|
||||
* @package Minify
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
*/
|
||||
abstract class Exception extends \Exception
|
||||
{
|
||||
}
|
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
/**
|
||||
* Basic exception
|
||||
*
|
||||
* Please report bugs on https://github.com/matthiasmullie/minify/issues
|
||||
*
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
namespace WP_Rocket\Dependencies\Minify\Exceptions;
|
||||
|
||||
use WP_Rocket\Dependencies\Minify\Exception;
|
||||
|
||||
/**
|
||||
* Basic Exception Class
|
||||
*
|
||||
* @package Minify\Exception
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
*/
|
||||
abstract class BasicException extends Exception
|
||||
{
|
||||
}
|
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
/**
|
||||
* File Import Exception
|
||||
*
|
||||
* Please report bugs on https://github.com/matthiasmullie/minify/issues
|
||||
*
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
namespace WP_Rocket\Dependencies\Minify\Exceptions;
|
||||
|
||||
/**
|
||||
* File Import Exception Class
|
||||
*
|
||||
* @package Minify\Exception
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
*/
|
||||
class FileImportException extends BasicException
|
||||
{
|
||||
}
|
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
/**
|
||||
* IO Exception
|
||||
*
|
||||
* Please report bugs on https://github.com/matthiasmullie/minify/issues
|
||||
*
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
namespace WP_Rocket\Dependencies\Minify\Exceptions;
|
||||
|
||||
/**
|
||||
* IO Exception Class
|
||||
*
|
||||
* @package Minify\Exception
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
*/
|
||||
class IOException extends BasicException
|
||||
{
|
||||
}
|
612
wp-content/plugins/wp-rocket/inc/Dependencies/Minify/JS.php
Normal file
612
wp-content/plugins/wp-rocket/inc/Dependencies/Minify/JS.php
Normal file
File diff suppressed because one or more lines are too long
497
wp-content/plugins/wp-rocket/inc/Dependencies/Minify/Minify.php
Normal file
497
wp-content/plugins/wp-rocket/inc/Dependencies/Minify/Minify.php
Normal file
@@ -0,0 +1,497 @@
|
||||
<?php
|
||||
/**
|
||||
* Abstract minifier class
|
||||
*
|
||||
* Please report bugs on https://github.com/matthiasmullie/minify/issues
|
||||
*
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
namespace WP_Rocket\Dependencies\Minify;
|
||||
|
||||
use WP_Rocket\Dependencies\Minify\Exceptions\IOException;
|
||||
use Psr\Cache\CacheItemInterface;
|
||||
|
||||
/**
|
||||
* Abstract minifier class.
|
||||
*
|
||||
* Please report bugs on https://github.com/matthiasmullie/minify/issues
|
||||
*
|
||||
* @package Minify
|
||||
* @author Matthias Mullie <minify@mullie.eu>
|
||||
* @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* @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 & write it to a CacheItemInterface object.
|
||||
*
|
||||
* @param CacheItemInterface $item Cache item to write the data to
|
||||
*
|
||||
* @return CacheItemInterface Cache item with the minifier data
|
||||
*/
|
||||
public function cache(CacheItemInterface $item)
|
||||
{
|
||||
$content = $this->execute();
|
||||
$item->set($content);
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
{
|
||||
$processed = '';
|
||||
$positions = array_fill(0, count($this->patterns), -1);
|
||||
$matches = array();
|
||||
|
||||
while ($content) {
|
||||
// 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] >= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$match = null;
|
||||
if (preg_match($pattern, $content, $match, PREG_OFFSET_CAPTURE)) {
|
||||
$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) {
|
||||
$processed .= $content;
|
||||
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)
|
||||
$discardLength = min($positions);
|
||||
$firstPattern = array_search($discardLength, $positions);
|
||||
$match = $matches[$firstPattern][0][0];
|
||||
|
||||
// execute the pattern that matches earliest in the content string
|
||||
list($pattern, $replacement) = $this->patterns[$firstPattern];
|
||||
$replacement = $this->replacePattern($pattern, $replacement, $content);
|
||||
|
||||
// figure out which part of the string was unmatched; that's the
|
||||
// part we'll execute the patterns on again next
|
||||
$content = (string) substr($content, $discardLength);
|
||||
$unmatched = (string) substr($content, strpos($content, $match) + strlen($match));
|
||||
|
||||
// move the replaced part to $processed and prepare $content to
|
||||
// again match batch of patterns against
|
||||
$processed .= substr($replacement, 0, strlen($replacement) - strlen($unmatched));
|
||||
$content = $unmatched;
|
||||
|
||||
// first match has been replaced & that content is to be left alone,
|
||||
// the next matches will start after this replacement, so we should
|
||||
// fix their offsets
|
||||
foreach ($positions as $i => $position) {
|
||||
$positions[$i] -= $discardLength + strlen($match);
|
||||
}
|
||||
}
|
||||
|
||||
return $processed;
|
||||
}
|
||||
|
||||
/**
|
||||
* This is where a pattern is matched against $content and the matches
|
||||
* are replaced by their respective value.
|
||||
* This function will be called plenty of times, where $content will always
|
||||
* move up 1 character.
|
||||
*
|
||||
* @param string $pattern Pattern to match
|
||||
* @param string|callable $replacement Replacement value
|
||||
* @param string $content Content to match pattern against
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function replacePattern($pattern, $replacement, $content)
|
||||
{
|
||||
if (is_callable($replacement)) {
|
||||
return preg_replace_callback($pattern, $replacement, $content, 1, $count);
|
||||
} else {
|
||||
return preg_replace($pattern, $replacement, $content, 1, $count);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
return strlen($path) < PHP_MAXPATHLEN && @is_file($path) && is_readable($path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 (($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 (($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.');
|
||||
}
|
||||
}
|
||||
}
|
@@ -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,204 @@
|
||||
<?php
|
||||
|
||||
namespace WP_Rocket\Dependencies\PathConverter;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* Please report bugs on https://github.com/matthiasmullie/path-converter/issues
|
||||
*
|
||||
* @author Matthias Mullie <pathconverter@mullie.eu>
|
||||
* @copyright Copyright (c) 2015, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace WP_Rocket\Dependencies\PathConverter;
|
||||
|
||||
/**
|
||||
* Convert file paths.
|
||||
*
|
||||
* Please report bugs on https://github.com/matthiasmullie/path-converter/issues
|
||||
*
|
||||
* @author Matthias Mullie <pathconverter@mullie.eu>
|
||||
* @copyright Copyright (c) 2015, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
interface ConverterInterface
|
||||
{
|
||||
/**
|
||||
* Convert file paths.
|
||||
*
|
||||
* @param string $path The path to be converted
|
||||
*
|
||||
* @return string The new path
|
||||
*/
|
||||
public function convert($path);
|
||||
}
|
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace WP_Rocket\Dependencies\PathConverter;
|
||||
|
||||
/**
|
||||
* Don't convert paths.
|
||||
*
|
||||
* Please report bugs on https://github.com/matthiasmullie/path-converter/issues
|
||||
*
|
||||
* @author Matthias Mullie <pathconverter@mullie.eu>
|
||||
* @copyright Copyright (c) 2015, Matthias Mullie. All rights reserved
|
||||
* @license MIT License
|
||||
*/
|
||||
class NoConverter implements ConverterInterface
|
||||
{
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function convert($path)
|
||||
{
|
||||
return $path;
|
||||
}
|
||||
}
|
@@ -0,0 +1,290 @@
|
||||
<?php
|
||||
/**
|
||||
* Handle the lazyload required assets: inline CSS and JS
|
||||
*
|
||||
* @package RocketLazyload
|
||||
*/
|
||||
|
||||
namespace WP_Rocket\Dependencies\RocketLazyload;
|
||||
|
||||
/**
|
||||
* Class containing the methods to return or print the assets needed for lazyloading
|
||||
*/
|
||||
class Assets {
|
||||
|
||||
/**
|
||||
* Inserts the lazyload script in the HTML
|
||||
*
|
||||
* @param array $args Array of arguments to populate the lazyload script tag.
|
||||
* @return void
|
||||
*/
|
||||
public function insertLazyloadScript( $args = [] ) {
|
||||
echo $this->getLazyloadScript( $args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the inline lazyload script configuration
|
||||
*
|
||||
* @param array $args Array of arguments to populate the lazyload script options.
|
||||
* @return string
|
||||
*/
|
||||
public function getInlineLazyloadScript( $args = [] ) {
|
||||
$defaults = [
|
||||
'elements' => [
|
||||
'img',
|
||||
'iframe',
|
||||
],
|
||||
'threshold' => 300,
|
||||
'options' => [],
|
||||
];
|
||||
|
||||
$allowed_options = [
|
||||
'container' => 1,
|
||||
'thresholds' => 1,
|
||||
'data_bg' => 1,
|
||||
'class_error' => 1,
|
||||
'cancel_on_exit' => 1,
|
||||
'unobserve_completed' => 1,
|
||||
'callback_enter' => 1,
|
||||
'callback_exit' => 1,
|
||||
'callback_loading' => 1,
|
||||
'callback_error' => 1,
|
||||
'callback_finish' => 1,
|
||||
'use_native' => 1,
|
||||
];
|
||||
|
||||
$args = wp_parse_args( $args, $defaults );
|
||||
$script = '';
|
||||
|
||||
$args['options'] = array_intersect_key( $args['options'], $allowed_options );
|
||||
|
||||
$script .= 'window.lazyLoadOptions = {
|
||||
elements_selector: "' . esc_attr( implode( ',', $args['elements'] ) ) . '",
|
||||
data_src: "lazy-src",
|
||||
data_srcset: "lazy-srcset",
|
||||
data_sizes: "lazy-sizes",
|
||||
class_loading: "lazyloading",
|
||||
class_loaded: "lazyloaded",
|
||||
threshold: ' . esc_attr( $args['threshold'] ) . ',
|
||||
callback_loaded: function(element) {
|
||||
if ( element.tagName === "IFRAME" && element.dataset.rocketLazyload == "fitvidscompatible" ) {
|
||||
if (element.classList.contains("lazyloaded") ) {
|
||||
if (typeof window.jQuery != "undefined") {
|
||||
if (jQuery.fn.fitVids) {
|
||||
jQuery(element).parent().fitVids();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}';
|
||||
|
||||
if ( ! empty( $args['options'] ) ) {
|
||||
$script .= ',' . PHP_EOL;
|
||||
|
||||
foreach ( $args['options'] as $option => $value ) {
|
||||
$script .= $option . ': ' . $value . ',';
|
||||
}
|
||||
|
||||
$script = rtrim( $script, ',' );
|
||||
}
|
||||
|
||||
$script .= '};';
|
||||
|
||||
$script .= '
|
||||
window.addEventListener(\'LazyLoad::Initialized\', function (e) {
|
||||
var lazyLoadInstance = e.detail.instance;
|
||||
|
||||
if (window.MutationObserver) {
|
||||
var observer = new MutationObserver(function(mutations) {
|
||||
var image_count = 0;
|
||||
var iframe_count = 0;
|
||||
var rocketlazy_count = 0;
|
||||
|
||||
mutations.forEach(function(mutation) {
|
||||
for (i = 0; i < mutation.addedNodes.length; i++) {
|
||||
if (typeof mutation.addedNodes[i].getElementsByTagName !== \'function\') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof mutation.addedNodes[i].getElementsByClassName !== \'function\') {
|
||||
continue;
|
||||
}
|
||||
|
||||
images = mutation.addedNodes[i].getElementsByTagName(\'img\');
|
||||
is_image = mutation.addedNodes[i].tagName == "IMG";
|
||||
iframes = mutation.addedNodes[i].getElementsByTagName(\'iframe\');
|
||||
is_iframe = mutation.addedNodes[i].tagName == "IFRAME";
|
||||
rocket_lazy = mutation.addedNodes[i].getElementsByClassName(\'rocket-lazyload\');
|
||||
|
||||
image_count += images.length;
|
||||
iframe_count += iframes.length;
|
||||
rocketlazy_count += rocket_lazy.length;
|
||||
|
||||
if(is_image){
|
||||
image_count += 1;
|
||||
}
|
||||
|
||||
if(is_iframe){
|
||||
iframe_count += 1;
|
||||
}
|
||||
}
|
||||
} );
|
||||
|
||||
if(image_count > 0 || iframe_count > 0 || rocketlazy_count > 0){
|
||||
lazyLoadInstance.update();
|
||||
}
|
||||
} );
|
||||
|
||||
var b = document.getElementsByTagName("body")[0];
|
||||
var config = { childList: true, subtree: true };
|
||||
|
||||
observer.observe(b, config);
|
||||
}
|
||||
}, false);';
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the lazyload inline script
|
||||
*
|
||||
* @param array $args Array of arguments to populate the lazyload script options.
|
||||
* @return string
|
||||
*/
|
||||
public function getLazyloadScript( $args = [] ) {
|
||||
$defaults = [
|
||||
'base_url' => '',
|
||||
'version' => '',
|
||||
'polyfill' => false,
|
||||
];
|
||||
|
||||
$args = wp_parse_args( $args, $defaults );
|
||||
$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
|
||||
$script = '';
|
||||
|
||||
if ( isset( $args['polyfill'] ) && $args['polyfill'] ) {
|
||||
$script .= '<script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?flags=gated&features=default%2CIntersectionObserver%2CIntersectionObserverEntry"></script>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the script tag for the lazyload script
|
||||
*
|
||||
* @since 2.2.6
|
||||
*
|
||||
* @param $script_tag HTML tag for the lazyload script.
|
||||
*/
|
||||
$script .= apply_filters( 'rocket_lazyload_script_tag', '<script data-no-minify="1" async src="' . $args['base_url'] . $args['version'] . '/lazyload' . $min . '.js"></script>' );
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts in the HTML the script to replace the Youtube thumbnail by the iframe.
|
||||
*
|
||||
* @param array $args Array of arguments to populate the script options.
|
||||
* @return void
|
||||
*/
|
||||
public function insertYoutubeThumbnailScript( $args = [] ) {
|
||||
echo $this->getYoutubeThumbnailScript( $args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Youtube Thumbnail inline script
|
||||
*
|
||||
* @param array $args Array of arguments to populate the script options.
|
||||
* @return string
|
||||
*/
|
||||
public function getYoutubeThumbnailScript( $args = [] ) {
|
||||
$defaults = [
|
||||
'resolution' => 'hqdefault',
|
||||
'lazy_image' => false,
|
||||
];
|
||||
|
||||
$allowed_resolutions = [
|
||||
'default' => [
|
||||
'width' => 120,
|
||||
'height' => 90,
|
||||
],
|
||||
'mqdefault' => [
|
||||
'width' => 320,
|
||||
'height' => 180,
|
||||
],
|
||||
'hqdefault' => [
|
||||
'width' => 480,
|
||||
'height' => 360,
|
||||
],
|
||||
'sddefault' => [
|
||||
'width' => 640,
|
||||
'height' => 480,
|
||||
],
|
||||
|
||||
'maxresdefault' => [
|
||||
'width' => 1280,
|
||||
'height' => 720,
|
||||
],
|
||||
];
|
||||
|
||||
$args['resolution'] = ( isset( $args['resolution'] ) && isset( $allowed_resolutions[ $args['resolution'] ] ) ) ? $args['resolution'] : 'hqdefault';
|
||||
|
||||
$args = wp_parse_args( $args, $defaults );
|
||||
|
||||
$image = '<img src="https://i.ytimg.com/vi/ID/' . $args['resolution'] . '.jpg" alt="" width="' . $allowed_resolutions[ $args['resolution'] ]['width'] . '" height="' . $allowed_resolutions[ $args['resolution'] ]['height'] . '">';
|
||||
|
||||
if ( isset( $args['lazy_image'] ) && $args['lazy_image'] ) {
|
||||
$image = '<img loading="lazy" data-lazy-src="https://i.ytimg.com/vi/ID/' . $args['resolution'] . '.jpg" alt="" width="' . $allowed_resolutions[ $args['resolution'] ]['width'] . '" height="' . $allowed_resolutions[ $args['resolution'] ]['height'] . '"><noscript><img src="https://i.ytimg.com/vi/ID/' . $args['resolution'] . '.jpg" alt="" width="' . $allowed_resolutions[ $args['resolution'] ]['width'] . '" height="' . $allowed_resolutions[ $args['resolution'] ]['height'] . '"></noscript>';
|
||||
}
|
||||
|
||||
return "<script>function lazyLoadThumb(e){var t='{$image}',a='<div class=\"play\"></div>';return t.replace(\"ID\",e)+a}function lazyLoadYoutubeIframe(){var e=document.createElement(\"iframe\"),t=\"ID?autoplay=1\";t+=0===this.dataset.query.length?'':'&'+this.dataset.query;e.setAttribute(\"src\",t.replace(\"ID\",this.dataset.src)),e.setAttribute(\"frameborder\",\"0\"),e.setAttribute(\"allowfullscreen\",\"1\"),e.setAttribute(\"allow\", \"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\"),this.parentNode.replaceChild(e,this)}document.addEventListener(\"DOMContentLoaded\",function(){var e,t,a=document.getElementsByClassName(\"rll-youtube-player\");for(t=0;t<a.length;t++)e=document.createElement(\"div\"),e.setAttribute(\"data-id\",a[t].dataset.id),e.setAttribute(\"data-query\", a[t].dataset.query),e.setAttribute(\"data-src\", a[t].dataset.src),e.innerHTML=lazyLoadThumb(a[t].dataset.id),e.onclick=lazyLoadYoutubeIframe,a[t].appendChild(e)});</script>";
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the CSS to style the Youtube thumbnail container
|
||||
*
|
||||
* @param array $args Array of arguments to populate the CSS.
|
||||
* @return void
|
||||
*/
|
||||
public function insertYoutubeThumbnailCSS( $args = [] ) {
|
||||
wp_register_style( 'rocket-lazyload', false );
|
||||
wp_enqueue_style( 'rocket-lazyload' );
|
||||
wp_add_inline_style( 'rocket-lazyload', $this->getYoutubeThumbnailCSS( $args ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the CSS for the Youtube Thumbnail
|
||||
*
|
||||
* @param array $args Array of arguments to populate the CSS.
|
||||
* @return string
|
||||
*/
|
||||
public function getYoutubeThumbnailCSS( $args = [] ) {
|
||||
$defaults = [
|
||||
'base_url' => '',
|
||||
'responsive_embeds' => true,
|
||||
];
|
||||
|
||||
$args = wp_parse_args( $args, $defaults );
|
||||
|
||||
$css = '.rll-youtube-player{position:relative;padding-bottom:56.23%;height:0;overflow:hidden;max-width:100%;}.rll-youtube-player iframe{position:absolute;top:0;left:0;width:100%;height:100%;z-index:100;background:0 0}.rll-youtube-player img{bottom:0;display:block;left:0;margin:auto;max-width:100%;width:100%;position:absolute;right:0;top:0;border:none;height:auto;cursor:pointer;-webkit-transition:.4s all;-moz-transition:.4s all;transition:.4s all}.rll-youtube-player img:hover{-webkit-filter:brightness(75%)}.rll-youtube-player .play{height:72px;width:72px;left:50%;top:50%;margin-left:-36px;margin-top:-36px;position:absolute;background:url(' . $args['base_url'] . 'img/youtube.png) no-repeat;cursor:pointer}';
|
||||
|
||||
if ( $args['responsive_embeds'] ) {
|
||||
$css .= '.wp-has-aspect-ratio .rll-youtube-player{position:absolute;padding-bottom:0;width:100%;height:100%;top:0;bottom:0;left:0;right:0}';
|
||||
}
|
||||
|
||||
return $css;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the CSS needed when Javascript is not enabled to keep the display correct
|
||||
*/
|
||||
public function insertNoJSCSS() {
|
||||
echo $this->getNoJSCSS();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the CSS to correctly display images when JavaScript is disabled
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getNoJSCSS() {
|
||||
return '<noscript><style id="rocket-lazyload-nojs-css">.rll-youtube-player, [data-lazy-src]{display:none !important;}</style></noscript>';
|
||||
}
|
||||
}
|
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
/**
|
||||
* Handles lazyloading of iframes
|
||||
*
|
||||
* @package RocketLazyload
|
||||
*/
|
||||
|
||||
namespace WP_Rocket\Dependencies\RocketLazyload;
|
||||
|
||||
/**
|
||||
* A class to provide the methods needed to lazyload iframes in WP Rocket and Lazyload by WP Rocket
|
||||
*/
|
||||
class Iframe {
|
||||
|
||||
/**
|
||||
* Finds iframes in the HTML provided and call the methods to lazyload them
|
||||
*
|
||||
* @param string $html Original HTML.
|
||||
* @param string $buffer Content to parse.
|
||||
* @param array $args Array of arguments to use.
|
||||
* @return string
|
||||
*/
|
||||
public function lazyloadIframes( $html, $buffer, $args = [] ) {
|
||||
$defaults = [
|
||||
'youtube' => false,
|
||||
];
|
||||
|
||||
$args = wp_parse_args( $args, $defaults );
|
||||
|
||||
if ( ! preg_match_all( '@<iframe(?<atts>\s.+)>.*</iframe>@iUs', $buffer, $iframes, PREG_SET_ORDER ) ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$iframes = array_unique( $iframes, SORT_REGULAR );
|
||||
|
||||
foreach ( $iframes as $iframe ) {
|
||||
if ( $this->isIframeExcluded( $iframe ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Given the previous regex pattern, $iframe['atts'] starts with a whitespace character.
|
||||
if ( ! preg_match( '@\ssrc\s*=\s*(\'|")(?<src>.*)\1@iUs', $iframe['atts'], $atts ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$iframe['src'] = trim( $atts['src'] );
|
||||
|
||||
if ( '' === $iframe['src'] ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( $args['youtube'] ) {
|
||||
$iframe_lazyload = $this->replaceYoutubeThumbnail( $iframe );
|
||||
}
|
||||
|
||||
if ( empty( $iframe_lazyload ) ) {
|
||||
$iframe_lazyload = $this->replaceIframe( $iframe );
|
||||
}
|
||||
|
||||
$html = str_replace( $iframe[0], $iframe_lazyload, $html );
|
||||
|
||||
unset( $iframe_lazyload );
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the provided iframe is excluded from lazyload
|
||||
*
|
||||
* @param array $iframe Array of matched patterns.
|
||||
* @return boolean
|
||||
*/
|
||||
public function isIframeExcluded( $iframe ) {
|
||||
|
||||
foreach ( $this->getExcludedPatterns() as $excluded_pattern ) {
|
||||
if ( strpos( $iframe[0], $excluded_pattern ) !== false ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets patterns excluded from lazyload for iframes
|
||||
*
|
||||
* @since 2.1.1
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function getExcludedPatterns() {
|
||||
/**
|
||||
* Filters the patterns excluded from lazyload for iframes
|
||||
*
|
||||
* @since 2.1.1
|
||||
*
|
||||
* @param array $excluded_patterns Array of excluded patterns.
|
||||
*/
|
||||
return apply_filters(
|
||||
'rocket_lazyload_iframe_excluded_patterns',
|
||||
[
|
||||
'gform_ajax_frame',
|
||||
'data-no-lazy=',
|
||||
'recaptcha/api/fallback',
|
||||
'loading="eager"',
|
||||
'data-skip-lazy',
|
||||
'skip-lazy',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies lazyload on the iframe provided
|
||||
*
|
||||
* @param array $iframe Array of matched elements.
|
||||
* @return string
|
||||
*/
|
||||
private function replaceIframe( $iframe ) {
|
||||
/**
|
||||
* Filter the LazyLoad placeholder on src attribute
|
||||
*
|
||||
* @since 1.0
|
||||
*
|
||||
* @param string $placeholder placeholder that will be printed.
|
||||
*/
|
||||
$placeholder = apply_filters( 'rocket_lazyload_placeholder', 'about:blank' );
|
||||
|
||||
$placeholder_atts = str_replace( $iframe['src'], $placeholder, $iframe['atts'] );
|
||||
$iframe_lazyload = str_replace( $iframe['atts'], $placeholder_atts . ' data-rocket-lazyload="fitvidscompatible" data-lazy-src="' . esc_url( $iframe['src'] ) . '"', $iframe[0] );
|
||||
|
||||
if ( ! preg_match( '@\sloading\s*=\s*(\'|")(?:lazy|auto)\1@i', $iframe_lazyload ) ) {
|
||||
$iframe_lazyload = str_replace( '<iframe', '<iframe loading="lazy"', $iframe_lazyload );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the LazyLoad HTML output on iframes
|
||||
*
|
||||
* @since 1.0
|
||||
*
|
||||
* @param array $html Output that will be printed.
|
||||
*/
|
||||
$iframe_lazyload = apply_filters( 'rocket_lazyload_iframe_html', $iframe_lazyload );
|
||||
$iframe_lazyload .= '<noscript>' . $iframe[0] . '</noscript>';
|
||||
|
||||
return $iframe_lazyload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the iframe provided by the Youtube thumbnail
|
||||
*
|
||||
* @param array $iframe Array of matched elements.
|
||||
* @return bool|string
|
||||
*/
|
||||
private function replaceYoutubeThumbnail( $iframe ) {
|
||||
$youtube_id = $this->getYoutubeIDFromURL( $iframe['src'] );
|
||||
|
||||
if ( ! $youtube_id ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$query = wp_parse_url( htmlspecialchars_decode( $iframe['src'] ), PHP_URL_QUERY );
|
||||
|
||||
$youtube_url = $this->changeYoutubeUrlForYoutuDotBe( $iframe['src'] );
|
||||
$youtube_url = $this->cleanYoutubeUrl( $iframe['src'] );
|
||||
/**
|
||||
* Filter the LazyLoad HTML output on Youtube iframes
|
||||
*
|
||||
* @since 2.11
|
||||
*
|
||||
* @param array $html Output that will be printed.
|
||||
*/
|
||||
$youtube_lazyload = apply_filters( 'rocket_lazyload_youtube_html', '<div class="rll-youtube-player" data-src="' . esc_attr( $youtube_url ) . '" data-id="' . esc_attr( $youtube_id ) . '" data-query="' . esc_attr( $query ) . '"></div>' );
|
||||
$youtube_lazyload .= '<noscript>' . $iframe[0] . '</noscript>';
|
||||
|
||||
return $youtube_lazyload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Youtube ID from the URL provided
|
||||
*
|
||||
* @param string $url URL to search.
|
||||
* @return bool|string
|
||||
*/
|
||||
public function getYoutubeIDFromURL( $url ) {
|
||||
$pattern = '#^(?:https?:)?(?://)?(?:www\.)?(?:youtu\.be|youtube\.com|youtube-nocookie\.com)/(?:embed/|v/|watch/?\?v=)?([\w-]{11})#iU';
|
||||
$result = preg_match( $pattern, $url, $matches );
|
||||
|
||||
if ( ! $result ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// exclude playlist.
|
||||
if ( 'videoseries' === $matches[1] ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes URL youtu.be/ID to youtube.com/embed/ID
|
||||
*
|
||||
* @param string $url URL to replace.
|
||||
* @return string Unchanged URL or modified URL.
|
||||
*/
|
||||
public function changeYoutubeUrlForYoutuDotBe( $url ) {
|
||||
$pattern = '#^(?:https?:)?(?://)?(?:www\.)?(?:youtu\.be)/(?:embed/|v/|watch/?\?v=)?([\w-]{11})#iU';
|
||||
$result = preg_match( $pattern, $url, $matches );
|
||||
|
||||
if ( ! $result ) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
return 'https://www.youtube.com/embed/' . $matches[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans Youtube URL. Keeps only scheme, host and path.
|
||||
*
|
||||
* @param string $url URL to be cleaned.
|
||||
* @return string Cleaned URL
|
||||
*/
|
||||
public function cleanYoutubeUrl( $url ) {
|
||||
$parsed_url = wp_parse_url( $url, -1 );
|
||||
$scheme = isset( $parsed_url['scheme'] ) ? $parsed_url['scheme'] . '://' : '//';
|
||||
$host = isset( $parsed_url['host'] ) ? $parsed_url['host'] : '';
|
||||
$path = isset( $parsed_url['path'] ) ? $parsed_url['path'] : '';
|
||||
|
||||
return $scheme . $host . $path;
|
||||
}
|
||||
}
|
@@ -0,0 +1,602 @@
|
||||
<?php
|
||||
/**
|
||||
* Handles lazyloading of images
|
||||
*
|
||||
* @package RocketLazyload
|
||||
*/
|
||||
|
||||
namespace WP_Rocket\Dependencies\RocketLazyload;
|
||||
|
||||
/**
|
||||
* A class to provide the methods needed to lazyload images in WP Rocket and Lazyload by WP Rocket
|
||||
*/
|
||||
class Image {
|
||||
|
||||
/**
|
||||
* Finds the images to be lazyloaded and call the callback method to replace them.
|
||||
*
|
||||
* @param string $html Original HTML.
|
||||
* @param string $buffer Content to parse.
|
||||
* @return string
|
||||
*/
|
||||
public function lazyloadImages( $html, $buffer ) {
|
||||
$clean_buffer = preg_replace( '/<script\b(?:[^>]*)>(?:.+)?<\/script>/Umsi', '', $html );
|
||||
$clean_buffer = preg_replace( '#<noscript>(?:.+)</noscript>#Umsi', '', $clean_buffer );
|
||||
if (! preg_match_all('#<img(?<atts>\s.+)\s?/?>#iUs', $clean_buffer, $images, PREG_SET_ORDER)) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$images = array_unique( $images, SORT_REGULAR );
|
||||
|
||||
foreach ( $images as $image ) {
|
||||
$image = $this->canLazyload( $image );
|
||||
|
||||
if ( ! $image ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$image_lazyload = $this->replaceImage( $image );
|
||||
$image_lazyload .= $this->noscript( $image[0] );
|
||||
$html = str_replace( $image[0], $image_lazyload, $html );
|
||||
|
||||
unset( $image_lazyload );
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies lazyload on background images defined in style attributes
|
||||
*
|
||||
* @param string $html Original HTML.
|
||||
* @param string $buffer Content to parse.
|
||||
* @return string
|
||||
*/
|
||||
public function lazyloadBackgroundImages( $html, $buffer ) {
|
||||
if ( ! preg_match_all( '#<(?<tag>div|figure|section|span|li|a)\s+(?<before>[^>]+[\'"\s])?style\s*=\s*([\'"])(?<styles>.*?)\3(?<after>[^>]*)>#is', $buffer, $elements, PREG_SET_ORDER ) ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
foreach ( $elements as $element ) {
|
||||
if ( $this->isExcluded( $element['before'] . $element['after'], $this->getExcludedAttributes() ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( ! preg_match( '#background-image\s*:\s*(?<attr>\s*url\s*\((?<url>[^)]+)\))\s*;?#is', $element['styles'], $url ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$url['url'] = esc_url(
|
||||
trim(
|
||||
strip_tags(
|
||||
html_entity_decode(
|
||||
$url['url'], ENT_QUOTES|ENT_HTML5
|
||||
)
|
||||
), '\'" '
|
||||
)
|
||||
);
|
||||
|
||||
if ( $this->isExcluded( $url['url'], $this->getExcludedSrc() ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$lazy_bg = $this->addLazyCLass( $element[0] );
|
||||
$lazy_bg = str_replace( $url[0], '', $lazy_bg );
|
||||
$lazy_bg = str_replace( '<' . $element['tag'], '<' . $element['tag'] . ' data-bg="' . esc_attr( $url['url'] ) . '"', $lazy_bg );
|
||||
|
||||
$html = str_replace( $element[0], $lazy_bg, $html );
|
||||
unset( $lazy_bg );
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the identifier class to the element
|
||||
*
|
||||
* @param string $element Element to add the class to.
|
||||
* @return string
|
||||
*/
|
||||
private function addLazyClass( $element ) {
|
||||
$class = $this->getClasses( $element );
|
||||
if ( empty( $class ) ) {
|
||||
return preg_replace( '#<(img|div|figure|section|li|span|a)([^>]*)>#is', '<\1 class="rocket-lazyload"\2>', $element );
|
||||
}
|
||||
|
||||
if ( empty( $class['attribute'] ) || empty( $class['classes'] ) ) {
|
||||
return str_replace( $class['attribute'], 'class="rocket-lazyload"', $element );
|
||||
}
|
||||
|
||||
$quotes = $this->getAttributeQuotes( $class['classes'] );
|
||||
$classes = $this->trimOuterQuotes( $class['classes'], $quotes );
|
||||
|
||||
if ( empty( $classes ) ) {
|
||||
return str_replace( $class['attribute'], 'class="rocket-lazyload"', $element );
|
||||
}
|
||||
|
||||
$classes .= ' rocket-lazyload';
|
||||
|
||||
return str_replace(
|
||||
$class['attribute'],
|
||||
'class=' . $this->normalizeClasses( $classes, $quotes ),
|
||||
$element
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the attribute value's outer quotation mark, if one exists, i.e. " or '.
|
||||
*
|
||||
* @param string $attribute_value The target attribute's value.
|
||||
*
|
||||
* @return bool|string quotation character; else false when no quotation mark.
|
||||
*/
|
||||
private function getAttributeQuotes( $attribute_value ) {
|
||||
$attribute_value = trim( $attribute_value );
|
||||
$first_char = $attribute_value[0];
|
||||
|
||||
if ( '"' === $first_char || "'" === $first_char ) {
|
||||
return $first_char;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the class attribute and values from the given element, if it exists.
|
||||
*
|
||||
* @param string $element Given HTML element to extract classes from.
|
||||
*
|
||||
* @return bool|string[] {
|
||||
* @type string $attribute Class attribute and value, e.g. class="value"
|
||||
* @type string $classes String of class attribute's value(s)
|
||||
* }; else, false when no class attribute exists.
|
||||
*/
|
||||
private function getClasses( $element ) {
|
||||
if ( ! preg_match( '#class\s*=\s*(?<classes>["\'].*?["\']|[^\s]+)#is', $element, $class ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( empty( $class ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( ! isset( $class['classes'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return [
|
||||
'attribute' => $class[0],
|
||||
'classes' => $class['classes'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes outer single or double quotations.
|
||||
*
|
||||
* @param string $string String to strip quotes from.
|
||||
* @param string $quotes The outer quotes to remove.
|
||||
*
|
||||
* @return string string without quotes.
|
||||
*/
|
||||
private function trimOuterQuotes( $string, $quotes ) {
|
||||
$string = trim( $string );
|
||||
if ( empty( $string ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ( empty( $quotes ) ) {
|
||||
return $string;
|
||||
}
|
||||
|
||||
$string = ltrim( $string, $quotes );
|
||||
$string = rtrim( $string, $quotes );
|
||||
return trim( $string );
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the class attribute values to ensure well-formed.
|
||||
*
|
||||
* @param string $classes String of class attribute value(s).
|
||||
* @param string|bool $quotes Optional. Quotation mark to wrap around the classes.
|
||||
*
|
||||
* @return string well-formed class attributes.
|
||||
*/
|
||||
private function normalizeClasses( $classes, $quotes = '"' ) {
|
||||
$array_of_classes = $this->stringToArray( $classes );
|
||||
$classes = implode( ' ', $array_of_classes );
|
||||
|
||||
if ( false === $quotes ) {
|
||||
$quotes = '"';
|
||||
}
|
||||
|
||||
return $quotes . $classes . $quotes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given string into an array of strings.
|
||||
*
|
||||
* Note:
|
||||
* 1. Removes empties.
|
||||
* 2. Trims each string.
|
||||
*
|
||||
* @param string $string The target string to convert.
|
||||
* @param string $delimiter Optional. Default: ' ' empty string.
|
||||
*
|
||||
* @return array An array of trimmed strings.
|
||||
*/
|
||||
private function stringToArray( $string, $delimiter = ' ' ) {
|
||||
if ( empty( $string ) ) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$array = explode( $delimiter, $string );
|
||||
$array = array_map('trim', $array );
|
||||
|
||||
// Remove empties.
|
||||
return array_filter( $array );
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies lazyload on picture elements found in the HTML.
|
||||
*
|
||||
* @param string $html Original HTML.
|
||||
* @param string $buffer Content to parse.
|
||||
* @return string
|
||||
*/
|
||||
public function lazyloadPictures( $html, $buffer ) {
|
||||
if ( ! preg_match_all( '#<picture(?:.*)?>(?<sources>.*)</picture>#iUs', $buffer, $pictures, PREG_SET_ORDER ) ) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$pictures = array_unique( $pictures, SORT_REGULAR );
|
||||
$excluded = array_merge( $this->getExcludedAttributes(), $this->getExcludedSrc() );
|
||||
|
||||
foreach ( $pictures as $picture ) {
|
||||
if ( $this->isExcluded( $picture[0], $excluded ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( preg_match_all( '#<source(?<atts>\s.+)>#iUs', $picture['sources'], $sources, PREG_SET_ORDER ) ) {
|
||||
$sources = array_unique( $sources, SORT_REGULAR );
|
||||
|
||||
$lazy_sources = 0;
|
||||
|
||||
foreach ( $sources as $source ) {
|
||||
$lazyload_srcset = preg_replace( '/([\s"\'])srcset/i', '\1data-lazy-srcset', $source[0] );
|
||||
$html = str_replace( $source[0], $lazyload_srcset, $html );
|
||||
|
||||
unset( $lazyload_srcset );
|
||||
$lazy_sources++;
|
||||
}
|
||||
}
|
||||
|
||||
if ( 0 === $lazy_sources ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( ! preg_match( '#<img(?<atts>\s.+)\s?/?>#iUs', $picture[0], $img ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$img = $this->canLazyload( $img );
|
||||
|
||||
if ( ! $img ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$img_lazy = $this->replaceImage( $img );
|
||||
$img_lazy .= $this->noscript( $img[0] );
|
||||
$safe_img = str_replace('/', '\/', preg_quote( $img[0], '#' ));
|
||||
$html = preg_replace( '#<noscript[^>]*>.*' . $safe_img . '.*<\/noscript>(*SKIP)(*FAIL)|' . $safe_img . '#iU', $img_lazy, $html );
|
||||
|
||||
unset( $img_lazy );
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the image can be lazyloaded
|
||||
*
|
||||
* @param Array $image Array of image data coming from Regex.
|
||||
* @return bool|Array
|
||||
*/
|
||||
private function canLazyload( $image ) {
|
||||
if ( $this->isExcluded( $image['atts'], $this->getExcludedAttributes() ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Given the previous regex pattern, $image['atts'] starts with a whitespace character.
|
||||
if ( ! preg_match( '@\ssrc\s*=\s*(\'|")(?<src>.*)\1@iUs', $image['atts'], $atts ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$image['src'] = trim( $atts['src'] );
|
||||
|
||||
if ( '' === $image['src'] ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( $this->isExcluded( $image['src'], $this->getExcludedSrc() ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Don't apply LazyLoad on images from WP Retina x2.
|
||||
if ( function_exists( 'wr2x_picture_rewrite' ) ) {
|
||||
if ( wr2x_get_retina( trailingslashit( ABSPATH ) . wr2x_get_pathinfo_from_image_src( trim( $image['src'], '"' ) ) ) ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return $image;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the provided string matches with the provided excluded patterns
|
||||
*
|
||||
* @param string $string String to check.
|
||||
* @param array $excluded_values Patterns to match against.
|
||||
* @return boolean
|
||||
*/
|
||||
public function isExcluded( $string, $excluded_values ) {
|
||||
if ( ! is_array( $excluded_values ) ) {
|
||||
(array) $excluded_values;
|
||||
}
|
||||
|
||||
if ( empty( $excluded_values ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $excluded_values as $excluded_value ) {
|
||||
if ( strpos( $string, $excluded_value ) !== false ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of excluded attributes
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getExcludedAttributes() {
|
||||
/**
|
||||
* Filters the attributes used to prevent lazylad from being applied
|
||||
*
|
||||
* @since 1.0
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param array $excluded_attributes An array of excluded attributes.
|
||||
*/
|
||||
return apply_filters(
|
||||
'rocket_lazyload_excluded_attributes',
|
||||
[
|
||||
'data-src=',
|
||||
'data-no-lazy=',
|
||||
'data-lazy-original=',
|
||||
'data-lazy-src=',
|
||||
'data-lazysrc=',
|
||||
'data-lazyload=',
|
||||
'data-bgposition=',
|
||||
'data-envira-src=',
|
||||
'fullurl=',
|
||||
'lazy-slider-img=',
|
||||
'data-srcset=',
|
||||
'class="ls-l',
|
||||
'class="ls-bg',
|
||||
'soliloquy-image',
|
||||
'loading="eager"',
|
||||
'swatch-img',
|
||||
'data-height-percentage',
|
||||
'data-large_image',
|
||||
'avia-bg-style-fixed',
|
||||
'data-skip-lazy',
|
||||
'skip-lazy',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of excluded src
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getExcludedSrc() {
|
||||
/**
|
||||
* Filters the src used to prevent lazylad from being applied
|
||||
*
|
||||
* @since 1.0
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param array $excluded_src An array of excluded src.
|
||||
*/
|
||||
return apply_filters(
|
||||
'rocket_lazyload_excluded_src',
|
||||
[
|
||||
'/wpcf7_captcha/',
|
||||
'timthumb.php?src',
|
||||
'woocommerce/assets/images/placeholder.png',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the original image by the lazyload one
|
||||
*
|
||||
* @param array $image Array of matches elements.
|
||||
* @return string
|
||||
*/
|
||||
private function replaceImage( $image ) {
|
||||
$width = 0;
|
||||
$height = 0;
|
||||
|
||||
if ( preg_match( '@[\s"\']width\s*=\s*(\'|")(?<width>.*)\1@iUs', $image['atts'], $atts ) ) {
|
||||
$width = absint( $atts['width'] );
|
||||
}
|
||||
|
||||
if ( preg_match( '@[\s"\']height\s*=\s*(\'|")(?<height>.*)\1@iUs', $image['atts'], $atts ) ) {
|
||||
$height = absint( $atts['height'] );
|
||||
}
|
||||
|
||||
$placeholder_atts = preg_replace( '@\ssrc\s*=\s*(\'|")(?<src>.*)\1@iUs', ' src="' . $this->getPlaceholder( $width, $height ) . '"', $image['atts'] );
|
||||
|
||||
$image_lazyload = str_replace( $image['atts'], $placeholder_atts . ' data-lazy-src="' . $image['src'] . '"', $image[0] );
|
||||
|
||||
if ( ! preg_match( '@\sloading\s*=\s*(\'|")(?:lazy|auto)\1@i', $image_lazyload ) && apply_filters( 'rocket_use_native_lazyload', false ) ) {
|
||||
$image_lazyload = str_replace( '<img', '<img loading="lazy"', $image_lazyload );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the LazyLoad HTML output
|
||||
*
|
||||
* @since 1.0
|
||||
*
|
||||
* @param string $html Output that will be printed
|
||||
*/
|
||||
$image_lazyload = apply_filters( 'rocket_lazyload_html', $image_lazyload );
|
||||
|
||||
return $image_lazyload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the HTML tag wrapped inside noscript tags
|
||||
*
|
||||
* @param string $element Element to wrap.
|
||||
* @return string
|
||||
*/
|
||||
private function noscript( $element ) {
|
||||
return '<noscript>' . $element . '</noscript>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies lazyload on srcset and sizes attributes
|
||||
*
|
||||
* @param string $html HTML image tag.
|
||||
* @return string
|
||||
*/
|
||||
public function lazyloadResponsiveAttributes( $html ) {
|
||||
$html = preg_replace( '/[\s|"|\'](srcset)\s*=\s*("|\')([^"|\']+)\2/i', ' data-lazy-$1=$2$3$2', $html );
|
||||
$html = preg_replace( '/[\s|"|\'](sizes)\s*=\s*("|\')([^"|\']+)\2/i', ' data-lazy-$1=$2$3$2', $html );
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds patterns matching smiley and call the callback method to replace them with the image
|
||||
*
|
||||
* @param string $text Content to search in.
|
||||
* @return string
|
||||
*/
|
||||
public function convertSmilies( $text ) {
|
||||
global $wp_smiliessearch;
|
||||
|
||||
if ( ! get_option( 'use_smilies' ) || empty( $wp_smiliessearch ) ) {
|
||||
return $text;
|
||||
}
|
||||
|
||||
$output = '';
|
||||
// HTML loop taken from texturize function, could possible be consolidated.
|
||||
$textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between.
|
||||
$stop = count( $textarr );// loop stuff.
|
||||
|
||||
// Ignore proessing of specific tags.
|
||||
$tags_to_ignore = 'code|pre|style|script|textarea';
|
||||
$ignore_block_element = '';
|
||||
|
||||
for ( $i = 0; $i < $stop; $i++ ) {
|
||||
$content = $textarr[ $i ];
|
||||
|
||||
// If we're in an ignore block, wait until we find its closing tag.
|
||||
if ( '' === $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
|
||||
$ignore_block_element = $matches[1];
|
||||
}
|
||||
|
||||
// If it's not a tag and not in ignore block.
|
||||
if ( '' === $ignore_block_element && strlen( $content ) > 0 && '<' !== $content[0] ) {
|
||||
$content = preg_replace_callback( $wp_smiliessearch, [ $this, 'translateSmiley' ], $content );
|
||||
}
|
||||
|
||||
// did we exit ignore block.
|
||||
if ( '' !== $ignore_block_element && '</' . $ignore_block_element . '>' === $content ) {
|
||||
$ignore_block_element = '';
|
||||
}
|
||||
|
||||
$output .= $content;
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace matches by smiley image, lazyloaded
|
||||
*
|
||||
* @param array $matches Array of matches.
|
||||
* @return string
|
||||
*/
|
||||
private function translateSmiley( $matches ) {
|
||||
global $wpsmiliestrans;
|
||||
|
||||
if ( count( $matches ) === 0 ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$smiley = trim( reset( $matches ) );
|
||||
$img = $wpsmiliestrans[ $smiley ];
|
||||
|
||||
$matches = [];
|
||||
$ext = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
|
||||
$image_exts = [ 'jpg', 'jpeg', 'jpe', 'gif', 'png' ];
|
||||
|
||||
// Don't convert smilies that aren't images - they're probably emoji.
|
||||
if ( ! in_array( $ext, $image_exts, true ) ) {
|
||||
return $img;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the Smiley image URL before it's used in the image element.
|
||||
*
|
||||
* @since 2.9.0
|
||||
*
|
||||
* @param string $smiley_url URL for the smiley image.
|
||||
* @param string $img Filename for the smiley image.
|
||||
* @param string $site_url Site URL, as returned by site_url().
|
||||
*/
|
||||
$src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
|
||||
|
||||
// Don't LazyLoad if process is stopped for these reasons.
|
||||
if ( is_feed() || is_preview() ) {
|
||||
return sprintf( ' <img src="%s" alt="%s" class="wp-smiley" /> ', esc_url( $src_url ), esc_attr( $smiley ) );
|
||||
}
|
||||
|
||||
return sprintf( ' <img src="%s" data-lazy-src="%s" alt="%s" class="wp-smiley" /> ', $this->getPlaceholder(), esc_url( $src_url ), esc_attr( $smiley ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the placeholder for the src attribute
|
||||
*
|
||||
* @since 1.2
|
||||
* @author Remy Perona
|
||||
*
|
||||
* @param int $width Width of the placeholder image. Default 0.
|
||||
* @param int $height Height of the placeholder image. Default 0.
|
||||
* @return string
|
||||
*/
|
||||
public function getPlaceholder( $width = 0, $height = 0 ) {
|
||||
$width = 0 === $width ? 0 : absint( $width );
|
||||
$height = 0 === $height ? 0 : absint( $height );
|
||||
|
||||
$placeholder = str_replace( ' ', '%20', "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 $width $height'%3E%3C/svg%3E" );
|
||||
/**
|
||||
* Filter the image lazyLoad placeholder on src attribute
|
||||
*
|
||||
* @since 1.1
|
||||
*
|
||||
* @param string $placeholder Placeholder that will be printed.
|
||||
* @param int $width Placeholder width.
|
||||
* @param int $height Placeholder height.
|
||||
*/
|
||||
return apply_filters( 'rocket_lazyload_placeholder', $placeholder, $width, $height );
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user