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.
35 * Maximum file size to still qualify for in-line embedding as a data-URI
37 * 24,576 is used because Internet Explorer has a 32,768 byte limit for data URIs,
38 * which when base64 encoded will result in a 1/3 increase in size.
40 const EMBED_SIZE_LIMIT
= 24576;
41 const URL_REGEX
= 'url\(\s*[\'"]?(?P<file>[^\?\)\'"]*?)(?P<query>\?[^\)\'"]*?|)[\'"]?\s*\)';
42 const EMBED_REGEX
= '\/\*\s*\@embed\s*\*\/';
44 /* Protected Static Members */
46 /** @var array List of common image files extensions and mime-types */
47 protected static $mimeTypes = array(
49 'jpe' => 'image/jpeg',
50 'jpeg' => 'image/jpeg',
51 'jpg' => 'image/jpeg',
53 'tif' => 'image/tiff',
54 'tiff' => 'image/tiff',
55 'xbm' => 'image/x-xbitmap',
56 'svg' => 'image/svg+xml',
62 * Gets a list of local file paths which are referenced in a CSS style sheet
64 * @param string $source CSS data to remap
65 * @param string $path File path where the source was read from (optional)
66 * @return array List of local file references
68 public static function getLocalFileReferences( $source, $path = null ) {
70 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER
;
71 if ( preg_match_all( '/' . self
::URL_REGEX
. '/', $source, $matches, $rFlags ) ) {
72 foreach ( $matches as $match ) {
73 $file = ( isset( $path )
74 ?
rtrim( $path, '/' ) . '/'
75 : '' ) . "{$match['file'][0]}";
77 // Only proceed if we can access the file
78 if ( !is_null( $path ) && file_exists( $file ) ) {
87 * Encode an image file as a base64 data URI.
88 * If the image file has a suitable MIME type and size, encode it as a
89 * base64 data URI. Return false if the image type is unfamiliar or exceeds
92 * @param string $file Image file to encode.
93 * @param string|null $type File's MIME type or null. If null, CSSMin will
94 * try to autodetect the type.
95 * @param int|bool $sizeLimit If the size of the target file is greater than
96 * this value, decline to encode the image file and return false
97 * instead. If $sizeLimit is false, no limit is enforced.
98 * @return string|bool: Image contents encoded as a data URI or false.
100 public static function encodeImageAsDataURI( $file, $type = null, $sizeLimit = self
::EMBED_SIZE_LIMIT
) {
101 if ( $sizeLimit !== false && filesize( $file ) >= $sizeLimit ) {
104 if ( $type === null ) {
105 $type = self
::getMimeType( $file );
110 $data = base64_encode( file_get_contents( $file ) );
111 return 'data:' . $type . ';base64,' . $data;
115 * @param $file string
116 * @return bool|string
118 public static function getMimeType( $file ) {
119 $realpath = realpath( $file );
120 // Try a couple of different ways to get the mime-type of a file, in order of
124 && function_exists( 'finfo_file' )
125 && function_exists( 'finfo_open' )
126 && defined( 'FILEINFO_MIME_TYPE' )
128 // As of PHP 5.3, this is how you get the mime-type of a file; it uses the Fileinfo
130 return finfo_file( finfo_open( FILEINFO_MIME_TYPE
), $realpath );
131 } elseif ( function_exists( 'mime_content_type' ) ) {
132 // Before this was deprecated in PHP 5.3, this was how you got the mime-type of a file
133 return mime_content_type( $file );
135 // Worst-case scenario has happened, use the file extension to infer the mime-type
136 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION
) );
137 if ( isset( self
::$mimeTypes[$ext] ) ) {
138 return self
::$mimeTypes[$ext];
145 * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
146 * and escaping quotes as necessary.
148 * @param string $url URL to process
149 * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
151 public static function buildUrlValue( $url ) {
152 // The list below has been crafted to match URLs such as:
153 // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
154 // data:image/png;base64,R0lGODlh/+==
155 if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
158 return 'url("' . strtr( $url, array( '\\' => '\\\\', '"' => '\\"' ) ) . '")';
163 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules or url() values
164 * preceded by an / * @embed * / comment.
166 * @param string $source CSS data to remap
167 * @param string $local File path where the source was read from
168 * @param string $remote URL path to the file
169 * @param bool $embedData If false, never do any data URI embedding, even if / * @embed * / is found
170 * @return string Remapped CSS data
172 public static function remap( $source, $local, $remote, $embedData = true ) {
173 // High-level overview:
174 // * For each CSS rule in $source that includes at least one url() value:
175 // * Check for an @embed comment at the start indicating that all URIs should be embedded
176 // * For each url() value:
177 // * Check for an @embed comment directly preceding the value
178 // * If either @embed comment exists:
179 // * Embedding the URL as data: URI, if it's possible / allowed
180 // * Otherwise remap the URL to work in generated stylesheets
182 // Guard against trailing slashes, because "some/remote/../foo.png"
183 // resolves to "some/remote/foo.png" on (some?) clients (bug 27052).
184 if ( substr( $remote, -1 ) == '/' ) {
185 $remote = substr( $remote, 0, -1 );
188 // Note: This will not correctly handle cases where ';', '{' or '}' appears in the rule itself,
189 // e.g. in a quoted string. You are advised not to use such characters in file names.
190 // We also match start/end of the string to be consistent in edge-cases ('@import url(…)').
191 $pattern = '/(?:^|[;{])\K[^;{}]*' . CSSMin
::URL_REGEX
. '[^;}]*(?=[;}]|$)/';
192 return preg_replace_callback( $pattern, function ( $matchOuter ) use ( $local, $remote, $embedData ) {
193 $rule = $matchOuter[0];
195 // Check for global @embed comment and remove it
197 $rule = preg_replace( '/^(\s*)' . CSSMin
::EMBED_REGEX
. '\s*/', '$1', $rule, 1, $embedAll );
199 // Build two versions of current rule: with remapped URLs and with embedded data: URIs (where possible)
200 $pattern = '/(?P<embed>' . CSSMin
::EMBED_REGEX
. '\s*|)' . CSSMin
::URL_REGEX
. '/';
202 $ruleWithRemapped = preg_replace_callback( $pattern, function ( $match ) use ( $local, $remote ) {
203 $remapped = CSSMin
::remapOne( $match['file'], $match['query'], $local, $remote, false );
204 return CSSMin
::buildUrlValue( $remapped );
208 $ruleWithEmbedded = preg_replace_callback( $pattern, function ( $match ) use ( $embedAll, $local, $remote ) {
209 $embed = $embedAll ||
$match['embed'];
210 $embedded = CSSMin
::remapOne( $match['file'], $match['query'], $local, $remote, $embed );
211 return CSSMin
::buildUrlValue( $embedded );
215 if ( $embedData && $ruleWithEmbedded !== $ruleWithRemapped ) {
216 // Build 2 CSS properties; one which uses a base64 encoded data URI in place
217 // of the @embed comment to try and retain line-number integrity, and the
218 // other with a remapped an versioned URL and an Internet Explorer hack
219 // making it ignored in all browsers that support data URIs
220 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
222 // No reason to repeat twice
223 return $ruleWithRemapped;
229 * Remap or embed a CSS URL path.
231 * @param string $file URL to remap/embed
232 * @param string $query
233 * @param string $local File path where the source was read from
234 * @param string $remote URL path to the file
235 * @param bool $embed Whether to do any data URI embedding
236 * @return string Remapped/embedded URL data
238 public static function remapOne( $file, $query, $local, $remote, $embed ) {
239 // The full URL possibly with query, as passed to the 'url()' value in CSS
240 $url = $file . $query;
242 // Skip fully-qualified and protocol-relative URLs and data URIs
243 $urlScheme = substr( $url, 0, 2 ) === '//' ||
parse_url( $url, PHP_URL_SCHEME
);
248 // URLs with absolute paths like /w/index.php need to be expanded
249 // to absolute URLs but otherwise left alone
250 if ( $url !== '' && $url[0] === '/' ) {
251 // Replace the file path with an expanded (possibly protocol-relative) URL
252 // ...but only if wfExpandUrl() is even available.
253 // This will not be the case if we're running outside of MW
254 if ( function_exists( 'wfExpandUrl' ) ) {
255 return wfExpandUrl( $url, PROTO_RELATIVE
);
261 if ( $local === false ) {
262 // Assume that all paths are relative to $remote, and make them absolute
263 return $remote . '/' . $url;
265 // We drop the query part here and instead make the path relative to $remote
266 $url = "{$remote}/{$file}";
267 // Path to the actual file on the filesystem
268 $localFile = "{$local}/{$file}";
269 if ( file_exists( $localFile ) ) {
270 // Add version parameter as a time-stamp in ISO 8601 format,
271 // using Z for the timezone, meaning GMT
272 $url .= '?' . gmdate( 'Y-m-d\TH:i:s\Z', round( filemtime( $localFile ), -2 ) );
274 $data = self
::encodeImageAsDataURI( $localFile );
275 if ( $data !== false ) {
280 // If any of these conditions failed (file missing, we don't want to embed it
281 // or it's not embeddable), return the URL (possibly with ?timestamp part)
287 * Removes whitespace from CSS data
289 * @param string $css CSS data to minify
290 * @return string Minified CSS data
292 public static function minify( $css ) {
295 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
296 array( ';', ':', '{', '{', ',', '}', '}' ),
297 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )