Merge "Restore Signupstart and Signupend messages for account creation"
[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 * Remaps CSS URL paths and automatically embeds data URIs for CSS rules or url() values
145 * preceded by an / * @embed * / comment.
146 *
147 * @param string $source CSS data to remap
148 * @param string $local File path where the source was read from
149 * @param string $remote URL path to the file
150 * @param bool $embedData If false, never do any data URI embedding, even if / * @embed * / is found
151 * @return string Remapped CSS data
152 */
153 public static function remap( $source, $local, $remote, $embedData = true ) {
154 // High-level overview:
155 // * For each CSS rule in $source that includes at least one url() value:
156 // * Check for an @embed comment at the start indicating that all URIs should be embedded
157 // * For each url() value:
158 // * Check for an @embed comment directly preceding the value
159 // * If either @embed comment exists:
160 // * Embedding the URL as data: URI, if it's possible / allowed
161 // * Otherwise remap the URL to work in generated stylesheets
162
163 // Guard against trailing slashes, because "some/remote/../foo.png"
164 // resolves to "some/remote/foo.png" on (some?) clients (bug 27052).
165 if ( substr( $remote, -1 ) == '/' ) {
166 $remote = substr( $remote, 0, -1 );
167 }
168
169 // Note: This will not correctly handle cases where ';', '{' or '}' appears in the rule itself,
170 // e.g. in a quoted string. You are advised not to use such characters in file names.
171 $pattern = '/[;{]\K[^;}]*' . CSSMin::URL_REGEX . '[^;}]*(?=[;}])/';
172 return preg_replace_callback( $pattern, function ( $matchOuter ) use ( $local, $remote, $embedData ) {
173 $rule = $matchOuter[0];
174
175 // Check for global @embed comment and remove it
176 $embedAll = false;
177 $rule = preg_replace( '/^(\s*)' . CSSMin::EMBED_REGEX . '\s*/', '$1', $rule, 1, $embedAll );
178
179 // Build two versions of current rule: with remapped URLs and with embedded data: URIs (where possible)
180 $pattern = '/(?P<embed>' . CSSMin::EMBED_REGEX . '\s*|)' . CSSMin::URL_REGEX . '/';
181
182 $ruleWithRemapped = preg_replace_callback( $pattern, function ( $match ) use ( $local, $remote ) {
183 $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
184 return "url({$remapped})";
185 }, $rule );
186
187 if ( $embedData ) {
188 $ruleWithEmbedded = preg_replace_callback( $pattern, function ( $match ) use ( $embedAll, $local, $remote ) {
189 $embed = $embedAll || $match['embed'];
190 $embedded = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, $embed );
191 return "url({$embedded})";
192 }, $rule );
193 }
194
195 if ( $embedData && $ruleWithEmbedded !== $ruleWithRemapped ) {
196 // Build 2 CSS properties; one which uses a base64 encoded data URI in place
197 // of the @embed comment to try and retain line-number integrity, and the
198 // other with a remapped an versioned URL and an Internet Explorer hack
199 // making it ignored in all browsers that support data URIs
200 return "$ruleWithEmbedded;$ruleWithRemapped!ie";
201 } else {
202 // No reason to repeat twice
203 return $ruleWithRemapped;
204 }
205 }, $source );
206
207 return $source;
208 }
209
210 /**
211 * Remap or embed a CSS URL path.
212 *
213 * @param string $file URL to remap/embed
214 * @param string $query
215 * @param string $local File path where the source was read from
216 * @param string $remote URL path to the file
217 * @param bool $embed Whether to do any data URI embedding
218 * @return string Remapped/embedded URL data
219 */
220 public static function remapOne( $file, $query, $local, $remote, $embed ) {
221 // Skip fully-qualified URLs and data URIs
222 $urlScheme = parse_url( $file, PHP_URL_SCHEME );
223 if ( $urlScheme ) {
224 return $file;
225 }
226
227 // URLs with absolute paths like /w/index.php need to be expanded
228 // to absolute URLs but otherwise left alone
229 if ( $file !== '' && $file[0] === '/' ) {
230 // Replace the file path with an expanded (possibly protocol-relative) URL
231 // ...but only if wfExpandUrl() is even available.
232 // This will not be the case if we're running outside of MW
233 if ( function_exists( 'wfExpandUrl' ) ) {
234 return wfExpandUrl( $file, PROTO_RELATIVE );
235 } else {
236 return $file;
237 }
238 }
239
240 $url = "{$remote}/{$file}";
241 $file = "{$local}/{$file}";
242
243 $replacement = false;
244
245 if ( $local !== false && file_exists( $file ) ) {
246 // Add version parameter as a time-stamp in ISO 8601 format,
247 // using Z for the timezone, meaning GMT
248 $url .= '?' . gmdate( 'Y-m-d\TH:i:s\Z', round( filemtime( $file ), -2 ) );
249 if ( $embed ) {
250 $data = self::encodeImageAsDataURI( $file );
251 if ( $data !== false ) {
252 return $data;
253 } else {
254 return $url;
255 }
256 } else {
257 // Assume that all paths are relative to $remote, and make them absolute
258 return $url;
259 }
260 } elseif ( $local === false ) {
261 // Assume that all paths are relative to $remote, and make them absolute
262 return $url . $query;
263 } else {
264 return $file;
265 }
266 }
267
268 /**
269 * Removes whitespace from CSS data
270 *
271 * @param string $css CSS data to minify
272 * @return string Minified CSS data
273 */
274 public static function minify( $css ) {
275 return trim(
276 str_replace(
277 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
278 array( ';', ':', '{', '{', ',', '}', '}' ),
279 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )
280 )
281 );
282 }
283 }