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