2 // @codingStandardsIgnoreFile
3 // @ignore comment_docblock_file:file
4 // @ignore style_curly_braces:file
5 // @ignore style_string_spacing:file
6 // @ignore style_else_spacing:file
7 // @ignore comment_comment_docblock_missing:file
8 // @ignore comment_comment_eg:file
9 // @ignore production_code:file
10 // @ignore druplart_unary:file
11 // @ignore style_uppercase_constants:file
12 // @ignore comment_comment_space:file
13 // @ignore druplart_conditional_assignment:file
14 // @ignore style_paren_spacing:file
19 * Author: Tubal Martin - http://tubalmartin.me/
20 * Repo: https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port
22 * This is a PHP port of the CSS minification tool distributed with YUICompressor,
23 * itself a port of the cssmin utility by Isaac Schlueter - http://foohack.com/
24 * Permission is hereby granted to use the PHP version under the same
25 * conditions as the YUICompressor.
30 * http://developer.yahoo.com/yui/compressor/
31 * Author: Julien Lecomte - http://www.julienlecomte.net/
32 * Copyright (c) 2013 Yahoo! Inc. All rights reserved.
33 * The copyrights embodied in the content of this file are licensed
34 * by Yahoo! Inc. under the BSD (revised) open source license.
39 const NL = '___YUICSSMIN_PRESERVED_NL___';
40 const TOKEN = '___YUICSSMIN_PRESERVED_TOKEN_';
41 const COMMENT = '___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_';
42 const CLASSCOLON = '___YUICSSMIN_PSEUDOCLASSCOLON___';
43 const QUERY_FRACTION = '___YUICSSMIN_QUERY_FRACTION___';
46 private $preserved_tokens;
47 private $memory_limit;
48 private $max_execution_time;
49 private $pcre_backtrack_limit;
50 private $pcre_recursion_limit;
51 private $raise_php_limits;
54 * @param bool|int $raise_php_limits
55 * If true, PHP settings will be raised if needed
57 public function __construct($raise_php_limits = TRUE)
59 // Set suggested PHP limits
60 $this->memory_limit = 128 * 1048576; // 128MB in bytes
61 $this->max_execution_time = 60; // 1 min
62 $this->pcre_backtrack_limit = 1000 * 1000;
63 $this->pcre_recursion_limit = 500 * 1000;
65 $this->raise_php_limits = (bool) $raise_php_limits;
69 * Minify a string of CSS
71 * @param int|bool $linebreak_pos
74 public function run($css = '', $linebreak_pos = FALSE)
80 if ($this->raise_php_limits) {
81 $this->do_raise_php_limits();
84 $this->comments = array();
85 $this->preserved_tokens = array();
88 $length = strlen($css);
90 $css = $this->extract_data_urls($css);
92 // collect all comment blocks...
93 while (($start_index = $this->index_of($css, '/*', $start_index)) >= 0) {
94 $end_index = $this->index_of($css, '*/', $start_index + 2);
98 $comment_found = $this->str_slice($css, $start_index + 2, $end_index);
99 $this->comments[] = $comment_found;
100 $comment_preserve_string = self::COMMENT . (count($this->comments) - 1) . '___';
101 $css = $this->str_slice($css, 0, $start_index + 2) . $comment_preserve_string . $this->str_slice($css, $end_index);
102 // Set correct start_index: Fixes issue #2528130
103 $start_index = $end_index + 2 + strlen($comment_preserve_string) - strlen($comment_found);
106 // preserve strings so their content doesn't get accidentally minified
107 $css = preg_replace_callback('/(?:"(?:[^\\\\"]|\\\\.|\\\\)*")|'."(?:'(?:[^\\\\']|\\\\.|\\\\)*')/S", array($this, 'replace_string'), $css);
109 // Let's divide css code in chunks of 5.000 chars aprox.
110 // Reason: PHP's PCRE functions like preg_replace have a "backtrack limit"
111 // of 100.000 chars by default (php < 5.3.7) so if we're dealing with really
112 // long strings and a (sub)pattern matches a number of chars greater than
113 // the backtrack limit number (i.e. /(.*)/s) PCRE functions may fail silently
114 // returning NULL and $css would be empty.
116 $charset_regexp = '/(@charset)( [^;]+;)/i';
117 $css_chunks = array();
118 $css_chunk_length = 5000; // aprox size, not exact
120 $i = $css_chunk_length; // save initial iterations
124 // if the number of characters is 5000 or less, do not chunk
125 if ($l <= $css_chunk_length) {
126 $css_chunks[] = $css;
128 // chunk css code securely
130 $i += 50; // save iterations
131 if ($l - $start_index <= $css_chunk_length || $i >= $l) {
132 $css_chunks[] = $this->str_slice($css, $start_index);
135 if ($css[$i - 1] === '}' && $i - $start_index > $css_chunk_length) {
136 // If there are two ending curly braces }} separated or not by spaces,
137 // join them in the same chunk (i.e. @media blocks)
138 $next_chunk = substr($css, $i);
139 if (preg_match('/^\s*\}/', $next_chunk)) {
140 $i = $i + $this->index_of($next_chunk, '}') + 1;
143 $css_chunks[] = $this->str_slice($css, $start_index, $i);
150 for ($i = 0, $n = count($css_chunks); $i < $n; $i++) {
151 $css_chunks[$i] = $this->minify($css_chunks[$i], $linebreak_pos);
152 // Keep the first @charset at-rule found
153 if (empty($charset) && preg_match($charset_regexp, $css_chunks[$i], $matches)) {
154 $charset = strtolower($matches[1]) . $matches[2];
156 // Delete all @charset at-rules
157 $css_chunks[$i] = preg_replace($charset_regexp, '', $css_chunks[$i]);
160 // Update the first chunk and push the charset to the top of the file.
161 $css_chunks[0] = $charset . $css_chunks[0];
163 return implode('', $css_chunks);
167 * Sets the memory limit for this script
168 * @param int|string $limit
170 public function set_memory_limit($limit)
172 $this->memory_limit = $this->normalize_int($limit);
176 * Sets the maximum execution time for this script
177 * @param int|string $seconds
179 public function set_max_execution_time($seconds)
181 $this->max_execution_time = (int) $seconds;
185 * Sets the PCRE backtrack limit for this script
188 public function set_pcre_backtrack_limit($limit)
190 $this->pcre_backtrack_limit = (int) $limit;
194 * Sets the PCRE recursion limit for this script
197 public function set_pcre_recursion_limit($limit)
199 $this->pcre_recursion_limit = (int) $limit;
203 * Try to configure PHP to use at least the suggested minimum settings
205 private function do_raise_php_limits()
208 'memory_limit' => $this->memory_limit,
209 'max_execution_time' => $this->max_execution_time,
210 'pcre.backtrack_limit' => $this->pcre_backtrack_limit,
211 'pcre.recursion_limit' => $this->pcre_recursion_limit
214 // If current settings are higher respect them.
215 foreach ($php_limits as $name => $suggested) {
216 $current = $this->normalize_int(ini_get($name));
217 // memory_limit exception: allow -1 for "no memory limit".
218 if ($current > -1 && ($suggested == -1 || $current < $suggested)) {
219 ini_set($name, $suggested);
225 * Does bulk of the minification
227 * @param int|bool $linebreak_pos
230 private function minify($css, $linebreak_pos)
232 // strings are safe, now wrestle the comments
233 for ($i = 0, $max = count($this->comments); $i < $max; $i++) {
235 $token = $this->comments[$i];
236 $placeholder = '/' . self::COMMENT . $i . '___/';
238 // ! in the first position of the comment means preserve
239 // so push to the preserved tokens keeping the !
240 if (substr($token, 0, 1) === '!') {
241 $this->preserved_tokens[] = $token;
242 $token_tring = self::TOKEN . (count($this->preserved_tokens) - 1) . '___';
243 $css = preg_replace($placeholder, $token_tring, $css, 1);
244 // Preserve new lines for /*! important comments
245 $css = preg_replace('/\s*[\n\r\f]+\s*(\/\*'. $token_tring .')/S', self::NL.'$1', $css);
246 $css = preg_replace('/('. $token_tring .'\*\/)\s*[\n\r\f]+\s*/', '$1'.self::NL, $css);
250 // \ in the last position looks like hack for Mac/IE5
251 // shorten that to /*\*/ and the next one to /**/
252 if (substr($token, (strlen($token) - 1), 1) === '\\') {
253 $this->preserved_tokens[] = '\\';
254 $css = preg_replace($placeholder, self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1);
255 $i = $i + 1; // attn: advancing the loop
256 $this->preserved_tokens[] = '';
257 $css = preg_replace('/' . self::COMMENT . $i . '___/', self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1);
261 // keep empty comments after child selectors (IE7 hack)
262 // e.g. html >/**/ body
263 if (strlen($token) === 0) {
264 $start_index = $this->index_of($css, $this->str_slice($placeholder, 1, -1));
265 if ($start_index > 2) {
266 if (substr($css, $start_index - 3, 1) === '>') {
267 $this->preserved_tokens[] = '';
268 $css = preg_replace($placeholder, self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1);
273 // in all other cases kill the comment
274 $css = preg_replace('/\/\*' . $this->str_slice($placeholder, 1, -1) . '\*\//', '', $css, 1);
278 // Normalize all whitespace strings to single spaces. Easier to work with that way.
279 $css = preg_replace('/\s+/', ' ', $css);
281 // Fix IE7 issue on matrix filters which browser accept whitespaces between Matrix parameters
282 $css = preg_replace_callback('/\s*filter\:\s*progid:DXImageTransform\.Microsoft\.Matrix\(([^\)]+)\)/', array($this, 'preserve_old_IE_specific_matrix_definition'), $css);
284 // Shorten & preserve calculations calc(...) since spaces are important
285 $css = preg_replace_callback('/calc(\(((?:[^\(\)]+|(?1))*)\))/i', array($this, 'replace_calc'), $css);
287 // Replace positive sign from numbers preceded by : or a white-space before the leading space is removed
288 // +1.2em to 1.2em, +.8px to .8px, +2% to 2%
289 $css = preg_replace('/((?<!\\\\)\:|\s)\+(\.?\d+)/S', '$1$2', $css);
291 // Remove leading zeros from integer and float numbers preceded by : or a white-space
292 // 000.6 to .6, -0.8 to -.8, 0050 to 50, -01.05 to -1.05
293 $css = preg_replace('/((?<!\\\\)\:|\s)(\-?)0+(\.?\d+)/S', '$1$2$3', $css);
295 // Remove trailing zeros from float numbers preceded by : or a white-space
296 // -6.0100em to -6.01em, .0100 to .01, 1.200px to 1.2px
297 $css = preg_replace('/((?<!\\\\)\:|\s)(\-?)(\d?\.\d+?)0+([^\d])/S', '$1$2$3$4', $css);
299 // Remove trailing .0 -> -9.0 to -9
300 $css = preg_replace('/((?<!\\\\)\:|\s)(\-?\d+)\.0([^\d])/S', '$1$2$3', $css);
302 // Replace 0 length numbers with 0
303 $css = preg_replace('/((?<!\\\\)\:|\s)\-?\.?0+([^\d])/S', '${1}0$2', $css);
305 // Remove the spaces before the things that should not have spaces before them.
306 // But, be careful not to turn "p :link {...}" into "p:link{...}"
307 // Swap out any pseudo-class colons with the token, and then swap back.
308 $css = preg_replace_callback('/(?:^|\})[^\{]*\s+\:/', array($this, 'replace_colon'), $css);
310 // Remove spaces before the things that should not have spaces before them.
311 $css = preg_replace('/\s+([\!\{\}\;\:\>\+\(\)\]\~\=,])/', '$1', $css);
313 // Restore spaces for !important
314 $css = preg_replace('/\!important/i', ' !important', $css);
316 // bring back the colon
317 $css = preg_replace('/' . self::CLASSCOLON . '/', ':', $css);
319 // retain space for special IE6 cases
320 $css = preg_replace_callback('/\:first\-(line|letter)(\{|,)/i', array($this, 'lowercase_pseudo_first'), $css);
322 // no space after the end of a preserved comment
323 $css = preg_replace('/\*\/ /', '*/', $css);
325 // lowercase some popular @directives
326 $css = preg_replace_callback('/@(font-face|import|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?keyframe|media|page|namespace)/i', array($this, 'lowercase_directives'), $css);
328 // lowercase some more common pseudo-elements
329 $css = preg_replace_callback('/:(active|after|before|checked|disabled|empty|enabled|first-(?:child|of-type)|focus|hover|last-(?:child|of-type)|link|only-(?:child|of-type)|root|:selection|target|visited)/i', array($this, 'lowercase_pseudo_elements'), $css);
331 // lowercase some more common functions
332 $css = preg_replace_callback('/:(lang|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|(?:-(?:moz|webkit)-)?any)\(/i', array($this, 'lowercase_common_functions'), $css);
334 // lower case some common function that can be values
335 // NOTE: rgb() isn't useful as we replace with #hex later, as well as and() is already done for us
336 $css = preg_replace_callback('/([:,\( ]\s*)(attr|color-stop|from|rgba|to|url|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?(?:calc|max|min|(?:repeating-)?(?:linear|radial)-gradient)|-webkit-gradient)/iS', array($this, 'lowercase_common_functions_values'), $css);
338 // Put the space back in some cases, to support stuff like
339 // @media screen and (-webkit-min-device-pixel-ratio:0){
340 $css = preg_replace('/\band\(/i', 'and (', $css);
342 // Remove the spaces after the things that should not have spaces after them.
343 $css = preg_replace('/([\!\{\}\:;\>\+\(\[\~\=,])\s+/S', '$1', $css);
345 // remove unnecessary semicolons
346 $css = preg_replace('/;+\}/', '}', $css);
348 // Fix for issue: #2528146
349 // Restore semicolon if the last property is prefixed with a `*` (lte IE7 hack)
350 // to avoid issues on Symbian S60 3.x browsers.
351 $css = preg_replace('/(\*[a-z0-9\-]+\s*\:[^;\}]+)(\})/', '$1;$2', $css);
353 // Replace 0 <length> and 0 <percentage> values with 0.
354 // <length> data type: https://developer.mozilla.org/en-US/docs/Web/CSS/length
355 // <percentage> data type: https://developer.mozilla.org/en-US/docs/Web/CSS/percentage
356 $css = preg_replace('/([^\\\\]\:|\s)0(?:em|ex|ch|rem|vw|vh|vm|vmin|cm|mm|in|px|pt|pc|%)/iS', '${1}0', $css);
358 // 0% step in a keyframe? restore the % unit
359 $css = preg_replace_callback('/(@[a-z\-]*?keyframes[^\{]+\{)(.*?)(\}\})/iS', array($this, 'replace_keyframe_zero'), $css);
361 // Replace 0 0; or 0 0 0; or 0 0 0 0; with 0.
362 $css = preg_replace('/\:0(?: 0){1,3}(;|\}| \!)/', ':0$1', $css);
364 // Fix for issue: #2528142
365 // Replace text-shadow:0; with text-shadow:0 0 0;
366 $css = preg_replace('/(text-shadow\:0)(;|\}| \!)/i', '$1 0 0$2', $css);
368 // Replace background-position:0; with background-position:0 0;
369 // same for transform-origin
370 // Changing -webkit-mask-position: 0 0 to just a single 0 will result in the second parameter defaulting to 50% (center)
371 $css = preg_replace('/(background|background\-position|webkit\-mask\-position|(?:webkit|moz|o|ms|)\-?transform\-origin)\:0(;|\}| \!)/iS', '$1:0 0$2', $css);
373 // Shorten colors from rgb(51,102,153) to #336699, rgb(100%,0%,0%) to #ff0000 (sRGB color space)
374 // Shorten colors from hsl(0, 100%, 50%) to #ff0000 (sRGB color space)
375 // This makes it more likely that it'll get further compressed in the next step.
376 $css = preg_replace_callback('/rgb\s*\(\s*([0-9,\s\-\.\%]+)\s*\)(.{1})/i', array($this, 'rgb_to_hex'), $css);
377 $css = preg_replace_callback('/hsl\s*\(\s*([0-9,\s\-\.\%]+)\s*\)(.{1})/i', array($this, 'hsl_to_hex'), $css);
379 // Shorten colors from #AABBCC to #ABC or short color name.
380 $css = $this->compress_hex_colors($css);
382 // border: none to border:0, outline: none to outline:0
383 $css = preg_replace('/(border\-?(?:top|right|bottom|left|)|outline)\:none(;|\}| \!)/iS', '$1:0$2', $css);
385 // shorter opacity IE filter
386 $css = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $css);
388 // Find a fraction that is used for Opera's -o-device-pixel-ratio query
389 // Add token to add the "\" back in later
390 $css = preg_replace('/\(([a-z\-]+):([0-9]+)\/([0-9]+)\)/i', '($1:$2'. self::QUERY_FRACTION .'$3)', $css);
392 // Remove empty rules.
393 $css = preg_replace('/[^\};\{\/]+\{\}/S', '', $css);
395 // Add "/" back to fix Opera -o-device-pixel-ratio query
396 $css = preg_replace('/'. self::QUERY_FRACTION .'/', '/', $css);
398 // Replace multiple semi-colons in a row by a single one
399 // See SF bug #1980989
400 $css = preg_replace('/;;+/', ';', $css);
402 // Restore new lines for /*! important comments
403 $css = preg_replace('/'. self::NL .'/', "\n", $css);
405 // Lowercase all uppercase properties
406 $css = preg_replace_callback('/(\{|\;)([A-Z\-]+)(\:)/', array($this, 'lowercase_properties'), $css);
408 // Some source control tools don't like it when files containing lines longer
409 // than, say 8000 characters, are checked in. The linebreak option is used in
410 // that case to split long lines after a specific column.
411 if ($linebreak_pos !== FALSE && (int) $linebreak_pos >= 0) {
412 $linebreak_pos = (int) $linebreak_pos;
413 $start_index = $i = 0;
414 while ($i < strlen($css)) {
416 if ($css[$i - 1] === '}' && $i - $start_index > $linebreak_pos) {
417 $css = $this->str_slice($css, 0, $i) . "\n" . $this->str_slice($css, $i);
423 // restore preserved comments and strings in reverse order
424 for ($i = count($this->preserved_tokens) - 1; $i >= 0; $i--) {
425 $css = preg_replace('/' . self::TOKEN . $i . '___/', $this->preserved_tokens[$i], $css, 1);
428 // Trim the final string (for any leading or trailing white spaces)
433 * Utility method to replace all data urls with tokens before we start
434 * compressing, to avoid performance issues running some of the subsequent
435 * regexes against large strings chunks.
440 private function extract_data_urls($css)
442 // Leave data urls alone to increase parse performance.
443 $max_index = strlen($css) - 1;
444 $append_index = $index = $last_index = $offset = 0;
446 $pattern = '/url\(\s*(["\']?)data\:/i';
448 // Since we need to account for non-base64 data urls, we need to handle
449 // ' and ) being part of the data string. Hence switching to indexOf,
450 // to determine whether or not we have matching string terminators and
451 // handling sb appends directly, instead of using matcher.append* methods.
453 while (preg_match($pattern, $css, $m, 0, $offset)) {
454 $index = $this->index_of($css, $m[0], $offset);
455 $last_index = $index + strlen($m[0]);
456 $start_index = $index + 4; // "url(".length()
457 $end_index = $last_index - 1;
458 $terminator = $m[1]; // ', " or empty (not quoted)
459 $found_terminator = FALSE;
461 if (strlen($terminator) === 0) {
465 while ($found_terminator === FALSE && $end_index+1 <= $max_index) {
466 $end_index = $this->index_of($css, $terminator, $end_index + 1);
468 // endIndex == 0 doesn't really apply here
469 if ($end_index > 0 && substr($css, $end_index - 1, 1) !== '\\') {
470 $found_terminator = TRUE;
471 if (')' != $terminator) {
472 $end_index = $this->index_of($css, ')', $end_index);
477 // Enough searching, start moving stuff over to the buffer
478 $sb[] = $this->str_slice($css, $append_index, $index);
480 if ($found_terminator) {
481 $token = $this->str_slice($css, $start_index, $end_index);
482 $token = preg_replace('/\s+/', '', $token);
483 $this->preserved_tokens[] = $token;
485 $preserver = 'url(' . self::TOKEN . (count($this->preserved_tokens) - 1) . '___)';
488 $append_index = $end_index + 1;
490 // No end terminator found, re-add the whole match. Should we throw/warn here?
491 $sb[] = $this->str_slice($css, $index, $last_index);
492 $append_index = $last_index;
495 $offset = $last_index;
498 $sb[] = $this->str_slice($css, $append_index);
500 return implode('', $sb);
504 * Utility method to compress hex color values of the form #AABBCC to #ABC or short color name.
506 * DOES NOT compress CSS ID selectors which match the above pattern (which would break things).
507 * e.g. #AddressForm { ... }
509 * DOES NOT compress IE filters, which have hex color values (which would break things).
510 * e.g. filter: chroma(color="#FFFFFF");
512 * DOES NOT compress invalid hex values.
513 * e.g. background-color: #aabbccdd
518 private function compress_hex_colors($css)
520 // Look for hex colors inside { ... } (to avoid IDs) and which don't have a =, or a " in front of them (to avoid filters)
521 $pattern = '/(\=\s*?["\']?)?#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])(\}|[^0-9a-f{][^{]*?\})/iS';
522 $_index = $index = $last_index = $offset = 0;
524 // See: http://ajaxmin.codeplex.com/wikipage?title=CSS%20Colors
527 '#008000' => 'green',
528 '#800000' => 'maroon',
530 '#808000' => 'olive',
531 '#ffa500' => 'orange',
532 '#800080' => 'purple',
533 '#c0c0c0' => 'silver',
538 while (preg_match($pattern, $css, $m, 0, $offset)) {
539 $index = $this->index_of($css, $m[0], $offset);
540 $last_index = $index + strlen($m[0]);
541 $is_filter = $m[1] !== null && $m[1] !== '';
543 $sb[] = $this->str_slice($css, $_index, $index);
546 // Restore, maintain case, otherwise filter will break
547 $sb[] = $m[1] . '#' . $m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7];
549 if (strtolower($m[2]) == strtolower($m[3]) &&
550 strtolower($m[4]) == strtolower($m[5]) &&
551 strtolower($m[6]) == strtolower($m[7])) {
553 $hex = '#' . strtolower($m[3] . $m[5] . $m[7]);
555 // Non compressible color, restore but lower case.
556 $hex = '#' . strtolower($m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7]);
558 // replace Hex colors to short safe color names
559 $sb[] = array_key_exists($hex, $short_safe) ? $short_safe[$hex] : $hex;
562 $_index = $offset = $last_index - strlen($m[8]);
565 $sb[] = $this->str_slice($css, $_index);
567 return implode('', $sb);
571 * ---------------------------------------------------------------------------------------------
574 private function replace_string($matches)
576 $match = $matches[0];
577 $quote = substr($match, 0, 1);
578 // Must use addcslashes in PHP to avoid parsing of backslashes
579 $match = addcslashes($this->str_slice($match, 1, -1), '\\');
581 // maybe the string contains a comment-like substring?
582 // one, maybe more? put'em back then
583 if (($pos = $this->index_of($match, self::COMMENT)) >= 0) {
584 for ($i = 0, $max = count($this->comments); $i < $max; $i++) {
585 $match = preg_replace('/' . self::COMMENT . $i . '___/', $this->comments[$i], $match, 1);
589 // minify alpha opacity in filter strings
590 $match = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $match);
592 $this->preserved_tokens[] = $match;
593 return $quote . self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . $quote;
596 private function replace_colon($matches)
598 return preg_replace('/\:/', self::CLASSCOLON, $matches[0]);
601 private function replace_calc($matches)
603 $this->preserved_tokens[] = trim(preg_replace('/\s*([\*\/\(\),])\s*/', '$1', $matches[2]));
604 return 'calc('. self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . ')';
607 private function preserve_old_IE_specific_matrix_definition($matches)
609 $this->preserved_tokens[] = $matches[1];
610 return 'filter:progid:DXImageTransform.Microsoft.Matrix(' . self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . ')';
613 private function replace_keyframe_zero($matches)
615 return $matches[1] . preg_replace('/0(\{|,[^\)\{]+\{)/', '0%$1', $matches[2]) . $matches[3];
618 private function rgb_to_hex($matches)
620 // Support for percentage values rgb(100%, 0%, 45%);
621 if ($this->index_of($matches[1], '%') >= 0){
622 $rgbcolors = explode(',', str_replace('%', '', $matches[1]));
623 for ($i = 0; $i < count($rgbcolors); $i++) {
624 $rgbcolors[$i] = $this->round_number(floatval($rgbcolors[$i]) * 2.55);
627 $rgbcolors = explode(',', $matches[1]);
630 // Values outside the sRGB color space should be clipped (0-255)
631 for ($i = 0; $i < count($rgbcolors); $i++) {
632 $rgbcolors[$i] = $this->clamp_number(intval($rgbcolors[$i], 10), 0, 255);
633 $rgbcolors[$i] = sprintf("%02x", $rgbcolors[$i]);
636 // Fix for issue #2528093
637 if (!preg_match('/[\s\,\);\}]/', $matches[2])){
638 $matches[2] = ' ' . $matches[2];
641 return '#' . implode('', $rgbcolors) . $matches[2];
644 private function hsl_to_hex($matches)
646 $values = explode(',', str_replace('%', '', $matches[1]));
647 $h = floatval($values[0]);
648 $s = floatval($values[1]);
649 $l = floatval($values[2]);
651 // Wrap and clamp, then fraction!
652 $h = ((($h % 360) + 360) % 360) / 360;
653 $s = $this->clamp_number($s, 0, 100) / 100;
654 $l = $this->clamp_number($l, 0, 100) / 100;
657 $r = $g = $b = $this->round_number(255 * $l);
659 $v2 = $l < 0.5 ? $l * (1 + $s) : ($l + $s) - ($s * $l);
660 $v1 = (2 * $l) - $v2;
661 $r = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h + (1/3)));
662 $g = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h));
663 $b = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h - (1/3)));
666 return $this->rgb_to_hex(array('', $r.','.$g.','.$b, $matches[2]));
669 private function lowercase_pseudo_first($matches)
671 return ':first-'. strtolower($matches[1]) .' '. $matches[2];
674 private function lowercase_directives($matches)
676 return '@'. strtolower($matches[1]);
679 private function lowercase_pseudo_elements($matches)
681 return ':'. strtolower($matches[1]);
684 private function lowercase_common_functions($matches)
686 return ':'. strtolower($matches[1]) .'(';
689 private function lowercase_common_functions_values($matches)
691 return $matches[1] . strtolower($matches[2]);
694 private function lowercase_properties($matches)
696 return $matches[1].strtolower($matches[2]).$matches[3];
700 * ---------------------------------------------------------------------------------------------
703 private function hue_to_rgb($v1, $v2, $vh)
705 $vh = $vh < 0 ? $vh + 1 : ($vh > 1 ? $vh - 1 : $vh);
706 if ($vh * 6 < 1) return $v1 + ($v2 - $v1) * 6 * $vh;
707 if ($vh * 2 < 1) return $v2;
708 if ($vh * 3 < 2) return $v1 + ($v2 - $v1) * ((2/3) - $vh) * 6;
712 private function round_number($n)
714 return intval(floor(floatval($n) + 0.5), 10);
717 private function clamp_number($n, $min, $max)
719 return min(max($n, $min), $max);
723 * PHP port of Javascript's "indexOf" function for strings only
724 * Author: Tubal Martin http://blog.margenn.com
726 * @param string $haystack
727 * @param string $needle
728 * @param int $offset index (optional)
731 private function index_of($haystack, $needle, $offset = 0)
733 $index = strpos($haystack, $needle, $offset);
735 return ($index !== FALSE) ? $index : -1;
739 * PHP port of Javascript's "slice" function for strings only
740 * Author: Tubal Martin http://blog.margenn.com
741 * Tests: http://margenn.com/tubal/str_slice/
744 * @param int $start index
745 * @param int|bool $end index (optional)
748 private function str_slice($str, $start = 0, $end = FALSE)
750 if ($end !== FALSE && ($start < 0 || $end <= 0)) {
754 if (($start = $max + $start) < 0) {
760 if (($end = $max + $end) < 0) {
765 if ($end <= $start) {
770 $slice = ($end === FALSE) ? substr($str, $start) : substr($str, $start, $end - $start);
771 return ($slice === FALSE) ? '' : $slice;
775 * Convert strings like "64M" or "30" to int values
779 private function normalize_int($size)
781 if (is_string($size)) {
782 switch (substr($size, -1)) {
783 case 'M': case 'm': return (int) $size * 1048576;
784 case 'K': case 'k': return (int) $size * 1024;
785 case 'G': case 'g': return (int) $size * 1073741824;