Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.61% covered (success)
98.61%
142 / 144
91.67% covered (success)
91.67%
11 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
CSSMin
99.30% covered (success)
99.30%
142 / 143
91.67% covered (success)
91.67%
11 / 12
44
0.00% covered (danger)
0.00%
0 / 1
 getLocalFileReferences
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
7
 encodeImageAsDataURI
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
4.03
 encodeStringAsDataURI
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
2
 serializeStringValue
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 getMimeType
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 buildUrlValue
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 remap
100.00% covered (success)
100.00%
50 / 50
100.00% covered (success)
100.00%
1 / 1
4
 isRemoteUrl
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 isLocalUrl
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
4
 getUrlRegex
n/a
0 / 0
n/a
0 / 0
2
 resolveUrl
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
 remapOne
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
9
 minify
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2declare( strict_types = 1 );
3
4/**
5 * Copyright 2010 Trevor Parscal <tparscal@wikimedia.org>
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may 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
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * @file
20 * @license Apache-2.0
21 */
22
23namespace Wikimedia\Minify;
24
25use Net_URL2;
26
27/**
28 * Transforms CSS data.
29 *
30 * This class provides minification, URL remapping, URL extracting, and data-URL embedding.
31 */
32class CSSMin {
33
34    /**
35     * Strip marker for comments
36     */
37    private const PLACEHOLDER = "\x7fPLACEHOLDER\x7f";
38
39    /**
40     * Maximum file size to embed in a stylesheet.
41     *
42     * Use of `@embed` is generally discouraged (see T121730, T118514, and T120984).
43     *
44     * In a nut shell: Stylesheets, and thus any images we embed inside of them,
45     * are required to be fully downloaded by a browser before literally any content
46     * or interface component can be rendered on-screen. Embedding an image means
47     * you are saying it is more important to render this image than to render the
48     * page content (or that it is undesirable to render even the first paragraph
49     * of an article unless this image is also immediately there in the first paint).
50     *
51     * There are some cases where a small image can be worth embedding, for example
52     * if the image's file size is comparable or smaller than to size of the URL from
53     * which it would be lazy-loaded when CSS rules are applied. In that case, embedding
54     * the file content in place of the web address could be an uncompromising win for
55     * all users.
56     *
57     * To avoid mistakes and protect performance, we put an arbitrary limit on this.
58     * If a file is larger than this limit, it should probably be loaded using the
59     * default CSS behaviour (by URL, without `@embed` instruction), or embedded as
60     * SVG directly in the HTML response if it is such a vital part of the page.
61     *
62     * See encodeImageAsDataURI().
63     */
64    private const DATA_URI_SIZE_LIMIT = 32768;
65
66    private const EMBED_REGEX = '\/\*\s*\@embed\s*\*\/';
67    private const COMMENT_REGEX = '\/\*.*?\*\/';
68
69    /**
70     * List of common image files extensions and MIME-types
71     */
72    private const MIME_TYPES = [
73        'gif' => 'image/gif',
74        'jpe' => 'image/jpeg',
75        'jpeg' => 'image/jpeg',
76        'jpg' => 'image/jpeg',
77        'png' => 'image/png',
78        'tif' => 'image/tiff',
79        'tiff' => 'image/tiff',
80        'xbm' => 'image/x-xbitmap',
81        'svg' => 'image/svg+xml',
82    ];
83
84    /**
85     * Get a list of local files referenced in a stylesheet (includes non-existent files).
86     *
87     * @param string $source CSS stylesheet source to process
88     * @param string $path File path where the source was read from
89     * @return string[] List of local file references
90     */
91    public static function getLocalFileReferences( $source, $path ) {
92        $stripped = preg_replace( '/' . self::COMMENT_REGEX . '/s', '', $source );
93        $path = rtrim( $path, '/' ) . '/';
94        $files = [];
95
96        $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER;
97        if ( preg_match_all( '/' . self::getUrlRegex() . '/J', $stripped, $matches, $rFlags ) ) {
98            foreach ( $matches as $match ) {
99                $url = $match['file'][0];
100
101                // Skip fully-qualified and protocol-relative URLs and data URIs
102                if (
103                    str_starts_with( $url, '//' ) ||
104                    parse_url( $url, PHP_URL_SCHEME )
105                ) {
106                    break;
107                }
108
109                // Strip trailing anchors - T115436
110                $anchor = strpos( $url, '#' );
111                if ( $anchor !== false ) {
112                    $url = substr( $url, 0, $anchor );
113
114                    // '#some-anchors' is not a file
115                    if ( $url === '' ) {
116                        break;
117                    }
118                }
119
120                $files[] = $path . $url;
121            }
122        }
123        return $files;
124    }
125
126    /**
127     * Encode an image file as a data URI.
128     *
129     * If the image file has a suitable MIME type and size, encode it as a data URI, base64-encoded
130     * for binary files or just percent-encoded otherwise. Return false if the image type is
131     * unfamiliar or the file exceeds the size limit.
132     *
133     * @param string $file Image file to encode.
134     * @param string|null $type File's MIME type or null. If null, CSSMin will
135     *     try to autodetect the type.
136     * @return string|false Image contents encoded as a data URI or false.
137     */
138    public static function encodeImageAsDataURI( $file, $type = null ) {
139        // Fast-fail for files that exceed the maximum data URI length
140        if ( filesize( $file ) >= self::DATA_URI_SIZE_LIMIT ) {
141            trigger_error( "File exceeds limit for embedded files: $file", E_USER_WARNING );
142            return false;
143        }
144
145        if ( $type === null ) {
146            $type = self::getMimeType( $file );
147        }
148        if ( !$type ) {
149            return false;
150        }
151
152        return self::encodeStringAsDataURI( file_get_contents( $file ), $type );
153    }
154
155    /**
156     * Encode file contents as a data URI with chosen MIME type.
157     *
158     * The URI will be base64-encoded for binary files or just percent-encoded otherwise.
159     *
160     * @since 2.0.0
161     * @param string $contents File contents to encode.
162     * @param string $type File's MIME type.
163     * @return string Image contents encoded as a data URI or false.
164     */
165    public static function encodeStringAsDataURI( $contents, $type ) {
166        // Try #1: Non-encoded data URI
167        // Remove XML declaration, it's not needed with data URI usage
168        $contents = preg_replace( "/<\\?xml.*?\\?>/", '', $contents );
169        // The regular expression matches ASCII whitespace and printable characters.
170        if ( preg_match( '/^[\r\n\t\x20-\x7e]+$/', $contents ) ) {
171            // Do not base64-encode non-binary files (sensible SVGs).
172            // (This often produces longer URLs, but they compress better, yielding a net smaller size.)
173            $encoded = rawurlencode( $contents );
174            // Unencode some things that don't need to be encoded, to make the encoding smaller
175            $encoded = strtr( $encoded, [
176                // Unencode spaces
177                '%20' => ' ',
178                // Unencode slashes
179                '%2F' => '/',
180                // Unencode colons
181                '%3A' => ':',
182                // Unencode equals signs
183                '%3D' => '=',
184                // Change newlines to spaces
185                '%0A' => ' ',
186                // Change carriage returns to spaces
187                '%0D' => ' ',
188                // Change tabs to spaces
189                '%09' => ' ',
190            ] );
191            // Consolidate runs of multiple spaces in a row
192            $encoded = preg_replace( '/ {2,}/', ' ', $encoded );
193            // Remove leading and trailing spaces
194            $encoded = trim( $encoded, ' ' );
195            return 'data:' . $type . ',' . $encoded;
196        }
197
198        // Try #2: Encoded data URI
199        return 'data:' . $type . ';base64,' . base64_encode( $contents );
200    }
201
202    /**
203     * Serialize a string (escape and quote) for use as a CSS string value.
204     * https://drafts.csswg.org/cssom/#serialize-a-string
205     *
206     * @param string $value
207     * @return string
208     */
209    public static function serializeStringValue( $value ) {
210        $value = strtr( $value, [ "\0" => "\u{FFFD}", '\\' => '\\\\', '"' => '\\"' ] );
211        $value = preg_replace_callback( '/[\x01-\x1f\x7f]/', static function ( $match ) {
212            return '\\' . base_convert( (string)ord( $match[0] ), 10, 16 ) . ' ';
213        }, $value );
214        return '"' . $value . '"';
215    }
216
217    /**
218     * @param string $file
219     * @return bool|string
220     */
221    public static function getMimeType( $file ) {
222        // Infer the MIME-type from the file extension
223        $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
224        return self::MIME_TYPES[$ext] ?? mime_content_type( realpath( $file ) );
225    }
226
227    /**
228     * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
229     * and escaping quotes as necessary.
230     *
231     * See http://www.w3.org/TR/css-syntax-3/#consume-a-url-token
232     *
233     * @param string $url URL to process
234     * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
235     */
236    public static function buildUrlValue( $url ) {
237        // The list below has been crafted to match URLs such as:
238        //   scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
239        //   data:image/png;base64,R0lGODlh/+==
240        if ( preg_match( '!^[\w:@/~.%+;,?&=-]+$!', $url ) ) {
241            return "url($url)";
242        } else {
243            return 'url("' . strtr( $url, [ '\\' => '\\\\', '"' => '\\"' ] ) . '")';
244        }
245    }
246
247    /**
248     * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
249     * or url() values preceded by an `/ * @embed * /` comment.
250     *
251     * @param string $source CSS data to remap
252     * @param string $local File path where the source was read from
253     * @param string $remote Full URL to the file's directory (may be protocol-relative, trailing slash is optional)
254     * @param bool $embedData If false, never do any data URI embedding,
255     *   even if `/ * @embed * /` is found.
256     * @return string Remapped CSS data
257     */
258    public static function remap( $source, $local, $remote, $embedData = true ) {
259        // High-level overview:
260        // * For each CSS rule in $source that includes at least one url() value:
261        //   * Check for an @embed comment at the start indicating that all URIs should be embedded
262        //   * For each url() value:
263        //     * Check for an @embed comment directly preceding the value
264        //     * If either @embed comment exists:
265        //       * Embedding the URL as data: URI, if it's possible / allowed
266        //       * Otherwise remap the URL to work in generated stylesheets
267
268        // Guard against trailing slashes, because "some/remote/../foo.png"
269        // resolves to "some/remote/foo.png" on (some?) clients (T29052).
270        // But, don't turn "/" into "" since that is invalid as base URL (T282280).
271        $remote = $remote === '/' ? $remote : rtrim( $remote, '/' );
272
273        // Disallow U+007F DELETE, which is illegal anyway, and which
274        // we use for comment placeholders.
275        $source = strtr( $source, "\x7f", "?" );
276
277        // Replace all comments by a placeholder so they will not interfere with the remapping.
278        // Warning: This will also catch on anything looking like the start of a comment between
279        // quotation marks (e.g. "foo /* bar").
280        $comments = [];
281
282        $pattern = '/(?!' . self::EMBED_REGEX . ')(' . self::COMMENT_REGEX . ')/s';
283
284        $source = preg_replace_callback(
285            $pattern,
286            static function ( $match ) use ( &$comments ) {
287                $comments[] = $match[ 0 ];
288                return self::PLACEHOLDER . ( count( $comments ) - 1 ) . 'x';
289            },
290            $source
291        );
292
293        // Note: This will not correctly handle cases where ';', '{' or '}'
294        // appears in the rule itself, e.g. in a quoted string. You are advised
295        // not to use such characters in file names. We also match start/end of
296        // the string to be consistent in edge-cases ('@import url(…)').
297        $pattern = '/(?:^|[;{])\K[^;{}]*' . self::getUrlRegex() . '[^;}]*+(?=[;}]|$)/J';
298
299        $source = preg_replace_callback(
300            $pattern,
301            static function ( $matchOuter ) use ( $local, $remote, $embedData ) {
302                $rule = $matchOuter[0];
303
304                // Check for global @embed comment and remove it. Allow other comments to be present
305                // before @embed (they have been replaced with placeholders at this point).
306                $embedAll = false;
307                $rule = preg_replace(
308                    '/^((?:\s++|' .
309                        self::PLACEHOLDER .
310                        '(\d+)x)*+)' .
311                        self::EMBED_REGEX .
312                        '\s*/',
313                    '$1',
314                    $rule,
315                    1,
316                    $embedAll
317                );
318
319                // Build two versions of current rule: with remapped URLs
320                // and with embedded data: URIs (where possible).
321                $pattern = '/(?P<embed>' . self::EMBED_REGEX . '\s*|)' . self::getUrlRegex() . '/J';
322
323                return preg_replace_callback(
324                    $pattern,
325                    static function ( $match ) use ( $local, $remote, $embedData, $embedAll ) {
326                        // For each url reference in the CSS, call remapOne()
327                        // to insert either a remapped URL or an embedded data URI.
328                        // We enable use of data URIs if both of these are true:
329                        // 1. The PHP caller enabled the option,
330                        // 2. and, the CSS declared `@embed` either above the rule
331                        //    for all URLs inside that block, or above the individual
332                        //    property for that one property.
333                        $embedOne = $embedData && ( $embedAll || $match['embed'] );
334                        $remapped = self::remapOne(
335                            $match['file'],
336                            $match['query'],
337                            $local,
338                            $remote,
339                            $embedOne
340                        );
341                        return self::buildUrlValue( $remapped );
342                    },
343                    $rule
344                );
345            }, $source );
346
347        // Re-insert comments
348        $pattern = '/' . self::PLACEHOLDER . '(\d+)x/';
349        return preg_replace_callback( $pattern, static function ( $match ) use ( &$comments ) {
350            return $comments[ $match[1] ];
351        }, $source );
352    }
353
354    /**
355     * Is this CSS rule referencing a remote URL?
356     *
357     * @param string $maybeUrl
358     * @return bool
359     */
360    protected static function isRemoteUrl( $maybeUrl ) {
361        return str_starts_with( $maybeUrl, '//' ) || parse_url( $maybeUrl, PHP_URL_SCHEME );
362    }
363
364    /**
365     * Is this CSS rule referencing a local URL?
366     *
367     * @param string $maybeUrl
368     * @return bool
369     */
370    protected static function isLocalUrl( $maybeUrl ) {
371        // Accept "/" (known local)
372        // Accept "/anything" (known local)
373        // Reject "//anything" (known remote)
374        // Reject "" (invalid/uncertain)
375        return $maybeUrl === '/' || ( isset( $maybeUrl[1] ) && $maybeUrl[0] === '/' && $maybeUrl[1] !== '/' );
376    }
377
378    /**
379     * @codeCoverageIgnore
380     * @return string
381     */
382    private static function getUrlRegex() {
383        static $urlRegex;
384        if ( $urlRegex === null ) {
385            // The extra + avoid backtracking where it is not needed
386            $urlRegex = 'url\(\s*+(?:' .
387                // Unquoted url
388                '(?P<file>[^\'"][^?)]+?)(?P<query>\?[^)]*?|)' .
389                // Single quoted url
390                '|\'(?P<file>[^?\']++)(?P<query>\?[^\']*+|)\'' .
391                // Double quoted url
392                '|"(?P<file>[^?"]++)(?P<query>\?[^"]*+|)"' .
393                ')\s*\)';
394        }
395        return $urlRegex;
396    }
397
398    /**
399     * Resolve a possibly-relative URL against a base URL.
400     *
401     * @param string $base
402     * @param string $url
403     * @return string
404     */
405    private static function resolveUrl( string $base, string $url ): string {
406        // Net_URL2::resolve() doesn't allow for resolving against server-less URLs.
407        // We need this as for MediaWiki/ResourceLoader, the remote base path may either
408        // be separate (e.g. a separate domain), or simply local (like "/w"). In the
409        // local case, we don't want to needlessly include the server in the output.
410        $isServerless = self::isLocalUrl( $base );
411        if ( $isServerless ) {
412            $base = "https://placeholder.invalid$base";
413        }
414        // Net_URL2::resolve() doesn't allow for protocol-relative URLs, but we want to.
415        $isProtoRelative = str_starts_with( $base, '//' );
416        if ( $isProtoRelative ) {
417            $base = "https:$base";
418        }
419
420        $baseUrl = new Net_URL2( $base );
421        $ret = $baseUrl->resolve( $url );
422        if ( $isProtoRelative ) {
423            $ret->setScheme( false );
424        }
425        if ( $isServerless ) {
426            $ret->setScheme( false );
427            $ret->setHost( false );
428        }
429        return $ret->getURL();
430    }
431
432    /**
433     * Remap or embed a CSS URL path.
434     *
435     * @param string $file URL to remap/embed
436     * @param string $query
437     * @param string $local File path where the source was read from
438     * @param string $remote Full URL to the file's directory (may be protocol-relative, trailing slash is optional)
439     * @param bool $embed Whether to do any data URI embedding
440     * @return string Remapped/embedded URL data
441     */
442    public static function remapOne( $file, $query, $local, $remote, $embed ) {
443        // The full URL possibly with query, as passed to the 'url()' value in CSS
444        $url = $file . $query;
445
446        // Expand local URLs with absolute paths to a full URL (possibly protocol-relative).
447        if ( self::isLocalUrl( $url ) ) {
448            return self::resolveUrl( $remote, $url );
449        }
450
451        // Pass through fully-qualified and protocol-relative URLs and data URIs, as well as local URLs if
452        // we can't expand them.
453        // Also skips anchors or the rare `behavior` property specifying application's default behavior
454        if (
455            self::isRemoteUrl( $url ) ||
456            ( $url[0] ?? '' ) === '#'
457        ) {
458            return $url;
459        }
460
461        // The $remote must have a trailing slash beyond this point for correct path resolution.
462        if ( ( $remote[-1] ?? '' ) !== '/' ) {
463            $remote .= '/';
464        }
465
466        if ( $local === false ) {
467            // CSS specifies a path that is neither a local file path, nor a local URL.
468            // It is probably already a fully-qualitied URL or data URI, but try to expand
469            // it just in case.
470            $url = self::resolveUrl( $remote, $url );
471        } else {
472            // We drop the query part here and instead make the path relative to $remote
473            $url = self::resolveUrl( $remote, $file );
474            // Path to the actual file on the filesystem
475            $localFile = "{$local}/{$file}";
476            if ( file_exists( $localFile ) ) {
477                if ( $embed ) {
478                    $data = self::encodeImageAsDataURI( $localFile );
479                    if ( $data !== false ) {
480                        return $data;
481                    }
482                }
483                // Add version parameter as the first five hex digits
484                // of the MD5 hash of the file's contents.
485                $url .= '?' . substr( md5_file( $localFile ), 0, 5 );
486            }
487            // If any of these conditions failed (file missing, we don't want to embed it
488            // or it's not embeddable), return the URL (possibly with ?timestamp part)
489        }
490        return $url;
491    }
492
493    /**
494     * Removes whitespace from CSS data
495     *
496     * @param string $css CSS data to minify
497     * @return string Minified CSS data
498     */
499    public static function minify( $css ) {
500        return trim(
501            str_replace(
502                [ '; ', ': ', ' {', '{ ', ', ', '} ', ';}', '( ', ' )', '[ ', ' ]' ],
503                [ ';', ':', '{', '{', ',', '}', '}', '(', ')', '[', ']' ],
504                preg_replace( [ '/\s+/', '/\/\*.*?\*\//s' ], [ ' ', '' ], $css )
505            )
506        );
507    }
508}
509
510/**
511 * @deprecated since 2.1.0 Use Wikimedia\Minify\CSSMin instead
512 */
513class_alias( CSSMin::class, 'CSSMin' );