[mediawiki.action.watch] clean up
[lhc/web/wiklou.git] / includes / libs / CSSMin.php
1 <?php
2 /**
3 * Copyright 2010 Wikimedia Foundation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License"); you may
6 * not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software distributed
12 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
13 * OF ANY KIND, either express or implied. See the License for the
14 * specific language governing permissions and limitations under the License.
15 */
16
17 /**
18 * Transforms CSS data
19 *
20 * This class provides minification, URL remapping, URL extracting, and data-URL embedding.
21 *
22 * @file
23 * @version 0.1.1 -- 2010-09-11
24 * @author Trevor Parscal <tparscal@wikimedia.org>
25 * @copyright Copyright 2010 Wikimedia Foundation
26 * @license http://www.apache.org/licenses/LICENSE-2.0
27 */
28 class CSSMin {
29
30 /* Constants */
31
32 /**
33 * Maximum file size to still qualify for in-line embedding as a data-URI
34 *
35 * 24,576 is used because Internet Explorer has a 32,768 byte limit for data URIs,
36 * which when base64 encoded will result in a 1/3 increase in size.
37 */
38 const EMBED_SIZE_LIMIT = 24576;
39 const URL_REGEX = 'url\(\s*[\'"]?(?P<file>[^\?\)\'"]*)(?P<query>\??[^\)\'"]*)[\'"]?\s*\)';
40
41 /* Protected Static Members */
42
43 /** @var array List of common image files extensions and mime-types */
44 protected static $mimeTypes = array(
45 'gif' => 'image/gif',
46 'jpe' => 'image/jpeg',
47 'jpeg' => 'image/jpeg',
48 'jpg' => 'image/jpeg',
49 'png' => 'image/png',
50 'tif' => 'image/tiff',
51 'tiff' => 'image/tiff',
52 'xbm' => 'image/x-xbitmap',
53 );
54
55 /* Static Methods */
56
57 /**
58 * Gets a list of local file paths which are referenced in a CSS style sheet
59 *
60 * @param $source string CSS data to remap
61 * @param $path string File path where the source was read from (optional)
62 * @return array List of local file references
63 */
64 public static function getLocalFileReferences( $source, $path = null ) {
65 $files = array();
66 $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER;
67 if ( preg_match_all( '/' . self::URL_REGEX . '/', $source, $matches, $rFlags ) ) {
68 foreach ( $matches as $match ) {
69 $file = ( isset( $path )
70 ? rtrim( $path, '/' ) . '/'
71 : '' ) . "{$match['file'][0]}";
72
73 // Only proceed if we can access the file
74 if ( !is_null( $path ) && file_exists( $file ) ) {
75 $files[] = $file;
76 }
77 }
78 }
79 return $files;
80 }
81
82 /**
83 * @param $file string
84 * @return bool|string
85 */
86 protected static function getMimeType( $file ) {
87 $realpath = realpath( $file );
88 // Try a couple of different ways to get the mime-type of a file, in order of
89 // preference
90 if (
91 $realpath
92 && function_exists( 'finfo_file' )
93 && function_exists( 'finfo_open' )
94 && defined( 'FILEINFO_MIME_TYPE' )
95 ) {
96 // As of PHP 5.3, this is how you get the mime-type of a file; it uses the Fileinfo
97 // PECL extension
98 return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
99 } elseif ( function_exists( 'mime_content_type' ) ) {
100 // Before this was deprecated in PHP 5.3, this was how you got the mime-type of a file
101 return mime_content_type( $file );
102 } else {
103 // Worst-case scenario has happened, use the file extension to infer the mime-type
104 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
105 if ( isset( self::$mimeTypes[$ext] ) ) {
106 return self::$mimeTypes[$ext];
107 }
108 }
109 return false;
110 }
111
112 /**
113 * Remaps CSS URL paths and automatically embeds data URIs for URL rules
114 * preceded by an /* @embed * / comment
115 *
116 * @param $source string CSS data to remap
117 * @param $local string File path where the source was read from
118 * @param $remote string URL path to the file
119 * @param $embedData bool If false, never do any data URI embedding, even if / * @embed * / is found
120 * @return string Remapped CSS data
121 */
122 public static function remap( $source, $local, $remote, $embedData = true ) {
123 $pattern = '/((?P<embed>\s*\/\*\s*\@embed\s*\*\/)(?P<pre>[^\;\}]*))?' .
124 self::URL_REGEX . '(?P<post>[^;]*)[\;]?/';
125 $offset = 0;
126 while ( preg_match( $pattern, $source, $match, PREG_OFFSET_CAPTURE, $offset ) ) {
127 // Skip fully-qualified URLs and data URIs
128 $urlScheme = parse_url( $match['file'][0], PHP_URL_SCHEME );
129 if ( $urlScheme ) {
130 // Move the offset to the end of the match, leaving it alone
131 $offset = $match[0][1] + strlen( $match[0][0] );
132 continue;
133 }
134 // URLs with absolute paths like /w/index.php need to be expanded
135 // to absolute URLs but otherwise left alone
136 if ( $match['file'][0] !== '' && $match['file'][0][0] === '/' ) {
137 // Replace the file path with an expanded (possibly protocol-relative) URL
138 // ...but only if wfExpandUrl() is even available.
139 // This will not be the case if we're running outside of MW
140 $lengthIncrease = 0;
141 if ( function_exists( 'wfExpandUrl' ) ) {
142 $expanded = wfExpandUrl( $match['file'][0], PROTO_RELATIVE );
143 $origLength = strlen( $match['file'][0] );
144 $lengthIncrease = strlen( $expanded ) - $origLength;
145 $source = substr_replace( $source, $expanded,
146 $match['file'][1], $origLength
147 );
148 }
149 // Move the offset to the end of the match, leaving it alone
150 $offset = $match[0][1] + strlen( $match[0][0] ) + $lengthIncrease;
151 continue;
152 }
153 // Shortcuts
154 $embed = $match['embed'][0];
155 $pre = $match['pre'][0];
156 $post = $match['post'][0];
157 $query = $match['query'][0];
158 $url = "{$remote}/{$match['file'][0]}";
159 $file = "{$local}/{$match['file'][0]}";
160 // bug 27052 - Guard against double slashes, because foo//../bar
161 // apparently resolves to foo/bar on (some?) clients
162 $url = preg_replace( '#([^:])//+#', '\1/', $url );
163 $replacement = false;
164 if ( $local !== false && file_exists( $file ) ) {
165 // Add version parameter as a time-stamp in ISO 8601 format,
166 // using Z for the timezone, meaning GMT
167 $url .= '?' . gmdate( 'Y-m-d\TH:i:s\Z', round( filemtime( $file ), -2 ) );
168 // Embedding requires a bit of extra processing, so let's skip that if we can
169 if ( $embedData && $embed ) {
170 $type = self::getMimeType( $file );
171 // Detect when URLs were preceeded with embed tags, and also verify file size is
172 // below the limit
173 if (
174 $type
175 && $match['embed'][1] > 0
176 && filesize( $file ) < self::EMBED_SIZE_LIMIT
177 ) {
178 // Strip off any trailing = symbols (makes browsers freak out)
179 $data = base64_encode( file_get_contents( $file ) );
180 // Build 2 CSS properties; one which uses a base64 encoded data URI in place
181 // of the @embed comment to try and retain line-number integrity, and the
182 // other with a remapped an versioned URL and an Internet Explorer hack
183 // making it ignored in all browsers that support data URIs
184 $replacement = "{$pre}url(data:{$type};base64,{$data}){$post};";
185 $replacement .= "{$pre}url({$url}){$post}!ie;";
186 }
187 }
188 if ( $replacement === false ) {
189 // Assume that all paths are relative to $remote, and make them absolute
190 $replacement = "{$embed}{$pre}url({$url}){$post};";
191 }
192 } elseif ( $local === false ) {
193 // Assume that all paths are relative to $remote, and make them absolute
194 $replacement = "{$embed}{$pre}url({$url}{$query}){$post};";
195 }
196 if ( $replacement !== false ) {
197 // Perform replacement on the source
198 $source = substr_replace(
199 $source, $replacement, $match[0][1], strlen( $match[0][0] )
200 );
201 // Move the offset to the end of the replacement in the source
202 $offset = $match[0][1] + strlen( $replacement );
203 continue;
204 }
205 // Move the offset to the end of the match, leaving it alone
206 $offset = $match[0][1] + strlen( $match[0][0] );
207 }
208 return $source;
209 }
210
211 /**
212 * Removes whitespace from CSS data
213 *
214 * @param $css string CSS data to minify
215 * @return string Minified CSS data
216 */
217 public static function minify( $css ) {
218 return trim(
219 str_replace(
220 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
221 array( ';', ':', '{', '{', ',', '}', '}' ),
222 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )
223 )
224 );
225 }
226 }