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