Fixed some doxygen warnings
[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 not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
11 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
12 * specific language governing permissions and limitations under the License.
13 */
14
15 /**
16 * Transforms CSS data
17 *
18 * This class provides minification, URL remapping, URL extracting, and data-URL embedding.
19 *
20 * @file
21 * @version 0.1.1 -- 2010-09-11
22 * @author Trevor Parscal <tparscal@wikimedia.org>
23 * @copyright Copyright 2010 Wikimedia Foundation
24 * @license http://www.apache.org/licenses/LICENSE-2.0
25 */
26 class CSSMin {
27
28 /* Constants */
29
30 /**
31 * Maximum file size to still qualify for in-line embedding as a data-URI
32 *
33 * 24,576 is used because Internet Explorer has a 32,768 byte limit for data URIs, which when base64 encoded will
34 * result in a 1/3 increase in size.
35 */
36 const EMBED_SIZE_LIMIT = 24576;
37 const URL_REGEX = 'url\([\'"]?(?<file>[^\?\)\:\'"]*)\??[^\)\'"]*[\'"]?\)';
38
39 /* Protected Static Members */
40
41 /** @var array List of common image files extensions and mime-types */
42 protected static $mimeTypes = array(
43 'gif' => 'image/gif',
44 'jpe' => 'image/jpeg',
45 'jpeg' => 'image/jpeg',
46 'jpg' => 'image/jpeg',
47 'png' => 'image/png',
48 'tif' => 'image/tiff',
49 'tiff' => 'image/tiff',
50 'xbm' => 'image/x-xbitmap',
51 );
52
53 /* Static Methods */
54
55 /**
56 * Gets a list of local file paths which are referenced in a CSS style sheet
57 *
58 * @param $source string CSS data to remap
59 * @param $path string File path where the source was read from (optional)
60 * @return array List of local file references
61 */
62 public static function getLocalFileReferences( $source, $path = null ) {
63 $files = array();
64 if ( preg_match_all( '/' . self::URL_REGEX . '/', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER ) ) {
65 foreach ( $matches as $match ) {
66 $file = ( isset( $path ) ? rtrim( $path, '/' ) . '/' : '' ) . "{$match['file'][0]}";
67
68 // Only proceed if we can access the file
69 if ( !is_null( $path ) && file_exists( $file ) ) {
70 $files[] = $file;
71 }
72 }
73 }
74 return $files;
75 }
76
77 /**
78 * Remaps CSS URL paths and automatically embeds data URIs for URL rules preceded by an /* @embed * / comment
79 *
80 * @param $source string CSS data to remap
81 * @param $local string File path where the source was read from
82 * @param $remote string URL path to the file
83 * @param $embed ???
84 * @return string Remapped CSS data
85 */
86 public static function remap( $source, $local, $remote, $embed = true ) {
87 $pattern = '/((?<embed>\s*\/\*\s*\@embed\s*\*\/)(?<pre>[^\;\}]*))?' . self::URL_REGEX . '(?<post>[^;]*)[\;]?/';
88 $offset = 0;
89 while ( preg_match( $pattern, $source, $match, PREG_OFFSET_CAPTURE, $offset ) ) {
90 // Shortcuts
91 $embed = $match['embed'][0];
92 $pre = $match['pre'][0];
93 $post = $match['post'][0];
94 $file = "{$local}/{$match['file'][0]}";
95 $url = "{$remote}/{$match['file'][0]}";
96 // Only proceed if we can access the fill
97 if ( file_exists( $file ) ) {
98 // Add version parameter as a time-stamp in ISO 8601 format, using Z for the timezone, meaning GMT
99 $url .= '?' . gmdate( 'Y-m-d\TH:i:s\Z', round( filemtime( $file ), -2 ) );
100 // If we the mime-type can't be determined, no embedding will take place
101 $type = false;
102 // Try a couple of different ways to get the mime-type of a file, in order of preference
103 if ( function_exists( 'finfo_file' ) && function_exists( 'finfo_open' ) ) {
104 // As of PHP 5.3, this is how you get the mime-type of a file; it uses the Fileinfo PECL extension
105 $type = finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $file );
106 } else if ( function_exists( 'mime_content_type' ) ) {
107 // Before this was deprecated in PHP 5.3, this used to be how you get the mime-type of a file
108 $type = mime_content_type( $file );
109 } else {
110 // Worst-case scenario has happend, use the file extension to infer the mime-type
111 $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
112 if ( isset( self::$mimeTypes[$ext] ) ) {
113 $type = self::$mimeTypes[$ext];
114 }
115 }
116 // Detect when URLs were preceeded with embed tags, and also verify file size is below the limit
117 if ( $embed && $type && $match['embed'][1] > 0 && filesize( $file ) < self::EMBED_SIZE_LIMIT ) {
118 // Strip off any trailing = symbols (makes browsers freak out)
119 $data = base64_encode( file_get_contents( $file ) );
120 // Build 2 CSS properties; one which uses a base64 encoded data URI in place of the @embed
121 // comment to try and retain line-number integrity , and the other with a remapped an versioned
122 // URL and an Internet Explorer hack making it ignored in all browsers that support data URIs
123 $replacement = "{$pre}url(data:{$type};base64,{$data}){$post};{$pre}url({$url}){$post}!ie;";
124 } else {
125 // Build a CSS property with a remapped and versioned URL, preserving comment for debug mode
126 $replacement = "{$embed}{$pre}url({$url}){$post};";
127 }
128
129 // Perform replacement on the source
130 $source = substr_replace( $source, $replacement, $match[0][1], strlen( $match[0][0] ) );
131 // Move the offset to the end of the replacement in the source
132 $offset = $match[0][1] + strlen( $replacement );
133 continue;
134 }
135 // Move the offset to the end of the match, leaving it alone
136 $offset = $match[0][1] + strlen( $match[0][0] );
137 }
138 return $source;
139 }
140
141 /**
142 * Removes whitespace from CSS data
143 *
144 * @param $css string CSS data to minify
145 * @return string Minified CSS data
146 */
147 public static function minify( $css ) {
148 return trim(
149 str_replace(
150 array( '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ),
151 array( ';', ':', '{', '{', ',', '}', '}' ),
152 preg_replace( array( '/\s+/', '/\/\*.*?\*\//s' ), array( ' ', '' ), $css )
153 )
154 );
155 }
156 }