Merge "CSSMin: Skip #default#behaviorName when detecting local files"
[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
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 = [
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 * Get a list of local files referenced in a stylesheet (includes non-existent files).
64 *
65 * @param string $source CSS stylesheet source to process
66 * @param string $path File path where the source was read from
67 * @return array List of local file references
68 */
69 public static function getLocalFileReferences( $source, $path ) {
70 $stripped = preg_replace( '/' . self::COMMENT_REGEX . '/s', '', $source );
71 $path = rtrim( $path, '/' ) . '/';
72 $files = [];
73
74 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER;
75 if ( preg_match_all( '/' . self::getUrlRegex() . '/', $stripped, $matches, $rFlags ) ) {
76 foreach ( $matches as $match ) {
77 self::processUrlMatch( $match, $rFlags );
78 $url = $match['file'][0];
79
80 // Skip fully-qualified and protocol-relative URLs and data URIs
81 // Also skips the rare `behavior` property specifying application's default behavior
82 if (
83 substr( $url, 0, 2 ) === '//' ||
84 parse_url( $url, PHP_URL_SCHEME ) ||
85 substr( $url, 0, 9 ) === '#default#'
86 ) {
87 break;
88 }
89
90 $files[] = $path . $url;
91 }
92 }
93 return $files;
94 }
95
96 /**
97 * Encode an image file as a data URI.
98 *
99 * If the image file has a suitable MIME type and size, encode it as a data URI, base64-encoded
100 * for binary files or just percent-encoded otherwise. Return false if the image type is
101 * unfamiliar or file exceeds the size limit.
102 *
103 * @param string $file Image file to encode.
104 * @param string|null $type File's MIME type or null. If null, CSSMin will
105 * try to autodetect the type.
106 * @param bool $ie8Compat By default, a data URI will only be produced if it can be made short
107 * enough to fit in Internet Explorer 8 (and earlier) URI length limit (32,768 bytes). Pass
108 * `false` to remove this limitation.
109 * @return string|bool Image contents encoded as a data URI or false.
110 */
111 public static function encodeImageAsDataURI( $file, $type = null, $ie8Compat = true ) {
112 // Fast-fail for files that definitely exceed the maximum data URI length
113 if ( $ie8Compat && filesize( $file ) >= self::DATA_URI_SIZE_LIMIT ) {
114 return false;
115 }
116
117 if ( $type === null ) {
118 $type = self::getMimeType( $file );
119 }
120 if ( !$type ) {
121 return false;
122 }
123
124 return self::encodeStringAsDataURI( file_get_contents( $file ), $type, $ie8Compat );
125 }
126
127 /**
128 * Encode file contents as a data URI with chosen MIME type.
129 *
130 * The URI will be base64-encoded for binary files or just percent-encoded otherwise.
131 *
132 * @since 1.25
133 *
134 * @param string $contents File contents to encode.
135 * @param string $type File's MIME type.
136 * @param bool $ie8Compat See encodeImageAsDataURI().
137 * @return string|bool Image contents encoded as a data URI or false.
138 */
139 public static function encodeStringAsDataURI( $contents, $type, $ie8Compat = true ) {
140 // Try #1: Non-encoded data URI
141 // The regular expression matches ASCII whitespace and printable characters.
142 if ( preg_match( '/^[\r\n\t\x20-\x7e]+$/', $contents ) ) {
143 // Do not base64-encode non-binary files (sane SVGs).
144 // (This often produces longer URLs, but they compress better, yielding a net smaller size.)
145 $uri = 'data:' . $type . ',' . rawurlencode( $contents );
146 if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
147 return $uri;
148 }
149 }
150
151 // Try #2: Encoded data URI
152 $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
153 if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
154 return $uri;
155 }
156
157 // A data URI couldn't be produced
158 return false;
159 }
160
161 /**
162 * Serialize a string (escape and quote) for use as a CSS string value.
163 * http://www.w3.org/TR/2013/WD-cssom-20131205/#serialize-a-string
164 *
165 * @param string $value
166 * @return string
167 * @throws Exception
168 */
169 public static function serializeStringValue( $value ) {
170 if ( strstr( $value, "\0" ) ) {
171 throw new Exception( "Invalid character in CSS string" );
172 }
173 $value = strtr( $value, [ '\\' => '\\\\', '"' => '\\"' ] );
174 $value = preg_replace_callback( '/[\x01-\x1f\x7f-\x9f]/', function ( $match ) {
175 return '\\' . base_convert( ord( $match[0] ), 10, 16 ) . ' ';
176 }, $value );
177 return '"' . $value . '"';
178 }
179
180 /**
181 * @param string $file
182 * @return bool|string
183 */
184 public static function getMimeType( $file ) {
185 // Infer the MIME-type from the file extension
186 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
187 if ( isset( self::$mimeTypes[$ext] ) ) {
188 return self::$mimeTypes[$ext];
189 }
190
191 $realpath = realpath( $file );
192 if (
193 $realpath
194 && function_exists( 'finfo_file' )
195 && function_exists( 'finfo_open' )
196 && defined( 'FILEINFO_MIME_TYPE' )
197 ) {
198 return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
199 }
200
201 return false;
202 }
203
204 /**
205 * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
206 * and escaping quotes as necessary.
207 *
208 * See http://www.w3.org/TR/css-syntax-3/#consume-a-url-token
209 *
210 * @param string $url URL to process
211 * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
212 */
213 public static function buildUrlValue( $url ) {
214 // The list below has been crafted to match URLs such as:
215 // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
216 // data:image/png;base64,R0lGODlh/+==
217 if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
218 return "url($url)";
219 } else {
220 return 'url("' . strtr( $url, [ '\\' => '\\\\', '"' => '\\"' ] ) . '")';
221 }
222 }
223
224 /**
225 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
226 * or url() values preceded by an / * @embed * / comment.
227 *
228 * @param string $source CSS data to remap
229 * @param string $local File path where the source was read from
230 * @param string $remote URL path to the file
231 * @param bool $embedData If false, never do any data URI embedding,
232 * even if / * @embed * / is found.
233 * @return string Remapped CSS data
234 */
235 public static function remap( $source, $local, $remote, $embedData = true ) {
236 // High-level overview:
237 // * For each CSS rule in $source that includes at least one url() value:
238 // * Check for an @embed comment at the start indicating that all URIs should be embedded
239 // * For each url() value:
240 // * Check for an @embed comment directly preceding the value
241 // * If either @embed comment exists:
242 // * Embedding the URL as data: URI, if it's possible / allowed
243 // * Otherwise remap the URL to work in generated stylesheets
244
245 // Guard against trailing slashes, because "some/remote/../foo.png"
246 // resolves to "some/remote/foo.png" on (some?) clients (T29052).
247 if ( substr( $remote, -1 ) == '/' ) {
248 $remote = substr( $remote, 0, -1 );
249 }
250
251 // Disallow U+007F DELETE, which is illegal anyway, and which
252 // we use for comment placeholders.
253 $source = str_replace( "\x7f", "?", $source );
254
255 // Replace all comments by a placeholder so they will not interfere with the remapping.
256 // Warning: This will also catch on anything looking like the start of a comment between
257 // quotation marks (e.g. "foo /* bar").
258 $comments = [];
259
260 $pattern = '/(?!' . self::EMBED_REGEX . ')(' . self::COMMENT_REGEX . ')/s';
261
262 $source = preg_replace_callback(
263 $pattern,
264 function ( $match ) use ( &$comments ) {
265 $comments[] = $match[ 0 ];
266 return CSSMin::PLACEHOLDER . ( count( $comments ) - 1 ) . 'x';
267 },
268 $source
269 );
270
271 // Note: This will not correctly handle cases where ';', '{' or '}'
272 // appears in the rule itself, e.g. in a quoted string. You are advised
273 // not to use such characters in file names. We also match start/end of
274 // the string to be consistent in edge-cases ('@import url(…)').
275 $pattern = '/(?:^|[;{])\K[^;{}]*' . self::getUrlRegex() . '[^;}]*(?=[;}]|$)/';
276
277 $source = preg_replace_callback(
278 $pattern,
279 function ( $matchOuter ) use ( $local, $remote, $embedData ) {
280 $rule = $matchOuter[0];
281
282 // Check for global @embed comment and remove it. Allow other comments to be present
283 // before @embed (they have been replaced with placeholders at this point).
284 $embedAll = false;
285 $rule = preg_replace(
286 '/^((?:\s+|' .
287 CSSMin::PLACEHOLDER .
288 '(\d+)x)*)' .
289 CSSMin::EMBED_REGEX .
290 '\s*/',
291 '$1',
292 $rule,
293 1,
294 $embedAll
295 );
296
297 // Build two versions of current rule: with remapped URLs
298 // and with embedded data: URIs (where possible).
299 $pattern = '/(?P<embed>' . CSSMin::EMBED_REGEX . '\s*|)' . self::getUrlRegex() . '/';
300
301 $ruleWithRemapped = preg_replace_callback(
302 $pattern,
303 function ( $match ) use ( $local, $remote ) {
304 self::processUrlMatch( $match );
305
306 $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
307 return CSSMin::buildUrlValue( $remapped );
308 },
309 $rule
310 );
311
312 if ( $embedData ) {
313 // Remember the occurring MIME types to avoid fallbacks when embedding some files.
314 $mimeTypes = [];
315
316 $ruleWithEmbedded = preg_replace_callback(
317 $pattern,
318 function ( $match ) use ( $embedAll, $local, $remote, &$mimeTypes ) {
319 self::processUrlMatch( $match );
320
321 $embed = $embedAll || $match['embed'];
322 $embedded = CSSMin::remapOne(
323 $match['file'],
324 $match['query'],
325 $local,
326 $remote,
327 $embed
328 );
329
330 $url = $match['file'] . $match['query'];
331 $file = "{$local}/{$match['file']}";
332 if (
333 !self::isRemoteUrl( $url ) && !self::isLocalUrl( $url )
334 && file_exists( $file )
335 ) {
336 $mimeTypes[ CSSMin::getMimeType( $file ) ] = true;
337 }
338
339 return CSSMin::buildUrlValue( $embedded );
340 },
341 $rule
342 );
343
344 // Are all referenced images SVGs?
345 $needsEmbedFallback = $mimeTypes !== [ 'image/svg+xml' => true ];
346 }
347
348 if ( !$embedData || $ruleWithEmbedded === $ruleWithRemapped ) {
349 // We're not embedding anything, or we tried to but the file is not embeddable
350 return $ruleWithRemapped;
351 } elseif ( $embedData && $needsEmbedFallback ) {
352 // Build 2 CSS properties; one which uses a data URI in place of the @embed comment, and
353 // the other with a remapped and versioned URL with an Internet Explorer 6 and 7 hack
354 // making it ignored in all browsers that support data URIs
355 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
356 } else {
357 // Look ma, no fallbacks! This is for files which IE 6 and 7 don't support anyway: SVG.
358 return $ruleWithEmbedded;
359 }
360 }, $source );
361
362 // Re-insert comments
363 $pattern = '/' . self::PLACEHOLDER . '(\d+)x/';
364 $source = preg_replace_callback( $pattern, function ( $match ) use ( &$comments ) {
365 return $comments[ $match[1] ];
366 }, $source );
367
368 return $source;
369 }
370
371 /**
372 * Is this CSS rule referencing a remote URL?
373 *
374 * @param string $maybeUrl
375 * @return bool
376 */
377 protected static function isRemoteUrl( $maybeUrl ) {
378 if ( substr( $maybeUrl, 0, 2 ) === '//' || parse_url( $maybeUrl, PHP_URL_SCHEME ) ) {
379 return true;
380 }
381 return false;
382 }
383
384 /**
385 * Is this CSS rule referencing a local URL?
386 *
387 * @param string $maybeUrl
388 * @return bool
389 */
390 protected static function isLocalUrl( $maybeUrl ) {
391 if ( $maybeUrl !== '' && $maybeUrl[0] === '/' && !self::isRemoteUrl( $maybeUrl ) ) {
392 return true;
393 }
394 return false;
395 }
396
397 private static function getUrlRegex() {
398 static $urlRegex;
399 if ( $urlRegex === null ) {
400 // Match these three variants separately to avoid broken urls when
401 // e.g. a double quoted url contains a parenthesis, or when a
402 // single quoted url contains a double quote, etc.
403 // Note: PCRE doesn't support multiple capture groups with the same name by default.
404 // - PCRE 6.7 introduced the "J" modifier (PCRE_INFO_JCHANGED for PCRE_DUPNAMES).
405 // https://secure.php.net/manual/en/reference.pcre.pattern.modifiers.php
406 // However this isn't useful since it just ignores all but the first one.
407 // Also, while the modifier was introduced in PCRE 6.7 (PHP 5.2+) it was
408 // not exposed to public preg_* functions until PHP 5.6.0.
409 // - PCRE 8.36 fixed this to work as expected (e.g. merge conceptually to
410 // only return the one matched in the part that actually matched).
411 // However MediaWiki supports 5.5.9, which has PCRE 8.32
412 // Per https://secure.php.net/manual/en/pcre.installation.php:
413 // - PCRE 8.32 (PHP 5.5.0)
414 // - PCRE 8.34 (PHP 5.5.10, PHP 5.6.0)
415 // - PCRE 8.37 (PHP 5.5.26, PHP 5.6.9, PHP 7.0.0)
416 // Workaround by using different groups and merge via processUrlMatch().
417 // - Using string concatenation for class constant or member assignments
418 // is only supported in PHP 5.6. Use a getter method for now.
419 $urlRegex = '(' .
420 // Unquoted url
421 'url\(\s*(?P<file0>[^\'"][^\?\)]*?)(?P<query0>\?[^\)]*?|)\s*\)' .
422 // Single quoted url
423 '|url\(\s*\'(?P<file1>[^\?\']*?)(?P<query1>\?[^\']*?|)\'\s*\)' .
424 // Double quoted url
425 '|url\(\s*"(?P<file2>[^\?"]*?)(?P<query2>\?[^"]*?|)"\s*\)' .
426 ')';
427 }
428 return $urlRegex;
429 }
430
431 private static function processUrlMatch( array &$match, $flags = 0 ) {
432 if ( $flags & PREG_SET_ORDER ) {
433 // preg_match_all with PREG_SET_ORDER will return each group in each
434 // match array, and if it didn't match, instead of the sub array
435 // being an empty array it is `[ '', -1 ]`...
436 if ( isset( $match['file0'] ) && $match['file0'][1] !== -1 ) {
437 $match['file'] = $match['file0'];
438 $match['query'] = $match['query0'];
439 } elseif ( isset( $match['file1'] ) && $match['file1'][1] !== -1 ) {
440 $match['file'] = $match['file1'];
441 $match['query'] = $match['query1'];
442 } else {
443 $match['file'] = $match['file2'];
444 $match['query'] = $match['query2'];
445 }
446 } else {
447 if ( isset( $match['file0'] ) && $match['file0'] !== '' ) {
448 $match['file'] = $match['file0'];
449 $match['query'] = $match['query0'];
450 } elseif ( isset( $match['file1'] ) && $match['file1'] !== '' ) {
451 $match['file'] = $match['file1'];
452 $match['query'] = $match['query1'];
453 } else {
454 $match['file'] = $match['file2'];
455 $match['query'] = $match['query2'];
456 }
457 }
458 }
459
460 /**
461 * Remap or embed a CSS URL path.
462 *
463 * @param string $file URL to remap/embed
464 * @param string $query
465 * @param string $local File path where the source was read from
466 * @param string $remote URL path to the file
467 * @param bool $embed Whether to do any data URI embedding
468 * @return string Remapped/embedded URL data
469 */
470 public static function remapOne( $file, $query, $local, $remote, $embed ) {
471 // The full URL possibly with query, as passed to the 'url()' value in CSS
472 $url = $file . $query;
473
474 // Expand local URLs with absolute paths like /w/index.php to possibly protocol-relative URL, if
475 // wfExpandUrl() is available. (This will not be the case if we're running outside of MW.)
476 if ( self::isLocalUrl( $url ) && function_exists( 'wfExpandUrl' ) ) {
477 return wfExpandUrl( $url, PROTO_RELATIVE );
478 }
479
480 // Pass thru fully-qualified and protocol-relative URLs and data URIs, as well as local URLs if
481 // we can't expand them.
482 // Also skips the rare `behavior` property specifying application's default behavior
483 if (
484 self::isRemoteUrl( $url ) ||
485 self::isLocalUrl( $url ) ||
486 substr( $url, 0, 9 ) === '#default#'
487 ) {
488 return $url;
489 }
490
491 if ( $local === false ) {
492 // Assume that all paths are relative to $remote, and make them absolute
493 $url = $remote . '/' . $url;
494 } else {
495 // We drop the query part here and instead make the path relative to $remote
496 $url = "{$remote}/{$file}";
497 // Path to the actual file on the filesystem
498 $localFile = "{$local}/{$file}";
499 if ( file_exists( $localFile ) ) {
500 if ( $embed ) {
501 $data = self::encodeImageAsDataURI( $localFile );
502 if ( $data !== false ) {
503 return $data;
504 }
505 }
506 if ( method_exists( 'OutputPage', 'transformFilePath' ) ) {
507 $url = OutputPage::transformFilePath( $remote, $local, $file );
508 } else {
509 // Add version parameter as the first five hex digits
510 // of the MD5 hash of the file's contents.
511 $url .= '?' . substr( md5_file( $localFile ), 0, 5 );
512 }
513 }
514 // If any of these conditions failed (file missing, we don't want to embed it
515 // or it's not embeddable), return the URL (possibly with ?timestamp part)
516 }
517 if ( function_exists( 'wfRemoveDotSegments' ) ) {
518 $url = wfRemoveDotSegments( $url );
519 }
520 return $url;
521 }
522
523 /**
524 * Removes whitespace from CSS data
525 *
526 * @param string $css CSS data to minify
527 * @return string Minified CSS data
528 */
529 public static function minify( $css ) {
530 return trim(
531 str_replace(
532 [ '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ],
533 [ ';', ':', '{', '{', ',', '}', '}' ],
534 preg_replace( [ '/\s+/', '/\/\*.*?\*\//s' ], [ ' ', '' ], $css )
535 )
536 );
537 }
538 }