4 * CSSTidy - CSS Parser and Optimiser
8 * Copyright 2005, 2006, 2007 Florian Schmitz
10 * This file is part of CSSTidy.
12 * CSSTidy is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Lesser General Public License as published by
14 * the Free Software Foundation; either version 2.1 of the License, or
15 * (at your option) any later version.
17 * CSSTidy is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 * @license http://opensource.org/licenses/lgpl-license.php GNU Lesser General Public License
27 * @author Florian Schmitz (floele at gmail dot com) 2005-2007
28 * @author Brett Zamir (brettz9 at yahoo dot com) 2007
29 * @author Nikolay Matsievsky (speed at webo dot name) 2009-2010
30 * @author Cedric Morin (cedric at yterium dot com) 2010-2012
31 * @author Christopher Finke (cfinke at gmail.com) 2012
32 * @author Mark Scherer (remove $GLOBALS once and for all + PHP5.4 comp) 2012
36 * Defines ctype functions if required.
38 * @TODO: Make these methods of CSSTidy.
41 if (!function_exists('ctype_space')){
42 /* ctype_space Check for whitespace character(s) */
43 function ctype_space($text){
44 return (1===preg_match("/^[ \r\n\t\f]+$/", $text));
47 if (!function_exists('ctype_alpha')){
48 /* ctype_alpha Check for alphabetic character(s) */
49 function ctype_alpha($text){
50 return (1===preg_match('/^[a-zA-Z]+$/', $text));
53 if (!function_exists('ctype_xdigit')){
54 /* ctype_xdigit Check for HEX character(s) */
55 function ctype_xdigit($text){
56 return (1===preg_match('/^[a-fA-F0-9]+$/', $text));
62 * @todo //TODO: make them class constants of csstidy
64 define('AT_START', 1);
66 define('SEL_START', 3);
68 define('PROPERTY', 5);
71 define('DEFAULT_AT', 41);
74 * Contains a class for printing CSS code
78 require('class.csstidy_print.php');
81 * Contains a class for optimising CSS code
85 require('class.csstidy_optimise.php');
90 * This class represents a CSS parser which reads CSS code and saves it in an array.
91 * In opposite to most other CSS parsers, it does not use regular expressions and
92 * thus has full CSS2 support and a higher reliability.
93 * Additional to that it applies some optimisations and fixes to the CSS code.
94 * An online version should be available here: http://cdburnerxp.se/cssparse/css_optimiser.php
96 * @author Florian Schmitz (floele at gmail dot com) 2005-2006
102 * Saves the parsed CSS. This array is empty if preserve_css is on.
106 public $css = array();
108 * Saves the parsed CSS (raw)
112 public $tokens = array();
122 * @see csstidy_optimise
128 * Saves the CSS charset (@charset)
132 public $charset = '';
134 * Saves all @import URLs
138 public $import = array();
140 * Saves the namespace
144 public $namespace = '';
146 * Contains the version of csstidy
150 public $version = '1.5.5';
152 * Stores the settings
156 public $settings = array();
158 * Saves the parser-status.
164 * - instr = in string (started at " or ' or ( )
165 * - ic = in comment (ignore everything)
171 public $status = 'is';
173 * Saves the current at rule (@media)
179 * Saves the at rule for next selector (during @font-face or other @)
183 public $next_selector_at = '';
186 * Saves the current selector
190 public $selector = '';
192 * Saves the current property
196 public $property = '';
198 * Saves the position of , in selectors
202 public $sel_separate = array();
204 * Saves the current value
210 * Saves the current sub-value
212 * Example for a subvalue:
213 * background:url(foo.png) red no-repeat;
214 * "url(foo.png)", "red", and "no-repeat" are subvalues,
215 * seperated by whitespace
219 public $sub_value = '';
221 * Array which saves all subvalues for a property.
226 public $sub_value_arr = array();
228 * Saves the stack of characters that opened the current strings
232 public $str_char = array();
233 public $cur_string = array();
235 * Status from which the parser switched to ic or instr
239 public $from = array();
242 * =true if in invalid at-rule
246 public $invalid_at = false;
248 * =true if something has been added to the current selector
252 public $added = false;
254 * Array which saves the message log
258 public $log = array();
260 * Saves the line number
266 * Marks if we need to leave quotes for a string
270 public $quoted_string = array();
276 public $tokens_list = "";
279 * Various CSS Data for CSSTidy
282 public $data = array();
285 * Loads standard template and sets default settings
289 public function __construct() {
291 include('data.inc.php');
294 $this->settings
['remove_bslash'] = true;
295 $this->settings
['compress_colors'] = true;
296 $this->settings
['compress_font-weight'] = true;
297 $this->settings
['lowercase_s'] = false;
299 1 common shorthands optimization
300 2 + font property optimization
301 3 + background property optimization
303 $this->settings
['optimise_shorthands'] = 1;
304 $this->settings
['remove_last_;'] = true;
305 $this->settings
['space_before_important'] = false;
306 /* rewrite all properties with low case, better for later gzip OK, safe*/
307 $this->settings
['case_properties'] = 1;
308 /* sort properties in alpabetic order, better for later gzip
309 * but can cause trouble in case of overiding same propertie or using hack
311 $this->settings
['sort_properties'] = false;
313 1, 3, 5, etc -- enable sorting selectors inside @media: a{}b{}c{}
314 2, 5, 8, etc -- enable sorting selectors inside one CSS declaration: a,b,c{}
315 preserve order by default cause it can break functionnality
317 $this->settings
['sort_selectors'] = 0;
318 /* is dangeroues to be used: CSS is broken sometimes */
319 $this->settings
['merge_selectors'] = 0;
320 /* preserve or not browser hacks */
321 $this->settings
['discard_invalid_selectors'] = false;
322 $this->settings
['discard_invalid_properties'] = false;
323 $this->settings
['css_level'] = 'CSS3.0';
324 $this->settings
['preserve_css'] = false;
325 $this->settings
['timestamp'] = false;
326 $this->settings
['template'] = ''; // say that propertie exist
327 $this->set_cfg('template','default'); // call load_template
328 $this->optimise
= new csstidy_optimise($this);
330 $this->tokens_list
= & $this->data
['csstidy']['tokens'];
334 * Get the value of a setting.
335 * @param string $setting
340 public function get_cfg($setting) {
341 if (isset($this->settings
[$setting])) {
342 return $this->settings
[$setting];
349 * @param string $template used by set_cfg to load a template via a configuration setting
353 public function _load_template($template) {
356 $this->load_template('default');
360 $this->load_template('highest_compression');
364 $this->load_template('high_compression');
368 $this->load_template('low_compression');
372 $this->load_template($template);
378 * Set the value of a setting.
379 * @param string $setting
380 * @param mixed $value
385 public function set_cfg($setting, $value=null) {
386 if (is_array($setting) && $value === null) {
387 foreach ($setting as $setprop => $setval) {
388 $this->settings
[$setprop] = $setval;
390 if (array_key_exists('template', $setting)) {
391 $this->_load_template($this->settings
['template']);
394 } elseif (isset($this->settings
[$setting]) && $value !== '') {
395 $this->settings
[$setting] = $value;
396 if ($setting === 'template') {
397 $this->_load_template($this->settings
['template']);
405 * Adds a token to $this->tokens
407 * @param string $data
408 * @param bool $do add a token even if preserve_css is off
412 public function _add_token($type, $data, $do = false) {
413 if ($this->get_cfg('preserve_css') ||
$do) {
414 $this->tokens
[] = array($type, ($type == COMMENT
) ?
$data : trim($data));
419 * Add a message to the message log
420 * @param string $message
421 * @param string $type
422 * @param integer $line
426 public function log($message, $type, $line = -1) {
430 $line = intval($line);
431 $add = array('m' => $message, 't' => $type);
432 if (!isset($this->log
[$line]) ||
!in_array($add, $this->log
[$line])) {
433 $this->log
[$line][] = $add;
438 * Parse unicode notations and find a replacement character
439 * @param string $string
445 public function _unicode(&$string, &$i) {
450 while ($i < strlen($string) && (ctype_xdigit($string{$i}) ||
ctype_space($string{$i})) && strlen($add) < 6) {
453 if (ctype_space($string{$i})) {
459 if (hexdec($add) > 47 && hexdec($add) < 58 ||
hexdec($add) > 64 && hexdec($add) < 91 ||
hexdec($add) > 96 && hexdec($add) < 123) {
460 $this->log('Replaced unicode notation: Changed \\' . $add . ' to ' . chr(hexdec($add)), 'Information');
461 $add = chr(hexdec($add));
464 $add = trim('\\' . $add);
467 if (@ctype_xdigit
($string{$i +
1}) && ctype_space($string{$i})
468 && !$replaced ||
!ctype_space($string{$i})) {
472 if ($add !== '\\' ||
!$this->get_cfg('remove_bslash') ||
strpos($this->tokens_list
, $string{$i +
1}) !== false) {
477 $this->log('Removed unnecessary backslash', 'Information');
483 * Write formatted output to a file
484 * @param string $filename
485 * @param string $doctype when printing formatted, is a shorthand for the document type
486 * @param bool $externalcss when printing formatted, indicates whether styles to be attached internally or as an external stylesheet
487 * @param string $title when printing formatted, is the title to be added in the head of the document
488 * @param string $lang when printing formatted, gives a two-letter language code to be added to the output
492 public function write_page($filename, $doctype='xhtml1.1', $externalcss=true, $title='', $lang='en') {
493 $this->write($filename, true);
497 * Write plain output to a file
498 * @param string $filename
499 * @param bool $formatted whether to print formatted or not
500 * @param string $doctype when printing formatted, is a shorthand for the document type
501 * @param bool $externalcss when printing formatted, indicates whether styles to be attached internally or as an external stylesheet
502 * @param string $title when printing formatted, is the title to be added in the head of the document
503 * @param string $lang when printing formatted, gives a two-letter language code to be added to the output
504 * @param bool $pre_code whether to add pre and code tags around the code (for light HTML formatted templates)
508 public function write($filename, $formatted=false, $doctype='xhtml1.1', $externalcss=true, $title='', $lang='en', $pre_code=true) {
509 $filename .= ( $formatted) ?
'.xhtml' : '.css';
511 if (!is_dir('temp')) {
512 $madedir = mkdir('temp');
514 print 'Could not make directory "temp" in ' . dirname(__FILE__
);
518 $handle = fopen('temp/' . $filename, 'w');
521 fwrite($handle, $this->print->plain());
523 fwrite($handle, $this->print->formatted_page($doctype, $externalcss, $title, $lang, $pre_code));
530 * Loads a new template
531 * @param string $content either filename (if $from_file == true), content of a template file, "high_compression", "highest_compression", "low_compression", or "default"
532 * @param bool $from_file uses $content as filename if true
535 * @see http://csstidy.sourceforge.net/templates.php
537 public function load_template($content, $from_file=true) {
538 $predefined_templates = & $this->data
['csstidy']['predefined_templates'];
539 if ($content === 'high_compression' ||
$content === 'default' ||
$content === 'highest_compression' ||
$content === 'low_compression') {
540 $this->template
= $predefined_templates[$content];
546 $content = strip_tags(file_get_contents($content), '<span>');
548 $content = str_replace("\r\n", "\n", $content); // Unify newlines (because the output also only uses \n)
549 $template = explode('|', $content);
551 for ($i = 0; $i < count($template); $i++
) {
552 $this->template
[$i] = $template[$i];
557 * Starts parsing from URL
562 public function parse_from_url($url) {
563 return $this->parse(@file_get_contents
($url));
567 * Checks if there is a token at the current position
568 * @param string $string
573 public function is_token(&$string, $i) {
574 return (strpos($this->tokens_list
, $string{$i}) !== false && !$this->escaped($string, $i));
578 * Parses CSS in $string. The code is saved as array in $this->css
579 * @param string $string the CSS code
584 public function parse($string) {
585 // Temporarily set locale to en_US in order to handle floats properly
586 $old = @setlocale
(LC_ALL
, 0);
587 @setlocale
(LC_ALL
, 'C');
589 // PHP bug? Settings need to be refreshed in PHP4
590 $this->print = new csstidy_print($this);
591 $this->optimise
= new csstidy_optimise($this);
593 $all_properties = & $this->data
['csstidy']['all_properties'];
594 $at_rules = & $this->data
['csstidy']['at_rules'];
595 $quoted_string_properties = & $this->data
['csstidy']['quoted_string_properties'];
597 $this->css
= array();
598 $this->print->input_css
= $string;
599 $string = str_replace("\r\n", "\n", $string) . ' ';
602 for ($i = 0, $size = strlen($string); $i < $size; $i++
) {
603 if ($string{$i} === "\n" ||
$string{$i} === "\r") {
607 switch ($this->status
) {
608 /* Case in at-block */
610 if ($this->is_token($string, $i)) {
611 if ($string{$i} === '/' && @$string{$i +
1} === '*') {
612 $this->status
= 'ic';
614 $this->from
[] = 'at';
615 } elseif ($string{$i} === '{') {
616 $this->status
= 'is';
617 $this->at
= $this->css_new_media_section($this->at
);
618 $this->_add_token(AT_START
, $this->at
);
619 } elseif ($string{$i} === ',') {
620 $this->at
= trim($this->at
) . ',';
621 } elseif ($string{$i} === '\\') {
622 $this->at
.= $this->_unicode($string, $i);
624 // fix for complicated media, i.e @media screen and (-webkit-min-device-pixel-ratio:1.5)
625 elseif (in_array($string{$i}, array('(', ')', ':', '.', '/'))) {
626 $this->at
.= $string{$i};
629 $lastpos = strlen($this->at
) - 1;
630 if (!( (ctype_space($this->at
{$lastpos}) ||
$this->is_token($this->at
, $lastpos) && $this->at
{$lastpos} === ',') && ctype_space($string{$i}))) {
631 $this->at
.= $string{$i};
636 /* Case in-selector */
638 if ($this->is_token($string, $i)) {
639 if ($string{$i} === '/' && @$string{$i +
1} === '*' && trim($this->selector
) == '') {
640 $this->status
= 'ic';
642 $this->from
[] = 'is';
643 } elseif ($string{$i} === '@' && trim($this->selector
) == '') {
645 $this->invalid_at
= true;
646 foreach ($at_rules as $name => $type) {
647 if (!strcasecmp(substr($string, $i +
1, strlen($name)), $name)) {
648 ($type === 'at') ?
$this->at
= '@' . $name : $this->selector
= '@' . $name;
649 if ($type === 'atis') {
650 $this->next_selector_at
= ($this->next_selector_at?
$this->next_selector_at
:($this->at?
$this->at
:DEFAULT_AT
));
651 $this->at
= $this->css_new_media_section(' ');
654 $this->status
= $type;
656 $this->invalid_at
= false;
660 if ($this->invalid_at
) {
661 $this->selector
= '@';
662 $invalid_at_name = '';
663 for ($j = $i +
1; $j < $size; ++
$j) {
664 if (!ctype_alpha($string{$j})) {
667 $invalid_at_name .= $string{$j};
669 $this->log('Invalid @-rule: ' . $invalid_at_name . ' (removed)', 'Warning');
671 } elseif (($string{$i} === '"' ||
$string{$i} === "'")) {
672 $this->cur_string
[] = $string{$i};
673 $this->status
= 'instr';
674 $this->str_char
[] = $string{$i};
675 $this->from
[] = 'is';
676 /* fixing CSS3 attribute selectors, i.e. a[href$=".mp3" */
677 $this->quoted_string
[] = ($string{$i - 1} === '=' );
678 } elseif ($this->invalid_at
&& $string{$i} === ';') {
679 $this->invalid_at
= false;
680 $this->status
= 'is';
681 if ($this->next_selector_at
) {
682 $this->at
= $this->css_new_media_section($this->next_selector_at
);
683 $this->next_selector_at
= '';
685 } elseif ($string{$i} === '{') {
686 $this->status
= 'ip';
687 if ($this->at
== '') {
688 $this->at
= $this->css_new_media_section(DEFAULT_AT
);
690 $this->selector
= $this->css_new_selector($this->at
,$this->selector
);
691 $this->_add_token(SEL_START
, $this->selector
);
692 $this->added
= false;
693 } elseif ($string{$i} === '}') {
694 $this->_add_token(AT_END
, $this->at
);
696 $this->selector
= '';
697 $this->sel_separate
= array();
698 } elseif ($string{$i} === ',') {
699 $this->selector
= trim($this->selector
) . ',';
700 $this->sel_separate
[] = strlen($this->selector
);
701 } elseif ($string{$i} === '\\') {
702 $this->selector
.= $this->_unicode($string, $i);
703 } elseif ($string{$i} === '*' && @in_array
($string{$i +
1}, array('.', '#', '[', ':')) && ($i==0 OR $string{$i - 1}!=='/')) {
704 // remove unnecessary universal selector, FS#147, but not comment in selector
706 $this->selector
.= $string{$i};
709 $lastpos = strlen($this->selector
) - 1;
710 if ($lastpos == -1 ||
!( (ctype_space($this->selector
{$lastpos}) ||
$this->is_token($this->selector
, $lastpos) && $this->selector
{$lastpos} === ',') && ctype_space($string{$i}))) {
711 $this->selector
.= $string{$i};
716 /* Case in-property */
718 if ($this->is_token($string, $i)) {
719 if (($string{$i} === ':' ||
$string{$i} === '=') && $this->property
!= '') {
720 $this->status
= 'iv';
721 if (!$this->get_cfg('discard_invalid_properties') ||
$this->property_is_valid($this->property
)) {
722 $this->property
= $this->css_new_property($this->at
,$this->selector
,$this->property
);
723 $this->_add_token(PROPERTY
, $this->property
);
725 } elseif ($string{$i} === '/' && @$string{$i +
1} === '*' && $this->property
== '') {
726 $this->status
= 'ic';
728 $this->from
[] = 'ip';
729 } elseif ($string{$i} === '}') {
730 $this->explode_selectors();
731 $this->status
= 'is';
732 $this->invalid_at
= false;
733 $this->_add_token(SEL_END
, $this->selector
);
734 $this->selector
= '';
735 $this->property
= '';
736 if ($this->next_selector_at
) {
737 $this->at
= $this->css_new_media_section($this->next_selector_at
);
738 $this->next_selector_at
= '';
740 } elseif ($string{$i} === ';') {
741 $this->property
= '';
742 } elseif ($string{$i} === '\\') {
743 $this->property
.= $this->_unicode($string, $i);
745 // else this is dumb IE a hack, keep it
747 elseif (($this->property
=== '' && !ctype_space($string{$i}))
748 ||
($this->property
=== '/' ||
$string{$i} === '/')) {
749 $this->property
.= $string{$i};
751 } elseif (!ctype_space($string{$i})) {
752 $this->property
.= $string{$i};
758 $pn = (($string{$i} === "\n" ||
$string{$i} === "\r") && $this->property_is_next($string, $i +
1) ||
$i == strlen($string) - 1);
759 if ($this->is_token($string, $i) ||
$pn) {
760 if ($string{$i} === '/' && @$string{$i +
1} === '*') {
761 $this->status
= 'ic';
763 $this->from
[] = 'iv';
764 } elseif (($string{$i} === '"' ||
$string{$i} === "'" ||
$string{$i} === '(')) {
765 $this->cur_string
[] = $string{$i};
766 $this->str_char
[] = ($string{$i} === '(') ?
')' : $string{$i};
767 $this->status
= 'instr';
768 $this->from
[] = 'iv';
769 $this->quoted_string
[] = in_array(strtolower($this->property
), $quoted_string_properties);
770 } elseif ($string{$i} === ',') {
771 $this->sub_value
= trim($this->sub_value
) . ',';
772 } elseif ($string{$i} === '\\') {
773 $this->sub_value
.= $this->_unicode($string, $i);
774 } elseif ($string{$i} === ';' ||
$pn) {
775 if ($this->selector
{0} === '@' && isset($at_rules[substr($this->selector
, 1)]) && $at_rules[substr($this->selector
, 1)] === 'iv') {
776 /* Add quotes to charset, import, namespace */
777 $this->sub_value_arr
[] = trim($this->sub_value
);
779 $this->status
= 'is';
781 switch ($this->selector
) {
782 case '@charset': $this->charset
= '"'.$this->sub_value_arr
[0].'"';
784 case '@namespace': $this->namespace = implode(' ', $this->sub_value_arr
);
786 case '@import': $this->import
[] = implode(' ', $this->sub_value_arr
);
790 $this->sub_value_arr
= array();
791 $this->sub_value
= '';
792 $this->selector
= '';
793 $this->sel_separate
= array();
795 $this->status
= 'ip';
797 } elseif ($string{$i} !== '}') {
798 $this->sub_value
.= $string{$i};
800 if (($string{$i} === '}' ||
$string{$i} === ';' ||
$pn) && !empty($this->selector
)) {
801 if ($this->at
== '') {
802 $this->at
= $this->css_new_media_section(DEFAULT_AT
);
806 if ($this->get_cfg('lowercase_s')) {
807 $this->selector
= strtolower($this->selector
);
809 $this->property
= strtolower($this->property
);
811 $this->optimise
->subvalue();
812 if ($this->sub_value
!= '') {
813 $this->sub_value_arr
[] = $this->sub_value
;
814 $this->sub_value
= '';
818 while (count($this->sub_value_arr
)) {
819 $sub = array_shift($this->sub_value_arr
);
820 if (strstr($this->selector
, 'font-face')) {
821 $sub = $this->quote_font_format($sub);
825 $this->value
.= ((!strlen($this->value
) ||
substr($this->value
,-1,1) === ',')?
'':' ').$sub;
828 $this->optimise
->value();
830 $valid = $this->property_is_valid($this->property
);
831 if ((!$this->invalid_at ||
$this->get_cfg('preserve_css')) && (!$this->get_cfg('discard_invalid_properties') ||
$valid)) {
832 $this->css_add_property($this->at
, $this->selector
, $this->property
, $this->value
);
833 $this->_add_token(VALUE
, $this->value
);
834 $this->optimise
->shorthands();
837 if ($this->get_cfg('discard_invalid_properties')) {
838 $this->log('Removed invalid property: ' . $this->property
, 'Warning');
840 $this->log('Invalid property in ' . strtoupper($this->get_cfg('css_level')) . ': ' . $this->property
, 'Warning');
844 $this->property
= '';
845 $this->sub_value_arr
= array();
848 if ($string{$i} === '}') {
849 $this->explode_selectors();
850 $this->_add_token(SEL_END
, $this->selector
);
851 $this->status
= 'is';
852 $this->invalid_at
= false;
853 $this->selector
= '';
854 if ($this->next_selector_at
) {
855 $this->at
= $this->css_new_media_section($this->next_selector_at
);
856 $this->next_selector_at
= '';
860 $this->sub_value
.= $string{$i};
862 if (ctype_space($string{$i})) {
863 $this->optimise
->subvalue();
864 if ($this->sub_value
!= '') {
865 $this->sub_value_arr
[] = $this->sub_value
;
866 $this->sub_value
= '';
874 $_str_char = $this->str_char
[count($this->str_char
)-1];
875 $_cur_string = $this->cur_string
[count($this->cur_string
)-1];
876 $_quoted_string = $this->quoted_string
[count($this->quoted_string
)-1];
877 $temp_add = $string{$i};
879 // Add another string to the stack. Strings can't be nested inside of quotes, only parentheses, but
880 // parentheticals can be nested more than once.
881 if ($_str_char === ")" && ($string{$i} === "(" ||
$string{$i} === '"' ||
$string{$i} === '\'') && !$this->escaped($string, $i)) {
882 $this->cur_string
[] = $string{$i};
883 $this->str_char
[] = $string{$i} === '(' ?
')' : $string{$i};
884 $this->from
[] = 'instr';
885 $this->quoted_string
[] = ($_str_char === ')' && $string{$i} !== '(' && trim($_cur_string)==='(')?
$_quoted_string:!($string{$i} === '(');
889 if ($_str_char !== ")" && ($string{$i} === "\n" ||
$string{$i} === "\r") && !($string{$i - 1} === '\\' && !$this->escaped($string, $i - 1))) {
891 $this->log('Fixed incorrect newline in string', 'Warning');
894 $_cur_string .= $temp_add;
896 if ($string{$i} === $_str_char && !$this->escaped($string, $i)) {
897 $this->status
= array_pop($this->from
);
899 if (!preg_match('|[' . implode('', $this->data
['csstidy']['whitespace']) . ']|uis', $_cur_string) && $this->property
!== 'content') {
900 if (!$_quoted_string) {
901 if ($_str_char !== ')') {
902 // Convert properties like
903 // font-family: 'Arial';
905 // font-family: Arial;
910 $_cur_string = substr($_cur_string, 1, -1);
913 $_quoted_string = false;
917 array_pop($this->cur_string
);
918 array_pop($this->quoted_string
);
919 array_pop($this->str_char
);
921 if ($_str_char === ')') {
922 $_cur_string = '(' . trim(substr($_cur_string, 1, -1)) . ')';
925 if ($this->status
=== 'iv') {
926 if (!$_quoted_string) {
927 if (strpos($_cur_string,',') !== false)
928 // we can on only remove space next to ','
929 $_cur_string = implode(',', array_map('trim', explode(',',$_cur_string)));
930 // and multiple spaces (too expensive)
931 if (strpos($_cur_string, ' ') !== false)
932 $_cur_string = preg_replace(",\s+,", ' ', $_cur_string);
934 $this->sub_value
.= $_cur_string;
935 } elseif ($this->status
=== 'is') {
936 $this->selector
.= $_cur_string;
937 } elseif ($this->status
=== 'instr') {
938 $this->cur_string
[count($this->cur_string
)-1] .= $_cur_string;
941 $this->cur_string
[count($this->cur_string
)-1] = $_cur_string;
945 /* Case in-comment */
947 if ($string{$i} === '*' && $string{$i +
1} === '/') {
948 $this->status
= array_pop($this->from
);
950 $this->_add_token(COMMENT
, $cur_comment);
953 $cur_comment .= $string{$i};
959 $this->optimise
->postparse();
961 $this->print->_reset();
963 @setlocale
(LC_ALL
, $old); // Set locale back to original setting
965 return!(empty($this->css
) && empty($this->import
) && empty($this->charset
) && empty($this->tokens
) && empty($this->namespace));
970 * format() in font-face needs quoted values for somes browser (FF at least)
975 public function quote_font_format($value) {
976 if (strncmp($value,'format',6) == 0) {
977 $p = strpos($value,')',7);
978 $end = substr($value,$p);
979 $format_strings = $this->parse_string_list(substr($value, 7, $p-7));
980 if (!$format_strings) {
985 foreach ($format_strings as $format_string) {
986 $value .= '"' . str_replace('"', '\\"', $format_string) . '",';
989 $value = substr($value, 0, -1) . $end;
1000 public function explode_selectors() {
1001 // Explode multiple selectors
1002 if ($this->get_cfg('merge_selectors') === 1) {
1003 $new_sels = array();
1005 $this->sel_separate
[] = strlen($this->selector
);
1006 foreach ($this->sel_separate
as $num => $pos) {
1007 if ($num == count($this->sel_separate
) - 1) {
1011 $new_sels[] = substr($this->selector
, $lastpos, $pos - $lastpos - 1);
1015 if (count($new_sels) > 1) {
1016 foreach ($new_sels as $selector) {
1017 if (isset($this->css
[$this->at
][$this->selector
])) {
1018 $this->merge_css_blocks($this->at
, $selector, $this->css
[$this->at
][$this->selector
]);
1021 unset($this->css
[$this->at
][$this->selector
]);
1024 $this->sel_separate
= array();
1028 * Checks if a character is escaped (and returns true if it is)
1029 * @param string $string
1030 * @param integer $pos
1035 static function escaped(&$string, $pos) {
1036 return!(@($string{$pos - 1} !== '\\') || csstidy
::escaped($string, $pos - 1));
1040 * Adds a property with value to the existing CSS code
1041 * @param string $media
1042 * @param string $selector
1043 * @param string $property
1044 * @param string $new_val
1048 public function css_add_property($media, $selector, $property, $new_val) {
1049 if ($this->get_cfg('preserve_css') ||
trim($new_val) == '') {
1053 $this->added
= true;
1054 if (isset($this->css
[$media][$selector][$property])) {
1055 if (($this->is_important($this->css
[$media][$selector][$property]) && $this->is_important($new_val)) ||
!$this->is_important($this->css
[$media][$selector][$property])) {
1056 $this->css
[$media][$selector][$property] = trim($new_val);
1059 $this->css
[$media][$selector][$property] = trim($new_val);
1064 * Start a new media section.
1065 * Check if the media is not already known,
1066 * else rename it with extra spaces
1069 * @param string $media
1072 public function css_new_media_section($media) {
1073 if ($this->get_cfg('preserve_css')) {
1077 // if the last @media is the same as this
1079 if (!$this->css ||
!is_array($this->css
) ||
empty($this->css
)) {
1083 list($at,) = each($this->css
);
1084 if ($at == $media) {
1087 while (isset($this->css
[$media]))
1088 if (is_numeric($media))
1096 * Start a new selector.
1097 * If already referenced in this media section,
1098 * rename it with extra space to avoid merging
1099 * except if merging is required,
1100 * or last selector is the same (merge siblings)
1102 * never merge @font-face
1104 * @param string $media
1105 * @param string $selector
1108 public function css_new_selector($media,$selector) {
1109 if ($this->get_cfg('preserve_css')) {
1112 $selector = trim($selector);
1113 if (strncmp($selector,'@font-face',10)!=0) {
1114 if ($this->settings
['merge_selectors'] != false)
1117 if (!$this->css ||
!isset($this->css
[$media]) ||
!$this->css
[$media])
1120 // if last is the same, keep it
1121 end($this->css
[$media]);
1122 list($sel,) = each($this->css
[$media]);
1123 if ($sel == $selector) {
1128 while (isset($this->css
[$media][$selector]))
1134 * Start a new propertie.
1135 * If already references in this selector,
1136 * rename it with extra space to avoid override
1138 * @param string $media
1139 * @param string $selector
1140 * @param string $property
1143 public function css_new_property($media, $selector, $property) {
1144 if ($this->get_cfg('preserve_css')) {
1147 if (!$this->css ||
!isset($this->css
[$media][$selector]) ||
!$this->css
[$media][$selector])
1150 while (isset($this->css
[$media][$selector][$property]))
1157 * Adds CSS to an existing media/selector
1158 * @param string $media
1159 * @param string $selector
1160 * @param array $css_add
1164 public function merge_css_blocks($media, $selector, $css_add) {
1165 foreach ($css_add as $property => $value) {
1166 $this->css_add_property($media, $selector, $property, $value, false);
1171 * Checks if $value is !important.
1172 * @param string $value
1177 public function is_important(&$value) {
1179 strpos($value, '!') !== false // quick test
1180 AND !strcasecmp(substr(str_replace($this->data
['csstidy']['whitespace'], '', $value), -10, 10), '!important'));
1184 * Returns a value without !important
1185 * @param string $value
1190 public function gvw_important($value) {
1191 if ($this->is_important($value)) {
1192 $value = trim($value);
1193 $value = substr($value, 0, -9);
1194 $value = trim($value);
1195 $value = substr($value, 0, -1);
1196 $value = trim($value);
1203 * Checks if the next word in a string from pos is a CSS property
1204 * @param string $istring
1205 * @param integer $pos
1210 public function property_is_next($istring, $pos) {
1211 $all_properties = & $this->data
['csstidy']['all_properties'];
1212 $istring = substr($istring, $pos, strlen($istring) - $pos);
1213 $pos = strpos($istring, ':');
1214 if ($pos === false) {
1217 $istring = strtolower(trim(substr($istring, 0, $pos)));
1218 if (isset($all_properties[$istring])) {
1219 $this->log('Added semicolon to the end of declaration', 'Warning');
1226 * Checks if a property is valid
1227 * @param string $property
1232 public function property_is_valid($property) {
1233 if (in_array(trim($property), $this->data
['csstidy']['multiple_properties'])) $property = trim($property);
1234 $all_properties = & $this->data
['csstidy']['all_properties'];
1235 return (isset($all_properties[$property]) && strpos($all_properties[$property], strtoupper($this->get_cfg('css_level'))) !== false );
1239 * Accepts a list of strings (e.g., the argument to format() in a @font-face src property)
1240 * and returns a list of the strings. Converts things like:
1242 * format(abc) => format("abc")
1243 * format(abc def) => format("abc","def")
1244 * format(abc "def") => format("abc","def")
1245 * format(abc, def, ghi) => format("abc","def","ghi")
1246 * format("abc",'def') => format("abc","def")
1247 * format("abc, def, ghi") => format("abc, def, ghi")
1253 public function parse_string_list($value) {
1254 $value = trim($value);
1257 if (!$value) return array();
1262 $current_string = '';
1264 for ($i = 0, $_len = strlen($value); $i < $_len; $i++
) {
1265 if (($value{$i} === ',' ||
$value{$i} === ' ') && $in_str === true) {
1267 $strings[] = $current_string;
1268 $current_string = '';
1269 } elseif ($value{$i} === '"' ||
$value{$i} === "'") {
1270 if ($in_str === $value{$i}) {
1271 $strings[] = $current_string;
1273 $current_string = '';
1275 } elseif (!$in_str) {
1276 $in_str = $value{$i};
1280 $current_string .= $value{$i};
1282 if (!preg_match("/[\s,]/", $value{$i})) {
1284 $current_string = $value{$i};
1290 if ($current_string) {
1291 $strings[] = $current_string;