PageRenderTime 55ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/jyaml/vendor/JsCssChunker/src/lib/compressor/CSSMin.php

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