2c904319c34a5c517e265ff11cc633c3570978e7
[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 /** @var string Strip marker for comments. **/
35 const PLACEHOLDER = "\x7fPLACEHOLDER\x7f";
36
37 /**
38 * Internet Explorer data URI length limit. See encodeImageAsDataURI().
39 */
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 = '\/\*.*?\*\/';
44
45 /* Protected Static Members */
46
47 /** @var array List of common image files extensions and MIME-types */
48 protected static $mimeTypes = array(
49 'gif' => 'image/gif',
50 'jpe' => 'image/jpeg',
51 'jpeg' => 'image/jpeg',
52 'jpg' => 'image/jpeg',
53 'png' => 'image/png',
54 'tif' => 'image/tiff',
55 'tiff' => 'image/tiff',
56 'xbm' => 'image/x-xbitmap',
57 'svg' => 'image/svg+xml',
58 );
59
60 /* Static Methods */
61
62 /**
63 * Gets a list of local file paths which are referenced in a CSS style sheet
64 *
65 * This function will always return an empty array if the second parameter is not given or null
66 * for backwards-compatibility.
67 *
68 * @param string $source CSS data to remap
69 * @param string $path File path where the source was read from (optional)
70 * @return array List of local file references
71 */
72 public static function getLocalFileReferences( $source, $path = null ) {
73 if ( $path === null ) {
74 return array();
75 }
76
77 $path = rtrim( $path, '/' ) . '/';
78 $files = array();
79
80 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER;
81 if ( preg_match_all( '/' . self::URL_REGEX . '/', $source, $matches, $rFlags ) ) {
82 foreach ( $matches as $match ) {
83 $url = $match['file'][0];
84
85 // Skip fully-qualified and protocol-relative URLs and data URIs
86 if ( substr( $url, 0, 2 ) === '//' || parse_url( $url, PHP_URL_SCHEME ) ) {
87 break;
88 }
89
90 $file = $path . $url;
91 // Skip non-existent files
92 if ( file_exists( $file ) ) {
93 break;
94 }
95
96 $files[] = $file;
97 }
98 }
99 return $files;
100 }
101
102 /**
103 * Encode an image file as a data URI.
104 *
105 * If the image file has a suitable MIME type and size, encode it as a data URI, base64-encoded
106 * for binary files or just percent-encoded otherwise. Return false if the image type is
107 * unfamiliar or file exceeds the size limit.
108 *
109 * @param string $file Image file to encode.
110 * @param string|null $type File's MIME type or null. If null, CSSMin will
111 * try to autodetect the type.
112 * @param bool $ie8Compat By default, a data URI will only be produced if it can be made short
113 * enough to fit in Internet Explorer 8 (and earlier) URI length limit (32,768 bytes). Pass
114 * `false` to remove this limitation.
115 * @return string|bool Image contents encoded as a data URI or false.
116 */
117 public static function encodeImageAsDataURI( $file, $type = null, $ie8Compat = true ) {
118 // Fast-fail for files that definitely exceed the maximum data URI length
119 if ( $ie8Compat && filesize( $file ) >= self::DATA_URI_SIZE_LIMIT ) {
120 return false;
121 }
122
123 if ( $type === null ) {
124 $type = self::getMimeType( $file );
125 }
126 if ( !$type ) {
127 return false;
128 }
129
130 return self::encodeStringAsDataURI( file_get_contents( $file ), $type, $ie8Compat );
131 }
132
133 /**
134 * Encode file contents as a data URI with chosen MIME type.
135 *
136 * The URI will be base64-encoded for binary files or just percent-encoded otherwise.
137 *
138 * @since 1.25
139 *
140 * @param string $contents File contents to encode.
141 * @param string $type File's MIME type.
142 * @param bool $ie8Compat See encodeImageAsDataURI().
143 * @return string|bool Image contents encoded as a data URI or false.
144 */
145 public static function encodeStringAsDataURI( $contents, $type, $ie8Compat = true ) {
146 // Try #1: Non-encoded data URI
147 // The regular expression matches ASCII whitespace and printable characters.
148 if ( preg_match( '/^[\r\n\t\x20-\x7e]+$/', $contents ) ) {
149 // Do not base64-encode non-binary files (sane SVGs).
150 // (This often produces longer URLs, but they compress better, yielding a net smaller size.)
151 $uri = 'data:' . $type . ',' . rawurlencode( $contents );
152 if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
153 return $uri;
154 }
155 }
156
157 // Try #2: Encoded data URI
158 $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
159 if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
160 return $uri;
161 }
162
163 // A data URI couldn't be produced
164 return false;
165 }
166
167 /**
168 * @param $file string
169 * @return bool|string
170 */
171 public static function getMimeType( $file ) {
172 $realpath = realpath( $file );
173 if (
174 $realpath
175 && function_exists( 'finfo_file' )
176 && function_exists( 'finfo_open' )
177 && defined( 'FILEINFO_MIME_TYPE' )
178 ) {
179 return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
180 }
181
182 // Infer the MIME-type from the file extension
183 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
184 if ( isset( self::$mimeTypes[$ext] ) ) {
185 return self::$mimeTypes[$ext];
186 }
187
188 return false;
189 }
190
191 /**
192 * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
193 * and escaping quotes as necessary.
194 *
195 * See http://www.w3.org/TR/css-syntax-3/#consume-a-url-token
196 *
197 * @param string $url URL to process
198 * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
199 */
200 public static function buildUrlValue( $url ) {
201 // The list below has been crafted to match URLs such as:
202 // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
203 // data:image/png;base64,R0lGODlh/+==
204 if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
205 return "url($url)";
206 } else {
207 return 'url("' . strtr( $url, array( '\\' => '\\\\', '"' => '\\"' ) ) . '")';
208 }
209 }
210
211 /**
212 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
213 * or url() values preceded by an / * @embed * / comment.
214 *
215 * @param string $source CSS data to remap
216 * @param string $local File path where the source was read from
217 * @param string $remote URL path to the file
218 * @param bool $embedData If false, never do any data URI embedding,
219 * even if / * @embed * / is found.
220 * @return string Remapped CSS data
221 */
222 public static function remap( $source, $local, $remote, $embedData = true ) {
223 // High-level overview:
224 // * For each CSS rule in $source that includes at least one url() value:
225 // * Check for an @embed comment at the start indicating that all URIs should be embedded
226 // * For each url() value:
227 // * Check for an @embed comment directly preceding the value
228 // * If either @embed comment exists:
229 // * Embedding the URL as data: URI, if it's possible / allowed
230 // * Otherwise remap the URL to work in generated stylesheets
231
232 // Guard against trailing slashes, because "some/remote/../foo.png"
233 // resolves to "some/remote/foo.png" on (some?) clients (bug 27052).
234 if ( substr( $remote, -1 ) == '/' ) {
235 $remote = substr( $remote, 0, -1 );
236 }
237
238 // Disallow U+007F DELETE, which is illegal anyway, and which
239 // we use for comment placeholders.
240 $source = str_replace( "\x7f", "?", $source );
241
242 // Replace all comments by a placeholder so they will not interfere with the remapping.
243 // Warning: This will also catch on anything looking like the start of a comment between
244 // quotation marks (e.g. "foo /* bar").
245 $comments = array();
246
247 $pattern = '/(?!' . CSSMin::EMBED_REGEX . ')(' . CSSMin::COMMENT_REGEX . ')/s';
248
249 $source = preg_replace_callback(
250 $pattern,
251 function ( $match ) use ( &$comments ) {
252 $comments[] = $match[ 0 ];
253 return CSSMin::PLACEHOLDER . ( count( $comments ) - 1 ) . 'x';
254 },
255 $source
256 );
257
258 // Note: This will not correctly handle cases where ';', '{' or '}'
259 // appears in the rule itself, e.g. in a quoted string. You are advised
260 // not to use such characters in file names. We also match start/end of
261 // the string to be consistent in edge-cases ('@import url(…)').
262 $pattern = '/(?:^|[;{])\K[^;{}]*' . CSSMin::URL_REGEX . '[^;}]*(?=[;}]|$)/';
263
264 $source = preg_replace_callback(
265 $pattern,
266 function ( $matchOuter ) use ( $local, $remote, $embedData ) {
267 $rule = $matchOuter[0];
268
269 // Check for global @embed comment and remove it. Allow other comments to be present
270 // before @embed (they have been replaced with placeholders at this point).
271 $embedAll = false;
272 $rule = preg_replace( '/^((?:\s+|' . CSSMin::PLACEHOLDER . '(\d+)x)*)' . CSSMin::EMBED_REGEX . '\s*/', '$1', $rule, 1, $embedAll );
273
274 // Build two versions of current rule: with remapped URLs
275 // and with embedded data: URIs (where possible).
276 $pattern = '/(?P<embed>' . CSSMin::EMBED_REGEX . '\s*|)' . CSSMin::URL_REGEX . '/';
277
278 $ruleWithRemapped = preg_replace_callback(
279 $pattern,
280 function ( $match ) use ( $local, $remote ) {
281 $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
282
283 return CSSMin::buildUrlValue( $remapped );
284 },
285 $rule
286 );
287
288 if ( $embedData ) {
289 // Remember the occurring MIME types to avoid fallbacks when embedding some files.
290 $mimeTypes = array();
291
292 $ruleWithEmbedded = preg_replace_callback(
293 $pattern,
294 function ( $match ) use ( $embedAll, $local, $remote, &$mimeTypes ) {
295 $embed = $embedAll || $match['embed'];
296 $embedded = CSSMin::remapOne(
297 $match['file'],
298 $match['query'],
299 $local,
300 $remote,
301 $embed
302 );
303
304 $url = $match['file'] . $match['query'];
305 $file = $local . $match['file'];
306 if (
307 !CSSMin::isRemoteUrl( $url ) && !CSSMin::isLocalUrl( $url )
308 && file_exists( $file )
309 ) {
310 $mimeTypes[ CSSMin::getMimeType( $file ) ] = true;
311 }
312
313 return CSSMin::buildUrlValue( $embedded );
314 },
315 $rule
316 );
317
318 // Are all referenced images SVGs?
319 $needsEmbedFallback = $mimeTypes !== array( 'image/svg+xml' => true );
320 }
321
322 if ( !$embedData || $ruleWithEmbedded === $ruleWithRemapped ) {
323 // We're not embedding anything, or we tried to but the file is not embeddable
324 return $ruleWithRemapped;
325 } elseif ( $embedData && $needsEmbedFallback ) {
326 // Build 2 CSS properties; one which uses a data URI in place of the @embed comment, and
327 // the other with a remapped and versioned URL with an Internet Explorer 6 and 7 hack
328 // making it ignored in all browsers that support data URIs
329 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
330 } else {
331 // Look ma, no fallbacks! This is for files which IE 6 and 7 don't support anyway: SVG.
332 return $ruleWithEmbedded;
333 }
334 }, $source );
335
336 // Re-insert comments
337 $pattern = '/' . CSSMin::PLACEHOLDER . '(\d+)x/';
338 $source = preg_replace_callback( $pattern, function( $match ) use ( &$comments ) {
339 return $comments[ $match[1] ];
340 }, $source );
341
342 return $source;
343
344 }
345
346 /**
347 * Is this CSS rule referencing a remote URL?
348 *
349 * @private Until we require PHP 5.5 and we can access self:: from closures.
350 * @param string $maybeUrl
351 * @return bool
352 */
353 public static function isRemoteUrl( $maybeUrl ) {
354 if ( substr( $maybeUrl, 0, 2 ) === '//' || parse_url( $maybeUrl, PHP_URL_SCHEME ) ) {
355 return true;
356 }
357 return false;
358 }
359
360 /**
361 * Is this CSS rule referencing a local URL?
362 *
363 * @private Until we require PHP 5.5 and we can access self:: from closures.
364 * @param string $maybeUrl
365 * @return bool
366 */
367 public static function isLocalUrl( $maybeUrl ) {
368 if ( $maybeUrl !== '' && $maybeUrl[0] === '/' && !self::isRemoteUrl( $maybeUrl ) ) {
369 return true;
370 }
371 return false;
372 }
373
374 /**
375 * Remap or embed a CSS URL path.
376 *
377 * @param string $file URL to remap/embed
378 * @param string $query
379 * @param string $local File path where the source was read from
380 * @param string $remote URL path to the file
381 * @param bool $embed Whether to do any data URI embedding
382 * @return string Remapped/embedded URL data
383 */
384 public static function remapOne( $file, $query, $local, $remote, $embed ) {
385 // The full URL possibly with query, as passed to the 'url()' value in CSS
386 $url = $file . $query;
387
388 // Expand local URLs with absolute paths like /w/index.php to possibly protocol-relative URL, if
389 // wfExpandUrl() is available. (This will not be the case if we're running outside of MW.)
390 if ( self::isLocalUrl( $url ) && function_exists( 'wfExpandUrl' ) ) {
391 return wfExpandUrl( $url, PROTO_RELATIVE );
392 }
393
394 // Pass thru fully-qualified and protocol-relative URLs and data URIs, as well as local URLs if
395 // we can't expand them.
396 if ( self::isRemoteUrl( $url ) || self::isLocalUrl( $url ) ) {
397 return $url;
398 }
399
400 if ( $local === false ) {
401 // Assume that all paths are relative to $remote, and make them absolute
402 $url = $remote . '/' . $url;
403 } else {
404 // We drop the query part here and instead make the path relative to $remote
405 $url = "{$remote}/{$file}";
406 // Path to the actual file on the filesystem
407 $localFile = "{$local}/{$file}";
408 if ( file_exists( $localFile ) ) {
409 // Add version parameter as the first five hex digits
410 // of the MD5 hash of the file's contents.
411 $url .= '?' . substr( md5_file( $localFile ), 0, 5 );
412 if ( $embed ) {
413 $data = self::encodeImageAsDataURI( $localFile );
414 if ( $data !== false ) {
415 return $data;
416 }
417 }
418 }
419 // If any of these conditions failed (file missing, we don't want to embed it
420 // or it's not embeddable), return the URL (possibly with ?timestamp part)
421 }
422 if ( function_exists( 'wfRemoveDotSegments' ) ) {
423 $url = wfRemoveDotSegments( $url );
424 }
425 return $url;
426 }
427
428 /**
429 * Removes whitespace from CSS data
430 *
431 * @param string $css CSS data to minify
432 * @return string Minified CSS data
433 */
434 public static function minify( $css ) {
435 return trim(
436 str_replace(
437 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
438 array( ';', ':', '{', '{', ',', '}', '}' ),
439 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )
440 )
441 );
442 }
443 }