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