CSSMin.php 8.1 KB

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