PageRenderTime 52ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/application/libraries/CSSmin.php

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