CSSmin.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. <?php
  2. /*!
  3. * cssmin.php v2.4.8-4
  4. * Author: Tubal Martin - http://tubalmartin.me/
  5. * Repo: https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port
  6. *
  7. * This is a PHP port of the CSS minification tool distributed with YUICompressor,
  8. * itself a port of the cssmin utility by Isaac Schlueter - http://foohack.com/
  9. * Permission is hereby granted to use the PHP version under the same
  10. * conditions as the YUICompressor.
  11. */
  12. /*!
  13. * YUI Compressor
  14. * http://developer.yahoo.com/yui/compressor/
  15. * Author: Julien Lecomte - http://www.julienlecomte.net/
  16. * Copyright (c) 2013 Yahoo! Inc. All rights reserved.
  17. * The copyrights embodied in the content of this file are licensed
  18. * by Yahoo! Inc. under the BSD (revised) open source license.
  19. */
  20. class CSSmin
  21. {
  22. const NL = '___YUICSSMIN_PRESERVED_NL___';
  23. const TOKEN = '___YUICSSMIN_PRESERVED_TOKEN_';
  24. const COMMENT = '___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_';
  25. const CLASSCOLON = '___YUICSSMIN_PSEUDOCLASSCOLON___';
  26. const QUERY_FRACTION = '___YUICSSMIN_QUERY_FRACTION___';
  27. private $comments;
  28. private $preserved_tokens;
  29. private $memory_limit;
  30. private $max_execution_time;
  31. private $pcre_backtrack_limit;
  32. private $pcre_recursion_limit;
  33. private $raise_php_limits;
  34. /**
  35. * @param bool|int $raise_php_limits
  36. * If true, PHP settings will be raised if needed
  37. */
  38. public function __construct($raise_php_limits = TRUE)
  39. {
  40. // Set suggested PHP limits
  41. $this->memory_limit = 128 * 1048576; // 128MB in bytes
  42. $this->max_execution_time = 60; // 1 min
  43. $this->pcre_backtrack_limit = 1000 * 1000;
  44. $this->pcre_recursion_limit = 500 * 1000;
  45. $this->raise_php_limits = (bool) $raise_php_limits;
  46. }
  47. /**
  48. * Minify a string of CSS
  49. * @param string $css
  50. * @param int|bool $linebreak_pos
  51. * @return string
  52. */
  53. public function run($css = '', $linebreak_pos = FALSE)
  54. {
  55. if (empty($css)) {
  56. return '';
  57. }
  58. if ($this->raise_php_limits) {
  59. $this->do_raise_php_limits();
  60. }
  61. $this->comments = array();
  62. $this->preserved_tokens = array();
  63. $start_index = 0;
  64. $length = strlen($css);
  65. $css = $this->extract_data_urls($css);
  66. // collect all comment blocks...
  67. while (($start_index = $this->index_of($css, '/*', $start_index)) >= 0) {
  68. $end_index = $this->index_of($css, '*/', $start_index + 2);
  69. if ($end_index < 0) {
  70. $end_index = $length;
  71. }
  72. $comment_found = $this->str_slice($css, $start_index + 2, $end_index);
  73. $this->comments[] = $comment_found;
  74. $comment_preserve_string = self::COMMENT . (count($this->comments) - 1) . '___';
  75. $css = $this->str_slice($css, 0, $start_index + 2) . $comment_preserve_string . $this->str_slice($css, $end_index);
  76. // Set correct start_index: Fixes issue #2528130
  77. $start_index = $end_index + 2 + strlen($comment_preserve_string) - strlen($comment_found);
  78. }
  79. // preserve strings so their content doesn't get accidentally minified
  80. $css = preg_replace_callback('/(?:"(?:[^\\\\"]|\\\\.|\\\\)*")|'."(?:'(?:[^\\\\']|\\\\.|\\\\)*')/S", array($this, 'replace_string'), $css);
  81. // Let's divide css code in chunks of 5.000 chars aprox.
  82. // Reason: PHP's PCRE functions like preg_replace have a "backtrack limit"
  83. // of 100.000 chars by default (php < 5.3.7) so if we're dealing with really
  84. // long strings and a (sub)pattern matches a number of chars greater than
  85. // the backtrack limit number (i.e. /(.*)/s) PCRE functions may fail silently
  86. // returning NULL and $css would be empty.
  87. $charset = '';
  88. $charset_regexp = '/(@charset)( [^;]+;)/i';
  89. $css_chunks = array();
  90. $css_chunk_length = 5000; // aprox size, not exact
  91. $start_index = 0;
  92. $i = $css_chunk_length; // save initial iterations
  93. $l = strlen($css);
  94. // if the number of characters is 5000 or less, do not chunk
  95. if ($l <= $css_chunk_length) {
  96. $css_chunks[] = $css;
  97. } else {
  98. // chunk css code securely
  99. while ($i < $l) {
  100. $i += 50; // save iterations
  101. if ($l - $start_index <= $css_chunk_length || $i >= $l) {
  102. $css_chunks[] = $this->str_slice($css, $start_index);
  103. break;
  104. }
  105. if ($css[$i - 1] === '}' && $i - $start_index > $css_chunk_length) {
  106. // If there are two ending curly braces }} separated or not by spaces,
  107. // join them in the same chunk (i.e. @media blocks)
  108. $next_chunk = substr($css, $i);
  109. if (preg_match('/^\s*\}/', $next_chunk)) {
  110. $i = $i + $this->index_of($next_chunk, '}') + 1;
  111. }
  112. $css_chunks[] = $this->str_slice($css, $start_index, $i);
  113. $start_index = $i;
  114. }
  115. }
  116. }
  117. // Minify each chunk
  118. for ($i = 0, $n = count($css_chunks); $i < $n; $i++) {
  119. $css_chunks[$i] = $this->minify($css_chunks[$i], $linebreak_pos);
  120. // Keep the first @charset at-rule found
  121. if (empty($charset) && preg_match($charset_regexp, $css_chunks[$i], $matches)) {
  122. $charset = strtolower($matches[1]) . $matches[2];
  123. }
  124. // Delete all @charset at-rules
  125. $css_chunks[$i] = preg_replace($charset_regexp, '', $css_chunks[$i]);
  126. }
  127. // Update the first chunk and push the charset to the top of the file.
  128. $css_chunks[0] = $charset . $css_chunks[0];
  129. return implode('', $css_chunks);
  130. }
  131. /**
  132. * Sets the memory limit for this script
  133. * @param int|string $limit
  134. */
  135. public function set_memory_limit($limit)
  136. {
  137. $this->memory_limit = $this->normalize_int($limit);
  138. }
  139. /**
  140. * Sets the maximum execution time for this script
  141. * @param int|string $seconds
  142. */
  143. public function set_max_execution_time($seconds)
  144. {
  145. $this->max_execution_time = (int) $seconds;
  146. }
  147. /**
  148. * Sets the PCRE backtrack limit for this script
  149. * @param int $limit
  150. */
  151. public function set_pcre_backtrack_limit($limit)
  152. {
  153. $this->pcre_backtrack_limit = (int) $limit;
  154. }
  155. /**
  156. * Sets the PCRE recursion limit for this script
  157. * @param int $limit
  158. */
  159. public function set_pcre_recursion_limit($limit)
  160. {
  161. $this->pcre_recursion_limit = (int) $limit;
  162. }
  163. /**
  164. * Try to configure PHP to use at least the suggested minimum settings
  165. */
  166. private function do_raise_php_limits()
  167. {
  168. $php_limits = array(
  169. 'memory_limit' => $this->memory_limit,
  170. 'max_execution_time' => $this->max_execution_time,
  171. 'pcre.backtrack_limit' => $this->pcre_backtrack_limit,
  172. 'pcre.recursion_limit' => $this->pcre_recursion_limit
  173. );
  174. // If current settings are higher respect them.
  175. foreach ($php_limits as $name => $suggested) {
  176. $current = $this->normalize_int(ini_get($name));
  177. // memory_limit exception: allow -1 for "no memory limit".
  178. if ($current > -1 && ($suggested == -1 || $current < $suggested)) {
  179. ini_set($name, $suggested);
  180. }
  181. }
  182. }
  183. /**
  184. * Does bulk of the minification
  185. * @param string $css
  186. * @param int|bool $linebreak_pos
  187. * @return string
  188. */
  189. private function minify($css, $linebreak_pos)
  190. {
  191. // strings are safe, now wrestle the comments
  192. for ($i = 0, $max = count($this->comments); $i < $max; $i++) {
  193. $token = $this->comments[$i];
  194. $placeholder = '/' . self::COMMENT . $i . '___/';
  195. // ! in the first position of the comment means preserve
  196. // so push to the preserved tokens keeping the !
  197. if (substr($token, 0, 1) === '!') {
  198. $this->preserved_tokens[] = $token;
  199. $token_tring = self::TOKEN . (count($this->preserved_tokens) - 1) . '___';
  200. $css = preg_replace($placeholder, $token_tring, $css, 1);
  201. // Preserve new lines for /*! important comments
  202. $css = preg_replace('/\s*[\n\r\f]+\s*(\/\*'. $token_tring .')/S', self::NL.'$1', $css);
  203. $css = preg_replace('/('. $token_tring .'\*\/)\s*[\n\r\f]+\s*/', '$1'.self::NL, $css);
  204. continue;
  205. }
  206. // \ in the last position looks like hack for Mac/IE5
  207. // shorten that to /*\*/ and the next one to /**/
  208. if (substr($token, (strlen($token) - 1), 1) === '\\') {
  209. $this->preserved_tokens[] = '\\';
  210. $css = preg_replace($placeholder, self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1);
  211. $i = $i + 1; // attn: advancing the loop
  212. $this->preserved_tokens[] = '';
  213. $css = preg_replace('/' . self::COMMENT . $i . '___/', self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1);
  214. continue;
  215. }
  216. // keep empty comments after child selectors (IE7 hack)
  217. // e.g. html >/**/ body
  218. if (strlen($token) === 0) {
  219. $start_index = $this->index_of($css, $this->str_slice($placeholder, 1, -1));
  220. if ($start_index > 2) {
  221. if (substr($css, $start_index - 3, 1) === '>') {
  222. $this->preserved_tokens[] = '';
  223. $css = preg_replace($placeholder, self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1);
  224. }
  225. }
  226. }
  227. // in all other cases kill the comment
  228. $css = preg_replace('/\/\*' . $this->str_slice($placeholder, 1, -1) . '\*\//', '', $css, 1);
  229. }
  230. // Normalize all whitespace strings to single spaces. Easier to work with that way.
  231. $css = preg_replace('/\s+/', ' ', $css);
  232. // Fix IE7 issue on matrix filters which browser accept whitespaces between Matrix parameters
  233. $css = preg_replace_callback('/\s*filter\:\s*progid:DXImageTransform\.Microsoft\.Matrix\(([^\)]+)\)/', array($this, 'preserve_old_IE_specific_matrix_definition'), $css);
  234. // Shorten & preserve calculations calc(...) since spaces are important
  235. $css = preg_replace_callback('/calc(\(((?:[^\(\)]+|(?1))*)\))/i', array($this, 'replace_calc'), $css);
  236. // Replace positive sign from numbers preceded by : or a white-space before the leading space is removed
  237. // +1.2em to 1.2em, +.8px to .8px, +2% to 2%
  238. $css = preg_replace('/((?<!\\\\)\:|\s)\+(\.?\d+)/S', '$1$2', $css);
  239. // Remove leading zeros from integer and float numbers preceded by : or a white-space
  240. // 000.6 to .6, -0.8 to -.8, 0050 to 50, -01.05 to -1.05
  241. $css = preg_replace('/((?<!\\\\)\:|\s)(\-?)0+(\.?\d+)/S', '$1$2$3', $css);
  242. // Remove trailing zeros from float numbers preceded by : or a white-space
  243. // -6.0100em to -6.01em, .0100 to .01, 1.200px to 1.2px
  244. $css = preg_replace('/((?<!\\\\)\:|\s)(\-?)(\d?\.\d+?)0+([^\d])/S', '$1$2$3$4', $css);
  245. // Remove trailing .0 -> -9.0 to -9
  246. $css = preg_replace('/((?<!\\\\)\:|\s)(\-?\d+)\.0([^\d])/S', '$1$2$3', $css);
  247. // Replace 0 length numbers with 0
  248. $css = preg_replace('/((?<!\\\\)\:|\s)\-?\.?0+([^\d])/S', '${1}0$2', $css);
  249. // Remove the spaces before the things that should not have spaces before them.
  250. // But, be careful not to turn "p :link {...}" into "p:link{...}"
  251. // Swap out any pseudo-class colons with the token, and then swap back.
  252. $css = preg_replace_callback('/(?:^|\})[^\{]*\s+\:/', array($this, 'replace_colon'), $css);
  253. // Remove spaces before the things that should not have spaces before them.
  254. $css = preg_replace('/\s+([\!\{\}\;\:\>\+\(\)\]\~\=,])/', '$1', $css);
  255. // Restore spaces for !important
  256. $css = preg_replace('/\!important/i', ' !important', $css);
  257. // bring back the colon
  258. $css = preg_replace('/' . self::CLASSCOLON . '/', ':', $css);
  259. // retain space for special IE6 cases
  260. $css = preg_replace_callback('/\:first\-(line|letter)(\{|,)/i', array($this, 'lowercase_pseudo_first'), $css);
  261. // no space after the end of a preserved comment
  262. $css = preg_replace('/\*\/ /', '*/', $css);
  263. // lowercase some popular @directives
  264. $css = preg_replace_callback('/@(font-face|import|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?keyframe|media|page|namespace)/i', array($this, 'lowercase_directives'), $css);
  265. // lowercase some more common pseudo-elements
  266. $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);
  267. // lowercase some more common functions
  268. $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);
  269. // lower case some common function that can be values
  270. // NOTE: rgb() isn't useful as we replace with #hex later, as well as and() is already done for us
  271. $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);
  272. // Put the space back in some cases, to support stuff like
  273. // @media screen and (-webkit-min-device-pixel-ratio:0){
  274. $css = preg_replace('/\band\(/i', 'and (', $css);
  275. // Remove the spaces after the things that should not have spaces after them.
  276. $css = preg_replace('/([\!\{\}\:;\>\+\(\[\~\=,])\s+/S', '$1', $css);
  277. // remove unnecessary semicolons
  278. $css = preg_replace('/;+\}/', '}', $css);
  279. // Fix for issue: #2528146
  280. // Restore semicolon if the last property is prefixed with a `*` (lte IE7 hack)
  281. // to avoid issues on Symbian S60 3.x browsers.
  282. $css = preg_replace('/(\*[a-z0-9\-]+\s*\:[^;\}]+)(\})/', '$1;$2', $css);
  283. // Replace 0 <length> and 0 <percentage> values with 0.
  284. // <length> data type: https://developer.mozilla.org/en-US/docs/Web/CSS/length
  285. // <percentage> data type: https://developer.mozilla.org/en-US/docs/Web/CSS/percentage
  286. $css = preg_replace('/([^\\\\]\:|\s)0(?:em|ex|ch|rem|vw|vh|vm|vmin|cm|mm|in|px|pt|pc|%)/iS', '${1}0', $css);
  287. // 0% step in a keyframe? restore the % unit
  288. $css = preg_replace_callback('/(@[a-z\-]*?keyframes[^\{]+\{)(.*?)(\}\})/iS', array($this, 'replace_keyframe_zero'), $css);
  289. // Replace 0 0; or 0 0 0; or 0 0 0 0; with 0.
  290. $css = preg_replace('/\:0(?: 0){1,3}(;|\}| \!)/', ':0$1', $css);
  291. // Fix for issue: #2528142
  292. // Replace text-shadow:0; with text-shadow:0 0 0;
  293. $css = preg_replace('/(text-shadow\:0)(;|\}| \!)/i', '$1 0 0$2', $css);
  294. // Replace background-position:0; with background-position:0 0;
  295. // same for transform-origin
  296. // Changing -webkit-mask-position: 0 0 to just a single 0 will result in the second parameter defaulting to 50% (center)
  297. $css = preg_replace('/(background\-position|webkit-mask-position|(?:webkit|moz|o|ms|)\-?transform\-origin)\:0(;|\}| \!)/iS', '$1:0 0$2', $css);
  298. // Shorten colors from rgb(51,102,153) to #336699, rgb(100%,0%,0%) to #ff0000 (sRGB color space)
  299. // Shorten colors from hsl(0, 100%, 50%) to #ff0000 (sRGB color space)
  300. // This makes it more likely that it'll get further compressed in the next step.
  301. $css = preg_replace_callback('/rgb\s*\(\s*([0-9,\s\-\.\%]+)\s*\)(.{1})/i', array($this, 'rgb_to_hex'), $css);
  302. $css = preg_replace_callback('/hsl\s*\(\s*([0-9,\s\-\.\%]+)\s*\)(.{1})/i', array($this, 'hsl_to_hex'), $css);
  303. // Shorten colors from #AABBCC to #ABC or short color name.
  304. $css = $this->compress_hex_colors($css);
  305. // border: none to border:0, outline: none to outline:0
  306. $css = preg_replace('/(border\-?(?:top|right|bottom|left|)|outline)\:none(;|\}| \!)/iS', '$1:0$2', $css);
  307. // shorter opacity IE filter
  308. $css = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $css);
  309. // Find a fraction that is used for Opera's -o-device-pixel-ratio query
  310. // Add token to add the "\" back in later
  311. $css = preg_replace('/\(([a-z\-]+):([0-9]+)\/([0-9]+)\)/i', '($1:$2'. self::QUERY_FRACTION .'$3)', $css);
  312. // Remove empty rules.
  313. $css = preg_replace('/[^\};\{\/]+\{\}/S', '', $css);
  314. // Add "/" back to fix Opera -o-device-pixel-ratio query
  315. $css = preg_replace('/'. self::QUERY_FRACTION .'/', '/', $css);
  316. // Replace multiple semi-colons in a row by a single one
  317. // See SF bug #1980989
  318. $css = preg_replace('/;;+/', ';', $css);
  319. // Restore new lines for /*! important comments
  320. $css = preg_replace('/'. self::NL .'/', "\n", $css);
  321. // Lowercase all uppercase properties
  322. $css = preg_replace_callback('/(\{|\;)([A-Z\-]+)(\:)/', array($this, 'lowercase_properties'), $css);
  323. // Some source control tools don't like it when files containing lines longer
  324. // than, say 8000 characters, are checked in. The linebreak option is used in
  325. // that case to split long lines after a specific column.
  326. if ($linebreak_pos !== FALSE && (int) $linebreak_pos >= 0) {
  327. $linebreak_pos = (int) $linebreak_pos;
  328. $start_index = $i = 0;
  329. while ($i < strlen($css)) {
  330. $i++;
  331. if ($css[$i - 1] === '}' && $i - $start_index > $linebreak_pos) {
  332. $css = $this->str_slice($css, 0, $i) . "\n" . $this->str_slice($css, $i);
  333. $start_index = $i;
  334. }
  335. }
  336. }
  337. // restore preserved comments and strings in reverse order
  338. for ($i = count($this->preserved_tokens) - 1; $i >= 0; $i--) {
  339. $css = preg_replace('/' . self::TOKEN . $i . '___/', $this->preserved_tokens[$i], $css, 1);
  340. }
  341. // Trim the final string (for any leading or trailing white spaces)
  342. return trim($css);
  343. }
  344. /**
  345. * Utility method to replace all data urls with tokens before we start
  346. * compressing, to avoid performance issues running some of the subsequent
  347. * regexes against large strings chunks.
  348. *
  349. * @param string $css
  350. * @return string
  351. */
  352. private function extract_data_urls($css)
  353. {
  354. // Leave data urls alone to increase parse performance.
  355. $max_index = strlen($css) - 1;
  356. $append_index = $index = $last_index = $offset = 0;
  357. $sb = array();
  358. $pattern = '/url\(\s*(["\']?)data\:/i';
  359. // Since we need to account for non-base64 data urls, we need to handle
  360. // ' and ) being part of the data string. Hence switching to indexOf,
  361. // to determine whether or not we have matching string terminators and
  362. // handling sb appends directly, instead of using matcher.append* methods.
  363. while (preg_match($pattern, $css, $m, 0, $offset)) {
  364. $index = $this->index_of($css, $m[0], $offset);
  365. $last_index = $index + strlen($m[0]);
  366. $start_index = $index + 4; // "url(".length()
  367. $end_index = $last_index - 1;
  368. $terminator = $m[1]; // ', " or empty (not quoted)
  369. $found_terminator = FALSE;
  370. if (strlen($terminator) === 0) {
  371. $terminator = ')';
  372. }
  373. while ($found_terminator === FALSE && $end_index+1 <= $max_index) {
  374. $end_index = $this->index_of($css, $terminator, $end_index + 1);
  375. // endIndex == 0 doesn't really apply here
  376. if ($end_index > 0 && substr($css, $end_index - 1, 1) !== '\\') {
  377. $found_terminator = TRUE;
  378. if (')' != $terminator) {
  379. $end_index = $this->index_of($css, ')', $end_index);
  380. }
  381. }
  382. }
  383. // Enough searching, start moving stuff over to the buffer
  384. $sb[] = $this->str_slice($css, $append_index, $index);
  385. if ($found_terminator) {
  386. $token = $this->str_slice($css, $start_index, $end_index);
  387. $token = preg_replace('/\s+/', '', $token);
  388. $this->preserved_tokens[] = $token;
  389. $preserver = 'url(' . self::TOKEN . (count($this->preserved_tokens) - 1) . '___)';
  390. $sb[] = $preserver;
  391. $append_index = $end_index + 1;
  392. } else {
  393. // No end terminator found, re-add the whole match. Should we throw/warn here?
  394. $sb[] = $this->str_slice($css, $index, $last_index);
  395. $append_index = $last_index;
  396. }
  397. $offset = $last_index;
  398. }
  399. $sb[] = $this->str_slice($css, $append_index);
  400. return implode('', $sb);
  401. }
  402. /**
  403. * Utility method to compress hex color values of the form #AABBCC to #ABC or short color name.
  404. *
  405. * DOES NOT compress CSS ID selectors which match the above pattern (which would break things).
  406. * e.g. #AddressForm { ... }
  407. *
  408. * DOES NOT compress IE filters, which have hex color values (which would break things).
  409. * e.g. filter: chroma(color="#FFFFFF");
  410. *
  411. * DOES NOT compress invalid hex values.
  412. * e.g. background-color: #aabbccdd
  413. *
  414. * @param string $css
  415. * @return string
  416. */
  417. private function compress_hex_colors($css)
  418. {
  419. // Look for hex colors inside { ... } (to avoid IDs) and which don't have a =, or a " in front of them (to avoid filters)
  420. $pattern = '/(\=\s*?["\']?)?#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])(\}|[^0-9a-f{][^{]*?\})/iS';
  421. $_index = $index = $last_index = $offset = 0;
  422. $sb = array();
  423. // See: http://ajaxmin.codeplex.com/wikipage?title=CSS%20Colors
  424. $short_safe = array(
  425. '#808080' => 'gray',
  426. '#008000' => 'green',
  427. '#800000' => 'maroon',
  428. '#000080' => 'navy',
  429. '#808000' => 'olive',
  430. '#ffa500' => 'orange',
  431. '#800080' => 'purple',
  432. '#c0c0c0' => 'silver',
  433. '#008080' => 'teal',
  434. '#f00' => 'red'
  435. );
  436. while (preg_match($pattern, $css, $m, 0, $offset)) {
  437. $index = $this->index_of($css, $m[0], $offset);
  438. $last_index = $index + strlen($m[0]);
  439. $is_filter = $m[1] !== null && $m[1] !== '';
  440. $sb[] = $this->str_slice($css, $_index, $index);
  441. if ($is_filter) {
  442. // Restore, maintain case, otherwise filter will break
  443. $sb[] = $m[1] . '#' . $m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7];
  444. } else {
  445. if (strtolower($m[2]) == strtolower($m[3]) &&
  446. strtolower($m[4]) == strtolower($m[5]) &&
  447. strtolower($m[6]) == strtolower($m[7])) {
  448. // Compress.
  449. $hex = '#' . strtolower($m[3] . $m[5] . $m[7]);
  450. } else {
  451. // Non compressible color, restore but lower case.
  452. $hex = '#' . strtolower($m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7]);
  453. }
  454. // replace Hex colors to short safe color names
  455. $sb[] = array_key_exists($hex, $short_safe) ? $short_safe[$hex] : $hex;
  456. }
  457. $_index = $offset = $last_index - strlen($m[8]);
  458. }
  459. $sb[] = $this->str_slice($css, $_index);
  460. return implode('', $sb);
  461. }
  462. /* CALLBACKS
  463. * ---------------------------------------------------------------------------------------------
  464. */
  465. private function replace_string($matches)
  466. {
  467. $match = $matches[0];
  468. $quote = substr($match, 0, 1);
  469. // Must use addcslashes in PHP to avoid parsing of backslashes
  470. $match = addcslashes($this->str_slice($match, 1, -1), '\\');
  471. // maybe the string contains a comment-like substring?
  472. // one, maybe more? put'em back then
  473. if (($pos = $this->index_of($match, self::COMMENT)) >= 0) {
  474. for ($i = 0, $max = count($this->comments); $i < $max; $i++) {
  475. $match = preg_replace('/' . self::COMMENT . $i . '___/', $this->comments[$i], $match, 1);
  476. }
  477. }
  478. // minify alpha opacity in filter strings
  479. $match = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $match);
  480. $this->preserved_tokens[] = $match;
  481. return $quote . self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . $quote;
  482. }
  483. private function replace_colon($matches)
  484. {
  485. return preg_replace('/\:/', self::CLASSCOLON, $matches[0]);
  486. }
  487. private function replace_calc($matches)
  488. {
  489. $this->preserved_tokens[] = trim(preg_replace('/\s*([\*\/\(\),])\s*/', '$1', $matches[2]));
  490. return 'calc('. self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . ')';
  491. }
  492. private function preserve_old_IE_specific_matrix_definition($matches)
  493. {
  494. $this->preserved_tokens[] = $matches[1];
  495. return 'filter:progid:DXImageTransform.Microsoft.Matrix(' . self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . ')';
  496. }
  497. private function replace_keyframe_zero($matches)
  498. {
  499. return $matches[1] . preg_replace('/0(\{|,[^\)\{]+\{)/', '0%$1', $matches[2]) . $matches[3];
  500. }
  501. private function rgb_to_hex($matches)
  502. {
  503. // Support for percentage values rgb(100%, 0%, 45%);
  504. if ($this->index_of($matches[1], '%') >= 0){
  505. $rgbcolors = explode(',', str_replace('%', '', $matches[1]));
  506. for ($i = 0; $i < count($rgbcolors); $i++) {
  507. $rgbcolors[$i] = $this->round_number(floatval($rgbcolors[$i]) * 2.55);
  508. }
  509. } else {
  510. $rgbcolors = explode(',', $matches[1]);
  511. }
  512. // Values outside the sRGB color space should be clipped (0-255)
  513. for ($i = 0; $i < count($rgbcolors); $i++) {
  514. $rgbcolors[$i] = $this->clamp_number(intval($rgbcolors[$i], 10), 0, 255);
  515. $rgbcolors[$i] = sprintf("%02x", $rgbcolors[$i]);
  516. }
  517. // Fix for issue #2528093
  518. if (!preg_match('/[\s\,\);\}]/', $matches[2])){
  519. $matches[2] = ' ' . $matches[2];
  520. }
  521. return '#' . implode('', $rgbcolors) . $matches[2];
  522. }
  523. private function hsl_to_hex($matches)
  524. {
  525. $values = explode(',', str_replace('%', '', $matches[1]));
  526. $h = floatval($values[0]);
  527. $s = floatval($values[1]);
  528. $l = floatval($values[2]);
  529. // Wrap and clamp, then fraction!
  530. $h = ((($h % 360) + 360) % 360) / 360;
  531. $s = $this->clamp_number($s, 0, 100) / 100;
  532. $l = $this->clamp_number($l, 0, 100) / 100;
  533. if ($s == 0) {
  534. $r = $g = $b = $this->round_number(255 * $l);
  535. } else {
  536. $v2 = $l < 0.5 ? $l * (1 + $s) : ($l + $s) - ($s * $l);
  537. $v1 = (2 * $l) - $v2;
  538. $r = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h + (1/3)));
  539. $g = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h));
  540. $b = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h - (1/3)));
  541. }
  542. return $this->rgb_to_hex(array('', $r.','.$g.','.$b, $matches[2]));
  543. }
  544. private function lowercase_pseudo_first($matches)
  545. {
  546. return ':first-'. strtolower($matches[1]) .' '. $matches[2];
  547. }
  548. private function lowercase_directives($matches)
  549. {
  550. return '@'. strtolower($matches[1]);
  551. }
  552. private function lowercase_pseudo_elements($matches)
  553. {
  554. return ':'. strtolower($matches[1]);
  555. }
  556. private function lowercase_common_functions($matches)
  557. {
  558. return ':'. strtolower($matches[1]) .'(';
  559. }
  560. private function lowercase_common_functions_values($matches)
  561. {
  562. return $matches[1] . strtolower($matches[2]);
  563. }
  564. private function lowercase_properties($matches)
  565. {
  566. return $matches[1].strtolower($matches[2]).$matches[3];
  567. }
  568. /* HELPERS
  569. * ---------------------------------------------------------------------------------------------
  570. */
  571. private function hue_to_rgb($v1, $v2, $vh)
  572. {
  573. $vh = $vh < 0 ? $vh + 1 : ($vh > 1 ? $vh - 1 : $vh);
  574. if ($vh * 6 < 1) return $v1 + ($v2 - $v1) * 6 * $vh;
  575. if ($vh * 2 < 1) return $v2;
  576. if ($vh * 3 < 2) return $v1 + ($v2 - $v1) * ((2/3) - $vh) * 6;
  577. return $v1;
  578. }
  579. private function round_number($n)
  580. {
  581. return intval(floor(floatval($n) + 0.5), 10);
  582. }
  583. private function clamp_number($n, $min, $max)
  584. {
  585. return min(max($n, $min), $max);
  586. }
  587. /**
  588. * PHP port of Javascript's "indexOf" function for strings only
  589. * Author: Tubal Martin http://blog.margenn.com
  590. *
  591. * @param string $haystack
  592. * @param string $needle
  593. * @param int $offset index (optional)
  594. * @return int
  595. */
  596. private function index_of($haystack, $needle, $offset = 0)
  597. {
  598. $index = strpos($haystack, $needle, $offset);
  599. return ($index !== FALSE) ? $index : -1;
  600. }
  601. /**
  602. * PHP port of Javascript's "slice" function for strings only
  603. * Author: Tubal Martin http://blog.margenn.com
  604. * Tests: http://margenn.com/tubal/str_slice/
  605. *
  606. * @param string $str
  607. * @param int $start index
  608. * @param int|bool $end index (optional)
  609. * @return string
  610. */
  611. private function str_slice($str, $start = 0, $end = FALSE)
  612. {
  613. if ($end !== FALSE && ($start < 0 || $end <= 0)) {
  614. $max = strlen($str);
  615. if ($start < 0) {
  616. if (($start = $max + $start) < 0) {
  617. return '';
  618. }
  619. }
  620. if ($end < 0) {
  621. if (($end = $max + $end) < 0) {
  622. return '';
  623. }
  624. }
  625. if ($end <= $start) {
  626. return '';
  627. }
  628. }
  629. $slice = ($end === FALSE) ? substr($str, $start) : substr($str, $start, $end - $start);
  630. return ($slice === FALSE) ? '' : $slice;
  631. }
  632. /**
  633. * Convert strings like "64M" or "30" to int values
  634. * @param mixed $size
  635. * @return int
  636. */
  637. private function normalize_int($size)
  638. {
  639. if (is_string($size)) {
  640. switch (substr($size, -1)) {
  641. case 'M': case 'm': return $size * 1048576;
  642. case 'K': case 'k': return $size * 1024;
  643. case 'G': case 'g': return $size * 1073741824;
  644. }
  645. }
  646. return (int) $size;
  647. }
  648. }