3 * Minification of CSS stylesheets.
5 * Copyright 2010 Wikimedia Foundation
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may
8 * not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software distributed
14 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
15 * OF ANY KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations under the License.
19 * @version 0.1.1 -- 2010-09-11
20 * @author Trevor Parscal <tparscal@wikimedia.org>
21 * @copyright Copyright 2010 Wikimedia Foundation
22 * @license http://www.apache.org/licenses/LICENSE-2.0
28 * This class provides minification, URL remapping, URL extracting, and data-URL embedding.
34 /** @var string Strip marker for comments. **/
35 const PLACEHOLDER
= "\x7fPLACEHOLDER\x7f";
38 * Internet Explorer data URI length limit. See encodeImageAsDataURI().
40 const DATA_URI_SIZE_LIMIT
= 32768;
42 const EMBED_REGEX
= '\/\*\s*\@embed\s*\*\/';
43 const COMMENT_REGEX
= '\/\*.*?\*\/';
45 /* Protected Static Members */
47 /** @var array List of common image files extensions and MIME-types */
48 protected static $mimeTypes = [
50 'jpe' => 'image/jpeg',
51 'jpeg' => 'image/jpeg',
52 'jpg' => 'image/jpeg',
54 'tif' => 'image/tiff',
55 'tiff' => 'image/tiff',
56 'xbm' => 'image/x-xbitmap',
57 'svg' => 'image/svg+xml',
63 * Get a list of local files referenced in a stylesheet (includes non-existent files).
65 * @param string $source CSS stylesheet source to process
66 * @param string $path File path where the source was read from
67 * @return array List of local file references
69 public static function getLocalFileReferences( $source, $path ) {
70 $stripped = preg_replace( '/' . self
::COMMENT_REGEX
. '/s', '', $source );
71 $path = rtrim( $path, '/' ) . '/';
74 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER
;
75 if ( preg_match_all( '/' . self
::getUrlRegex() . '/', $stripped, $matches, $rFlags ) ) {
76 foreach ( $matches as $match ) {
77 self
::processUrlMatch( $match, $rFlags );
78 $url = $match['file'][0];
80 // Skip fully-qualified and protocol-relative URLs and data URIs
81 if ( substr( $url, 0, 2 ) === '//' ||
parse_url( $url, PHP_URL_SCHEME
) ) {
85 $files[] = $path . $url;
92 * Encode an image file as a data URI.
94 * If the image file has a suitable MIME type and size, encode it as a data URI, base64-encoded
95 * for binary files or just percent-encoded otherwise. Return false if the image type is
96 * unfamiliar or file exceeds the size limit.
98 * @param string $file Image file to encode.
99 * @param string|null $type File's MIME type or null. If null, CSSMin will
100 * try to autodetect the type.
101 * @param bool $ie8Compat By default, a data URI will only be produced if it can be made short
102 * enough to fit in Internet Explorer 8 (and earlier) URI length limit (32,768 bytes). Pass
103 * `false` to remove this limitation.
104 * @return string|bool Image contents encoded as a data URI or false.
106 public static function encodeImageAsDataURI( $file, $type = null, $ie8Compat = true ) {
107 // Fast-fail for files that definitely exceed the maximum data URI length
108 if ( $ie8Compat && filesize( $file ) >= self
::DATA_URI_SIZE_LIMIT
) {
112 if ( $type === null ) {
113 $type = self
::getMimeType( $file );
119 return self
::encodeStringAsDataURI( file_get_contents( $file ), $type, $ie8Compat );
123 * Encode file contents as a data URI with chosen MIME type.
125 * The URI will be base64-encoded for binary files or just percent-encoded otherwise.
129 * @param string $contents File contents to encode.
130 * @param string $type File's MIME type.
131 * @param bool $ie8Compat See encodeImageAsDataURI().
132 * @return string|bool Image contents encoded as a data URI or false.
134 public static function encodeStringAsDataURI( $contents, $type, $ie8Compat = true ) {
135 // Try #1: Non-encoded data URI
136 // The regular expression matches ASCII whitespace and printable characters.
137 if ( preg_match( '/^[\r\n\t\x20-\x7e]+$/', $contents ) ) {
138 // Do not base64-encode non-binary files (sane SVGs).
139 // (This often produces longer URLs, but they compress better, yielding a net smaller size.)
140 $uri = 'data:' . $type . ',' . rawurlencode( $contents );
141 if ( !$ie8Compat ||
strlen( $uri ) < self
::DATA_URI_SIZE_LIMIT
) {
146 // Try #2: Encoded data URI
147 $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
148 if ( !$ie8Compat ||
strlen( $uri ) < self
::DATA_URI_SIZE_LIMIT
) {
152 // A data URI couldn't be produced
157 * Serialize a string (escape and quote) for use as a CSS string value.
158 * http://www.w3.org/TR/2013/WD-cssom-20131205/#serialize-a-string
160 * @param string $value
164 public static function serializeStringValue( $value ) {
165 if ( strstr( $value, "\0" ) ) {
166 throw new Exception( "Invalid character in CSS string" );
168 $value = strtr( $value, [ '\\' => '\\\\', '"' => '\\"' ] );
169 $value = preg_replace_callback( '/[\x01-\x1f\x7f-\x9f]/', function ( $match ) {
170 return '\\' . base_convert( ord( $match[0] ), 10, 16 ) . ' ';
172 return '"' . $value . '"';
176 * @param string $file
177 * @return bool|string
179 public static function getMimeType( $file ) {
180 // Infer the MIME-type from the file extension
181 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION
) );
182 if ( isset( self
::$mimeTypes[$ext] ) ) {
183 return self
::$mimeTypes[$ext];
186 $realpath = realpath( $file );
189 && function_exists( 'finfo_file' )
190 && function_exists( 'finfo_open' )
191 && defined( 'FILEINFO_MIME_TYPE' )
193 return finfo_file( finfo_open( FILEINFO_MIME_TYPE
), $realpath );
200 * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
201 * and escaping quotes as necessary.
203 * See http://www.w3.org/TR/css-syntax-3/#consume-a-url-token
205 * @param string $url URL to process
206 * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
208 public static function buildUrlValue( $url ) {
209 // The list below has been crafted to match URLs such as:
210 // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
211 // data:image/png;base64,R0lGODlh/+==
212 if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
215 return 'url("' . strtr( $url, [ '\\' => '\\\\', '"' => '\\"' ] ) . '")';
220 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
221 * or url() values preceded by an / * @embed * / comment.
223 * @param string $source CSS data to remap
224 * @param string $local File path where the source was read from
225 * @param string $remote URL path to the file
226 * @param bool $embedData If false, never do any data URI embedding,
227 * even if / * @embed * / is found.
228 * @return string Remapped CSS data
230 public static function remap( $source, $local, $remote, $embedData = true ) {
231 // High-level overview:
232 // * For each CSS rule in $source that includes at least one url() value:
233 // * Check for an @embed comment at the start indicating that all URIs should be embedded
234 // * For each url() value:
235 // * Check for an @embed comment directly preceding the value
236 // * If either @embed comment exists:
237 // * Embedding the URL as data: URI, if it's possible / allowed
238 // * Otherwise remap the URL to work in generated stylesheets
240 // Guard against trailing slashes, because "some/remote/../foo.png"
241 // resolves to "some/remote/foo.png" on (some?) clients (T29052).
242 if ( substr( $remote, -1 ) == '/' ) {
243 $remote = substr( $remote, 0, -1 );
246 // Disallow U+007F DELETE, which is illegal anyway, and which
247 // we use for comment placeholders.
248 $source = str_replace( "\x7f", "?", $source );
250 // Replace all comments by a placeholder so they will not interfere with the remapping.
251 // Warning: This will also catch on anything looking like the start of a comment between
252 // quotation marks (e.g. "foo /* bar").
255 $pattern = '/(?!' . self
::EMBED_REGEX
. ')(' . self
::COMMENT_REGEX
. ')/s';
257 $source = preg_replace_callback(
259 function ( $match ) use ( &$comments ) {
260 $comments[] = $match[ 0 ];
261 return CSSMin
::PLACEHOLDER
. ( count( $comments ) - 1 ) . 'x';
266 // Note: This will not correctly handle cases where ';', '{' or '}'
267 // appears in the rule itself, e.g. in a quoted string. You are advised
268 // not to use such characters in file names. We also match start/end of
269 // the string to be consistent in edge-cases ('@import url(…)').
270 $pattern = '/(?:^|[;{])\K[^;{}]*' . self
::getUrlRegex() . '[^;}]*(?=[;}]|$)/';
272 $source = preg_replace_callback(
274 function ( $matchOuter ) use ( $local, $remote, $embedData ) {
275 $rule = $matchOuter[0];
277 // Check for global @embed comment and remove it. Allow other comments to be present
278 // before @embed (they have been replaced with placeholders at this point).
280 $rule = preg_replace(
282 CSSMin
::PLACEHOLDER
.
284 CSSMin
::EMBED_REGEX
.
292 // Build two versions of current rule: with remapped URLs
293 // and with embedded data: URIs (where possible).
294 $pattern = '/(?P<embed>' . CSSMin
::EMBED_REGEX
. '\s*|)' . self
::getUrlRegex() . '/';
296 $ruleWithRemapped = preg_replace_callback(
298 function ( $match ) use ( $local, $remote ) {
299 self
::processUrlMatch( $match );
301 $remapped = CSSMin
::remapOne( $match['file'], $match['query'], $local, $remote, false );
302 return CSSMin
::buildUrlValue( $remapped );
308 // Remember the occurring MIME types to avoid fallbacks when embedding some files.
311 $ruleWithEmbedded = preg_replace_callback(
313 function ( $match ) use ( $embedAll, $local, $remote, &$mimeTypes ) {
314 self
::processUrlMatch( $match );
316 $embed = $embedAll ||
$match['embed'];
317 $embedded = CSSMin
::remapOne(
325 $url = $match['file'] . $match['query'];
326 $file = "{$local}/{$match['file']}";
328 !self
::isRemoteUrl( $url ) && !self
::isLocalUrl( $url )
329 && file_exists( $file )
331 $mimeTypes[ CSSMin
::getMimeType( $file ) ] = true;
334 return CSSMin
::buildUrlValue( $embedded );
339 // Are all referenced images SVGs?
340 $needsEmbedFallback = $mimeTypes !== [ 'image/svg+xml' => true ];
343 if ( !$embedData ||
$ruleWithEmbedded === $ruleWithRemapped ) {
344 // We're not embedding anything, or we tried to but the file is not embeddable
345 return $ruleWithRemapped;
346 } elseif ( $embedData && $needsEmbedFallback ) {
347 // Build 2 CSS properties; one which uses a data URI in place of the @embed comment, and
348 // the other with a remapped and versioned URL with an Internet Explorer 6 and 7 hack
349 // making it ignored in all browsers that support data URIs
350 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
352 // Look ma, no fallbacks! This is for files which IE 6 and 7 don't support anyway: SVG.
353 return $ruleWithEmbedded;
357 // Re-insert comments
358 $pattern = '/' . self
::PLACEHOLDER
. '(\d+)x/';
359 $source = preg_replace_callback( $pattern, function ( $match ) use ( &$comments ) {
360 return $comments[ $match[1] ];
367 * Is this CSS rule referencing a remote URL?
369 * @param string $maybeUrl
372 protected static function isRemoteUrl( $maybeUrl ) {
373 if ( substr( $maybeUrl, 0, 2 ) === '//' ||
parse_url( $maybeUrl, PHP_URL_SCHEME
) ) {
380 * Is this CSS rule referencing a local URL?
382 * @param string $maybeUrl
385 protected static function isLocalUrl( $maybeUrl ) {
386 if ( $maybeUrl !== '' && $maybeUrl[0] === '/' && !self
::isRemoteUrl( $maybeUrl ) ) {
392 private static function getUrlRegex() {
394 if ( $urlRegex === null ) {
395 // Match these three variants separately to avoid broken urls when
396 // e.g. a double quoted url contains a parenthesis, or when a
397 // single quoted url contains a double quote, etc.
398 // Note: PCRE doesn't support multiple capture groups with the same name by default.
399 // - PCRE 6.7 introduced the "J" modifier (PCRE_INFO_JCHANGED for PCRE_DUPNAMES).
400 // https://secure.php.net/manual/en/reference.pcre.pattern.modifiers.php
401 // However this isn't useful since it just ignores all but the first one.
402 // Also, while the modifier was introduced in PCRE 6.7 (PHP 5.2+) it was
403 // not exposed to public preg_* functions until PHP 5.6.0.
404 // - PCRE 8.36 fixed this to work as expected (e.g. merge conceptually to
405 // only return the one matched in the part that actually matched).
406 // However MediaWiki supports 5.5.9, which has PCRE 8.32
407 // Per https://secure.php.net/manual/en/pcre.installation.php:
408 // - PCRE 8.32 (PHP 5.5.0)
409 // - PCRE 8.34 (PHP 5.5.10, PHP 5.6.0)
410 // - PCRE 8.37 (PHP 5.5.26, PHP 5.6.9, PHP 7.0.0)
411 // Workaround by using different groups and merge via processUrlMatch().
412 // - Using string concatenation for class constant or member assignments
413 // is only supported in PHP 5.6. Use a getter method for now.
416 'url\(\s*(?P<file0>[^\'"][^\?\)]*?)(?P<query0>\?[^\)]*?|)\s*\)' .
418 '|url\(\s*\'(?P<file1>[^\?\']*?)(?P<query1>\?[^\']*?|)\'\s*\)' .
420 '|url\(\s*"(?P<file2>[^\?"]*?)(?P<query2>\?[^"]*?|)"\s*\)' .
426 private static function processUrlMatch( array &$match, $flags = 0 ) {
427 if ( $flags & PREG_SET_ORDER
) {
428 // preg_match_all with PREG_SET_ORDER will return each group in each
429 // match array, and if it didn't match, instead of the sub array
430 // being an empty array it is `[ '', -1 ]`...
431 if ( isset( $match['file0'] ) && $match['file0'][1] !== -1 ) {
432 $match['file'] = $match['file0'];
433 $match['query'] = $match['query0'];
434 } elseif ( isset( $match['file1'] ) && $match['file1'][1] !== -1 ) {
435 $match['file'] = $match['file1'];
436 $match['query'] = $match['query1'];
438 $match['file'] = $match['file2'];
439 $match['query'] = $match['query2'];
442 if ( isset( $match['file0'] ) && $match['file0'] !== '' ) {
443 $match['file'] = $match['file0'];
444 $match['query'] = $match['query0'];
445 } elseif ( isset( $match['file1'] ) && $match['file1'] !== '' ) {
446 $match['file'] = $match['file1'];
447 $match['query'] = $match['query1'];
449 $match['file'] = $match['file2'];
450 $match['query'] = $match['query2'];
456 * Remap or embed a CSS URL path.
458 * @param string $file URL to remap/embed
459 * @param string $query
460 * @param string $local File path where the source was read from
461 * @param string $remote URL path to the file
462 * @param bool $embed Whether to do any data URI embedding
463 * @return string Remapped/embedded URL data
465 public static function remapOne( $file, $query, $local, $remote, $embed ) {
466 // The full URL possibly with query, as passed to the 'url()' value in CSS
467 $url = $file . $query;
469 // Expand local URLs with absolute paths like /w/index.php to possibly protocol-relative URL, if
470 // wfExpandUrl() is available. (This will not be the case if we're running outside of MW.)
471 if ( self
::isLocalUrl( $url ) && function_exists( 'wfExpandUrl' ) ) {
472 return wfExpandUrl( $url, PROTO_RELATIVE
);
475 // Pass thru fully-qualified and protocol-relative URLs and data URIs, as well as local URLs if
476 // we can't expand them.
477 if ( self
::isRemoteUrl( $url ) || self
::isLocalUrl( $url ) ) {
481 if ( $local === false ) {
482 // Assume that all paths are relative to $remote, and make them absolute
483 $url = $remote . '/' . $url;
485 // We drop the query part here and instead make the path relative to $remote
486 $url = "{$remote}/{$file}";
487 // Path to the actual file on the filesystem
488 $localFile = "{$local}/{$file}";
489 if ( file_exists( $localFile ) ) {
491 $data = self
::encodeImageAsDataURI( $localFile );
492 if ( $data !== false ) {
496 if ( method_exists( 'OutputPage', 'transformFilePath' ) ) {
497 $url = OutputPage
::transformFilePath( $remote, $local, $file );
499 // Add version parameter as the first five hex digits
500 // of the MD5 hash of the file's contents.
501 $url .= '?' . substr( md5_file( $localFile ), 0, 5 );
504 // If any of these conditions failed (file missing, we don't want to embed it
505 // or it's not embeddable), return the URL (possibly with ?timestamp part)
507 if ( function_exists( 'wfRemoveDotSegments' ) ) {
508 $url = wfRemoveDotSegments( $url );
514 * Removes whitespace from CSS data
516 * @param string $css CSS data to minify
517 * @return string Minified CSS data
519 public static function minify( $css ) {
522 [ '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ],
523 [ ';', ':', '{', '{', ',', '}', '}' ],
524 preg_replace( [ '/\s+/', '/\/\*.*?\*\//s' ], [ ' ', '' ], $css )