4 * CSSTidy - CSS Parser and Optimiser
7 * This class prints CSS data generated by csstidy.
9 * Copyright 2005, 2006, 2007 Florian Schmitz
11 * This file is part of CSSTidy.
13 * CSSTidy is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU Lesser General Public License as published by
15 * the Free Software Foundation; either version 2.1 of the License, or
16 * (at your option) any later version.
18 * CSSTidy is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License for more details.
23 * You should have received a copy of the GNU Lesser General Public License
24 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 * @license http://opensource.org/licenses/lgpl-license.php GNU Lesser General Public License
28 * @author Florian Schmitz (floele at gmail dot com) 2005-2007
29 * @author Brett Zamir (brettz9 at yahoo dot com) 2007
30 * @author Cedric Morin (cedric at yterium dot com) 2010-2012
36 * This class prints CSS data generated by csstidy.
39 * @author Florian Schmitz (floele at gmail dot com) 2005-2006
51 * Saves the input CSS string
55 public $input_css = '';
57 * Saves the formatted CSS string
61 public $output_css = '';
63 * Saves the formatted CSS string (plain text)
67 public $output_css_plain = '';
71 * @param array $css contains the class csstidy
75 public function __construct($css) {
77 $this->css
= & $css->css
;
78 $this->template
= & $css->template
;
79 $this->tokens
= & $css->tokens
;
80 $this->charset
= & $css->charset
;
81 $this->import
= & $css->import
;
82 $this->namespace = & $css->namespace;
86 * Resets output_css and output_css_plain (new css code)
90 public function _reset() {
91 $this->output_css
= '';
92 $this->output_css_plain
= '';
96 * Returns the CSS code as plain text
97 * @param string $default_media default @media to add to selectors without any @media
102 public function plain($default_media='') {
103 $this->_print(true, $default_media);
104 return $this->output_css_plain
;
108 * Returns the formatted CSS code
109 * @param string $default_media default @media to add to selectors without any @media
114 public function formatted($default_media='') {
115 $this->_print(false, $default_media);
116 return $this->output_css
;
120 * Returns the formatted CSS code to make a complete webpage
121 * @param string $doctype shorthand for the document type
122 * @param bool $externalcss indicates whether styles to be attached internally or as an external stylesheet
123 * @param string $title title to be added in the head of the document
124 * @param string $lang two-letter language code to be added to the output
129 public function formatted_page($doctype='html5', $externalcss=true, $title='', $lang='en') {
132 $doctype_output = '<!DOCTYPE html>';
134 case 'xhtml1.0strict':
135 $doctype_output = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
136 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
140 $doctype_output = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
141 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">';
145 $output = $cssparsed = '';
146 $this->output_css_plain
= & $output;
148 $output .= $doctype_output . "\n" . '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="' . $lang . '"';
149 $output .= ( $doctype === 'xhtml1.1') ?
'>' : ' lang="' . $lang . '">';
150 $output .= "\n<head>\n <title>$title</title>";
153 $output .= "\n <style type=\"text/css\">\n";
154 $cssparsed = file_get_contents('cssparsed.css');
155 $output .= $cssparsed; // Adds an invisible BOM or something, but not in css_optimised.php
156 $output .= "\n</style>";
158 $output .= "\n" . ' <link rel="stylesheet" type="text/css" href="cssparsed.css" />';
160 $output .= "\n</head>\n<body><code id=\"copytext\">";
161 $output .= $this->formatted();
162 $output .= '</code>' . "\n" . '</body></html>';
163 return $this->output_css_plain
;
167 * Returns the formatted CSS Code and saves it into $this->output_css and $this->output_css_plain
168 * @param bool $plain plain text or not
169 * @param string $default_media default @media to add to selectors without any @media
173 public function _print($plain = false, $default_media='') {
174 if ($this->output_css
&& $this->output_css_plain
) {
179 if (!$this->parser
->get_cfg('preserve_css')) {
180 $this->_convert_raw_css($default_media);
183 $template = & $this->template
;
186 $template = array_map('strip_tags', $template);
189 if ($this->parser
->get_cfg('timestamp')) {
190 array_unshift($this->tokens
, array(COMMENT
, ' CSSTidy ' . $this->parser
->version
. ': ' . date('r') . ' '));
193 if (!empty($this->charset
)) {
194 $output .= $template[0] . '@charset ' . $template[5] . $this->charset
. $template[6] . $template[13];
197 if (!empty($this->import
)) {
198 for ($i = 0, $size = count($this->import
); $i < $size; $i++
) {
199 if (substr($this->import
[$i], 0, 4) === 'url(' && substr($this->import
[$i], -1, 1) === ')') {
200 $this->import
[$i] = '"' . substr($this->import
[$i], 4, -1) . '"';
201 $this->parser
->log('Optimised @import : Removed "url("', 'Information');
203 else if (!preg_match('/^".+"$/',$this->import
[$i])) {
204 // fixes a bug for @import ".." instead of the expected @import url("..")
205 // If it comes in due to @import ".." the "" will be missing and the output will become @import .. (which is an error)
206 $this->import
[$i] = '"' . $this->import
[$i] . '"';
209 $output .= $template[0] . '@import ' . $template[5] . $this->import
[$i] . $template[6] . $template[13];
213 if (!empty($this->namespace)) {
214 if (($p=strpos($this->namespace,"url("))!==false && substr($this->namespace, -1, 1) === ')') {
215 $this->namespace = substr_replace($this->namespace,'"',$p,4);
216 $this->namespace = substr($this->namespace, 0, -1) . '"';
217 $this->parser
->log('Optimised @namespace : Removed "url("', 'Information');
219 $output .= $template[0] . '@namespace ' . $template[5] . $this->namespace . $template[6] . $template[13];
226 foreach ($this->tokens
as $key => $token) {
229 $out .= $template[0] . $this->_htmlsp($token[1], $plain) . $template[1];
231 if (!isset($in_at_out[$indent_level])) {
232 $in_at_out[$indent_level] = '';
234 $out = & $in_at_out[$indent_level];
238 if ($this->parser
->get_cfg('lowercase_s'))
239 $token[1] = strtolower($token[1]);
240 $out .= ( $token[1][0] !== '@') ?
$template[2] . $this->_htmlsp($token[1], $plain) : $template[0] . $this->_htmlsp($token[1], $plain);
241 $out .= $template[3];
245 if ($this->parser
->get_cfg('case_properties') === 2) {
246 $token[1] = strtoupper($token[1]);
247 } elseif ($this->parser
->get_cfg('case_properties') === 1) {
248 $token[1] = strtolower($token[1]);
250 $out .= $template[4] . $this->_htmlsp($token[1], $plain) . ':' . $template[5];
254 $out .= $this->_htmlsp($token[1], $plain);
255 if ($this->_seeknocomment($key, 1) == SEL_END
&& $this->parser
->get_cfg('remove_last_;')) {
256 $out .= str_replace(';', '', $template[6]);
258 $out .= $template[6];
263 $out .= $template[7];
264 if ($this->_seeknocomment($key, 1) != AT_END
)
265 $out .= $template[8];
269 if (strlen($template[10])) {
270 // indent the bloc we are closing
271 $out = str_replace("\n\n", "\r\n", $out); // don't fill empty lines
272 $out = str_replace("\n", "\n" . $template[10], $out);
273 $out = str_replace("\r\n", "\n\n", $out);
275 if ($indent_level > 1) {
276 $out = & $in_at_out[$indent_level-1];
281 $out .= $template[10] . $in_at_out[$indent_level];
282 if ($this->_seeknocomment($key, 1) != AT_END
) {
283 $out .= $template[9];
286 $out .= rtrim($template[9]);
289 unset($in_at_out[$indent_level]);
293 case IMPORTANT_COMMENT
:
295 $out .= $template[11] . '/*' . $this->_htmlsp($token[1], $plain) . '*/' . $template[12];
300 $output = trim($output);
303 $this->output_css
= $output;
306 // If using spaces in the template, don't want these to appear in the plain output
307 $this->output_css_plain
= str_replace(' ', '', $output);
312 * Gets the next token type which is $move away from $key, excluding comments
313 * @param integer $key current position
314 * @param integer $move move this far
315 * @return mixed a token type
319 public function _seeknocomment($key, $move) {
320 $go = ($move > 0) ?
1 : -1;
321 for ($i = $key +
1; abs($key - $i) - 1 < abs($move); $i +
= $go) {
322 if (!isset($this->tokens
[$i])) {
325 if ($this->tokens
[$i][0] == COMMENT
) {
329 return $this->tokens
[$i][0];
334 * Converts $this->css array to a raw array ($this->tokens)
335 * @param string $default_media default @media to add to selectors without any @media
339 public function _convert_raw_css($default_media='') {
340 $this->tokens
= array();
341 $sort_selectors = $this->parser
->get_cfg('sort_selectors');
342 $sort_properties = $this->parser
->get_cfg('sort_properties');
344 // important comment section ?
345 if (isset($this->css
['!'])) {
346 $this->parser
->_add_token(IMPORTANT_COMMENT
, rtrim($this->css
['!']), true);
347 unset($this->css
['!']);
350 foreach ($this->css
as $medium => $val) {
353 if (intval($medium) < DEFAULT_AT
) {
354 // un medium vide (contenant @font-face ou autre @) ne produit aucun conteneur
355 if (strlen(trim($medium))) {
356 $parts_to_open = explode('{', $medium);
357 foreach ($parts_to_open as $part) {
358 $this->parser
->_add_token(AT_START
, $part, true);
361 } elseif ($default_media) {
362 $this->parser
->_add_token(AT_START
, $default_media, true);
365 foreach ($val as $selector => $vali) {
366 if ($sort_properties)
368 $this->parser
->_add_token(SEL_START
, $selector, true);
371 '*' => array(), // IE7 hacks first
372 '_' => array(), // IE6 hacks
373 '/' => array(), // IE6 hacks
374 '-' => array() // IE6 hacks
376 foreach ($vali as $property => $valj) {
377 if (strncmp($property,"//",2)!==0) {
379 if ($sort_properties && preg_match('/^(\*|_|\/|-)(?!(ms|moz|o\b|xv|atsc|wap|khtml|webkit|ah|hp|ro|rim|tc)-)/', $property, $matches)) {
380 $invalid[$matches[1]][$property] = $valj;
382 $this->parser
->_add_token(PROPERTY
, $property, true);
383 $this->parser
->_add_token(VALUE
, $valj, true);
387 foreach ($invalid as $prefix => $props) {
388 foreach ($props as $property => $valj) {
389 $this->parser
->_add_token(PROPERTY
, $property, true);
390 $this->parser
->_add_token(VALUE
, $valj, true);
393 $this->parser
->_add_token(SEL_END
, $selector, true);
396 if (intval($medium) < DEFAULT_AT
) {
397 // un medium vide (contenant @font-face ou autre @) ne produit aucun conteneur
398 if (strlen(trim($medium))) {
399 $parts_to_close = explode('{', $medium);
400 foreach (array_reverse($parts_to_close) as $part) {
401 $this->parser
->_add_token(AT_END
, $part, true);
404 } elseif ($default_media) {
405 $this->parser
->_add_token(AT_END
, $default_media, true);
411 * Same as htmlspecialchars, only that chars are not replaced if $plain !== true. This makes print_code() cleaner.
412 * @param string $string
415 * @see csstidy_print::_print()
419 public function _htmlsp($string, $plain) {
421 return htmlspecialchars($string, ENT_QUOTES
, 'utf-8');
427 * Get compression ratio
432 public function get_ratio() {
433 if (!$this->output_css_plain
) {
436 return round((strlen($this->input_css
) - strlen($this->output_css_plain
)) / strlen($this->input_css
), 3) * 100;
440 * Get difference between the old and new code in bytes and prints the code if necessary.
445 public function get_diff() {
446 if (!$this->output_css_plain
) {
450 $diff = strlen($this->output_css_plain
) - strlen($this->input_css
);
454 } elseif ($diff == 0) {
462 * Get the size of either input or output CSS in KB
463 * @param string $loc default is "output"
468 public function size($loc = 'output') {
469 if ($loc === 'output' && !$this->output_css
) {
473 if ($loc === 'input') {
474 return (strlen($this->input_css
) / 1000);
476 return (strlen($this->output_css_plain
) / 1000);