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