CSSMin: Do not base64-encode non-binary files when embedding
[lhc/web/wiklou.git] / includes / libs / CSSMin.php
1 <?php
2 /**
3 * Minification of CSS stylesheets.
4 *
5 * Copyright 2010 Wikimedia Foundation
6 *
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
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
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.
17 *
18 * @file
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
23 */
24
25 /**
26 * Transforms CSS data
27 *
28 * This class provides minification, URL remapping, URL extracting, and data-URL embedding.
29 */
30 class CSSMin {
31
32 /* Constants */
33
34 /**
35 * Maximum file size to still qualify for in-line embedding as a data-URI
36 *
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.
39 */
40 const EMBED_SIZE_LIMIT = 24576;
41 const DATA_URI_SIZE_LIMIT = 32768;
42 const URL_REGEX = 'url\(\s*[\'"]?(?P<file>[^\?\)\'"]*?)(?P<query>\?[^\)\'"]*?|)[\'"]?\s*\)';
43 const EMBED_REGEX = '\/\*\s*\@embed\s*\*\/';
44 const COMMENT_REGEX = '\/\*.*?\*\/';
45
46 /* Protected Static Members */
47
48 /** @var array List of common image files extensions and MIME-types */
49 protected static $mimeTypes = array(
50 'gif' => 'image/gif',
51 'jpe' => 'image/jpeg',
52 'jpeg' => 'image/jpeg',
53 'jpg' => 'image/jpeg',
54 'png' => 'image/png',
55 'tif' => 'image/tiff',
56 'tiff' => 'image/tiff',
57 'xbm' => 'image/x-xbitmap',
58 'svg' => 'image/svg+xml',
59 );
60
61 /* Static Methods */
62
63 /**
64 * Gets a list of local file paths which are referenced in a CSS style sheet
65 *
66 * This function will always return an empty array if the second parameter is not given or null
67 * for backwards-compatibility.
68 *
69 * @param string $source CSS data to remap
70 * @param string $path File path where the source was read from (optional)
71 * @return array List of local file references
72 */
73 public static function getLocalFileReferences( $source, $path = null ) {
74 if ( $path === null ) {
75 return array();
76 }
77
78 $path = rtrim( $path, '/' ) . '/';
79 $files = array();
80
81 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER;
82 if ( preg_match_all( '/' . self::URL_REGEX . '/', $source, $matches, $rFlags ) ) {
83 foreach ( $matches as $match ) {
84 $url = $match['file'][0];
85
86 // Skip fully-qualified and protocol-relative URLs and data URIs
87 if ( substr( $url, 0, 2 ) === '//' || parse_url( $url, PHP_URL_SCHEME ) ) {
88 break;
89 }
90
91 $file = $path . $url;
92 // Skip non-existent files
93 if ( file_exists( $file ) ) {
94 break;
95 }
96
97 $files[] = $file;
98 }
99 }
100 return $files;
101 }
102
103 /**
104 * Encode an image file as a data URI.
105 *
106 * If the image file has a suitable MIME type and size, encode it as a data URI, base64-encoded
107 * for binary files or just percent-encoded otherwise. Return false if the image type is
108 * unfamiliar or file exceeds the size limit.
109 *
110 * @param string $file Image file to encode.
111 * @param string|null $type File's MIME type or null. If null, CSSMin will
112 * try to autodetect the type.
113 * @param int|bool $sizeLimit If the size of the target file is greater than
114 * this value, decline to encode the image file and return false
115 * instead. If $sizeLimit is false, no limit is enforced.
116 * @return string|bool Image contents encoded as a data URI or false.
117 */
118 public static function encodeImageAsDataURI( $file, $type = null,
119 $sizeLimit = self::EMBED_SIZE_LIMIT
120 ) {
121 if ( $sizeLimit !== false && filesize( $file ) >= $sizeLimit ) {
122 return false;
123 }
124 if ( $type === null ) {
125 $type = self::getMimeType( $file );
126 }
127 if ( !$type ) {
128 return false;
129 }
130
131 $contents = file_get_contents( $file );
132 // Only whitespace and printable ASCII characters
133 $isText = (bool)preg_match( '/^[\r\n\t\x20-\x7e]+$/', $contents );
134
135 if ( $isText ) {
136 // Do not base64-encode non-binary files (sane SVGs), unless that'd exceed URI length limit.
137 // (This often produces longer URLs, but they compress better, yielding a net smaller size.)
138 $uri = 'data:' . $type . ',' . rawurlencode( $contents );
139 if ( strlen( $uri ) >= self::DATA_URI_SIZE_LIMIT ) {
140 $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
141 }
142 } else {
143 $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
144 }
145
146 return $uri;
147 }
148
149 /**
150 * @param $file string
151 * @return bool|string
152 */
153 public static function getMimeType( $file ) {
154 $realpath = realpath( $file );
155 if (
156 $realpath
157 && function_exists( 'finfo_file' )
158 && function_exists( 'finfo_open' )
159 && defined( 'FILEINFO_MIME_TYPE' )
160 ) {
161 return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
162 }
163
164 // Infer the MIME-type from the file extension
165 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
166 if ( isset( self::$mimeTypes[$ext] ) ) {
167 return self::$mimeTypes[$ext];
168 }
169
170 return false;
171 }
172
173 /**
174 * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
175 * and escaping quotes as necessary.
176 *
177 * See http://www.w3.org/TR/css-syntax-3/#consume-a-url-token
178 *
179 * @param string $url URL to process
180 * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
181 */
182 public static function buildUrlValue( $url ) {
183 // The list below has been crafted to match URLs such as:
184 // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
185 // data:image/png;base64,R0lGODlh/+==
186 if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
187 return "url($url)";
188 } else {
189 return 'url("' . strtr( $url, array( '\\' => '\\\\', '"' => '\\"' ) ) . '")';
190 }
191 }
192
193 /**
194 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
195 * or url() values preceded by an / * @embed * / comment.
196 *
197 * @param string $source CSS data to remap
198 * @param string $local File path where the source was read from
199 * @param string $remote URL path to the file
200 * @param bool $embedData If false, never do any data URI embedding,
201 * even if / * @embed * / is found.
202 * @return string Remapped CSS data
203 */
204 public static function remap( $source, $local, $remote, $embedData = true ) {
205 // High-level overview:
206 // * For each CSS rule in $source that includes at least one url() value:
207 // * Check for an @embed comment at the start indicating that all URIs should be embedded
208 // * For each url() value:
209 // * Check for an @embed comment directly preceding the value
210 // * If either @embed comment exists:
211 // * Embedding the URL as data: URI, if it's possible / allowed
212 // * Otherwise remap the URL to work in generated stylesheets
213
214 // Guard against trailing slashes, because "some/remote/../foo.png"
215 // resolves to "some/remote/foo.png" on (some?) clients (bug 27052).
216 if ( substr( $remote, -1 ) == '/' ) {
217 $remote = substr( $remote, 0, -1 );
218 }
219
220 // Replace all comments by a placeholder so they will not interfere with the remapping.
221 // Warning: This will also catch on anything looking like the start of a comment between
222 // quotation marks (e.g. "foo /* bar").
223 $comments = array();
224 $placeholder = uniqid( '', true );
225
226 $pattern = '/(?!' . CSSMin::EMBED_REGEX . ')(' . CSSMin::COMMENT_REGEX . ')/s';
227
228 $source = preg_replace_callback(
229 $pattern,
230 function ( $match ) use ( &$comments, $placeholder ) {
231 $comments[] = $match[ 0 ];
232 return $placeholder . ( count( $comments ) - 1 ) . 'x';
233 },
234 $source
235 );
236
237 // Note: This will not correctly handle cases where ';', '{' or '}'
238 // appears in the rule itself, e.g. in a quoted string. You are advised
239 // not to use such characters in file names. We also match start/end of
240 // the string to be consistent in edge-cases ('@import url(…)').
241 $pattern = '/(?:^|[;{])\K[^;{}]*' . CSSMin::URL_REGEX . '[^;}]*(?=[;}]|$)/';
242
243 $source = preg_replace_callback(
244 $pattern,
245 function ( $matchOuter ) use ( $local, $remote, $embedData, $placeholder ) {
246 $rule = $matchOuter[0];
247
248 // Check for global @embed comment and remove it. Allow other comments to be present
249 // before @embed (they have been replaced with placeholders at this point).
250 $embedAll = false;
251 $rule = preg_replace( '/^((?:\s+|' . $placeholder . '(\d+)x)*)' . CSSMin::EMBED_REGEX . '\s*/', '$1', $rule, 1, $embedAll );
252
253 // Build two versions of current rule: with remapped URLs
254 // and with embedded data: URIs (where possible).
255 $pattern = '/(?P<embed>' . CSSMin::EMBED_REGEX . '\s*|)' . CSSMin::URL_REGEX . '/';
256
257 $ruleWithRemapped = preg_replace_callback(
258 $pattern,
259 function ( $match ) use ( $local, $remote ) {
260 $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
261
262 return CSSMin::buildUrlValue( $remapped );
263 },
264 $rule
265 );
266
267 if ( $embedData ) {
268 $ruleWithEmbedded = preg_replace_callback(
269 $pattern,
270 function ( $match ) use ( $embedAll, $local, $remote ) {
271 $embed = $embedAll || $match['embed'];
272 $embedded = CSSMin::remapOne(
273 $match['file'],
274 $match['query'],
275 $local,
276 $remote,
277 $embed
278 );
279
280 return CSSMin::buildUrlValue( $embedded );
281 },
282 $rule
283 );
284 }
285
286 if ( $embedData && $ruleWithEmbedded !== $ruleWithRemapped ) {
287 // Build 2 CSS properties; one which uses a base64 encoded data URI in place
288 // of the @embed comment to try and retain line-number integrity, and the
289 // other with a remapped an versioned URL and an Internet Explorer hack
290 // making it ignored in all browsers that support data URIs
291 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
292 } else {
293 // No reason to repeat twice
294 return $ruleWithRemapped;
295 }
296 }, $source );
297
298 // Re-insert comments
299 $pattern = '/' . $placeholder . '(\d+)x/';
300 $source = preg_replace_callback( $pattern, function( $match ) use ( &$comments ) {
301 return $comments[ $match[1] ];
302 }, $source );
303
304 return $source;
305
306 }
307
308 /**
309 * Remap or embed a CSS URL path.
310 *
311 * @param string $file URL to remap/embed
312 * @param string $query
313 * @param string $local File path where the source was read from
314 * @param string $remote URL path to the file
315 * @param bool $embed Whether to do any data URI embedding
316 * @return string Remapped/embedded URL data
317 */
318 public static function remapOne( $file, $query, $local, $remote, $embed ) {
319 // The full URL possibly with query, as passed to the 'url()' value in CSS
320 $url = $file . $query;
321
322 // Skip fully-qualified and protocol-relative URLs and data URIs
323 if ( substr( $url, 0, 2 ) === '//' || parse_url( $url, PHP_URL_SCHEME ) ) {
324 return $url;
325 }
326
327 // URLs with absolute paths like /w/index.php need to be expanded
328 // to absolute URLs but otherwise left alone
329 if ( $url !== '' && $url[0] === '/' ) {
330 // Replace the file path with an expanded (possibly protocol-relative) URL
331 // ...but only if wfExpandUrl() is even available.
332 // This will not be the case if we're running outside of MW
333 if ( function_exists( 'wfExpandUrl' ) ) {
334 return wfExpandUrl( $url, PROTO_RELATIVE );
335 } else {
336 return $url;
337 }
338 }
339
340 if ( $local === false ) {
341 // Assume that all paths are relative to $remote, and make them absolute
342 return $remote . '/' . $url;
343 } else {
344 // We drop the query part here and instead make the path relative to $remote
345 $url = "{$remote}/{$file}";
346 // Path to the actual file on the filesystem
347 $localFile = "{$local}/{$file}";
348 if ( file_exists( $localFile ) ) {
349 // Add version parameter as a time-stamp in ISO 8601 format,
350 // using Z for the timezone, meaning GMT
351 $url .= '?' . gmdate( 'Y-m-d\TH:i:s\Z', round( filemtime( $localFile ), -2 ) );
352 if ( $embed ) {
353 $data = self::encodeImageAsDataURI( $localFile );
354 if ( $data !== false ) {
355 return $data;
356 }
357 }
358 }
359 // If any of these conditions failed (file missing, we don't want to embed it
360 // or it's not embeddable), return the URL (possibly with ?timestamp part)
361 return $url;
362 }
363 }
364
365 /**
366 * Removes whitespace from CSS data
367 *
368 * @param string $css CSS data to minify
369 * @return string Minified CSS data
370 */
371 public static function minify( $css ) {
372 return trim(
373 str_replace(
374 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
375 array( ';', ':', '{', '{', ',', '}', '}' ),
376 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )
377 )
378 );
379 }
380 }