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