Merge "Properly escape the messages in CategoryViewer.php"
[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 * Internet Explorer data URI length limit. See encodeImageAsDataURI().
36 */
37 const DATA_URI_SIZE_LIMIT = 32768;
38 const URL_REGEX = 'url\(\s*[\'"]?(?P<file>[^\?\)\'"]*?)(?P<query>\?[^\)\'"]*?|)[\'"]?\s*\)';
39 const EMBED_REGEX = '\/\*\s*\@embed\s*\*\/';
40 const COMMENT_REGEX = '\/\*.*?\*\/';
41
42 /* Protected Static Members */
43
44 /** @var array List of common image files extensions and MIME-types */
45 protected static $mimeTypes = array(
46 'gif' => 'image/gif',
47 'jpe' => 'image/jpeg',
48 'jpeg' => 'image/jpeg',
49 'jpg' => 'image/jpeg',
50 'png' => 'image/png',
51 'tif' => 'image/tiff',
52 'tiff' => 'image/tiff',
53 'xbm' => 'image/x-xbitmap',
54 'svg' => 'image/svg+xml',
55 );
56
57 /* Static Methods */
58
59 /**
60 * Gets a list of local file paths which are referenced in a CSS style sheet
61 *
62 * This function will always return an empty array if the second parameter is not given or null
63 * for backwards-compatibility.
64 *
65 * @param string $source CSS data to remap
66 * @param string $path File path where the source was read from (optional)
67 * @return array List of local file references
68 */
69 public static function getLocalFileReferences( $source, $path = null ) {
70 if ( $path === null ) {
71 return array();
72 }
73
74 $path = rtrim( $path, '/' ) . '/';
75 $files = array();
76
77 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER;
78 if ( preg_match_all( '/' . self::URL_REGEX . '/', $source, $matches, $rFlags ) ) {
79 foreach ( $matches as $match ) {
80 $url = $match['file'][0];
81
82 // Skip fully-qualified and protocol-relative URLs and data URIs
83 if ( substr( $url, 0, 2 ) === '//' || parse_url( $url, PHP_URL_SCHEME ) ) {
84 break;
85 }
86
87 $file = $path . $url;
88 // Skip non-existent files
89 if ( file_exists( $file ) ) {
90 break;
91 }
92
93 $files[] = $file;
94 }
95 }
96 return $files;
97 }
98
99 /**
100 * Encode an image file as a data URI.
101 *
102 * If the image file has a suitable MIME type and size, encode it as a data URI, base64-encoded
103 * for binary files or just percent-encoded otherwise. Return false if the image type is
104 * unfamiliar or file exceeds the size limit.
105 *
106 * @param string $file Image file to encode.
107 * @param string|null $type File's MIME type or null. If null, CSSMin will
108 * try to autodetect the type.
109 * @param bool $ie8Compat By default, a data URI will only be produced if it can be made short
110 * enough to fit in Internet Explorer 8 (and earlier) URI length limit (32,768 bytes). Pass
111 * `false` to remove this limitation.
112 * @return string|bool Image contents encoded as a data URI or false.
113 */
114 public static function encodeImageAsDataURI( $file, $type = null, $ie8Compat = true ) {
115 // Fast-fail for files that definitely exceed the maximum data URI length
116 if ( $ie8Compat && filesize( $file ) >= self::DATA_URI_SIZE_LIMIT ) {
117 return false;
118 }
119
120 if ( $type === null ) {
121 $type = self::getMimeType( $file );
122 }
123 if ( !$type ) {
124 return false;
125 }
126
127 return self::encodeStringAsDataURI( file_get_contents( $file ), $type, $ie8Compat );
128 }
129
130 /**
131 * Encode file contents as a data URI with chosen MIME type.
132 *
133 * The URI will be base64-encoded for binary files or just percent-encoded otherwise.
134 *
135 * @since 1.25
136 *
137 * @param string $contents File contents to encode.
138 * @param string $type File's MIME type.
139 * @param bool $ie8Compat See encodeImageAsDataURI().
140 * @return string|bool Image contents encoded as a data URI or false.
141 */
142 public static function encodeStringAsDataURI( $contents, $type, $ie8Compat = true ) {
143 // Try #1: Non-encoded data URI
144 // The regular expression matches ASCII whitespace and printable characters.
145 if ( preg_match( '/^[\r\n\t\x20-\x7e]+$/', $contents ) ) {
146 // Do not base64-encode non-binary files (sane SVGs).
147 // (This often produces longer URLs, but they compress better, yielding a net smaller size.)
148 $uri = 'data:' . $type . ',' . rawurlencode( $contents );
149 if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
150 return $uri;
151 }
152 }
153
154 // Try #2: Encoded data URI
155 $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
156 if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
157 return $uri;
158 }
159
160 // A data URI couldn't be produced
161 return false;
162 }
163
164 /**
165 * @param $file string
166 * @return bool|string
167 */
168 public static function getMimeType( $file ) {
169 $realpath = realpath( $file );
170 if (
171 $realpath
172 && function_exists( 'finfo_file' )
173 && function_exists( 'finfo_open' )
174 && defined( 'FILEINFO_MIME_TYPE' )
175 ) {
176 return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
177 }
178
179 // Infer the MIME-type from the file extension
180 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
181 if ( isset( self::$mimeTypes[$ext] ) ) {
182 return self::$mimeTypes[$ext];
183 }
184
185 return false;
186 }
187
188 /**
189 * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
190 * and escaping quotes as necessary.
191 *
192 * See http://www.w3.org/TR/css-syntax-3/#consume-a-url-token
193 *
194 * @param string $url URL to process
195 * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
196 */
197 public static function buildUrlValue( $url ) {
198 // The list below has been crafted to match URLs such as:
199 // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
200 // data:image/png;base64,R0lGODlh/+==
201 if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
202 return "url($url)";
203 } else {
204 return 'url("' . strtr( $url, array( '\\' => '\\\\', '"' => '\\"' ) ) . '")';
205 }
206 }
207
208 /**
209 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
210 * or url() values preceded by an / * @embed * / comment.
211 *
212 * @param string $source CSS data to remap
213 * @param string $local File path where the source was read from
214 * @param string $remote URL path to the file
215 * @param bool $embedData If false, never do any data URI embedding,
216 * even if / * @embed * / is found.
217 * @return string Remapped CSS data
218 */
219 public static function remap( $source, $local, $remote, $embedData = true ) {
220 // High-level overview:
221 // * For each CSS rule in $source that includes at least one url() value:
222 // * Check for an @embed comment at the start indicating that all URIs should be embedded
223 // * For each url() value:
224 // * Check for an @embed comment directly preceding the value
225 // * If either @embed comment exists:
226 // * Embedding the URL as data: URI, if it's possible / allowed
227 // * Otherwise remap the URL to work in generated stylesheets
228
229 // Guard against trailing slashes, because "some/remote/../foo.png"
230 // resolves to "some/remote/foo.png" on (some?) clients (bug 27052).
231 if ( substr( $remote, -1 ) == '/' ) {
232 $remote = substr( $remote, 0, -1 );
233 }
234
235 // Replace all comments by a placeholder so they will not interfere with the remapping.
236 // Warning: This will also catch on anything looking like the start of a comment between
237 // quotation marks (e.g. "foo /* bar").
238 $comments = array();
239 $placeholder = uniqid( '', true );
240
241 $pattern = '/(?!' . CSSMin::EMBED_REGEX . ')(' . CSSMin::COMMENT_REGEX . ')/s';
242
243 $source = preg_replace_callback(
244 $pattern,
245 function ( $match ) use ( &$comments, $placeholder ) {
246 $comments[] = $match[ 0 ];
247 return $placeholder . ( count( $comments ) - 1 ) . 'x';
248 },
249 $source
250 );
251
252 // Note: This will not correctly handle cases where ';', '{' or '}'
253 // appears in the rule itself, e.g. in a quoted string. You are advised
254 // not to use such characters in file names. We also match start/end of
255 // the string to be consistent in edge-cases ('@import url(…)').
256 $pattern = '/(?:^|[;{])\K[^;{}]*' . CSSMin::URL_REGEX . '[^;}]*(?=[;}]|$)/';
257
258 $source = preg_replace_callback(
259 $pattern,
260 function ( $matchOuter ) use ( $local, $remote, $embedData, $placeholder ) {
261 $rule = $matchOuter[0];
262
263 // Check for global @embed comment and remove it. Allow other comments to be present
264 // before @embed (they have been replaced with placeholders at this point).
265 $embedAll = false;
266 $rule = preg_replace( '/^((?:\s+|' . $placeholder . '(\d+)x)*)' . CSSMin::EMBED_REGEX . '\s*/', '$1', $rule, 1, $embedAll );
267
268 // Build two versions of current rule: with remapped URLs
269 // and with embedded data: URIs (where possible).
270 $pattern = '/(?P<embed>' . CSSMin::EMBED_REGEX . '\s*|)' . CSSMin::URL_REGEX . '/';
271
272 $ruleWithRemapped = preg_replace_callback(
273 $pattern,
274 function ( $match ) use ( $local, $remote ) {
275 $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
276
277 return CSSMin::buildUrlValue( $remapped );
278 },
279 $rule
280 );
281
282 if ( $embedData ) {
283 // Remember the occurring MIME types to avoid fallbacks when embedding some files.
284 $mimeTypes = array();
285
286 $ruleWithEmbedded = preg_replace_callback(
287 $pattern,
288 function ( $match ) use ( $embedAll, $local, $remote, &$mimeTypes ) {
289 $embed = $embedAll || $match['embed'];
290 $embedded = CSSMin::remapOne(
291 $match['file'],
292 $match['query'],
293 $local,
294 $remote,
295 $embed
296 );
297
298 $url = $match['file'] . $match['query'];
299 $file = $local . $match['file'];
300 if (
301 !CSSMin::isRemoteUrl( $url ) && !CSSMin::isLocalUrl( $url )
302 && file_exists( $file )
303 ) {
304 $mimeTypes[ CSSMin::getMimeType( $file ) ] = true;
305 }
306
307 return CSSMin::buildUrlValue( $embedded );
308 },
309 $rule
310 );
311
312 // Are all referenced images SVGs?
313 $needsEmbedFallback = $mimeTypes !== array( 'image/svg+xml' => true );
314 }
315
316 if ( !$embedData || $ruleWithEmbedded === $ruleWithRemapped ) {
317 // We're not embedding anything, or we tried to but the file is not embeddable
318 return $ruleWithRemapped;
319 } elseif ( $embedData && $needsEmbedFallback ) {
320 // Build 2 CSS properties; one which uses a data URI in place of the @embed comment, and
321 // the other with a remapped and versioned URL with an Internet Explorer 6 and 7 hack
322 // making it ignored in all browsers that support data URIs
323 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
324 } else {
325 // Look ma, no fallbacks! This is for files which IE 6 and 7 don't support anyway: SVG.
326 return $ruleWithEmbedded;
327 }
328 }, $source );
329
330 // Re-insert comments
331 $pattern = '/' . $placeholder . '(\d+)x/';
332 $source = preg_replace_callback( $pattern, function( $match ) use ( &$comments ) {
333 return $comments[ $match[1] ];
334 }, $source );
335
336 return $source;
337
338 }
339
340 /**
341 * Is this CSS rule referencing a remote URL?
342 *
343 * @private Until we require PHP 5.5 and we can access self:: from closures.
344 * @param string $maybeUrl
345 * @return bool
346 */
347 public static function isRemoteUrl( $maybeUrl ) {
348 if ( substr( $maybeUrl, 0, 2 ) === '//' || parse_url( $maybeUrl, PHP_URL_SCHEME ) ) {
349 return true;
350 }
351 return false;
352 }
353
354 /**
355 * Is this CSS rule referencing a local URL?
356 *
357 * @private Until we require PHP 5.5 and we can access self:: from closures.
358 * @param string $maybeUrl
359 * @return bool
360 */
361 public static function isLocalUrl( $maybeUrl ) {
362 if ( $maybeUrl !== '' && $maybeUrl[0] === '/' && !self::isRemoteUrl( $maybeUrl ) ) {
363 return true;
364 }
365 return false;
366 }
367
368 /**
369 * Remap or embed a CSS URL path.
370 *
371 * @param string $file URL to remap/embed
372 * @param string $query
373 * @param string $local File path where the source was read from
374 * @param string $remote URL path to the file
375 * @param bool $embed Whether to do any data URI embedding
376 * @return string Remapped/embedded URL data
377 */
378 public static function remapOne( $file, $query, $local, $remote, $embed ) {
379 // The full URL possibly with query, as passed to the 'url()' value in CSS
380 $url = $file . $query;
381
382 // Expand local URLs with absolute paths like /w/index.php to possibly protocol-relative URL, if
383 // wfExpandUrl() is available. (This will not be the case if we're running outside of MW.)
384 if ( self::isLocalUrl( $url ) && function_exists( 'wfExpandUrl' ) ) {
385 return wfExpandUrl( $url, PROTO_RELATIVE );
386 }
387
388 // Pass thru fully-qualified and protocol-relative URLs and data URIs, as well as local URLs if
389 // we can't expand them.
390 if ( self::isRemoteUrl( $url ) || self::isLocalUrl( $url ) ) {
391 return $url;
392 }
393
394 if ( $local === false ) {
395 // Assume that all paths are relative to $remote, and make them absolute
396 return $remote . '/' . $url;
397 } else {
398 // We drop the query part here and instead make the path relative to $remote
399 $url = "{$remote}/{$file}";
400 // Path to the actual file on the filesystem
401 $localFile = "{$local}/{$file}";
402 if ( file_exists( $localFile ) ) {
403 // Add version parameter as a time-stamp in ISO 8601 format,
404 // using Z for the timezone, meaning GMT
405 $url .= '?' . gmdate( 'Y-m-d\TH:i:s\Z', round( filemtime( $localFile ), -2 ) );
406 if ( $embed ) {
407 $data = self::encodeImageAsDataURI( $localFile );
408 if ( $data !== false ) {
409 return $data;
410 }
411 }
412 }
413 // If any of these conditions failed (file missing, we don't want to embed it
414 // or it's not embeddable), return the URL (possibly with ?timestamp part)
415 return $url;
416 }
417 }
418
419 /**
420 * Removes whitespace from CSS data
421 *
422 * @param string $css CSS data to minify
423 * @return string Minified CSS data
424 */
425 public static function minify( $css ) {
426 return trim(
427 str_replace(
428 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
429 array( ';', ':', '{', '{', ',', '}', '}' ),
430 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )
431 )
432 );
433 }
434 }