PageRenderTime 32ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Plugin/CoreCompiler/lib/CSSmin.php

https://gitlab.com/x33n/ImpressPages
PHP | 758 lines | 449 code | 116 blank | 193 comment | 69 complexity | d3948af8f596faf3f5e18bfccf18e654 MD5 | raw file
  1. <?php
  2. /*!
  3. * cssmin.php rev ebaf67b 12/06/2013
  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 25.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 = 25000; // 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 25000 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. 500 checks for a closing curly brace }
  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. // Shorten & preserve calculations calc(...) since spaces are important
  233. $css = preg_replace_callback('/calc(\(((?:[^\(\)]+|(?1))*)\))/i', array($this, 'replace_calc'), $css);
  234. // Replace positive sign from numbers preceded by : or a white-space before the leading space is removed
  235. // +1.2em to 1.2em, +.8px to .8px, +2% to 2%
  236. $css = preg_replace('/((?<!\\\\)\:|\s)\+(\.?\d+)/S', '$1$2', $css);
  237. // Remove leading zeros from integer and float numbers preceded by : or a white-space
  238. // 000.6 to .6, -0.8 to -.8, 0050 to 50, -01.05 to -1.05
  239. $css = preg_replace('/((?<!\\\\)\:|\s)(\-?)0+(\.?\d+)/S', '$1$2$3', $css);
  240. // Remove trailing zeros from float numbers preceded by : or a white-space
  241. // -6.0100em to -6.01em, .0100 to .01, 1.200px to 1.2px
  242. $css = preg_replace('/((?<!\\\\)\:|\s)(\-?)(\d?\.\d+?)0+([^\d])/S', '$1$2$3$4', $css);
  243. // Remove trailing .0 -> -9.0 to -9
  244. $css = preg_replace('/((?<!\\\\)\:|\s)(\-?\d+)\.0([^\d])/S', '$1$2$3', $css);
  245. // Replace 0 length numbers with 0
  246. $css = preg_replace('/((?<!\\\\)\:|\s)\-?\.?0+([^\d])/S', '${1}0$2', $css);
  247. // Remove the spaces before the things that should not have spaces before them.
  248. // But, be careful not to turn "p :link {...}" into "p:link{...}"
  249. // Swap out any pseudo-class colons with the token, and then swap back.
  250. $css = preg_replace_callback('/(?:^|\})(?:(?:[^\{\:])+\:)+(?:[^\{]*\{)/', array($this, 'replace_colon'), $css);
  251. // Remove spaces before the things that should not have spaces before them.
  252. $css = preg_replace('/\s+([\!\{\}\;\:\>\+\(\)\]\~\=,])/', '$1', $css);
  253. // Restore spaces for !important
  254. $css = preg_replace('/\!important/i', ' !important', $css);
  255. // bring back the colon
  256. $css = preg_replace('/' . self::CLASSCOLON . '/', ':', $css);
  257. // retain space for special IE6 cases
  258. $css = preg_replace_callback('/\:first\-(line|letter)(\{|,)/i', array($this, 'lowercase_pseudo_first'), $css);
  259. // no space after the end of a preserved comment
  260. $css = preg_replace('/\*\/ /', '*/', $css);
  261. // lowercase some popular @directives
  262. $css = preg_replace_callback('/@(font-face|import|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?keyframe|media|page|namespace)/i', array($this, 'lowercase_directives'), $css);
  263. // lowercase some more common pseudo-elements
  264. $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);
  265. // lowercase some more common functions
  266. $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);
  267. // lower case some common function that can be values
  268. // NOTE: rgb() isn't useful as we replace with #hex later, as well as and() is already done for us
  269. $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);
  270. // Put the space back in some cases, to support stuff like
  271. // @media screen and (-webkit-min-device-pixel-ratio:0){
  272. $css = preg_replace('/\band\(/i', 'and (', $css);
  273. // Remove the spaces after the things that should not have spaces after them.
  274. $css = preg_replace('/([\!\{\}\:;\>\+\(\[\~\=,])\s+/S', '$1', $css);
  275. // remove unnecessary semicolons
  276. $css = preg_replace('/;+\}/', '}', $css);
  277. // Fix for issue: #2528146
  278. // Restore semicolon if the last property is prefixed with a `*` (lte IE7 hack)
  279. // to avoid issues on Symbian S60 3.x browsers.
  280. $css = preg_replace('/(\*[a-z0-9\-]+\s*\:[^;\}]+)(\})/', '$1;$2', $css);
  281. // Replace 0 length units 0(px,em,%) with 0.
  282. $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);
  283. // Replace 0 0; or 0 0 0; or 0 0 0 0; with 0.
  284. $css = preg_replace('/\:0(?: 0){1,3}(;|\}| \!)/', ':0$1', $css);
  285. // Fix for issue: #2528142
  286. // Replace text-shadow:0; with text-shadow:0 0 0;
  287. $css = preg_replace('/(text-shadow\:0)(;|\}| \!)/i', '$1 0 0$2', $css);
  288. // Replace background-position:0; with background-position:0 0;
  289. // same for transform-origin
  290. // Changing -webkit-mask-position: 0 0 to just a single 0 will result in the second parameter defaulting to 50% (center)
  291. $css = preg_replace('/(background\-position|webkit-mask-position|(?:webkit|moz|o|ms|)\-?transform\-origin)\:0(;|\}| \!)/iS', '$1:0 0$2', $css);
  292. // Shorten colors from rgb(51,102,153) to #336699, rgb(100%,0%,0%) to #ff0000 (sRGB color space)
  293. // Shorten colors from hsl(0, 100%, 50%) to #ff0000 (sRGB color space)
  294. // This makes it more likely that it'll get further compressed in the next step.
  295. $css = preg_replace_callback('/rgb\s*\(\s*([0-9,\s\-\.\%]+)\s*\)(.{1})/i', array($this, 'rgb_to_hex'), $css);
  296. $css = preg_replace_callback('/hsl\s*\(\s*([0-9,\s\-\.\%]+)\s*\)(.{1})/i', array($this, 'hsl_to_hex'), $css);
  297. // Shorten colors from #AABBCC to #ABC or short color name.
  298. $css = $this->compress_hex_colors($css);
  299. // border: none to border:0, outline: none to outline:0
  300. $css = preg_replace('/(border\-?(?:top|right|bottom|left|)|outline)\:none(;|\}| \!)/iS', '$1:0$2', $css);
  301. // shorter opacity IE filter
  302. $css = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $css);
  303. // Find a fraction that is used for Opera's -o-device-pixel-ratio query
  304. // Add token to add the "\" back in later
  305. $css = preg_replace('/\(([a-z\-]+):([0-9]+)\/([0-9]+)\)/i', '($1:$2'. self::QUERY_FRACTION .'$3)', $css);
  306. // Remove empty rules.
  307. $css = preg_replace('/[^\};\{\/]+\{\}/S', '', $css);
  308. // Add "/" back to fix Opera -o-device-pixel-ratio query
  309. $css = preg_replace('/'. self::QUERY_FRACTION .'/', '/', $css);
  310. // Some source control tools don't like it when files containing lines longer
  311. // than, say 8000 characters, are checked in. The linebreak option is used in
  312. // that case to split long lines after a specific column.
  313. if ($linebreak_pos !== FALSE && (int) $linebreak_pos >= 0) {
  314. $linebreak_pos = (int) $linebreak_pos;
  315. $start_index = $i = 0;
  316. while ($i < strlen($css)) {
  317. $i++;
  318. if ($css[$i - 1] === '}' && $i - $start_index > $linebreak_pos) {
  319. $css = $this->str_slice($css, 0, $i) . "\n" . $this->str_slice($css, $i);
  320. $start_index = $i;
  321. }
  322. }
  323. }
  324. // Replace multiple semi-colons in a row by a single one
  325. // See SF bug #1980989
  326. $css = preg_replace('/;;+/', ';', $css);
  327. // Restore new lines for /*! important comments
  328. $css = preg_replace('/'. self::NL .'/', "\n", $css);
  329. // Lowercase all uppercase properties
  330. $css = preg_replace_callback('/(\{|\;)([A-Z\-]+)(\:)/', array($this, 'lowercase_properties'), $css);
  331. // restore preserved comments and strings
  332. for ($i = 0, $max = count($this->preserved_tokens); $i < $max; $i++) {
  333. $css = preg_replace('/' . self::TOKEN . $i . '___/', $this->preserved_tokens[$i], $css, 1);
  334. }
  335. // Trim the final string (for any leading or trailing white spaces)
  336. return trim($css);
  337. }
  338. /**
  339. * Utility method to replace all data urls with tokens before we start
  340. * compressing, to avoid performance issues running some of the subsequent
  341. * regexes against large strings chunks.
  342. *
  343. * @param string $css
  344. * @return string
  345. */
  346. private function extract_data_urls($css)
  347. {
  348. // Leave data urls alone to increase parse performance.
  349. $max_index = strlen($css) - 1;
  350. $append_index = $index = $last_index = $offset = 0;
  351. $sb = array();
  352. $pattern = '/url\(\s*(["\']?)data\:/i';
  353. // Since we need to account for non-base64 data urls, we need to handle
  354. // ' and ) being part of the data string. Hence switching to indexOf,
  355. // to determine whether or not we have matching string terminators and
  356. // handling sb appends directly, instead of using matcher.append* methods.
  357. while (preg_match($pattern, $css, $m, 0, $offset)) {
  358. $index = $this->index_of($css, $m[0], $offset);
  359. $last_index = $index + strlen($m[0]);
  360. $start_index = $index + 4; // "url(".length()
  361. $end_index = $last_index - 1;
  362. $terminator = $m[1]; // ', " or empty (not quoted)
  363. $found_terminator = FALSE;
  364. if (strlen($terminator) === 0) {
  365. $terminator = ')';
  366. }
  367. while ($found_terminator === FALSE && $end_index+1 <= $max_index) {
  368. $end_index = $this->index_of($css, $terminator, $end_index + 1);
  369. // endIndex == 0 doesn't really apply here
  370. if ($end_index > 0 && substr($css, $end_index - 1, 1) !== '\\') {
  371. $found_terminator = TRUE;
  372. if (')' != $terminator) {
  373. $end_index = $this->index_of($css, ')', $end_index);
  374. }
  375. }
  376. }
  377. // Enough searching, start moving stuff over to the buffer
  378. $sb[] = $this->str_slice($css, $append_index, $index);
  379. if ($found_terminator) {
  380. $token = $this->str_slice($css, $start_index, $end_index);
  381. $token = preg_replace('/\s+/', '', $token);
  382. $this->preserved_tokens[] = $token;
  383. $preserver = 'url(' . self::TOKEN . (count($this->preserved_tokens) - 1) . '___)';
  384. $sb[] = $preserver;
  385. $append_index = $end_index + 1;
  386. } else {
  387. // No end terminator found, re-add the whole match. Should we throw/warn here?
  388. $sb[] = $this->str_slice($css, $index, $last_index);
  389. $append_index = $last_index;
  390. }
  391. $offset = $last_index;
  392. }
  393. $sb[] = $this->str_slice($css, $append_index);
  394. return implode('', $sb);
  395. }
  396. /**
  397. * Utility method to compress hex color values of the form #AABBCC to #ABC or short color name.
  398. *
  399. * DOES NOT compress CSS ID selectors which match the above pattern (which would break things).
  400. * e.g. #AddressForm { ... }
  401. *
  402. * DOES NOT compress IE filters, which have hex color values (which would break things).
  403. * e.g. filter: chroma(color="#FFFFFF");
  404. *
  405. * DOES NOT compress invalid hex values.
  406. * e.g. background-color: #aabbccdd
  407. *
  408. * @param string $css
  409. * @return string
  410. */
  411. private function compress_hex_colors($css)
  412. {
  413. // Look for hex colors inside { ... } (to avoid IDs) and which don't have a =, or a " in front of them (to avoid filters)
  414. $pattern = '/(\=\s*?["\']?)?#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])(\}|[^0-9a-f{][^{]*?\})/iS';
  415. $_index = $index = $last_index = $offset = 0;
  416. $sb = array();
  417. // See: http://ajaxmin.codeplex.com/wikipage?title=CSS%20Colors
  418. $short_safe = array(
  419. '#808080' => 'gray',
  420. '#008000' => 'green',
  421. '#800000' => 'maroon',
  422. '#000080' => 'navy',
  423. '#808000' => 'olive',
  424. '#ffa500' => 'orange',
  425. '#800080' => 'purple',
  426. '#c0c0c0' => 'silver',
  427. '#008080' => 'teal',
  428. '#f00' => 'red'
  429. );
  430. while (preg_match($pattern, $css, $m, 0, $offset)) {
  431. $index = $this->index_of($css, $m[0], $offset);
  432. $last_index = $index + strlen($m[0]);
  433. $is_filter = $m[1] !== null && $m[1] !== '';
  434. $sb[] = $this->str_slice($css, $_index, $index);
  435. if ($is_filter) {
  436. // Restore, maintain case, otherwise filter will break
  437. $sb[] = $m[1] . '#' . $m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7];
  438. } else {
  439. if (strtolower($m[2]) == strtolower($m[3]) &&
  440. strtolower($m[4]) == strtolower($m[5]) &&
  441. strtolower($m[6]) == strtolower($m[7])) {
  442. // Compress.
  443. $hex = '#' . strtolower($m[3] . $m[5] . $m[7]);
  444. } else {
  445. // Non compressible color, restore but lower case.
  446. $hex = '#' . strtolower($m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7]);
  447. }
  448. // replace Hex colors to short safe color names
  449. $sb[] = array_key_exists($hex, $short_safe) ? $short_safe[$hex] : $hex;
  450. }
  451. $_index = $offset = $last_index - strlen($m[8]);
  452. }
  453. $sb[] = $this->str_slice($css, $_index);
  454. return implode('', $sb);
  455. }
  456. /* CALLBACKS
  457. * ---------------------------------------------------------------------------------------------
  458. */
  459. private function replace_string($matches)
  460. {
  461. $match = $matches[0];
  462. $quote = substr($match, 0, 1);
  463. // Must use addcslashes in PHP to avoid parsing of backslashes
  464. $match = addcslashes($this->str_slice($match, 1, -1), '\\');
  465. // maybe the string contains a comment-like substring?
  466. // one, maybe more? put'em back then
  467. if (($pos = $this->index_of($match, self::COMMENT)) >= 0) {
  468. for ($i = 0, $max = count($this->comments); $i < $max; $i++) {
  469. $match = preg_replace('/' . self::COMMENT . $i . '___/', $this->comments[$i], $match, 1);
  470. }
  471. }
  472. // minify alpha opacity in filter strings
  473. $match = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $match);
  474. $this->preserved_tokens[] = $match;
  475. return $quote . self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . $quote;
  476. }
  477. private function replace_colon($matches)
  478. {
  479. return preg_replace('/\:/', self::CLASSCOLON, $matches[0]);
  480. }
  481. private function replace_calc($matches)
  482. {
  483. $this->preserved_tokens[] = trim(preg_replace('/\s*([\*\/\(\),])\s*/', '$1', $matches[2]));
  484. return 'calc('. self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . ')';
  485. }
  486. private function rgb_to_hex($matches)
  487. {
  488. // Support for percentage values rgb(100%, 0%, 45%);
  489. if ($this->index_of($matches[1], '%') >= 0){
  490. $rgbcolors = explode(',', str_replace('%', '', $matches[1]));
  491. for ($i = 0; $i < count($rgbcolors); $i++) {
  492. $rgbcolors[$i] = $this->round_number(floatval($rgbcolors[$i]) * 2.55);
  493. }
  494. } else {
  495. $rgbcolors = explode(',', $matches[1]);
  496. }
  497. // Values outside the sRGB color space should be clipped (0-255)
  498. for ($i = 0; $i < count($rgbcolors); $i++) {
  499. $rgbcolors[$i] = $this->clamp_number(intval($rgbcolors[$i], 10), 0, 255);
  500. $rgbcolors[$i] = sprintf("%02x", $rgbcolors[$i]);
  501. }
  502. // Fix for issue #2528093
  503. if (!preg_match('/[\s\,\);\}]/', $matches[2])){
  504. $matches[2] = ' ' . $matches[2];
  505. }
  506. return '#' . implode('', $rgbcolors) . $matches[2];
  507. }
  508. private function hsl_to_hex($matches)
  509. {
  510. $values = explode(',', str_replace('%', '', $matches[1]));
  511. $h = floatval($values[0]);
  512. $s = floatval($values[1]);
  513. $l = floatval($values[2]);
  514. // Wrap and clamp, then fraction!
  515. $h = ((($h % 360) + 360) % 360) / 360;
  516. $s = $this->clamp_number($s, 0, 100) / 100;
  517. $l = $this->clamp_number($l, 0, 100) / 100;
  518. if ($s == 0) {
  519. $r = $g = $b = $this->round_number(255 * $l);
  520. } else {
  521. $v2 = $l < 0.5 ? $l * (1 + $s) : ($l + $s) - ($s * $l);
  522. $v1 = (2 * $l) - $v2;
  523. $r = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h + (1/3)));
  524. $g = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h));
  525. $b = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h - (1/3)));
  526. }
  527. return $this->rgb_to_hex(array('', $r.','.$g.','.$b, $matches[2]));
  528. }
  529. private function lowercase_pseudo_first($matches)
  530. {
  531. return ':first-'. strtolower($matches[1]) .' '. $matches[2];
  532. }
  533. private function lowercase_directives($matches)
  534. {
  535. return '@'. strtolower($matches[1]);
  536. }
  537. private function lowercase_pseudo_elements($matches)
  538. {
  539. return ':'. strtolower($matches[1]);
  540. }
  541. private function lowercase_common_functions($matches)
  542. {
  543. return ':'. strtolower($matches[1]) .'(';
  544. }
  545. private function lowercase_common_functions_values($matches)
  546. {
  547. return $matches[1] . strtolower($matches[2]);
  548. }
  549. private function lowercase_properties($matches)
  550. {
  551. return $matches[1].strtolower($matches[2]).$matches[3];
  552. }
  553. /* HELPERS
  554. * ---------------------------------------------------------------------------------------------
  555. */
  556. private function hue_to_rgb($v1, $v2, $vh)
  557. {
  558. $vh = $vh < 0 ? $vh + 1 : ($vh > 1 ? $vh - 1 : $vh);
  559. if ($vh * 6 < 1) return $v1 + ($v2 - $v1) * 6 * $vh;
  560. if ($vh * 2 < 1) return $v2;
  561. if ($vh * 3 < 2) return $v1 + ($v2 - $v1) * ((2/3) - $vh) * 6;
  562. return $v1;
  563. }
  564. private function round_number($n)
  565. {
  566. return intval(floor(floatval($n) + 0.5), 10);
  567. }
  568. private function clamp_number($n, $min, $max)
  569. {
  570. return min(max($n, $min), $max);
  571. }
  572. /**
  573. * PHP port of Javascript's "indexOf" function for strings only
  574. * Author: Tubal Martin http://blog.margenn.com
  575. *
  576. * @param string $haystack
  577. * @param string $needle
  578. * @param int $offset index (optional)
  579. * @return int
  580. */
  581. private function index_of($haystack, $needle, $offset = 0)
  582. {
  583. $index = strpos($haystack, $needle, $offset);
  584. return ($index !== FALSE) ? $index : -1;
  585. }
  586. /**
  587. * PHP port of Javascript's "slice" function for strings only
  588. * Author: Tubal Martin http://blog.margenn.com
  589. * Tests: http://margenn.com/tubal/str_slice/
  590. *
  591. * @param string $str
  592. * @param int $start index
  593. * @param int|bool $end index (optional)
  594. * @return string
  595. */
  596. private function str_slice($str, $start = 0, $end = FALSE)
  597. {
  598. if ($end !== FALSE && ($start < 0 || $end <= 0)) {
  599. $max = strlen($str);
  600. if ($start < 0) {
  601. if (($start = $max + $start) < 0) {
  602. return '';
  603. }
  604. }
  605. if ($end < 0) {
  606. if (($end = $max + $end) < 0) {
  607. return '';
  608. }
  609. }
  610. if ($end <= $start) {
  611. return '';
  612. }
  613. }
  614. $slice = ($end === FALSE) ? substr($str, $start) : substr($str, $start, $end - $start);
  615. return ($slice === FALSE) ? '' : $slice;
  616. }
  617. /**
  618. * Convert strings like "64M" or "30" to int values
  619. * @param mixed $size
  620. * @return int
  621. */
  622. private function normalize_int($size)
  623. {
  624. if (is_string($size)) {
  625. switch (substr($size, -1)) {
  626. case 'M': case 'm': return $size * 1048576;
  627. case 'K': case 'k': return $size * 1024;
  628. case 'G': case 'g': return $size * 1073741824;
  629. }
  630. }
  631. return (int) $size;
  632. }
  633. }