Fix "CSSMin url() value remapping not working in certain obscure cases"
[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 /**
35 * Maximum file size to still qualify for in-line embedding as a data-URI
36 *
37 * 24,576 is used because Internet Explorer has a 32,768 byte limit for data URIs,
38 * which when base64 encoded will result in a 1/3 increase in size.
39 */
40 const EMBED_SIZE_LIMIT = 24576;
41 const URL_REGEX = 'url\(\s*[\'"]?(?P<file>[^\?\)\'"]*?)(?P<query>\?[^\)\'"]*?|)[\'"]?\s*\)';
42 const EMBED_REGEX = '\/\*\s*\@embed\s*\*\/';
43
44 /* Protected Static Members */
45
46 /** @var array List of common image files extensions and mime-types */
47 protected static $mimeTypes = array(
48 'gif' => 'image/gif',
49 'jpe' => 'image/jpeg',
50 'jpeg' => 'image/jpeg',
51 'jpg' => 'image/jpeg',
52 'png' => 'image/png',
53 'tif' => 'image/tiff',
54 'tiff' => 'image/tiff',
55 'xbm' => 'image/x-xbitmap',
56 'svg' => 'image/svg+xml',
57 );
58
59 /* Static Methods */
60
61 /**
62 * Gets a list of local file paths which are referenced in a CSS style sheet
63 *
64 * This function will always return an empty array if the second parameter is not given or null
65 * for backwards-compatibility.
66 *
67 * @param string $source CSS data to remap
68 * @param string $path File path where the source was read from (optional)
69 * @return array List of local file references
70 */
71 public static function getLocalFileReferences( $source, $path = null ) {
72 if ( $path === null ) {
73 return array();
74 }
75
76 $path = rtrim( $path, '/' ) . '/';
77 $files = array();
78
79 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER;
80 if ( preg_match_all( '/' . self::URL_REGEX . '/', $source, $matches, $rFlags ) ) {
81 foreach ( $matches as $match ) {
82 $url = $match['file'][0];
83
84 // Skip fully-qualified and protocol-relative URLs and data URIs
85 if ( substr( $url, 0, 2 ) === '//' || parse_url( $url, PHP_URL_SCHEME ) ) {
86 break;
87 }
88
89 $file = $path . $url;
90 // Skip non-existent files
91 if ( file_exists( $file ) ) {
92 break;
93 }
94
95 $files[] = $file;
96 }
97 }
98 return $files;
99 }
100
101 /**
102 * Encode an image file as a base64 data URI.
103 * If the image file has a suitable MIME type and size, encode it as a
104 * base64 data URI. Return false if the image type is unfamiliar or exceeds
105 * the size limit.
106 *
107 * @param string $file Image file to encode.
108 * @param string|null $type File's MIME type or null. If null, CSSMin will
109 * try to autodetect the type.
110 * @param int|bool $sizeLimit If the size of the target file is greater than
111 * this value, decline to encode the image file and return false
112 * instead. If $sizeLimit is false, no limit is enforced.
113 * @return string|bool: Image contents encoded as a data URI or false.
114 */
115 public static function encodeImageAsDataURI( $file, $type = null,
116 $sizeLimit = self::EMBED_SIZE_LIMIT
117 ) {
118 if ( $sizeLimit !== false && filesize( $file ) >= $sizeLimit ) {
119 return false;
120 }
121 if ( $type === null ) {
122 $type = self::getMimeType( $file );
123 }
124 if ( !$type ) {
125 return false;
126 }
127 $data = base64_encode( file_get_contents( $file ) );
128 return 'data:' . $type . ';base64,' . $data;
129 }
130
131 /**
132 * @param $file string
133 * @return bool|string
134 */
135 public static function getMimeType( $file ) {
136 $realpath = realpath( $file );
137 // Try a couple of different ways to get the mime-type of a file, in order of
138 // preference
139 if (
140 $realpath
141 && function_exists( 'finfo_file' )
142 && function_exists( 'finfo_open' )
143 && defined( 'FILEINFO_MIME_TYPE' )
144 ) {
145 // As of PHP 5.3, this is how you get the mime-type of a file; it uses the Fileinfo
146 // PECL extension
147 return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
148 } elseif ( function_exists( 'mime_content_type' ) ) {
149 // Before this was deprecated in PHP 5.3, this was how you got the mime-type of a file
150 return mime_content_type( $file );
151 } else {
152 // Worst-case scenario has happened, use the file extension to infer the mime-type
153 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
154 if ( isset( self::$mimeTypes[$ext] ) ) {
155 return self::$mimeTypes[$ext];
156 }
157 }
158 return false;
159 }
160
161 /**
162 * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
163 * and escaping quotes as necessary.
164 *
165 * @param string $url URL to process
166 * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
167 */
168 public static function buildUrlValue( $url ) {
169 // The list below has been crafted to match URLs such as:
170 // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
171 // data:image/png;base64,R0lGODlh/+==
172 if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
173 return "url($url)";
174 } else {
175 return 'url("' . strtr( $url, array( '\\' => '\\\\', '"' => '\\"' ) ) . '")';
176 }
177 }
178
179 /**
180 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
181 * or url() values preceded by an / * @embed * / comment.
182 *
183 * @param string $source CSS data to remap
184 * @param string $local File path where the source was read from
185 * @param string $remote URL path to the file
186 * @param bool $embedData If false, never do any data URI embedding,
187 * even if / * @embed * / is found.
188 * @return string Remapped CSS data
189 */
190 public static function remap( $source, $local, $remote, $embedData = true ) {
191 // High-level overview:
192 // * For each CSS rule in $source that includes at least one url() value:
193 // * Check for an @embed comment at the start indicating that all URIs should be embedded
194 // * For each url() value:
195 // * Check for an @embed comment directly preceding the value
196 // * If either @embed comment exists:
197 // * Embedding the URL as data: URI, if it's possible / allowed
198 // * Otherwise remap the URL to work in generated stylesheets
199
200 // Guard against trailing slashes, because "some/remote/../foo.png"
201 // resolves to "some/remote/foo.png" on (some?) clients (bug 27052).
202 if ( substr( $remote, -1 ) == '/' ) {
203 $remote = substr( $remote, 0, -1 );
204 }
205
206 // Note: This will correctly handle cases where ';', '{' or '}' appears
207 // in a css block comment (/* ... */). All other occurrences, e.g. in
208 // quoted strings, will not be handled correctly. You are advised
209 // not to use such characters in file names. We also match start/end of
210 // the string to be consistent in edge-cases ('@import url(…)').
211 $pattern = '/(?:^|[;{])\K(?:\/\*.*?\*\/|[^;{}])*' . CSSMin::URL_REGEX . '(?:\/\*.*?\*\/|[^;}])*(?=[;}]|$)/';
212
213 return preg_replace_callback(
214 $pattern,
215 function ( $matchOuter ) use ( $local, $remote, $embedData ) {
216 $rule = $matchOuter[0];
217
218 // Check for global @embed comment and remove it
219 $embedAll = false;
220 $rule = preg_replace( '/^(\s*)' . CSSMin::EMBED_REGEX . '\s*/', '$1', $rule, 1, $embedAll );
221
222 // Build two versions of current rule: with remapped URLs
223 // and with embedded data: URIs (where possible).
224 $pattern = '/(?P<embed>' . CSSMin::EMBED_REGEX . '\s*|)' . CSSMin::URL_REGEX . '/';
225
226 $ruleWithRemapped = preg_replace_callback(
227 $pattern,
228 function ( $match ) use ( $local, $remote ) {
229 $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
230
231 return CSSMin::buildUrlValue( $remapped );
232 },
233 $rule
234 );
235
236 if ( $embedData ) {
237 $ruleWithEmbedded = preg_replace_callback(
238 $pattern,
239 function ( $match ) use ( $embedAll, $local, $remote ) {
240 $embed = $embedAll || $match['embed'];
241 $embedded = CSSMin::remapOne(
242 $match['file'],
243 $match['query'],
244 $local,
245 $remote,
246 $embed
247 );
248
249 return CSSMin::buildUrlValue( $embedded );
250 },
251 $rule
252 );
253 }
254
255 if ( $embedData && $ruleWithEmbedded !== $ruleWithRemapped ) {
256 // Build 2 CSS properties; one which uses a base64 encoded data URI in place
257 // of the @embed comment to try and retain line-number integrity, and the
258 // other with a remapped an versioned URL and an Internet Explorer hack
259 // making it ignored in all browsers that support data URIs
260 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
261 } else {
262 // No reason to repeat twice
263 return $ruleWithRemapped;
264 }
265 }, $source );
266 }
267
268 /**
269 * Remap or embed a CSS URL path.
270 *
271 * @param string $file URL to remap/embed
272 * @param string $query
273 * @param string $local File path where the source was read from
274 * @param string $remote URL path to the file
275 * @param bool $embed Whether to do any data URI embedding
276 * @return string Remapped/embedded URL data
277 */
278 public static function remapOne( $file, $query, $local, $remote, $embed ) {
279 // The full URL possibly with query, as passed to the 'url()' value in CSS
280 $url = $file . $query;
281
282 // Skip fully-qualified and protocol-relative URLs and data URIs
283 if ( substr( $url, 0, 2 ) === '//' || parse_url( $url, PHP_URL_SCHEME ) ) {
284 return $url;
285 }
286
287 // URLs with absolute paths like /w/index.php need to be expanded
288 // to absolute URLs but otherwise left alone
289 if ( $url !== '' && $url[0] === '/' ) {
290 // Replace the file path with an expanded (possibly protocol-relative) URL
291 // ...but only if wfExpandUrl() is even available.
292 // This will not be the case if we're running outside of MW
293 if ( function_exists( 'wfExpandUrl' ) ) {
294 return wfExpandUrl( $url, PROTO_RELATIVE );
295 } else {
296 return $url;
297 }
298 }
299
300 if ( $local === false ) {
301 // Assume that all paths are relative to $remote, and make them absolute
302 return $remote . '/' . $url;
303 } else {
304 // We drop the query part here and instead make the path relative to $remote
305 $url = "{$remote}/{$file}";
306 // Path to the actual file on the filesystem
307 $localFile = "{$local}/{$file}";
308 if ( file_exists( $localFile ) ) {
309 // Add version parameter as a time-stamp in ISO 8601 format,
310 // using Z for the timezone, meaning GMT
311 $url .= '?' . gmdate( 'Y-m-d\TH:i:s\Z', round( filemtime( $localFile ), -2 ) );
312 if ( $embed ) {
313 $data = self::encodeImageAsDataURI( $localFile );
314 if ( $data !== false ) {
315 return $data;
316 }
317 }
318 }
319 // If any of these conditions failed (file missing, we don't want to embed it
320 // or it's not embeddable), return the URL (possibly with ?timestamp part)
321 return $url;
322 }
323 }
324
325 /**
326 * Removes whitespace from CSS data
327 *
328 * @param string $css CSS data to minify
329 * @return string Minified CSS data
330 */
331 public static function minify( $css ) {
332 return trim(
333 str_replace(
334 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
335 array( ';', ':', '{', '{', ',', '}', '}' ),
336 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )
337 )
338 );
339 }
340 }