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 const URL_REGEX = 'url\(\s*[\'"]?(?P<file>[^\?\)\'"]*?)(?P<query>\?[^\)\'"]*?|)[\'"]?\s*\)';
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::URL_REGEX . '/', $stripped, $matches, $rFlags ) ) {
76 foreach ( $matches as $match ) {
77 $url = $match['file'][0];
78
79 // Skip fully-qualified and protocol-relative URLs and data URIs
80 // Also skips the rare `behavior` property specifying application's default behavior
81 if (
82 substr( $url, 0, 2 ) === '//' ||
83 parse_url( $url, PHP_URL_SCHEME ) ||
84 substr( $url, 0, 9 ) === '#default#'
85 ) {
86 break;
87 }
88
89 $files[] = $path . $url;
90 }
91 }
92 return $files;
93 }
94
95 /**
96 * Encode an image file as a data URI.
97 *
98 * If the image file has a suitable MIME type and size, encode it as a data URI, base64-encoded
99 * for binary files or just percent-encoded otherwise. Return false if the image type is
100 * unfamiliar or file exceeds the size limit.
101 *
102 * @param string $file Image file to encode.
103 * @param string|null $type File's MIME type or null. If null, CSSMin will
104 * try to autodetect the type.
105 * @param bool $ie8Compat By default, a data URI will only be produced if it can be made short
106 * enough to fit in Internet Explorer 8 (and earlier) URI length limit (32,768 bytes). Pass
107 * `false` to remove this limitation.
108 * @return string|bool Image contents encoded as a data URI or false.
109 */
110 public static function encodeImageAsDataURI( $file, $type = null, $ie8Compat = true ) {
111 // Fast-fail for files that definitely exceed the maximum data URI length
112 if ( $ie8Compat && filesize( $file ) >= self::DATA_URI_SIZE_LIMIT ) {
113 return false;
114 }
115
116 if ( $type === null ) {
117 $type = self::getMimeType( $file );
118 }
119 if ( !$type ) {
120 return false;
121 }
122
123 return self::encodeStringAsDataURI( file_get_contents( $file ), $type, $ie8Compat );
124 }
125
126 /**
127 * Encode file contents as a data URI with chosen MIME type.
128 *
129 * The URI will be base64-encoded for binary files or just percent-encoded otherwise.
130 *
131 * @since 1.25
132 *
133 * @param string $contents File contents to encode.
134 * @param string $type File's MIME type.
135 * @param bool $ie8Compat See encodeImageAsDataURI().
136 * @return string|bool Image contents encoded as a data URI or false.
137 */
138 public static function encodeStringAsDataURI( $contents, $type, $ie8Compat = true ) {
139 // Try #1: Non-encoded data URI
140 // The regular expression matches ASCII whitespace and printable characters.
141 if ( preg_match( '/^[\r\n\t\x20-\x7e]+$/', $contents ) ) {
142 // Do not base64-encode non-binary files (sane SVGs).
143 // (This often produces longer URLs, but they compress better, yielding a net smaller size.)
144 $uri = 'data:' . $type . ',' . rawurlencode( $contents );
145 if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
146 return $uri;
147 }
148 }
149
150 // Try #2: Encoded data URI
151 $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
152 if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
153 return $uri;
154 }
155
156 // A data URI couldn't be produced
157 return false;
158 }
159
160 /**
161 * Serialize a string (escape and quote) for use as a CSS string value.
162 * http://www.w3.org/TR/2013/WD-cssom-20131205/#serialize-a-string
163 *
164 * @param string $value
165 * @return string
166 * @throws Exception
167 */
168 public static function serializeStringValue( $value ) {
169 if ( strstr( $value, "\0" ) ) {
170 throw new Exception( "Invalid character in CSS string" );
171 }
172 $value = strtr( $value, [ '\\' => '\\\\', '"' => '\\"' ] );
173 $value = preg_replace_callback( '/[\x01-\x1f\x7f-\x9f]/', function ( $match ) {
174 return '\\' . base_convert( ord( $match[0] ), 10, 16 ) . ' ';
175 }, $value );
176 return '"' . $value . '"';
177 }
178
179 /**
180 * @param string $file
181 * @return bool|string
182 */
183 public static function getMimeType( $file ) {
184 // Infer the MIME-type from the file extension
185 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
186 if ( isset( self::$mimeTypes[$ext] ) ) {
187 return self::$mimeTypes[$ext];
188 }
189
190 $realpath = realpath( $file );
191 if (
192 $realpath
193 && function_exists( 'finfo_file' )
194 && function_exists( 'finfo_open' )
195 && defined( 'FILEINFO_MIME_TYPE' )
196 ) {
197 return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
198 }
199
200 return false;
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 = '/(?!' . CSSMin::EMBED_REGEX . ')(' . CSSMin::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[^;{}]*' . CSSMin::URL_REGEX . '[^;}]*(?=[;}]|$)/';
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*|)' . CSSMin::URL_REGEX . '/';
299
300 $ruleWithRemapped = preg_replace_callback(
301 $pattern,
302 function ( $match ) use ( $local, $remote ) {
303 $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
304
305 return CSSMin::buildUrlValue( $remapped );
306 },
307 $rule
308 );
309
310 if ( $embedData ) {
311 // Remember the occurring MIME types to avoid fallbacks when embedding some files.
312 $mimeTypes = [];
313
314 $ruleWithEmbedded = preg_replace_callback(
315 $pattern,
316 function ( $match ) use ( $embedAll, $local, $remote, &$mimeTypes ) {
317 $embed = $embedAll || $match['embed'];
318 $embedded = CSSMin::remapOne(
319 $match['file'],
320 $match['query'],
321 $local,
322 $remote,
323 $embed
324 );
325
326 $url = $match['file'] . $match['query'];
327 $file = "{$local}/{$match['file']}";
328 if (
329 !self::isRemoteUrl( $url ) && !self::isLocalUrl( $url )
330 && file_exists( $file )
331 ) {
332 $mimeTypes[ CSSMin::getMimeType( $file ) ] = true;
333 }
334
335 return CSSMin::buildUrlValue( $embedded );
336 },
337 $rule
338 );
339
340 // Are all referenced images SVGs?
341 $needsEmbedFallback = $mimeTypes !== [ 'image/svg+xml' => true ];
342 }
343
344 if ( !$embedData || $ruleWithEmbedded === $ruleWithRemapped ) {
345 // We're not embedding anything, or we tried to but the file is not embeddable
346 return $ruleWithRemapped;
347 } elseif ( $embedData && $needsEmbedFallback ) {
348 // Build 2 CSS properties; one which uses a data URI in place of the @embed comment, and
349 // the other with a remapped and versioned URL with an Internet Explorer 6 and 7 hack
350 // making it ignored in all browsers that support data URIs
351 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
352 } else {
353 // Look ma, no fallbacks! This is for files which IE 6 and 7 don't support anyway: SVG.
354 return $ruleWithEmbedded;
355 }
356 }, $source );
357
358 // Re-insert comments
359 $pattern = '/' . CSSMin::PLACEHOLDER . '(\d+)x/';
360 $source = preg_replace_callback( $pattern, function( $match ) use ( &$comments ) {
361 return $comments[ $match[1] ];
362 }, $source );
363
364 return $source;
365 }
366
367 /**
368 * Is this CSS rule referencing a remote URL?
369 *
370 * @param string $maybeUrl
371 * @return bool
372 */
373 protected static function isRemoteUrl( $maybeUrl ) {
374 if ( substr( $maybeUrl, 0, 2 ) === '//' || parse_url( $maybeUrl, PHP_URL_SCHEME ) ) {
375 return true;
376 }
377 return false;
378 }
379
380 /**
381 * Is this CSS rule referencing a local URL?
382 *
383 * @param string $maybeUrl
384 * @return bool
385 */
386 protected static function isLocalUrl( $maybeUrl ) {
387 if ( $maybeUrl !== '' && $maybeUrl[0] === '/' && !self::isRemoteUrl( $maybeUrl ) ) {
388 return true;
389 }
390 return false;
391 }
392
393 /**
394 * Remap or embed a CSS URL path.
395 *
396 * @param string $file URL to remap/embed
397 * @param string $query
398 * @param string $local File path where the source was read from
399 * @param string $remote URL path to the file
400 * @param bool $embed Whether to do any data URI embedding
401 * @return string Remapped/embedded URL data
402 */
403 public static function remapOne( $file, $query, $local, $remote, $embed ) {
404 // The full URL possibly with query, as passed to the 'url()' value in CSS
405 $url = $file . $query;
406
407 // Expand local URLs with absolute paths like /w/index.php to possibly protocol-relative URL, if
408 // wfExpandUrl() is available. (This will not be the case if we're running outside of MW.)
409 if ( self::isLocalUrl( $url ) && function_exists( 'wfExpandUrl' ) ) {
410 return wfExpandUrl( $url, PROTO_RELATIVE );
411 }
412
413 // Pass thru fully-qualified and protocol-relative URLs and data URIs, as well as local URLs if
414 // we can't expand them.
415 // Also skips the rare `behavior` property specifying application's default behavior
416 if (
417 self::isRemoteUrl( $url ) ||
418 self::isLocalUrl( $url ) ||
419 substr( $url, 0, 9 ) === '#default#'
420 ) {
421 return $url;
422 }
423
424 if ( $local === false ) {
425 // Assume that all paths are relative to $remote, and make them absolute
426 $url = $remote . '/' . $url;
427 } else {
428 // We drop the query part here and instead make the path relative to $remote
429 $url = "{$remote}/{$file}";
430 // Path to the actual file on the filesystem
431 $localFile = "{$local}/{$file}";
432 if ( file_exists( $localFile ) ) {
433 if ( $embed ) {
434 $data = self::encodeImageAsDataURI( $localFile );
435 if ( $data !== false ) {
436 return $data;
437 }
438 }
439 if ( method_exists( 'OutputPage', 'transformFilePath' ) ) {
440 $url = OutputPage::transformFilePath( $remote, $local, $file );
441 } else {
442 // Add version parameter as the first five hex digits
443 // of the MD5 hash of the file's contents.
444 $url .= '?' . substr( md5_file( $localFile ), 0, 5 );
445 }
446 }
447 // If any of these conditions failed (file missing, we don't want to embed it
448 // or it's not embeddable), return the URL (possibly with ?timestamp part)
449 }
450 if ( function_exists( 'wfRemoveDotSegments' ) ) {
451 $url = wfRemoveDotSegments( $url );
452 }
453 return $url;
454 }
455
456 /**
457 * Removes whitespace from CSS data
458 *
459 * @param string $css CSS data to minify
460 * @return string Minified CSS data
461 */
462 public static function minify( $css ) {
463 return trim(
464 str_replace(
465 [ '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ],
466 [ ';', ':', '{', '{', ',', '}', '}' ],
467 preg_replace( [ '/\s+/', '/\/\*.*?\*\//s' ], [ ' ', '' ], $css )
468 )
469 );
470 }
471 }