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;
41 const URL_REGEX
= 'url\(\s*[\'"]?(?P<file>[^\?\)\'"]*?)(?P<query>\?[^\)\'"]*?|)[\'"]?\s*\)';
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 = array(
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 * Gets a list of local file paths which are referenced in a CSS style sheet.
65 * If you wish non-existent files to be listed too, use getAllLocalFileReferences().
67 * For backwards-compatibility, if the second parameter is not given or null,
68 * this function will return an empty array instead of erroring out.
70 * @param string $source CSS stylesheet source to process
71 * @param string $path File path where the source was read from
72 * @return array List of local file references
74 public static function getLocalFileReferences( $source, $path = null ) {
75 if ( $path === null ) {
79 $files = self
::getAllLocalFileReferences( $source, $path );
81 // Skip non-existent files
82 $files = array_filter( $files, function ( $file ) {
83 return file_exists( $file );
90 * Gets a list of local file paths which are referenced in a CSS style sheet, including
93 * @param string $source CSS stylesheet source to process
94 * @param string $path File path where the source was read from
95 * @return array List of local file references
97 public static function getAllLocalFileReferences( $source, $path ) {
98 $stripped = preg_replace( '/' . self
::COMMENT_REGEX
. '/s', '', $source );
99 $path = rtrim( $path, '/' ) . '/';
102 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER
;
103 if ( preg_match_all( '/' . self
::URL_REGEX
. '/', $stripped, $matches, $rFlags ) ) {
104 foreach ( $matches as $match ) {
105 $url = $match['file'][0];
107 // Skip fully-qualified and protocol-relative URLs and data URIs
108 if ( substr( $url, 0, 2 ) === '//' ||
parse_url( $url, PHP_URL_SCHEME
) ) {
112 $files[] = $path . $url;
119 * Encode an image file as a data URI.
121 * If the image file has a suitable MIME type and size, encode it as a data URI, base64-encoded
122 * for binary files or just percent-encoded otherwise. Return false if the image type is
123 * unfamiliar or file exceeds the size limit.
125 * @param string $file Image file to encode.
126 * @param string|null $type File's MIME type or null. If null, CSSMin will
127 * try to autodetect the type.
128 * @param bool $ie8Compat By default, a data URI will only be produced if it can be made short
129 * enough to fit in Internet Explorer 8 (and earlier) URI length limit (32,768 bytes). Pass
130 * `false` to remove this limitation.
131 * @return string|bool Image contents encoded as a data URI or false.
133 public static function encodeImageAsDataURI( $file, $type = null, $ie8Compat = true ) {
134 // Fast-fail for files that definitely exceed the maximum data URI length
135 if ( $ie8Compat && filesize( $file ) >= self
::DATA_URI_SIZE_LIMIT
) {
139 if ( $type === null ) {
140 $type = self
::getMimeType( $file );
146 return self
::encodeStringAsDataURI( file_get_contents( $file ), $type, $ie8Compat );
150 * Encode file contents as a data URI with chosen MIME type.
152 * The URI will be base64-encoded for binary files or just percent-encoded otherwise.
156 * @param string $contents File contents to encode.
157 * @param string $type File's MIME type.
158 * @param bool $ie8Compat See encodeImageAsDataURI().
159 * @return string|bool Image contents encoded as a data URI or false.
161 public static function encodeStringAsDataURI( $contents, $type, $ie8Compat = true ) {
162 // Try #1: Non-encoded data URI
163 // The regular expression matches ASCII whitespace and printable characters.
164 if ( preg_match( '/^[\r\n\t\x20-\x7e]+$/', $contents ) ) {
165 // Do not base64-encode non-binary files (sane SVGs).
166 // (This often produces longer URLs, but they compress better, yielding a net smaller size.)
167 $uri = 'data:' . $type . ',' . rawurlencode( $contents );
168 if ( !$ie8Compat ||
strlen( $uri ) < self
::DATA_URI_SIZE_LIMIT
) {
173 // Try #2: Encoded data URI
174 $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
175 if ( !$ie8Compat ||
strlen( $uri ) < self
::DATA_URI_SIZE_LIMIT
) {
179 // A data URI couldn't be produced
184 * @param $file string
185 * @return bool|string
187 public static function getMimeType( $file ) {
188 $realpath = realpath( $file );
191 && function_exists( 'finfo_file' )
192 && function_exists( 'finfo_open' )
193 && defined( 'FILEINFO_MIME_TYPE' )
195 return finfo_file( finfo_open( FILEINFO_MIME_TYPE
), $realpath );
198 // Infer the MIME-type from the file extension
199 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION
) );
200 if ( isset( self
::$mimeTypes[$ext] ) ) {
201 return self
::$mimeTypes[$ext];
208 * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
209 * and escaping quotes as necessary.
211 * See http://www.w3.org/TR/css-syntax-3/#consume-a-url-token
213 * @param string $url URL to process
214 * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
216 public static function buildUrlValue( $url ) {
217 // The list below has been crafted to match URLs such as:
218 // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
219 // data:image/png;base64,R0lGODlh/+==
220 if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
223 return 'url("' . strtr( $url, array( '\\' => '\\\\', '"' => '\\"' ) ) . '")';
228 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
229 * or url() values preceded by an / * @embed * / comment.
231 * @param string $source CSS data to remap
232 * @param string $local File path where the source was read from
233 * @param string $remote URL path to the file
234 * @param bool $embedData If false, never do any data URI embedding,
235 * even if / * @embed * / is found.
236 * @return string Remapped CSS data
238 public static function remap( $source, $local, $remote, $embedData = true ) {
239 // High-level overview:
240 // * For each CSS rule in $source that includes at least one url() value:
241 // * Check for an @embed comment at the start indicating that all URIs should be embedded
242 // * For each url() value:
243 // * Check for an @embed comment directly preceding the value
244 // * If either @embed comment exists:
245 // * Embedding the URL as data: URI, if it's possible / allowed
246 // * Otherwise remap the URL to work in generated stylesheets
248 // Guard against trailing slashes, because "some/remote/../foo.png"
249 // resolves to "some/remote/foo.png" on (some?) clients (bug 27052).
250 if ( substr( $remote, -1 ) == '/' ) {
251 $remote = substr( $remote, 0, -1 );
254 // Disallow U+007F DELETE, which is illegal anyway, and which
255 // we use for comment placeholders.
256 $source = str_replace( "\x7f", "?", $source );
258 // Replace all comments by a placeholder so they will not interfere with the remapping.
259 // Warning: This will also catch on anything looking like the start of a comment between
260 // quotation marks (e.g. "foo /* bar").
263 $pattern = '/(?!' . CSSMin
::EMBED_REGEX
. ')(' . CSSMin
::COMMENT_REGEX
. ')/s';
265 $source = preg_replace_callback(
267 function ( $match ) use ( &$comments ) {
268 $comments[] = $match[ 0 ];
269 return CSSMin
::PLACEHOLDER
. ( count( $comments ) - 1 ) . 'x';
274 // Note: This will not correctly handle cases where ';', '{' or '}'
275 // appears in the rule itself, e.g. in a quoted string. You are advised
276 // not to use such characters in file names. We also match start/end of
277 // the string to be consistent in edge-cases ('@import url(…)').
278 $pattern = '/(?:^|[;{])\K[^;{}]*' . CSSMin
::URL_REGEX
. '[^;}]*(?=[;}]|$)/';
280 $source = preg_replace_callback(
282 function ( $matchOuter ) use ( $local, $remote, $embedData ) {
283 $rule = $matchOuter[0];
285 // Check for global @embed comment and remove it. Allow other comments to be present
286 // before @embed (they have been replaced with placeholders at this point).
288 $rule = preg_replace( '/^((?:\s+|' . CSSMin
::PLACEHOLDER
. '(\d+)x)*)' . CSSMin
::EMBED_REGEX
. '\s*/', '$1', $rule, 1, $embedAll );
290 // Build two versions of current rule: with remapped URLs
291 // and with embedded data: URIs (where possible).
292 $pattern = '/(?P<embed>' . CSSMin
::EMBED_REGEX
. '\s*|)' . CSSMin
::URL_REGEX
. '/';
294 $ruleWithRemapped = preg_replace_callback(
296 function ( $match ) use ( $local, $remote ) {
297 $remapped = CSSMin
::remapOne( $match['file'], $match['query'], $local, $remote, false );
299 return CSSMin
::buildUrlValue( $remapped );
305 // Remember the occurring MIME types to avoid fallbacks when embedding some files.
306 $mimeTypes = array();
308 $ruleWithEmbedded = preg_replace_callback(
310 function ( $match ) use ( $embedAll, $local, $remote, &$mimeTypes ) {
311 $embed = $embedAll ||
$match['embed'];
312 $embedded = CSSMin
::remapOne(
320 $url = $match['file'] . $match['query'];
321 $file = $local . $match['file'];
323 !CSSMin
::isRemoteUrl( $url ) && !CSSMin
::isLocalUrl( $url )
324 && file_exists( $file )
326 $mimeTypes[ CSSMin
::getMimeType( $file ) ] = true;
329 return CSSMin
::buildUrlValue( $embedded );
334 // Are all referenced images SVGs?
335 $needsEmbedFallback = $mimeTypes !== array( 'image/svg+xml' => true );
338 if ( !$embedData ||
$ruleWithEmbedded === $ruleWithRemapped ) {
339 // We're not embedding anything, or we tried to but the file is not embeddable
340 return $ruleWithRemapped;
341 } elseif ( $embedData && $needsEmbedFallback ) {
342 // Build 2 CSS properties; one which uses a data URI in place of the @embed comment, and
343 // the other with a remapped and versioned URL with an Internet Explorer 6 and 7 hack
344 // making it ignored in all browsers that support data URIs
345 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
347 // Look ma, no fallbacks! This is for files which IE 6 and 7 don't support anyway: SVG.
348 return $ruleWithEmbedded;
352 // Re-insert comments
353 $pattern = '/' . CSSMin
::PLACEHOLDER
. '(\d+)x/';
354 $source = preg_replace_callback( $pattern, function( $match ) use ( &$comments ) {
355 return $comments[ $match[1] ];
363 * Is this CSS rule referencing a remote URL?
365 * @private Until we require PHP 5.5 and we can access self:: from closures.
366 * @param string $maybeUrl
369 public static function isRemoteUrl( $maybeUrl ) {
370 if ( substr( $maybeUrl, 0, 2 ) === '//' ||
parse_url( $maybeUrl, PHP_URL_SCHEME
) ) {
377 * Is this CSS rule referencing a local URL?
379 * @private Until we require PHP 5.5 and we can access self:: from closures.
380 * @param string $maybeUrl
383 public static function isLocalUrl( $maybeUrl ) {
384 if ( $maybeUrl !== '' && $maybeUrl[0] === '/' && !self
::isRemoteUrl( $maybeUrl ) ) {
391 * Remap or embed a CSS URL path.
393 * @param string $file URL to remap/embed
394 * @param string $query
395 * @param string $local File path where the source was read from
396 * @param string $remote URL path to the file
397 * @param bool $embed Whether to do any data URI embedding
398 * @return string Remapped/embedded URL data
400 public static function remapOne( $file, $query, $local, $remote, $embed ) {
401 // The full URL possibly with query, as passed to the 'url()' value in CSS
402 $url = $file . $query;
404 // Expand local URLs with absolute paths like /w/index.php to possibly protocol-relative URL, if
405 // wfExpandUrl() is available. (This will not be the case if we're running outside of MW.)
406 if ( self
::isLocalUrl( $url ) && function_exists( 'wfExpandUrl' ) ) {
407 return wfExpandUrl( $url, PROTO_RELATIVE
);
410 // Pass thru fully-qualified and protocol-relative URLs and data URIs, as well as local URLs if
411 // we can't expand them.
412 if ( self
::isRemoteUrl( $url ) || self
::isLocalUrl( $url ) ) {
416 if ( $local === false ) {
417 // Assume that all paths are relative to $remote, and make them absolute
418 $url = $remote . '/' . $url;
420 // We drop the query part here and instead make the path relative to $remote
421 $url = "{$remote}/{$file}";
422 // Path to the actual file on the filesystem
423 $localFile = "{$local}/{$file}";
424 if ( file_exists( $localFile ) ) {
425 // Add version parameter as the first five hex digits
426 // of the MD5 hash of the file's contents.
427 $url .= '?' . substr( md5_file( $localFile ), 0, 5 );
429 $data = self
::encodeImageAsDataURI( $localFile );
430 if ( $data !== false ) {
435 // If any of these conditions failed (file missing, we don't want to embed it
436 // or it's not embeddable), return the URL (possibly with ?timestamp part)
438 if ( function_exists( 'wfRemoveDotSegments' ) ) {
439 $url = wfRemoveDotSegments( $url );
445 * Removes whitespace from CSS data
447 * @param string $css CSS data to minify
448 * @return string Minified CSS data
450 public static function minify( $css ) {
453 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
454 array( ';', ':', '{', '{', ',', '}', '}' ),
455 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )