CSSMin.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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 Apache-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. /** @var string Strip marker for comments. */
  31. const PLACEHOLDER = "\x7fPLACEHOLDER\x7f";
  32. /**
  33. * Internet Explorer data URI length limit. See encodeImageAsDataURI().
  34. */
  35. const DATA_URI_SIZE_LIMIT = 32768;
  36. const EMBED_REGEX = '\/\*\s*\@embed\s*\*\/';
  37. const COMMENT_REGEX = '\/\*.*?\*\/';
  38. /** @var string[] List of common image files extensions and MIME-types */
  39. protected static $mimeTypes = [
  40. 'gif' => 'image/gif',
  41. 'jpe' => 'image/jpeg',
  42. 'jpeg' => 'image/jpeg',
  43. 'jpg' => 'image/jpeg',
  44. 'png' => 'image/png',
  45. 'tif' => 'image/tiff',
  46. 'tiff' => 'image/tiff',
  47. 'xbm' => 'image/x-xbitmap',
  48. 'svg' => 'image/svg+xml',
  49. ];
  50. /**
  51. * Get a list of local files referenced in a stylesheet (includes non-existent files).
  52. *
  53. * @param string $source CSS stylesheet source to process
  54. * @param string $path File path where the source was read from
  55. * @return string[] List of local file references
  56. */
  57. public static function getLocalFileReferences( $source, $path ) {
  58. $stripped = preg_replace( '/' . self::COMMENT_REGEX . '/s', '', $source );
  59. $path = rtrim( $path, '/' ) . '/';
  60. $files = [];
  61. $rFlags = PREG_OFFSET_CAPTURE | PREG_SET_ORDER;
  62. if ( preg_match_all( '/' . self::getUrlRegex() . '/', $stripped, $matches, $rFlags ) ) {
  63. foreach ( $matches as $match ) {
  64. self::processUrlMatch( $match, $rFlags );
  65. $url = $match['file'][0];
  66. // Skip fully-qualified and protocol-relative URLs and data URIs
  67. if (
  68. substr( $url, 0, 2 ) === '//' ||
  69. parse_url( $url, PHP_URL_SCHEME )
  70. ) {
  71. break;
  72. }
  73. // Strip trailing anchors - T115436
  74. $anchor = strpos( $url, '#' );
  75. if ( $anchor !== false ) {
  76. $url = substr( $url, 0, $anchor );
  77. // '#some-anchors' is not a file
  78. if ( $url === '' ) {
  79. break;
  80. }
  81. }
  82. $files[] = $path . $url;
  83. }
  84. }
  85. return $files;
  86. }
  87. /**
  88. * Encode an image file as a data URI.
  89. *
  90. * If the image file has a suitable MIME type and size, encode it as a data URI, base64-encoded
  91. * for binary files or just percent-encoded otherwise. Return false if the image type is
  92. * unfamiliar or file exceeds the size limit.
  93. *
  94. * @param string $file Image file to encode.
  95. * @param string|null $type File's MIME type or null. If null, CSSMin will
  96. * try to autodetect the type.
  97. * @param bool $ie8Compat By default, a data URI will only be produced if it can be made short
  98. * enough to fit in Internet Explorer 8 (and earlier) URI length limit (32,768 bytes). Pass
  99. * `false` to remove this limitation.
  100. * @return string|false Image contents encoded as a data URI or false.
  101. */
  102. public static function encodeImageAsDataURI( $file, $type = null, $ie8Compat = true ) {
  103. // Fast-fail for files that definitely exceed the maximum data URI length
  104. if ( $ie8Compat && filesize( $file ) >= self::DATA_URI_SIZE_LIMIT ) {
  105. return false;
  106. }
  107. if ( $type === null ) {
  108. $type = self::getMimeType( $file );
  109. }
  110. if ( !$type ) {
  111. return false;
  112. }
  113. return self::encodeStringAsDataURI( file_get_contents( $file ), $type, $ie8Compat );
  114. }
  115. /**
  116. * Encode file contents as a data URI with chosen MIME type.
  117. *
  118. * The URI will be base64-encoded for binary files or just percent-encoded otherwise.
  119. *
  120. * @since 1.25
  121. *
  122. * @param string $contents File contents to encode.
  123. * @param string $type File's MIME type.
  124. * @param bool $ie8Compat See encodeImageAsDataURI().
  125. * @return string|false Image contents encoded as a data URI or false.
  126. */
  127. public static function encodeStringAsDataURI( $contents, $type, $ie8Compat = true ) {
  128. // Try #1: Non-encoded data URI
  129. // Remove XML declaration, it's not needed with data URI usage
  130. $contents = preg_replace( "/<\\?xml.*?\\?>/", '', $contents );
  131. // The regular expression matches ASCII whitespace and printable characters.
  132. if ( preg_match( '/^[\r\n\t\x20-\x7e]+$/', $contents ) ) {
  133. // Do not base64-encode non-binary files (sane SVGs).
  134. // (This often produces longer URLs, but they compress better, yielding a net smaller size.)
  135. $encoded = rawurlencode( $contents );
  136. // Unencode some things that don't need to be encoded, to make the encoding smaller
  137. $encoded = strtr( $encoded, [
  138. '%20' => ' ', // Unencode spaces
  139. '%2F' => '/', // Unencode slashes
  140. '%3A' => ':', // Unencode colons
  141. '%3D' => '=', // Unencode equals signs
  142. '%0A' => ' ', // Change newlines to spaces
  143. '%0D' => ' ', // Change carriage returns to spaces
  144. '%09' => ' ', // Change tabs to spaces
  145. ] );
  146. // Consolidate runs of multiple spaces in a row
  147. $encoded = preg_replace( '/ {2,}/', ' ', $encoded );
  148. // Remove leading and trailing spaces
  149. $encoded = preg_replace( '/^ | $/', '', $encoded );
  150. $uri = 'data:' . $type . ',' . $encoded;
  151. if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
  152. return $uri;
  153. }
  154. }
  155. // Try #2: Encoded data URI
  156. $uri = 'data:' . $type . ';base64,' . base64_encode( $contents );
  157. if ( !$ie8Compat || strlen( $uri ) < self::DATA_URI_SIZE_LIMIT ) {
  158. return $uri;
  159. }
  160. // A data URI couldn't be produced
  161. return false;
  162. }
  163. /**
  164. * Serialize a string (escape and quote) for use as a CSS string value.
  165. * https://drafts.csswg.org/cssom/#serialize-a-string
  166. *
  167. * @param string $value
  168. * @return string
  169. */
  170. public static function serializeStringValue( $value ) {
  171. $value = strtr( $value, [ "\0" => "\u{FFFD}", '\\' => '\\\\', '"' => '\\"' ] );
  172. $value = preg_replace_callback( '/[\x01-\x1f\x7f]/', function ( $match ) {
  173. return '\\' . base_convert( ord( $match[0] ), 10, 16 ) . ' ';
  174. }, $value );
  175. return '"' . $value . '"';
  176. }
  177. /**
  178. * @param string $file
  179. * @return bool|string
  180. */
  181. public static function getMimeType( $file ) {
  182. // Infer the MIME-type from the file extension
  183. $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
  184. return self::$mimeTypes[$ext] ?? mime_content_type( realpath( $file ) );
  185. }
  186. /**
  187. * Build a CSS 'url()' value for the given URL, quoting parentheses (and other funny characters)
  188. * and escaping quotes as necessary.
  189. *
  190. * See http://www.w3.org/TR/css-syntax-3/#consume-a-url-token
  191. *
  192. * @param string $url URL to process
  193. * @return string 'url()' value, usually just `"url($url)"`, quoted/escaped if necessary
  194. */
  195. public static function buildUrlValue( $url ) {
  196. // The list below has been crafted to match URLs such as:
  197. // scheme://user@domain:port/~user/fi%20le.png?query=yes&really=y+s
  198. // data:image/png;base64,R0lGODlh/+==
  199. if ( preg_match( '!^[\w\d:@/~.%+;,?&=-]+$!', $url ) ) {
  200. return "url($url)";
  201. } else {
  202. return 'url("' . strtr( $url, [ '\\' => '\\\\', '"' => '\\"' ] ) . '")';
  203. }
  204. }
  205. /**
  206. * Remaps CSS URL paths and automatically embeds data URIs for CSS rules
  207. * or url() values preceded by an / * @embed * / comment.
  208. *
  209. * @param string $source CSS data to remap
  210. * @param string $local File path where the source was read from
  211. * @param string $remote URL path to the file
  212. * @param bool $embedData If false, never do any data URI embedding,
  213. * even if / * @embed * / is found.
  214. * @return string Remapped CSS data
  215. */
  216. public static function remap( $source, $local, $remote, $embedData = true ) {
  217. // High-level overview:
  218. // * For each CSS rule in $source that includes at least one url() value:
  219. // * Check for an @embed comment at the start indicating that all URIs should be embedded
  220. // * For each url() value:
  221. // * Check for an @embed comment directly preceding the value
  222. // * If either @embed comment exists:
  223. // * Embedding the URL as data: URI, if it's possible / allowed
  224. // * Otherwise remap the URL to work in generated stylesheets
  225. // Guard against trailing slashes, because "some/remote/../foo.png"
  226. // resolves to "some/remote/foo.png" on (some?) clients (T29052).
  227. if ( substr( $remote, -1 ) == '/' ) {
  228. $remote = substr( $remote, 0, -1 );
  229. }
  230. // Disallow U+007F DELETE, which is illegal anyway, and which
  231. // we use for comment placeholders.
  232. $source = str_replace( "\x7f", "?", $source );
  233. // Replace all comments by a placeholder so they will not interfere with the remapping.
  234. // Warning: This will also catch on anything looking like the start of a comment between
  235. // quotation marks (e.g. "foo /* bar").
  236. $comments = [];
  237. $pattern = '/(?!' . self::EMBED_REGEX . ')(' . self::COMMENT_REGEX . ')/s';
  238. $source = preg_replace_callback(
  239. $pattern,
  240. function ( $match ) use ( &$comments ) {
  241. $comments[] = $match[ 0 ];
  242. return CSSMin::PLACEHOLDER . ( count( $comments ) - 1 ) . 'x';
  243. },
  244. $source
  245. );
  246. // Note: This will not correctly handle cases where ';', '{' or '}'
  247. // appears in the rule itself, e.g. in a quoted string. You are advised
  248. // not to use such characters in file names. We also match start/end of
  249. // the string to be consistent in edge-cases ('@import url(…)').
  250. $pattern = '/(?:^|[;{])\K[^;{}]*' . self::getUrlRegex() . '[^;}]*(?=[;}]|$)/';
  251. $source = preg_replace_callback(
  252. $pattern,
  253. function ( $matchOuter ) use ( $local, $remote, $embedData ) {
  254. $rule = $matchOuter[0];
  255. // Check for global @embed comment and remove it. Allow other comments to be present
  256. // before @embed (they have been replaced with placeholders at this point).
  257. $embedAll = false;
  258. $rule = preg_replace(
  259. '/^((?:\s+|' .
  260. CSSMin::PLACEHOLDER .
  261. '(\d+)x)*)' .
  262. CSSMin::EMBED_REGEX .
  263. '\s*/',
  264. '$1',
  265. $rule,
  266. 1,
  267. $embedAll
  268. );
  269. // Build two versions of current rule: with remapped URLs
  270. // and with embedded data: URIs (where possible).
  271. $pattern = '/(?P<embed>' . CSSMin::EMBED_REGEX . '\s*|)' . self::getUrlRegex() . '/';
  272. $ruleWithRemapped = preg_replace_callback(
  273. $pattern,
  274. function ( $match ) use ( $local, $remote ) {
  275. self::processUrlMatch( $match );
  276. $remapped = CSSMin::remapOne( $match['file'], $match['query'], $local, $remote, false );
  277. return CSSMin::buildUrlValue( $remapped );
  278. },
  279. $rule
  280. );
  281. if ( $embedData ) {
  282. // Remember the occurring MIME types to avoid fallbacks when embedding some files.
  283. $mimeTypes = [];
  284. $ruleWithEmbedded = preg_replace_callback(
  285. $pattern,
  286. function ( $match ) use ( $embedAll, $local, $remote, &$mimeTypes ) {
  287. self::processUrlMatch( $match );
  288. $embed = $embedAll || $match['embed'];
  289. $embedded = CSSMin::remapOne(
  290. $match['file'],
  291. $match['query'],
  292. $local,
  293. $remote,
  294. $embed
  295. );
  296. $url = $match['file'] . $match['query'];
  297. $file = "{$local}/{$match['file']}";
  298. if (
  299. !self::isRemoteUrl( $url ) && !self::isLocalUrl( $url )
  300. && file_exists( $file )
  301. ) {
  302. $mimeTypes[ CSSMin::getMimeType( $file ) ] = true;
  303. }
  304. return CSSMin::buildUrlValue( $embedded );
  305. },
  306. $rule
  307. );
  308. // Are all referenced images SVGs?
  309. $needsEmbedFallback = $mimeTypes !== [ 'image/svg+xml' => true ];
  310. }
  311. if ( !$embedData || $ruleWithEmbedded === $ruleWithRemapped ) {
  312. // We're not embedding anything, or we tried to but the file is not embeddable
  313. return $ruleWithRemapped;
  314. } elseif ( $embedData && $needsEmbedFallback ) {
  315. // Build 2 CSS properties; one which uses a data URI in place of the @embed comment, and
  316. // the other with a remapped and versioned URL with an Internet Explorer 6 and 7 hack
  317. // making it ignored in all browsers that support data URIs
  318. return "$ruleWithEmbedded;$ruleWithRemapped!ie";
  319. } else {
  320. // Look ma, no fallbacks! This is for files which IE 6 and 7 don't support anyway: SVG.
  321. return $ruleWithEmbedded;
  322. }
  323. }, $source );
  324. // Re-insert comments
  325. $pattern = '/' . self::PLACEHOLDER . '(\d+)x/';
  326. $source = preg_replace_callback( $pattern, function ( $match ) use ( &$comments ) {
  327. return $comments[ $match[1] ];
  328. }, $source );
  329. return $source;
  330. }
  331. /**
  332. * Is this CSS rule referencing a remote URL?
  333. *
  334. * @param string $maybeUrl
  335. * @return bool
  336. */
  337. protected static function isRemoteUrl( $maybeUrl ) {
  338. if ( substr( $maybeUrl, 0, 2 ) === '//' || parse_url( $maybeUrl, PHP_URL_SCHEME ) ) {
  339. return true;
  340. }
  341. return false;
  342. }
  343. /**
  344. * Is this CSS rule referencing a local URL?
  345. *
  346. * @param string $maybeUrl
  347. * @return bool
  348. */
  349. protected static function isLocalUrl( $maybeUrl ) {
  350. return isset( $maybeUrl[1] ) && $maybeUrl[0] === '/' && $maybeUrl[1] !== '/';
  351. }
  352. /**
  353. * @codeCoverageIgnore
  354. */
  355. private static function getUrlRegex() {
  356. static $urlRegex;
  357. if ( $urlRegex === null ) {
  358. // Match these three variants separately to avoid broken urls when
  359. // e.g. a double quoted url contains a parenthesis, or when a
  360. // single quoted url contains a double quote, etc.
  361. // FIXME: Simplify now we only support PHP 7.0.0+
  362. // Note: PCRE doesn't support multiple capture groups with the same name by default.
  363. // - PCRE 6.7 introduced the "J" modifier (PCRE_INFO_JCHANGED for PCRE_DUPNAMES).
  364. // https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
  365. // However this isn't useful since it just ignores all but the first one.
  366. // Also, while the modifier was introduced in PCRE 6.7 (PHP 5.2+) it was
  367. // not exposed to public preg_* functions until PHP 5.6.0.
  368. // - PCRE 8.36 fixed this to work as expected (e.g. merge conceptually to
  369. // only return the one matched in the part that actually matched).
  370. // However MediaWiki supports 5.5.9, which has PCRE 8.32
  371. // Per https://www.php.net/manual/en/pcre.installation.php:
  372. // - PCRE 8.32 (PHP 5.5.0)
  373. // - PCRE 8.34 (PHP 5.5.10, PHP 5.6.0)
  374. // - PCRE 8.37 (PHP 5.5.26, PHP 5.6.9, PHP 7.0.0)
  375. // Workaround by using different groups and merge via processUrlMatch().
  376. // - Using string concatenation for class constant or member assignments
  377. // is only supported in PHP 5.6. Use a getter method for now.
  378. $urlRegex = '(' .
  379. // Unquoted url
  380. 'url\(\s*(?P<file0>[^\s\'"][^\?\)]+?)(?P<query0>\?[^\)]*?|)\s*\)' .
  381. // Single quoted url
  382. '|url\(\s*\'(?P<file1>[^\?\']+?)(?P<query1>\?[^\']*?|)\'\s*\)' .
  383. // Double quoted url
  384. '|url\(\s*"(?P<file2>[^\?"]+?)(?P<query2>\?[^"]*?|)"\s*\)' .
  385. ')';
  386. }
  387. return $urlRegex;
  388. }
  389. private static function processUrlMatch( array &$match, $flags = 0 ) {
  390. if ( $flags & PREG_SET_ORDER ) {
  391. // preg_match_all with PREG_SET_ORDER will return each group in each
  392. // match array, and if it didn't match, instead of the sub array
  393. // being an empty array it is `[ '', -1 ]`...
  394. if ( isset( $match['file0'] ) && $match['file0'][1] !== -1 ) {
  395. $match['file'] = $match['file0'];
  396. $match['query'] = $match['query0'];
  397. } elseif ( isset( $match['file1'] ) && $match['file1'][1] !== -1 ) {
  398. $match['file'] = $match['file1'];
  399. $match['query'] = $match['query1'];
  400. } else {
  401. if ( !isset( $match['file2'] ) || $match['file2'][1] === -1 ) {
  402. throw new Exception( 'URL must be non-empty' );
  403. }
  404. $match['file'] = $match['file2'];
  405. $match['query'] = $match['query2'];
  406. }
  407. } else {
  408. if ( isset( $match['file0'] ) && $match['file0'] !== '' ) {
  409. $match['file'] = $match['file0'];
  410. $match['query'] = $match['query0'];
  411. } elseif ( isset( $match['file1'] ) && $match['file1'] !== '' ) {
  412. $match['file'] = $match['file1'];
  413. $match['query'] = $match['query1'];
  414. } else {
  415. if ( !isset( $match['file2'] ) || $match['file2'] === '' ) {
  416. throw new Exception( 'URL must be non-empty' );
  417. }
  418. $match['file'] = $match['file2'];
  419. $match['query'] = $match['query2'];
  420. }
  421. }
  422. }
  423. /**
  424. * Remap or embed a CSS URL path.
  425. *
  426. * @param string $file URL to remap/embed
  427. * @param string $query
  428. * @param string $local File path where the source was read from
  429. * @param string $remote URL path to the file
  430. * @param bool $embed Whether to do any data URI embedding
  431. * @return string Remapped/embedded URL data
  432. */
  433. public static function remapOne( $file, $query, $local, $remote, $embed ) {
  434. // The full URL possibly with query, as passed to the 'url()' value in CSS
  435. $url = $file . $query;
  436. // Expand local URLs with absolute paths like /w/index.php to possibly protocol-relative URL, if
  437. // wfExpandUrl() is available. (This will not be the case if we're running outside of MW.)
  438. if ( self::isLocalUrl( $url ) && function_exists( 'wfExpandUrl' ) ) {
  439. return wfExpandUrl( $url, PROTO_RELATIVE );
  440. }
  441. // Pass thru fully-qualified and protocol-relative URLs and data URIs, as well as local URLs if
  442. // we can't expand them.
  443. // Also skips anchors or the rare `behavior` property specifying application's default behavior
  444. if (
  445. self::isRemoteUrl( $url ) ||
  446. self::isLocalUrl( $url ) ||
  447. substr( $url, 0, 1 ) === '#'
  448. ) {
  449. return $url;
  450. }
  451. if ( $local === false ) {
  452. // Assume that all paths are relative to $remote, and make them absolute
  453. $url = $remote . '/' . $url;
  454. } else {
  455. // We drop the query part here and instead make the path relative to $remote
  456. $url = "{$remote}/{$file}";
  457. // Path to the actual file on the filesystem
  458. $localFile = "{$local}/{$file}";
  459. if ( file_exists( $localFile ) ) {
  460. if ( $embed ) {
  461. $data = self::encodeImageAsDataURI( $localFile );
  462. if ( $data !== false ) {
  463. return $data;
  464. }
  465. }
  466. if ( class_exists( OutputPage::class ) ) {
  467. $url = OutputPage::transformFilePath( $remote, $local, $file );
  468. } else {
  469. // Add version parameter as the first five hex digits
  470. // of the MD5 hash of the file's contents.
  471. $url .= '?' . substr( md5_file( $localFile ), 0, 5 );
  472. }
  473. }
  474. // If any of these conditions failed (file missing, we don't want to embed it
  475. // or it's not embeddable), return the URL (possibly with ?timestamp part)
  476. }
  477. if ( function_exists( 'wfRemoveDotSegments' ) ) {
  478. $url = wfRemoveDotSegments( $url );
  479. }
  480. return $url;
  481. }
  482. /**
  483. * Removes whitespace from CSS data
  484. *
  485. * @param string $css CSS data to minify
  486. * @return string Minified CSS data
  487. */
  488. public static function minify( $css ) {
  489. return trim(
  490. str_replace(
  491. [ '; ', ': ', ' {', '{ ', ', ', '} ', ';}', '( ', ' )', '[ ', ' ]' ],
  492. [ ';', ':', '{', '{', ',', '}', '}', '(', ')', '[', ']' ],
  493. preg_replace( [ '/\s+/', '/\/\*.*?\*\//s' ], [ ' ', '' ], $css )
  494. )
  495. );
  496. }
  497. }