Merge "Add wgRevisionId variable to ResourceLoader"
[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
43 /* Protected Static Members */
44
45 /** @var array List of common image files extensions and mime-types */
46 protected static $mimeTypes = array(
47 'gif' => 'image/gif',
48 'jpe' => 'image/jpeg',
49 'jpeg' => 'image/jpeg',
50 'jpg' => 'image/jpeg',
51 'png' => 'image/png',
52 'tif' => 'image/tiff',
53 'tiff' => 'image/tiff',
54 'xbm' => 'image/x-xbitmap',
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 * @param string $source CSS data to remap
63 * @param string $path File path where the source was read from (optional)
64 * @return array List of local file references
65 */
66 public static function getLocalFileReferences( $source, $path = null ) {
67 $files = array();
68 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER;
69 if ( preg_match_all( '/' . self::URL_REGEX . '/', $source, $matches, $rFlags ) ) {
70 foreach ( $matches as $match ) {
71 $file = ( isset( $path )
72 ? rtrim( $path, '/' ) . '/'
73 : '' ) . "{$match['file'][0]}";
74
75 // Only proceed if we can access the file
76 if ( !is_null( $path ) && file_exists( $file ) ) {
77 $files[] = $file;
78 }
79 }
80 }
81 return $files;
82 }
83
84 /**
85 * Encode an image file as a base64 data URI.
86 * If the image file has a suitable MIME type and size, encode it as a
87 * base64 data URI. Return false if the image type is unfamiliar or exceeds
88 * the size limit.
89 *
90 * @param string $file Image file to encode.
91 * @param string|null $type File's MIME type or null. If null, CSSMin will
92 * try to autodetect the type.
93 * @param int|bool $sizeLimit If the size of the target file is greater than
94 * this value, decline to encode the image file and return false
95 * instead. If $sizeLimit is false, no limit is enforced.
96 * @return string|bool: Image contents encoded as a data URI or false.
97 */
98 public static function encodeImageAsDataURI( $file, $type = null, $sizeLimit = self::EMBED_SIZE_LIMIT ) {
99 if ( $sizeLimit !== false && filesize( $file ) >= $sizeLimit ) {
100 return false;
101 }
102 if ( $type === null ) {
103 $type = self::getMimeType( $file );
104 }
105 if ( !$type ) {
106 return false;
107 }
108 $data = base64_encode( file_get_contents( $file ) );
109 return 'data:' . $type . ';base64,' . $data;
110 }
111
112 /**
113 * @param $file string
114 * @return bool|string
115 */
116 public static function getMimeType( $file ) {
117 $realpath = realpath( $file );
118 // Try a couple of different ways to get the mime-type of a file, in order of
119 // preference
120 if (
121 $realpath
122 && function_exists( 'finfo_file' )
123 && function_exists( 'finfo_open' )
124 && defined( 'FILEINFO_MIME_TYPE' )
125 ) {
126 // As of PHP 5.3, this is how you get the mime-type of a file; it uses the Fileinfo
127 // PECL extension
128 return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
129 } elseif ( function_exists( 'mime_content_type' ) ) {
130 // Before this was deprecated in PHP 5.3, this was how you got the mime-type of a file
131 return mime_content_type( $file );
132 } else {
133 // Worst-case scenario has happened, use the file extension to infer the mime-type
134 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
135 if ( isset( self::$mimeTypes[$ext] ) ) {
136 return self::$mimeTypes[$ext];
137 }
138 }
139 return false;
140 }
141
142 /**
143 * Remaps CSS URL paths and automatically embeds data URIs for URL rules
144 * preceded by an /* @embed * / comment
145 *
146 * @param string $source CSS data to remap
147 * @param string $local File path where the source was read from
148 * @param string $remote URL path to the file
149 * @param bool $embedData If false, never do any data URI embedding, even if / * @embed * / is found
150 * @return string Remapped CSS data
151 */
152 public static function remap( $source, $local, $remote, $embedData = true ) {
153 $pattern = '/((?P<embed>\s*\/\*\s*\@embed\s*\*\/)(?P<pre>[^\;\}]*))?' .
154 self::URL_REGEX . '(?P<post>[^;]*)[\;]?/';
155 $offset = 0;
156 while ( preg_match( $pattern, $source, $match, PREG_OFFSET_CAPTURE, $offset ) ) {
157 // Skip fully-qualified URLs and data URIs
158 $urlScheme = parse_url( $match['file'][0], PHP_URL_SCHEME );
159 if ( $urlScheme ) {
160 // Move the offset to the end of the match, leaving it alone
161 $offset = $match[0][1] + strlen( $match[0][0] );
162 continue;
163 }
164 // URLs with absolute paths like /w/index.php need to be expanded
165 // to absolute URLs but otherwise left alone
166 if ( $match['file'][0] !== '' && $match['file'][0][0] === '/' ) {
167 // Replace the file path with an expanded (possibly protocol-relative) URL
168 // ...but only if wfExpandUrl() is even available.
169 // This will not be the case if we're running outside of MW
170 $lengthIncrease = 0;
171 if ( function_exists( 'wfExpandUrl' ) ) {
172 $expanded = wfExpandUrl( $match['file'][0], PROTO_RELATIVE );
173 $origLength = strlen( $match['file'][0] );
174 $lengthIncrease = strlen( $expanded ) - $origLength;
175 $source = substr_replace( $source, $expanded,
176 $match['file'][1], $origLength
177 );
178 }
179 // Move the offset to the end of the match, leaving it alone
180 $offset = $match[0][1] + strlen( $match[0][0] ) + $lengthIncrease;
181 continue;
182 }
183
184 // Guard against double slashes, because "some/remote/../foo.png"
185 // resolves to "some/remote/foo.png" on (some?) clients (bug 27052).
186 if ( substr( $remote, -1 ) == '/' ) {
187 $remote = substr( $remote, 0, -1 );
188 }
189
190 // Shortcuts
191 $embed = $match['embed'][0];
192 $pre = $match['pre'][0];
193 $post = $match['post'][0];
194 $query = $match['query'][0];
195 $url = "{$remote}/{$match['file'][0]}";
196 $file = "{$local}/{$match['file'][0]}";
197
198 $replacement = false;
199
200 if ( $local !== false && file_exists( $file ) ) {
201 // Add version parameter as a time-stamp in ISO 8601 format,
202 // using Z for the timezone, meaning GMT
203 $url .= '?' . gmdate( 'Y-m-d\TH:i:s\Z', round( filemtime( $file ), -2 ) );
204 // Embedding requires a bit of extra processing, so let's skip that if we can
205 if ( $embedData && $embed && $match['embed'][1] > 0 ) {
206 $data = self::encodeImageAsDataURI( $file );
207 if ( $data !== false ) {
208 // Build 2 CSS properties; one which uses a base64 encoded data URI in place
209 // of the @embed comment to try and retain line-number integrity, and the
210 // other with a remapped an versioned URL and an Internet Explorer hack
211 // making it ignored in all browsers that support data URIs
212 $replacement = "{$pre}url({$data}){$post};{$pre}url({$url}){$post}!ie;";
213 }
214 }
215 if ( $replacement === false ) {
216 // Assume that all paths are relative to $remote, and make them absolute
217 $replacement = "{$embed}{$pre}url({$url}){$post};";
218 }
219 } elseif ( $local === false ) {
220 // Assume that all paths are relative to $remote, and make them absolute
221 $replacement = "{$embed}{$pre}url({$url}{$query}){$post};";
222 }
223 if ( $replacement !== false ) {
224 // Perform replacement on the source
225 $source = substr_replace(
226 $source, $replacement, $match[0][1], strlen( $match[0][0] )
227 );
228 // Move the offset to the end of the replacement in the source
229 $offset = $match[0][1] + strlen( $replacement );
230 continue;
231 }
232 // Move the offset to the end of the match, leaving it alone
233 $offset = $match[0][1] + strlen( $match[0][0] );
234 }
235 return $source;
236 }
237
238 /**
239 * Removes whitespace from CSS data
240 *
241 * @param string $css CSS data to minify
242 * @return string Minified CSS data
243 */
244 public static function minify( $css ) {
245 return trim(
246 str_replace(
247 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
248 array( ';', ':', '{', '{', ',', '}', '}' ),
249 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )
250 )
251 );
252 }
253 }