MediaWiki  1.29.1
CSSMin.php
Go to the documentation of this file.
1 <?php
30 class CSSMin {
31 
32  /* Constants */
33 
35  const PLACEHOLDER = "\x7fPLACEHOLDER\x7f";
36 
40  const DATA_URI_SIZE_LIMIT = 32768;
41  const URL_REGEX = 'url\(\s*[\'"]?(?P<file>[^\?\)\'"]*?)(?P<query>\?[^\)\'"]*?|)[\'"]?\s*\)';
42  const EMBED_REGEX = '\/\*\s*\@embed\s*\*\/';
43  const COMMENT_REGEX = '\/\*.*?\*\/';
44 
45  /* Protected Static Members */
46 
48  protected static $mimeTypes = [
49  'gif' => 'image/gif',
50  'jpe' => 'image/jpeg',
51  'jpeg' => 'image/jpeg',
52  'jpg' => 'image/jpeg',
53  'png' => 'image/png',
54  'tif' => 'image/tiff',
55  'tiff' => 'image/tiff',
56  'xbm' => 'image/x-xbitmap',
57  'svg' => 'image/svg+xml',
58  ];
59 
60  /* Static Methods */
61 
69  public static function getLocalFileReferences( $source, $path ) {
70  $stripped = preg_replace( '/' . self::COMMENT_REGEX . '/s', '', $source );
71  $path = rtrim( $path, '/' ) . '/';
72  $files = [];
73 
74  $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER;
75  if ( preg_match_all( '/' . self::URL_REGEX . '/', $stripped, $matches, $rFlags ) ) {
76  foreach ( $matches as $match ) {
77  $url = $match['file'][0];
78 
79  // Skip fully-qualified and protocol-relative URLs and data URIs
80  if ( substr( $url, 0, 2 ) === '//' || parse_url( $url, PHP_URL_SCHEME ) ) {
81  break;
82  }
83 
84  $files[] = $path . $url;
85  }
86  }
87  return $files;
88  }
89 
105  public static function encodeImageAsDataURI( $file, $type = null, $ie8Compat = true ) {
106  // Fast-fail for files that definitely exceed the maximum data URI length
107  if ( $ie8Compat && filesize( $file ) >= self::DATA_URI_SIZE_LIMIT ) {
108  return false;
109  }
110 
111  if ( $type === null ) {
112  $type = self::getMimeType( $file );
113  }
114  if ( !$type ) {
115  return false;
116  }
117 
118  return self::encodeStringAsDataURI( file_get_contents( $file ), $type, $ie8Compat );
119  }
120 
133  public static function encodeStringAsDataURI( $contents, $type, $ie8Compat = true ) {
134  // Try #1: Non-encoded data URI
135  // The regular expression matches ASCII whitespace and printable characters.
136  if ( preg_match( '/^[\r\n\t\x20-\x7e]+$/', $contents ) ) {
137  // Do not base64-encode non-binary files (sane SVGs).
138  // (This often produces longer URLs, but they compress better, yielding a net smaller size.)
139  $uri = 'data:' . $type . ',' . rawurlencode( $contents );
140  if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
141  return $uri;
142  }
143  }
144 
145  // Try #2: Encoded data URI
146  $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
147  if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
148  return $uri;
149  }
150 
151  // A data URI couldn't be produced
152  return false;
153  }
154 
163  public static function serializeStringValue( $value ) {
164  if ( strstr( $value, "\0" ) ) {
165  throw new Exception( "Invalid character in CSS string" );
166  }
167  $value = strtr( $value, [ '\\' => '\\\\', '"' => '\\"' ] );
168  $value = preg_replace_callback( '/[\x01-\x1f\x7f-\x9f]/', function ( $match ) {
169  return '\\' . base_convert( ord( $match[0] ), 10, 16 ) . ' ';
170  }, $value );
171  return '"' . $value . '"';
172  }
173 
178  public static function getMimeType( $file ) {
179  // Infer the MIME-type from the file extension
180  $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
181  if ( isset( self::$mimeTypes[$ext] ) ) {
182  return self::$mimeTypes[$ext];
183  }
184 
185  $realpath = realpath( $file );
186  if (
187  $realpath
188  && function_exists( 'finfo_file' )
189  && function_exists( 'finfo_open' )
190  && defined( 'FILEINFO_MIME_TYPE' )
191  ) {
192  return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
193  }
194 
195  return false;
196  }
197 
207  public static function buildUrlValue( $url ) {
208  // The list below has been crafted to match URLs such as:
209  // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
210  // data:image/png;base64,R0lGODlh/+==
211  if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
212  return "url($url)";
213  } else {
214  return 'url("' . strtr( $url, [ '\\' => '\\\\', '"' => '\\"' ] ) . '")';
215  }
216  }
217 
229  public static function remap( $source, $local, $remote, $embedData = true ) {
230  // High-level overview:
231  // * For each CSS rule in $source that includes at least one url() value:
232  // * Check for an @embed comment at the start indicating that all URIs should be embedded
233  // * For each url() value:
234  // * Check for an @embed comment directly preceding the value
235  // * If either @embed comment exists:
236  // * Embedding the URL as data: URI, if it's possible / allowed
237  // * Otherwise remap the URL to work in generated stylesheets
238 
239  // Guard against trailing slashes, because "some/remote/../foo.png"
240  // resolves to "some/remote/foo.png" on (some?) clients (T29052).
241  if ( substr( $remote, -1 ) == '/' ) {
242  $remote = substr( $remote, 0, -1 );
243  }
244 
245  // Disallow U+007F DELETE, which is illegal anyway, and which
246  // we use for comment placeholders.
247  $source = str_replace( "\x7f", "?", $source );
248 
249  // Replace all comments by a placeholder so they will not interfere with the remapping.
250  // Warning: This will also catch on anything looking like the start of a comment between
251  // quotation marks (e.g. "foo /* bar").
252  $comments = [];
253 
254  $pattern = '/(?!' . CSSMin::EMBED_REGEX . ')(' . CSSMin::COMMENT_REGEX . ')/s';
255 
256  $source = preg_replace_callback(
257  $pattern,
258  function ( $match ) use ( &$comments ) {
259  $comments[] = $match[ 0 ];
260  return CSSMin::PLACEHOLDER . ( count( $comments ) - 1 ) . 'x';
261  },
262  $source
263  );
264 
265  // Note: This will not correctly handle cases where ';', '{' or '}'
266  // appears in the rule itself, e.g. in a quoted string. You are advised
267  // not to use such characters in file names. We also match start/end of
268  // the string to be consistent in edge-cases ('@import url(…)').
269  $pattern = '/(?:^|[;{])\K[^;{}]*' . CSSMin::URL_REGEX . '[^;}]*(?=[;}]|$)/';
270 
271  $source = preg_replace_callback(
272  $pattern,
273  function ( $matchOuter ) use ( $local, $remote, $embedData ) {
274  $rule = $matchOuter[0];
275 
276  // Check for global @embed comment and remove it. Allow other comments to be present
277  // before @embed (they have been replaced with placeholders at this point).
278  $embedAll = false;
279  $rule = preg_replace(
280  '/^((?:\s+|' .
281  CSSMin::PLACEHOLDER .
282  '(\d+)x)*)' .
284  '\s*/',
285  '$1',
286  $rule,
287  1,
288  $embedAll
289  );
290 
291  // Build two versions of current rule: with remapped URLs
292  // and with embedded data: URIs (where possible).
293  $pattern = '/(?P<embed>' . CSSMin::EMBED_REGEX . '\s*|)' . CSSMin::URL_REGEX . '/';
294 
295  $ruleWithRemapped = preg_replace_callback(
296  $pattern,
297  function ( $match ) use ( $local, $remote ) {
298  $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
299 
300  return CSSMin::buildUrlValue( $remapped );
301  },
302  $rule
303  );
304 
305  if ( $embedData ) {
306  // Remember the occurring MIME types to avoid fallbacks when embedding some files.
307  $mimeTypes = [];
308 
309  $ruleWithEmbedded = preg_replace_callback(
310  $pattern,
311  function ( $match ) use ( $embedAll, $local, $remote, &$mimeTypes ) {
312  $embed = $embedAll || $match['embed'];
313  $embedded = CSSMin::remapOne(
314  $match['file'],
315  $match['query'],
316  $local,
317  $remote,
318  $embed
319  );
320 
321  $url = $match['file'] . $match['query'];
322  $file = "{$local}/{$match['file']}";
323  if (
324  !self::isRemoteUrl( $url ) && !self::isLocalUrl( $url )
325  && file_exists( $file )
326  ) {
327  $mimeTypes[ CSSMin::getMimeType( $file ) ] = true;
328  }
329 
330  return CSSMin::buildUrlValue( $embedded );
331  },
332  $rule
333  );
334 
335  // Are all referenced images SVGs?
336  $needsEmbedFallback = $mimeTypes !== [ 'image/svg+xml' => true ];
337  }
338 
339  if ( !$embedData || $ruleWithEmbedded === $ruleWithRemapped ) {
340  // We're not embedding anything, or we tried to but the file is not embeddable
341  return $ruleWithRemapped;
342  } elseif ( $embedData && $needsEmbedFallback ) {
343  // Build 2 CSS properties; one which uses a data URI in place of the @embed comment, and
344  // the other with a remapped and versioned URL with an Internet Explorer 6 and 7 hack
345  // making it ignored in all browsers that support data URIs
346  return "$ruleWithEmbedded;$ruleWithRemapped!ie";
347  } else {
348  // Look ma, no fallbacks! This is for files which IE 6 and 7 don't support anyway: SVG.
349  return $ruleWithEmbedded;
350  }
351  }, $source );
352 
353  // Re-insert comments
354  $pattern = '/' . CSSMin::PLACEHOLDER . '(\d+)x/';
355  $source = preg_replace_callback( $pattern, function( $match ) use ( &$comments ) {
356  return $comments[ $match[1] ];
357  }, $source );
358 
359  return $source;
360  }
361 
368  protected static function isRemoteUrl( $maybeUrl ) {
369  if ( substr( $maybeUrl, 0, 2 ) === '//' || parse_url( $maybeUrl, PHP_URL_SCHEME ) ) {
370  return true;
371  }
372  return false;
373  }
374 
381  protected static function isLocalUrl( $maybeUrl ) {
382  if ( $maybeUrl !== '' && $maybeUrl[0] === '/' && !self::isRemoteUrl( $maybeUrl ) ) {
383  return true;
384  }
385  return false;
386  }
387 
398  public static function remapOne( $file, $query, $local, $remote, $embed ) {
399  // The full URL possibly with query, as passed to the 'url()' value in CSS
400  $url = $file . $query;
401 
402  // Expand local URLs with absolute paths like /w/index.php to possibly protocol-relative URL, if
403  // wfExpandUrl() is available. (This will not be the case if we're running outside of MW.)
404  if ( self::isLocalUrl( $url ) && function_exists( 'wfExpandUrl' ) ) {
405  return wfExpandUrl( $url, PROTO_RELATIVE );
406  }
407 
408  // Pass thru fully-qualified and protocol-relative URLs and data URIs, as well as local URLs if
409  // we can't expand them.
410  if ( self::isRemoteUrl( $url ) || self::isLocalUrl( $url ) ) {
411  return $url;
412  }
413 
414  if ( $local === false ) {
415  // Assume that all paths are relative to $remote, and make them absolute
416  $url = $remote . '/' . $url;
417  } else {
418  // We drop the query part here and instead make the path relative to $remote
419  $url = "{$remote}/{$file}";
420  // Path to the actual file on the filesystem
421  $localFile = "{$local}/{$file}";
422  if ( file_exists( $localFile ) ) {
423  if ( $embed ) {
424  $data = self::encodeImageAsDataURI( $localFile );
425  if ( $data !== false ) {
426  return $data;
427  }
428  }
429  if ( method_exists( 'OutputPage', 'transformFilePath' ) ) {
430  $url = OutputPage::transformFilePath( $remote, $local, $file );
431  } else {
432  // Add version parameter as the first five hex digits
433  // of the MD5 hash of the file's contents.
434  $url .= '?' . substr( md5_file( $localFile ), 0, 5 );
435  }
436  }
437  // If any of these conditions failed (file missing, we don't want to embed it
438  // or it's not embeddable), return the URL (possibly with ?timestamp part)
439  }
440  if ( function_exists( 'wfRemoveDotSegments' ) ) {
441  $url = wfRemoveDotSegments( $url );
442  }
443  return $url;
444  }
445 
452  public static function minify( $css ) {
453  return trim(
454  str_replace(
455  [ '; ', ': ', ' {', '{ ', ', ', '} ', ';}' ],
456  [ ';', ':', '{', '{', ',', '}', '}' ],
457  preg_replace( [ '/\s+/', '/\/\*.*?\*\//s' ], [ ' ', '' ], $css )
458  )
459  );
460  }
461 }
CSSMin\isRemoteUrl
static isRemoteUrl( $maybeUrl)
Is this CSS rule referencing a remote URL?
Definition: CSSMin.php:368
CSSMin\buildUrlValue
static buildUrlValue( $url)
Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters) and esc...
Definition: CSSMin.php:207
CSSMin\minify
static minify( $css)
Removes whitespace from CSS data.
Definition: CSSMin.php:452
CSSMin\encodeStringAsDataURI
static encodeStringAsDataURI( $contents, $type, $ie8Compat=true)
Encode file contents as a data URI with chosen MIME type.
Definition: CSSMin.php:133
captcha-old.count
count
Definition: captcha-old.py:225
CSSMin\remap
static remap( $source, $local, $remote, $embedData=true)
Remaps CSS URL paths and automatically embeds data URIs for CSS rules or url() values preceded by an ...
Definition: CSSMin.php:229
wfRemoveDotSegments
wfRemoveDotSegments( $urlPath)
Remove all dot-segments in the provided URL path.
Definition: GlobalFunctions.php:680
CSSMin\$mimeTypes
static array $mimeTypes
List of common image files extensions and MIME-types.
Definition: CSSMin.php:48
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
CSSMin\serializeStringValue
static serializeStringValue( $value)
Serialize a string (escape and quote) for use as a CSS string value.
Definition: CSSMin.php:163
$type
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2536
CSSMin\encodeImageAsDataURI
static encodeImageAsDataURI( $file, $type=null, $ie8Compat=true)
Encode an image file as a data URI.
Definition: CSSMin.php:105
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
CSSMin\EMBED_REGEX
const EMBED_REGEX
Definition: CSSMin.php:42
$query
null for the wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1572
$css
$css
Definition: styleTest.css.php:50
$matches
$matches
Definition: NoLocalSettings.php:24
CSSMin\isLocalUrl
static isLocalUrl( $maybeUrl)
Is this CSS rule referencing a local URL?
Definition: CSSMin.php:381
CSSMin\URL_REGEX
const URL_REGEX
Definition: CSSMin.php:41
$value
$value
Definition: styleTest.css.php:45
CSSMin\getLocalFileReferences
static getLocalFileReferences( $source, $path)
Get a list of local files referenced in a stylesheet (includes non-existent files).
Definition: CSSMin.php:69
PROTO_RELATIVE
const PROTO_RELATIVE
Definition: Defines.php:219
CSSMin\DATA_URI_SIZE_LIMIT
const DATA_URI_SIZE_LIMIT
Internet Explorer data URI length limit.
Definition: CSSMin.php:40
CSSMin\COMMENT_REGEX
const COMMENT_REGEX
Definition: CSSMin.php:43
$ext
$ext
Definition: NoLocalSettings.php:25
CSSMin\getMimeType
static getMimeType( $file)
Definition: CSSMin.php:178
CSSMin
Transforms CSS data.
Definition: CSSMin.php:30
$path
$path
Definition: NoLocalSettings.php:26
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$source
$source
Definition: mwdoc-filter.php:45
true
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1956
CSSMin\remapOne
static remapOne( $file, $query, $local, $remote, $embed)
Remap or embed a CSS URL path.
Definition: CSSMin.php:398
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:552
array
the array() calling protocol came about after MediaWiki 1.4rc1.
OutputPage\transformFilePath
static transformFilePath( $remotePathPrefix, $localPath, $file)
Utility method for transformResourceFilePath().
Definition: OutputPage.php:3801