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