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