Merge "Fix and make some types in PHPDoc and JSDoc tags more specific"
[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 return mime_content_type( realpath( $file ) );
192 }
193
194 /**
195 * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
196 * and escaping quotes as necessary.
197 *
198 * See http://www.w3.org/TR/css-syntax-3/#consume-a-url-token
199 *
200 * @param string $url URL to process
201 * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
202 */
203 public static function buildUrlValue( $url ) {
204 // The list below has been crafted to match URLs such as:
205 // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
206 // data:image/png;base64,R0lGODlh/+==
207 if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
208 return "url($url)";
209 } else {
210 return 'url("' . strtr( $url, [ '\\' => '\\\\', '"' => '\\"' ] ) . '")';
211 }
212 }
213
214 /**
215 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
216 * or url() values preceded by an / * @embed * / comment.
217 *
218 * @param string $source CSS data to remap
219 * @param string $local File path where the source was read from
220 * @param string $remote URL path to the file
221 * @param bool $embedData If false, never do any data URI embedding,
222 * even if / * @embed * / is found.
223 * @return string Remapped CSS data
224 */
225 public static function remap( $source, $local, $remote, $embedData = true ) {
226 // High-level overview:
227 // * For each CSS rule in $source that includes at least one url() value:
228 // * Check for an @embed comment at the start indicating that all URIs should be embedded
229 // * For each url() value:
230 // * Check for an @embed comment directly preceding the value
231 // * If either @embed comment exists:
232 // * Embedding the URL as data: URI, if it's possible / allowed
233 // * Otherwise remap the URL to work in generated stylesheets
234
235 // Guard against trailing slashes, because "some/remote/../foo.png"
236 // resolves to "some/remote/foo.png" on (some?) clients (T29052).
237 if ( substr( $remote, -1 ) == '/' ) {
238 $remote = substr( $remote, 0, -1 );
239 }
240
241 // Disallow U+007F DELETE, which is illegal anyway, and which
242 // we use for comment placeholders.
243 $source = str_replace( "\x7f", "?", $source );
244
245 // Replace all comments by a placeholder so they will not interfere with the remapping.
246 // Warning: This will also catch on anything looking like the start of a comment between
247 // quotation marks (e.g. "foo /* bar").
248 $comments = [];
249
250 $pattern = '/(?!' . self::EMBED_REGEX . ')(' . self::COMMENT_REGEX . ')/s';
251
252 $source = preg_replace_callback(
253 $pattern,
254 function ( $match ) use ( &$comments ) {
255 $comments[] = $match[ 0 ];
256 return CSSMin::PLACEHOLDER . ( count( $comments ) - 1 ) . 'x';
257 },
258 $source
259 );
260
261 // Note: This will not correctly handle cases where ';', '{' or '}'
262 // appears in the rule itself, e.g. in a quoted string. You are advised
263 // not to use such characters in file names. We also match start/end of
264 // the string to be consistent in edge-cases ('@import url(…)').
265 $pattern = '/(?:^|[;{])\K[^;{}]*' . self::getUrlRegex() . '[^;}]*(?=[;}]|$)/';
266
267 $source = preg_replace_callback(
268 $pattern,
269 function ( $matchOuter ) use ( $local, $remote, $embedData ) {
270 $rule = $matchOuter[0];
271
272 // Check for global @embed comment and remove it. Allow other comments to be present
273 // before @embed (they have been replaced with placeholders at this point).
274 $embedAll = false;
275 $rule = preg_replace(
276 '/^((?:\s+|' .
277 CSSMin::PLACEHOLDER .
278 '(\d+)x)*)' .
279 CSSMin::EMBED_REGEX .
280 '\s*/',
281 '$1',
282 $rule,
283 1,
284 $embedAll
285 );
286
287 // Build two versions of current rule: with remapped URLs
288 // and with embedded data: URIs (where possible).
289 $pattern = '/(?P<embed>' . CSSMin::EMBED_REGEX . '\s*|)' . self::getUrlRegex() . '/';
290
291 $ruleWithRemapped = preg_replace_callback(
292 $pattern,
293 function ( $match ) use ( $local, $remote ) {
294 self::processUrlMatch( $match );
295
296 $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
297 return CSSMin::buildUrlValue( $remapped );
298 },
299 $rule
300 );
301
302 if ( $embedData ) {
303 // Remember the occurring MIME types to avoid fallbacks when embedding some files.
304 $mimeTypes = [];
305
306 $ruleWithEmbedded = preg_replace_callback(
307 $pattern,
308 function ( $match ) use ( $embedAll, $local, $remote, &$mimeTypes ) {
309 self::processUrlMatch( $match );
310
311 $embed = $embedAll || $match['embed'];
312 $embedded = CSSMin::remapOne(
313 $match['file'],
314 $match['query'],
315 $local,
316 $remote,
317 $embed
318 );
319
320 $url = $match['file'] . $match['query'];
321 $file = "{$local}/{$match['file']}";
322 if (
323 !self::isRemoteUrl( $url ) && !self::isLocalUrl( $url )
324 && file_exists( $file )
325 ) {
326 $mimeTypes[ CSSMin::getMimeType( $file ) ] = true;
327 }
328
329 return CSSMin::buildUrlValue( $embedded );
330 },
331 $rule
332 );
333
334 // Are all referenced images SVGs?
335 $needsEmbedFallback = $mimeTypes !== [ 'image/svg+xml' => true ];
336 }
337
338 if ( !$embedData || $ruleWithEmbedded === $ruleWithRemapped ) {
339 // We're not embedding anything, or we tried to but the file is not embeddable
340 return $ruleWithRemapped;
341 } elseif ( $embedData && $needsEmbedFallback ) {
342 // Build 2 CSS properties; one which uses a data URI in place of the @embed comment, and
343 // the other with a remapped and versioned URL with an Internet Explorer 6 and 7 hack
344 // making it ignored in all browsers that support data URIs
345 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
346 } else {
347 // Look ma, no fallbacks! This is for files which IE 6 and 7 don't support anyway: SVG.
348 return $ruleWithEmbedded;
349 }
350 }, $source );
351
352 // Re-insert comments
353 $pattern = '/' . self::PLACEHOLDER . '(\d+)x/';
354 $source = preg_replace_callback( $pattern, function ( $match ) use ( &$comments ) {
355 return $comments[ $match[1] ];
356 }, $source );
357
358 return $source;
359 }
360
361 /**
362 * Is this CSS rule referencing a remote URL?
363 *
364 * @param string $maybeUrl
365 * @return bool
366 */
367 protected static function isRemoteUrl( $maybeUrl ) {
368 if ( substr( $maybeUrl, 0, 2 ) === '//' || parse_url( $maybeUrl, PHP_URL_SCHEME ) ) {
369 return true;
370 }
371 return false;
372 }
373
374 /**
375 * Is this CSS rule referencing a local URL?
376 *
377 * @param string $maybeUrl
378 * @return bool
379 */
380 protected static function isLocalUrl( $maybeUrl ) {
381 if ( $maybeUrl !== '' && $maybeUrl[0] === '/' && !self::isRemoteUrl( $maybeUrl ) ) {
382 return true;
383 }
384 return false;
385 }
386
387 /**
388 * @codeCoverageIgnore
389 */
390 private static function getUrlRegex() {
391 static $urlRegex;
392 if ( $urlRegex === null ) {
393 // Match these three variants separately to avoid broken urls when
394 // e.g. a double quoted url contains a parenthesis, or when a
395 // single quoted url contains a double quote, etc.
396 // Note: PCRE doesn't support multiple capture groups with the same name by default.
397 // - PCRE 6.7 introduced the "J" modifier (PCRE_INFO_JCHANGED for PCRE_DUPNAMES).
398 // https://secure.php.net/manual/en/reference.pcre.pattern.modifiers.php
399 // However this isn't useful since it just ignores all but the first one.
400 // Also, while the modifier was introduced in PCRE 6.7 (PHP 5.2+) it was
401 // not exposed to public preg_* functions until PHP 5.6.0.
402 // - PCRE 8.36 fixed this to work as expected (e.g. merge conceptually to
403 // only return the one matched in the part that actually matched).
404 // However MediaWiki supports 5.5.9, which has PCRE 8.32
405 // Per https://secure.php.net/manual/en/pcre.installation.php:
406 // - PCRE 8.32 (PHP 5.5.0)
407 // - PCRE 8.34 (PHP 5.5.10, PHP 5.6.0)
408 // - PCRE 8.37 (PHP 5.5.26, PHP 5.6.9, PHP 7.0.0)
409 // Workaround by using different groups and merge via processUrlMatch().
410 // - Using string concatenation for class constant or member assignments
411 // is only supported in PHP 5.6. Use a getter method for now.
412 $urlRegex = '(' .
413 // Unquoted url
414 'url\(\s*(?P<file0>[^\'"][^\?\)]*?)(?P<query0>\?[^\)]*?|)\s*\)' .
415 // Single quoted url
416 '|url\(\s*\'(?P<file1>[^\?\']*?)(?P<query1>\?[^\']*?|)\'\s*\)' .
417 // Double quoted url
418 '|url\(\s*"(?P<file2>[^\?"]*?)(?P<query2>\?[^"]*?|)"\s*\)' .
419 ')';
420 }
421 return $urlRegex;
422 }
423
424 private static function processUrlMatch( array &$match, $flags = 0 ) {
425 if ( $flags & PREG_SET_ORDER ) {
426 // preg_match_all with PREG_SET_ORDER will return each group in each
427 // match array, and if it didn't match, instead of the sub array
428 // being an empty array it is `[ '', -1 ]`...
429 if ( isset( $match['file0'] ) && $match['file0'][1] !== -1 ) {
430 $match['file'] = $match['file0'];
431 $match['query'] = $match['query0'];
432 } elseif ( isset( $match['file1'] ) && $match['file1'][1] !== -1 ) {
433 $match['file'] = $match['file1'];
434 $match['query'] = $match['query1'];
435 } else {
436 $match['file'] = $match['file2'];
437 $match['query'] = $match['query2'];
438 }
439 } else {
440 if ( isset( $match['file0'] ) && $match['file0'] !== '' ) {
441 $match['file'] = $match['file0'];
442 $match['query'] = $match['query0'];
443 } elseif ( isset( $match['file1'] ) && $match['file1'] !== '' ) {
444 $match['file'] = $match['file1'];
445 $match['query'] = $match['query1'];
446 } else {
447 $match['file'] = $match['file2'];
448 $match['query'] = $match['query2'];
449 }
450 }
451 }
452
453 /**
454 * Remap or embed a CSS URL path.
455 *
456 * @param string $file URL to remap/embed
457 * @param string $query
458 * @param string $local File path where the source was read from
459 * @param string $remote URL path to the file
460 * @param bool $embed Whether to do any data URI embedding
461 * @return string Remapped/embedded URL data
462 */
463 public static function remapOne( $file, $query, $local, $remote, $embed ) {
464 // The full URL possibly with query, as passed to the 'url()' value in CSS
465 $url = $file . $query;
466
467 // Expand local URLs with absolute paths like /w/index.php to possibly protocol-relative URL, if
468 // wfExpandUrl() is available. (This will not be the case if we're running outside of MW.)
469 if ( self::isLocalUrl( $url ) && function_exists( 'wfExpandUrl' ) ) {
470 return wfExpandUrl( $url, PROTO_RELATIVE );
471 }
472
473 // Pass thru fully-qualified and protocol-relative URLs and data URIs, as well as local URLs if
474 // we can't expand them.
475 // Also skips the rare `behavior` property specifying application's default behavior
476 if (
477 self::isRemoteUrl( $url ) ||
478 self::isLocalUrl( $url ) ||
479 substr( $url, 0, 9 ) === '#default#'
480 ) {
481 return $url;
482 }
483
484 if ( $local === false ) {
485 // Assume that all paths are relative to $remote, and make them absolute
486 $url = $remote . '/' . $url;
487 } else {
488 // We drop the query part here and instead make the path relative to $remote
489 $url = "{$remote}/{$file}";
490 // Path to the actual file on the filesystem
491 $localFile = "{$local}/{$file}";
492 if ( file_exists( $localFile ) ) {
493 if ( $embed ) {
494 $data = self::encodeImageAsDataURI( $localFile );
495 if ( $data !== false ) {
496 return $data;
497 }
498 }
499 if ( method_exists( 'OutputPage', 'transformFilePath' ) ) {
500 $url = OutputPage::transformFilePath( $remote, $local, $file );
501 } else {
502 // Add version parameter as the first five hex digits
503 // of the MD5 hash of the file's contents.
504 $url .= '?' . substr( md5_file( $localFile ), 0, 5 );
505 }
506 }
507 // If any of these conditions failed (file missing, we don't want to embed it
508 // or it's not embeddable), return the URL (possibly with ?timestamp part)
509 }
510 if ( function_exists( 'wfRemoveDotSegments' ) ) {
511 $url = wfRemoveDotSegments( $url );
512 }
513 return $url;
514 }
515
516 /**
517 * Removes whitespace from CSS data
518 *
519 * @param string $css CSS data to minify
520 * @return string Minified CSS data
521 */
522 public static function minify( $css ) {
523 return trim(
524 str_replace(
525 [ '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ],
526 [ ';', ':', '{', '{', ',', '}', '}' ],
527 preg_replace( [ '/\s+/', '/\/\*.*?\*\//s' ], [ ' ', '' ], $css )
528 )
529 );
530 }
531 }