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*\)';
43 /* Protected Static Members */
45 /** @var array List of common image files extensions and mime-types */
46 protected static $mimeTypes = array(
48 'jpe' => 'image/jpeg',
49 'jpeg' => 'image/jpeg',
50 'jpg' => 'image/jpeg',
52 'tif' => 'image/tiff',
53 'tiff' => 'image/tiff',
54 'xbm' => 'image/x-xbitmap',
60 * Gets a list of local file paths which are referenced in a CSS style sheet
62 * @param string $source CSS data to remap
63 * @param string $path File path where the source was read from (optional)
64 * @return array List of local file references
66 public static function getLocalFileReferences( $source, $path = null ) {
68 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER
;
69 if ( preg_match_all( '/' . self
::URL_REGEX
. '/', $source, $matches, $rFlags ) ) {
70 foreach ( $matches as $match ) {
71 $file = ( isset( $path )
72 ?
rtrim( $path, '/' ) . '/'
73 : '' ) . "{$match['file'][0]}";
75 // Only proceed if we can access the file
76 if ( !is_null( $path ) && file_exists( $file ) ) {
85 * Encode an image file as a base64 data URI.
86 * If the image file has a suitable MIME type and size, encode it as a
87 * base64 data URI. Return false if the image type is unfamiliar or exceeds
90 * @param string $file Image file to encode.
91 * @param string|null $type File's MIME type or null. If null, CSSMin will
92 * try to autodetect the type.
93 * @param int|bool $sizeLimit If the size of the target file is greater than
94 * this value, decline to encode the image file and return false
95 * instead. If $sizeLimit is false, no limit is enforced.
96 * @return string|bool: Image contents encoded as a data URI or false.
98 public static function encodeImageAsDataURI( $file, $type = null, $sizeLimit = self
::EMBED_SIZE_LIMIT
) {
99 if ( $sizeLimit !== false && filesize( $file ) >= $sizeLimit ) {
102 if ( $type === null ) {
103 $type = self
::getMimeType( $file );
108 $data = base64_encode( file_get_contents( $file ) );
109 return 'data:' . $type . ';base64,' . $data;
113 * @param $file string
114 * @return bool|string
116 public static function getMimeType( $file ) {
117 $realpath = realpath( $file );
118 // Try a couple of different ways to get the mime-type of a file, in order of
122 && function_exists( 'finfo_file' )
123 && function_exists( 'finfo_open' )
124 && defined( 'FILEINFO_MIME_TYPE' )
126 // As of PHP 5.3, this is how you get the mime-type of a file; it uses the Fileinfo
128 return finfo_file( finfo_open( FILEINFO_MIME_TYPE
), $realpath );
129 } elseif ( function_exists( 'mime_content_type' ) ) {
130 // Before this was deprecated in PHP 5.3, this was how you got the mime-type of a file
131 return mime_content_type( $file );
133 // Worst-case scenario has happened, use the file extension to infer the mime-type
134 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION
) );
135 if ( isset( self
::$mimeTypes[$ext] ) ) {
136 return self
::$mimeTypes[$ext];
143 * Remaps CSS URL paths and automatically embeds data URIs for URL rules
144 * preceded by an /* @embed * / comment
146 * @param string $source CSS data to remap
147 * @param string $local File path where the source was read from
148 * @param string $remote URL path to the file
149 * @param bool $embedData If false, never do any data URI embedding, even if / * @embed * / is found
150 * @return string Remapped CSS data
152 public static function remap( $source, $local, $remote, $embedData = true ) {
153 $pattern = '/((?P<embed>\s*\/\*\s*\@embed\s*\*\/)(?P<pre>[^\;\}]*))?' .
154 self
::URL_REGEX
. '(?P<post>[^;]*)[\;]?/';
156 while ( preg_match( $pattern, $source, $match, PREG_OFFSET_CAPTURE
, $offset ) ) {
157 // Skip fully-qualified URLs and data URIs
158 $urlScheme = parse_url( $match['file'][0], PHP_URL_SCHEME
);
160 // Move the offset to the end of the match, leaving it alone
161 $offset = $match[0][1] +
strlen( $match[0][0] );
164 // URLs with absolute paths like /w/index.php need to be expanded
165 // to absolute URLs but otherwise left alone
166 if ( $match['file'][0] !== '' && $match['file'][0][0] === '/' ) {
167 // Replace the file path with an expanded (possibly protocol-relative) URL
168 // ...but only if wfExpandUrl() is even available.
169 // This will not be the case if we're running outside of MW
171 if ( function_exists( 'wfExpandUrl' ) ) {
172 $expanded = wfExpandUrl( $match['file'][0], PROTO_RELATIVE
);
173 $origLength = strlen( $match['file'][0] );
174 $lengthIncrease = strlen( $expanded ) - $origLength;
175 $source = substr_replace( $source, $expanded,
176 $match['file'][1], $origLength
179 // Move the offset to the end of the match, leaving it alone
180 $offset = $match[0][1] +
strlen( $match[0][0] ) +
$lengthIncrease;
184 // Guard against double slashes, because "some/remote/../foo.png"
185 // resolves to "some/remote/foo.png" on (some?) clients (bug 27052).
186 if ( substr( $remote, -1 ) == '/' ) {
187 $remote = substr( $remote, 0, -1 );
191 $embed = $match['embed'][0];
192 $pre = $match['pre'][0];
193 $post = $match['post'][0];
194 $query = $match['query'][0];
195 $url = "{$remote}/{$match['file'][0]}";
196 $file = "{$local}/{$match['file'][0]}";
198 $replacement = false;
200 if ( $local !== false && file_exists( $file ) ) {
201 // Add version parameter as a time-stamp in ISO 8601 format,
202 // using Z for the timezone, meaning GMT
203 $url .= '?' . gmdate( 'Y-m-d\TH:i:s\Z', round( filemtime( $file ), -2 ) );
204 // Embedding requires a bit of extra processing, so let's skip that if we can
205 if ( $embedData && $embed && $match['embed'][1] > 0 ) {
206 $data = self
::encodeImageAsDataURI( $file );
207 if ( $data !== false ) {
208 // Build 2 CSS properties; one which uses a base64 encoded data URI in place
209 // of the @embed comment to try and retain line-number integrity, and the
210 // other with a remapped an versioned URL and an Internet Explorer hack
211 // making it ignored in all browsers that support data URIs
212 $replacement = "{$pre}url({$data}){$post};{$pre}url({$url}){$post}!ie;";
215 if ( $replacement === false ) {
216 // Assume that all paths are relative to $remote, and make them absolute
217 $replacement = "{$embed}{$pre}url({$url}){$post};";
219 } elseif ( $local === false ) {
220 // Assume that all paths are relative to $remote, and make them absolute
221 $replacement = "{$embed}{$pre}url({$url}{$query}){$post};";
223 if ( $replacement !== false ) {
224 // Perform replacement on the source
225 $source = substr_replace(
226 $source, $replacement, $match[0][1], strlen( $match[0][0] )
228 // Move the offset to the end of the replacement in the source
229 $offset = $match[0][1] +
strlen( $replacement );
232 // Move the offset to the end of the match, leaving it alone
233 $offset = $match[0][1] +
strlen( $match[0][0] );
239 * Removes whitespace from CSS data
241 * @param string $css CSS data to minify
242 * @return string Minified CSS data
244 public static function minify( $css ) {
247 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
248 array( ';', ':', '{', '{', ',', '}', '}' ),
249 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )