5ed65c3750792643c2ae99c9478423da5c69e5e5
[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>[^\?\)\:\'"]*)\??[^\)\'"]*[\'"]?\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 * Remaps CSS URL paths and automatically embeds data URIs for URL rules
84 * preceded by an /* @embed * / comment
85 *
86 * @param $source string CSS data to remap
87 * @param $local string File path where the source was read from
88 * @param $remote string URL path to the file
89 * @param $embed ???
90 * @return string Remapped CSS data
91 */
92 public static function remap( $source, $local, $remote, $embed = true ) {
93 $pattern = '/((?P<embed>\s*\/\*\s*\@embed\s*\*\/)(?P<pre>[^\;\}]*))?' .
94 self::URL_REGEX . '(?P<post>[^;]*)[\;]?/';
95 $offset = 0;
96 while ( preg_match( $pattern, $source, $match, PREG_OFFSET_CAPTURE, $offset ) ) {
97 // Shortcuts
98 $embed = $match['embed'][0];
99 $pre = $match['pre'][0];
100 $post = $match['post'][0];
101 $file = "{$local}/{$match['file'][0]}";
102 $url = "{$remote}/{$match['file'][0]}";
103 // Only proceed if we can access the file
104 if ( file_exists( $file ) ) {
105 // Add version parameter as a time-stamp in ISO 8601 format,
106 // using Z for the timezone, meaning GMT
107 $url .= '?' . gmdate( 'Y-m-d\TH:i:s\Z', round( filemtime( $file ), -2 ) );
108 // If we the mime-type can't be determined, no embedding will take place
109 $type = false;
110 $realpath = realpath( $file );
111 // Try a couple of different ways to get the mime-type of a file,
112 // in order of preference
113 if ( $realpath
114 && function_exists( 'finfo_file' ) && function_exists( 'finfo_open' )
115 && defined( 'FILEINFO_MIME_TYPE' ) )
116 {
117 // As of PHP 5.3, this is how you get the mime-type of a file;
118 // it uses the Fileinfo PECL extension
119 $type = finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
120 } else if ( function_exists( 'mime_content_type' ) ) {
121 // Before this was deprecated in PHP 5.3,
122 // this used to be how you get the mime-type of a file
123 $type = mime_content_type( $file );
124 } else {
125 // Worst-case scenario has happened,
126 // use the file extension to infer the mime-type
127 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
128 if ( isset( self::$mimeTypes[$ext] ) ) {
129 $type = self::$mimeTypes[$ext];
130 }
131 }
132 // Detect when URLs were preceeded with embed tags,
133 // and also verify file size is below the limit
134 if ( $embed && $type && $match['embed'][1] > 0
135 && filesize( $file ) < self::EMBED_SIZE_LIMIT )
136 {
137 // Strip off any trailing = symbols (makes browsers freak out)
138 $data = base64_encode( file_get_contents( $file ) );
139 // Build 2 CSS properties; one which uses a base64 encoded data URI
140 // in place of the @embed comment to try and retain line-number integrity,
141 // and the other with a remapped an versioned URL and an Internet Explorer
142 // hack making it ignored in all browsers that support data URIs
143 $replacement = "{$pre}url(data:{$type};base64,{$data}){$post};";
144 $replacement .= "{$pre}url({$url}){$post}!ie;";
145 } else {
146 // Build a CSS property with a remapped and versioned URL,
147 // preserving comment for debug mode
148 $replacement = "{$embed}{$pre}url({$url}){$post};";
149 }
150
151 // Perform replacement on the source
152 $source = substr_replace( $source,
153 $replacement, $match[0][1], strlen( $match[0][0] ) );
154 // Move the offset to the end of the replacement in the source
155 $offset = $match[0][1] + strlen( $replacement );
156 continue;
157 }
158 // Move the offset to the end of the match, leaving it alone
159 $offset = $match[0][1] + strlen( $match[0][0] );
160 }
161 return $source;
162 }
163
164 /**
165 * Removes whitespace from CSS data
166 *
167 * @param $css string CSS data to minify
168 * @return string Minified CSS data
169 */
170 public static function minify( $css ) {
171 return trim(
172 str_replace(
173 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
174 array( ';', ':', '{', '{', ',', '}', '}' ),
175 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )
176 )
177 );
178 }
179 }