Fix incorrect PEARSax3 test assertion.
[htmlpurifier.git] / library / HTMLPurifier / Generator.php
blobe6221db760950ed628dab0cdbeb25fe4037f0711
1 <?php
3 /**
4 * Generates HTML from tokens.
5 * @todo Refactor interface so that configuration/context is determined
6 * upon instantiation, no need for messy generateFromTokens() calls
7 * @todo Make some of the more internal functions protected, and have
8 * unit tests work around that
9 */
10 class HTMLPurifier_Generator
13 /**
14 * Whether or not generator should produce XML output
16 private $_xhtml = true;
18 /**
19 * :HACK: Whether or not generator should comment the insides of <script> tags
21 private $_scriptFix = false;
23 /**
24 * Cache of HTMLDefinition during HTML output to determine whether or
25 * not attributes should be minimized.
27 private $_def;
29 /**
30 * Cache of %Output.SortAttr
32 private $_sortAttr;
34 /**
35 * Cache of %Output.FlashCompat
37 private $_flashCompat;
39 /**
40 * Stack for keeping track of object information when outputting IE
41 * compatibility code.
43 private $_flashStack = array();
45 /**
46 * Configuration for the generator
48 protected $config;
50 /**
51 * @param $config Instance of HTMLPurifier_Config
52 * @param $context Instance of HTMLPurifier_Context
54 public function __construct($config, $context) {
55 $this->config = $config;
56 $this->_scriptFix = $config->get('Output.CommentScriptContents');
57 $this->_sortAttr = $config->get('Output.SortAttr');
58 $this->_flashCompat = $config->get('Output.FlashCompat');
59 $this->_def = $config->getHTMLDefinition();
60 $this->_xhtml = $this->_def->doctype->xml;
63 /**
64 * Generates HTML from an array of tokens.
65 * @param $tokens Array of HTMLPurifier_Token
66 * @param $config HTMLPurifier_Config object
67 * @return Generated HTML
69 public function generateFromTokens($tokens) {
70 if (!$tokens) return '';
72 // Basic algorithm
73 $html = '';
74 for ($i = 0, $size = count($tokens); $i < $size; $i++) {
75 if ($this->_scriptFix && $tokens[$i]->name === 'script'
76 && $i + 2 < $size && $tokens[$i+2] instanceof HTMLPurifier_Token_End) {
77 // script special case
78 // the contents of the script block must be ONE token
79 // for this to work.
80 $html .= $this->generateFromToken($tokens[$i++]);
81 $html .= $this->generateScriptFromToken($tokens[$i++]);
83 $html .= $this->generateFromToken($tokens[$i]);
86 // Tidy cleanup
87 if (extension_loaded('tidy') && $this->config->get('Output.TidyFormat')) {
88 $tidy = new Tidy;
89 $tidy->parseString($html, array(
90 'indent'=> true,
91 'output-xhtml' => $this->_xhtml,
92 'show-body-only' => true,
93 'indent-spaces' => 2,
94 'wrap' => 68,
95 ), 'utf8');
96 $tidy->cleanRepair();
97 $html = (string) $tidy; // explicit cast necessary
100 // Normalize newlines to system defined value
101 if ($this->config->get('Core.NormalizeNewlines')) {
102 $nl = $this->config->get('Output.Newline');
103 if ($nl === null) $nl = PHP_EOL;
104 if ($nl !== "\n") $html = str_replace("\n", $nl, $html);
106 return $html;
110 * Generates HTML from a single token.
111 * @param $token HTMLPurifier_Token object.
112 * @return Generated HTML
114 public function generateFromToken($token) {
115 if (!$token instanceof HTMLPurifier_Token) {
116 trigger_error('Cannot generate HTML from non-HTMLPurifier_Token object', E_USER_WARNING);
117 return '';
119 } elseif ($token instanceof HTMLPurifier_Token_Start) {
120 $attr = $this->generateAttributes($token->attr, $token->name);
121 if ($this->_flashCompat) {
122 if ($token->name == "object") {
123 $flash = new stdclass();
124 $flash->attr = $token->attr;
125 $flash->param = array();
126 $this->_flashStack[] = $flash;
129 return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';
131 } elseif ($token instanceof HTMLPurifier_Token_End) {
132 $_extra = '';
133 if ($this->_flashCompat) {
134 if ($token->name == "object" && !empty($this->_flashStack)) {
135 $flash = array_pop($this->_flashStack);
136 $compat_token = new HTMLPurifier_Token_Empty("embed");
137 foreach ($flash->attr as $name => $val) {
138 if ($name == "classid") continue;
139 if ($name == "type") continue;
140 if ($name == "data") $name = "src";
141 $compat_token->attr[$name] = $val;
143 foreach ($flash->param as $name => $val) {
144 if ($name == "movie") $name = "src";
145 $compat_token->attr[$name] = $val;
147 $_extra = "<!--[if IE]>".$this->generateFromToken($compat_token)."<![endif]-->";
150 return $_extra . '</' . $token->name . '>';
152 } elseif ($token instanceof HTMLPurifier_Token_Empty) {
153 if ($this->_flashCompat && $token->name == "param" && !empty($this->_flashStack)) {
154 $this->_flashStack[count($this->_flashStack)-1]->param[$token->attr['name']] = $token->attr['value'];
156 $attr = $this->generateAttributes($token->attr, $token->name);
157 return '<' . $token->name . ($attr ? ' ' : '') . $attr .
158 ( $this->_xhtml ? ' /': '' ) // <br /> v. <br>
159 . '>';
161 } elseif ($token instanceof HTMLPurifier_Token_Text) {
162 return $this->escape($token->data, ENT_NOQUOTES);
164 } elseif ($token instanceof HTMLPurifier_Token_Comment) {
165 return '<!--' . $token->data . '-->';
166 } else {
167 return '';
173 * Special case processor for the contents of script tags
174 * @warning This runs into problems if there's already a literal
175 * --> somewhere inside the script contents.
177 public function generateScriptFromToken($token) {
178 if (!$token instanceof HTMLPurifier_Token_Text) return $this->generateFromToken($token);
179 // Thanks <http://lachy.id.au/log/2005/05/script-comments>
180 $data = preg_replace('#//\s*$#', '', $token->data);
181 return '<!--//--><![CDATA[//><!--' . "\n" . trim($data) . "\n" . '//--><!]]>';
185 * Generates attribute declarations from attribute array.
186 * @note This does not include the leading or trailing space.
187 * @param $assoc_array_of_attributes Attribute array
188 * @param $element Name of element attributes are for, used to check
189 * attribute minimization.
190 * @return Generate HTML fragment for insertion.
192 public function generateAttributes($assoc_array_of_attributes, $element = false) {
193 $html = '';
194 if ($this->_sortAttr) ksort($assoc_array_of_attributes);
195 foreach ($assoc_array_of_attributes as $key => $value) {
196 if (!$this->_xhtml) {
197 // Remove namespaced attributes
198 if (strpos($key, ':') !== false) continue;
199 // Check if we should minimize the attribute: val="val" -> val
200 if ($element && !empty($this->_def->info[$element]->attr[$key]->minimized)) {
201 $html .= $key . ' ';
202 continue;
205 $html .= $key.'="'.$this->escape($value).'" ';
207 return rtrim($html);
211 * Escapes raw text data.
212 * @todo This really ought to be protected, but until we have a facility
213 * for properly generating HTML here w/o using tokens, it stays
214 * public.
215 * @param $string String data to escape for HTML.
216 * @param $quote Quoting style, like htmlspecialchars. ENT_NOQUOTES is
217 * permissible for non-attribute output.
218 * @return String escaped data.
220 public function escape($string, $quote = null) {
221 // Workaround for APC bug on Mac Leopard reported by sidepodcast
222 // http://htmlpurifier.org/phorum/read.php?3,4823,4846
223 if ($quote === null) $quote = ENT_COMPAT;
224 return htmlspecialchars($string, $quote, 'UTF-8');
229 // vim: et sw=4 sts=4