Merge "Improve "selfmove" message's wording"
[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 $encoded = rawurlencode( $contents );
146 // Unencode some things that don't need to be encoded, to make the encoding smaller
147 $encoded = strtr( $encoded, [
148 '%20' => ' ', // Unencode spaces
149 '%2F' => '/', // Unencode slashes
150 '%3A' => ':', // Unencode colons
151 '%3D' => '=', // Unencode equals signs
152 '%22' => '"', // Unencode double quotes
153 '%0A' => ' ', // Change newlines to spaces
154 '%0D' => ' ', // Change carriage returns to spaces
155 '%09' => ' ', // Change tabs to spaces
156 ] );
157 // Consolidate runs of multiple spaces in a row
158 $encoded = preg_replace( '/ {2,}/', ' ', $encoded );
159 // Remove leading and trailing spaces
160 $encoded = preg_replace( '/^ | $/', '', $encoded );
161 $uri = 'data:' . $type . ',' . $encoded;
162 if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
163 return $uri;
164 }
165 }
166
167 // Try #2: Encoded data URI
168 $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
169 if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
170 return $uri;
171 }
172
173 // A data URI couldn't be produced
174 return false;
175 }
176
177 /**
178 * Serialize a string (escape and quote) for use as a CSS string value.
179 * http://www.w3.org/TR/2013/WD-cssom-20131205/#serialize-a-string
180 *
181 * @param string $value
182 * @return string
183 * @throws Exception
184 */
185 public static function serializeStringValue( $value ) {
186 if ( strstr( $value, "\0" ) ) {
187 throw new Exception( "Invalid character in CSS string" );
188 }
189 $value = strtr( $value, [ '\\' => '\\\\', '"' => '\\"' ] );
190 $value = preg_replace_callback( '/[\x01-\x1f\x7f-\x9f]/', function ( $match ) {
191 return '\\' . base_convert( ord( $match[0] ), 10, 16 ) . ' ';
192 }, $value );
193 return '"' . $value . '"';
194 }
195
196 /**
197 * @param string $file
198 * @return bool|string
199 */
200 public static function getMimeType( $file ) {
201 // Infer the MIME-type from the file extension
202 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
203 if ( isset( self::$mimeTypes[$ext] ) ) {
204 return self::$mimeTypes[$ext];
205 }
206
207 return mime_content_type( realpath( $file ) );
208 }
209
210 /**
211 * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
212 * and escaping quotes as necessary.
213 *
214 * See http://www.w3.org/TR/css-syntax-3/#consume-a-url-token
215 *
216 * @param string $url URL to process
217 * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
218 */
219 public static function buildUrlValue( $url ) {
220 // The list below has been crafted to match URLs such as:
221 // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
222 // data:image/png;base64,R0lGODlh/+==
223 if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
224 return "url($url)";
225 } else {
226 return "url('" . strtr( $url, [ '\\' => '\\\\', "'" => "\\'" ] ) . "')";
227 }
228 }
229
230 /**
231 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
232 * or url() values preceded by an / * @embed * / comment.
233 *
234 * @param string $source CSS data to remap
235 * @param string $local File path where the source was read from
236 * @param string $remote URL path to the file
237 * @param bool $embedData If false, never do any data URI embedding,
238 * even if / * @embed * / is found.
239 * @return string Remapped CSS data
240 */
241 public static function remap( $source, $local, $remote, $embedData = true ) {
242 // High-level overview:
243 // * For each CSS rule in $source that includes at least one url() value:
244 // * Check for an @embed comment at the start indicating that all URIs should be embedded
245 // * For each url() value:
246 // * Check for an @embed comment directly preceding the value
247 // * If either @embed comment exists:
248 // * Embedding the URL as data: URI, if it's possible / allowed
249 // * Otherwise remap the URL to work in generated stylesheets
250
251 // Guard against trailing slashes, because "some/remote/../foo.png"
252 // resolves to "some/remote/foo.png" on (some?) clients (T29052).
253 if ( substr( $remote, -1 ) == '/' ) {
254 $remote = substr( $remote, 0, -1 );
255 }
256
257 // Disallow U+007F DELETE, which is illegal anyway, and which
258 // we use for comment placeholders.
259 $source = str_replace( "\x7f", "?", $source );
260
261 // Replace all comments by a placeholder so they will not interfere with the remapping.
262 // Warning: This will also catch on anything looking like the start of a comment between
263 // quotation marks (e.g. "foo /* bar").
264 $comments = [];
265
266 $pattern = '/(?!' . self::EMBED_REGEX . ')(' . self::COMMENT_REGEX . ')/s';
267
268 $source = preg_replace_callback(
269 $pattern,
270 function ( $match ) use ( &$comments ) {
271 $comments[] = $match[ 0 ];
272 return CSSMin::PLACEHOLDER . ( count( $comments ) - 1 ) . 'x';
273 },
274 $source
275 );
276
277 // Note: This will not correctly handle cases where ';', '{' or '}'
278 // appears in the rule itself, e.g. in a quoted string. You are advised
279 // not to use such characters in file names. We also match start/end of
280 // the string to be consistent in edge-cases ('@import url(…)').
281 $pattern = '/(?:^|[;{])\K[^;{}]*' . self::getUrlRegex() . '[^;}]*(?=[;}]|$)/';
282
283 $source = preg_replace_callback(
284 $pattern,
285 function ( $matchOuter ) use ( $local, $remote, $embedData ) {
286 $rule = $matchOuter[0];
287
288 // Check for global @embed comment and remove it. Allow other comments to be present
289 // before @embed (they have been replaced with placeholders at this point).
290 $embedAll = false;
291 $rule = preg_replace(
292 '/^((?:\s+|' .
293 CSSMin::PLACEHOLDER .
294 '(\d+)x)*)' .
295 CSSMin::EMBED_REGEX .
296 '\s*/',
297 '$1',
298 $rule,
299 1,
300 $embedAll
301 );
302
303 // Build two versions of current rule: with remapped URLs
304 // and with embedded data: URIs (where possible).
305 $pattern = '/(?P<embed>' . CSSMin::EMBED_REGEX . '\s*|)' . self::getUrlRegex() . '/';
306
307 $ruleWithRemapped = preg_replace_callback(
308 $pattern,
309 function ( $match ) use ( $local, $remote ) {
310 self::processUrlMatch( $match );
311
312 $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
313 return CSSMin::buildUrlValue( $remapped );
314 },
315 $rule
316 );
317
318 if ( $embedData ) {
319 // Remember the occurring MIME types to avoid fallbacks when embedding some files.
320 $mimeTypes = [];
321
322 $ruleWithEmbedded = preg_replace_callback(
323 $pattern,
324 function ( $match ) use ( $embedAll, $local, $remote, &$mimeTypes ) {
325 self::processUrlMatch( $match );
326
327 $embed = $embedAll || $match['embed'];
328 $embedded = CSSMin::remapOne(
329 $match['file'],
330 $match['query'],
331 $local,
332 $remote,
333 $embed
334 );
335
336 $url = $match['file'] . $match['query'];
337 $file = "{$local}/{$match['file']}";
338 if (
339 !self::isRemoteUrl( $url ) && !self::isLocalUrl( $url )
340 && file_exists( $file )
341 ) {
342 $mimeTypes[ CSSMin::getMimeType( $file ) ] = true;
343 }
344
345 return CSSMin::buildUrlValue( $embedded );
346 },
347 $rule
348 );
349
350 // Are all referenced images SVGs?
351 $needsEmbedFallback = $mimeTypes !== [ 'image/svg+xml' => true ];
352 }
353
354 if ( !$embedData || $ruleWithEmbedded === $ruleWithRemapped ) {
355 // We're not embedding anything, or we tried to but the file is not embeddable
356 return $ruleWithRemapped;
357 } elseif ( $embedData && $needsEmbedFallback ) {
358 // Build 2 CSS properties; one which uses a data URI in place of the @embed comment, and
359 // the other with a remapped and versioned URL with an Internet Explorer 6 and 7 hack
360 // making it ignored in all browsers that support data URIs
361 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
362 } else {
363 // Look ma, no fallbacks! This is for files which IE 6 and 7 don't support anyway: SVG.
364 return $ruleWithEmbedded;
365 }
366 }, $source );
367
368 // Re-insert comments
369 $pattern = '/' . self::PLACEHOLDER . '(\d+)x/';
370 $source = preg_replace_callback( $pattern, function ( $match ) use ( &$comments ) {
371 return $comments[ $match[1] ];
372 }, $source );
373
374 return $source;
375 }
376
377 /**
378 * Is this CSS rule referencing a remote URL?
379 *
380 * @param string $maybeUrl
381 * @return bool
382 */
383 protected static function isRemoteUrl( $maybeUrl ) {
384 if ( substr( $maybeUrl, 0, 2 ) === '//' || parse_url( $maybeUrl, PHP_URL_SCHEME ) ) {
385 return true;
386 }
387 return false;
388 }
389
390 /**
391 * Is this CSS rule referencing a local URL?
392 *
393 * @param string $maybeUrl
394 * @return bool
395 */
396 protected static function isLocalUrl( $maybeUrl ) {
397 if ( $maybeUrl !== '' && $maybeUrl[0] === '/' && !self::isRemoteUrl( $maybeUrl ) ) {
398 return true;
399 }
400 return false;
401 }
402
403 /**
404 * @codeCoverageIgnore
405 */
406 private static function getUrlRegex() {
407 static $urlRegex;
408 if ( $urlRegex === null ) {
409 // Match these three variants separately to avoid broken urls when
410 // e.g. a double quoted url contains a parenthesis, or when a
411 // single quoted url contains a double quote, etc.
412 // Note: PCRE doesn't support multiple capture groups with the same name by default.
413 // - PCRE 6.7 introduced the "J" modifier (PCRE_INFO_JCHANGED for PCRE_DUPNAMES).
414 // https://secure.php.net/manual/en/reference.pcre.pattern.modifiers.php
415 // However this isn't useful since it just ignores all but the first one.
416 // Also, while the modifier was introduced in PCRE 6.7 (PHP 5.2+) it was
417 // not exposed to public preg_* functions until PHP 5.6.0.
418 // - PCRE 8.36 fixed this to work as expected (e.g. merge conceptually to
419 // only return the one matched in the part that actually matched).
420 // However MediaWiki supports 5.5.9, which has PCRE 8.32
421 // Per https://secure.php.net/manual/en/pcre.installation.php:
422 // - PCRE 8.32 (PHP 5.5.0)
423 // - PCRE 8.34 (PHP 5.5.10, PHP 5.6.0)
424 // - PCRE 8.37 (PHP 5.5.26, PHP 5.6.9, PHP 7.0.0)
425 // Workaround by using different groups and merge via processUrlMatch().
426 // - Using string concatenation for class constant or member assignments
427 // is only supported in PHP 5.6. Use a getter method for now.
428 $urlRegex = '(' .
429 // Unquoted url
430 'url\(\s*(?P<file0>[^\'"][^\?\)]*?)(?P<query0>\?[^\)]*?|)\s*\)' .
431 // Single quoted url
432 '|url\(\s*\'(?P<file1>[^\?\']*?)(?P<query1>\?[^\']*?|)\'\s*\)' .
433 // Double quoted url
434 '|url\(\s*"(?P<file2>[^\?"]*?)(?P<query2>\?[^"]*?|)"\s*\)' .
435 ')';
436 }
437 return $urlRegex;
438 }
439
440 private static function processUrlMatch( array &$match, $flags = 0 ) {
441 if ( $flags & PREG_SET_ORDER ) {
442 // preg_match_all with PREG_SET_ORDER will return each group in each
443 // match array, and if it didn't match, instead of the sub array
444 // being an empty array it is `[ '', -1 ]`...
445 if ( isset( $match['file0'] ) && $match['file0'][1] !== -1 ) {
446 $match['file'] = $match['file0'];
447 $match['query'] = $match['query0'];
448 } elseif ( isset( $match['file1'] ) && $match['file1'][1] !== -1 ) {
449 $match['file'] = $match['file1'];
450 $match['query'] = $match['query1'];
451 } else {
452 $match['file'] = $match['file2'];
453 $match['query'] = $match['query2'];
454 }
455 } else {
456 if ( isset( $match['file0'] ) && $match['file0'] !== '' ) {
457 $match['file'] = $match['file0'];
458 $match['query'] = $match['query0'];
459 } elseif ( isset( $match['file1'] ) && $match['file1'] !== '' ) {
460 $match['file'] = $match['file1'];
461 $match['query'] = $match['query1'];
462 } else {
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 }