Generator.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. <?php
  2. /**
  3. * Generates HTML from tokens.
  4. * @todo Refactor interface so that configuration/context is determined
  5. * upon instantiation, no need for messy generateFromTokens() calls
  6. * @todo Make some of the more internal functions protected, and have
  7. * unit tests work around that
  8. */
  9. class HTMLPurifier_Generator
  10. {
  11. /**
  12. * Whether or not generator should produce XML output
  13. */
  14. private $_xhtml = true;
  15. /**
  16. * :HACK: Whether or not generator should comment the insides of <script> tags
  17. */
  18. private $_scriptFix = false;
  19. /**
  20. * Cache of HTMLDefinition during HTML output to determine whether or
  21. * not attributes should be minimized.
  22. */
  23. private $_def;
  24. /**
  25. * Cache of %Output.SortAttr
  26. */
  27. private $_sortAttr;
  28. /**
  29. * Cache of %Output.FlashCompat
  30. */
  31. private $_flashCompat;
  32. /**
  33. * Cache of %Output.FixInnerHTML
  34. */
  35. private $_innerHTMLFix;
  36. /**
  37. * Stack for keeping track of object information when outputting IE
  38. * compatibility code.
  39. */
  40. private $_flashStack = array();
  41. /**
  42. * Configuration for the generator
  43. */
  44. protected $config;
  45. /**
  46. * @param $config Instance of HTMLPurifier_Config
  47. * @param $context Instance of HTMLPurifier_Context
  48. */
  49. public function __construct($config, $context) {
  50. $this->config = $config;
  51. $this->_scriptFix = $config->get('Output.CommentScriptContents');
  52. $this->_innerHTMLFix = $config->get('Output.FixInnerHTML');
  53. $this->_sortAttr = $config->get('Output.SortAttr');
  54. $this->_flashCompat = $config->get('Output.FlashCompat');
  55. $this->_def = $config->getHTMLDefinition();
  56. $this->_xhtml = $this->_def->doctype->xml;
  57. }
  58. /**
  59. * Generates HTML from an array of tokens.
  60. * @param $tokens Array of HTMLPurifier_Token
  61. * @param $config HTMLPurifier_Config object
  62. * @return Generated HTML
  63. */
  64. public function generateFromTokens($tokens) {
  65. if (!$tokens) return '';
  66. // Basic algorithm
  67. $html = '';
  68. for ($i = 0, $size = count($tokens); $i < $size; $i++) {
  69. if ($this->_scriptFix && $tokens[$i]->name === 'script'
  70. && $i + 2 < $size && $tokens[$i+2] instanceof HTMLPurifier_Token_End) {
  71. // script special case
  72. // the contents of the script block must be ONE token
  73. // for this to work.
  74. $html .= $this->generateFromToken($tokens[$i++]);
  75. $html .= $this->generateScriptFromToken($tokens[$i++]);
  76. }
  77. $html .= $this->generateFromToken($tokens[$i]);
  78. }
  79. // Tidy cleanup
  80. if (extension_loaded('tidy') && $this->config->get('Output.TidyFormat')) {
  81. $tidy = new Tidy;
  82. $tidy->parseString($html, array(
  83. 'indent'=> true,
  84. 'output-xhtml' => $this->_xhtml,
  85. 'show-body-only' => true,
  86. 'indent-spaces' => 2,
  87. 'wrap' => 68,
  88. ), 'utf8');
  89. $tidy->cleanRepair();
  90. $html = (string) $tidy; // explicit cast necessary
  91. }
  92. // Normalize newlines to system defined value
  93. if ($this->config->get('Core.NormalizeNewlines')) {
  94. $nl = $this->config->get('Output.Newline');
  95. if ($nl === null) $nl = PHP_EOL;
  96. if ($nl !== "\n") $html = str_replace("\n", $nl, $html);
  97. }
  98. return $html;
  99. }
  100. /**
  101. * Generates HTML from a single token.
  102. * @param $token HTMLPurifier_Token object.
  103. * @return Generated HTML
  104. */
  105. public function generateFromToken($token) {
  106. if (!$token instanceof HTMLPurifier_Token) {
  107. trigger_error('Cannot generate HTML from non-HTMLPurifier_Token object', E_USER_WARNING);
  108. return '';
  109. } elseif ($token instanceof HTMLPurifier_Token_Start) {
  110. $attr = $this->generateAttributes($token->attr, $token->name);
  111. if ($this->_flashCompat) {
  112. if ($token->name == "object") {
  113. $flash = new stdclass();
  114. $flash->attr = $token->attr;
  115. $flash->param = array();
  116. $this->_flashStack[] = $flash;
  117. }
  118. }
  119. return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';
  120. } elseif ($token instanceof HTMLPurifier_Token_End) {
  121. $_extra = '';
  122. if ($this->_flashCompat) {
  123. if ($token->name == "object" && !empty($this->_flashStack)) {
  124. // doesn't do anything for now
  125. }
  126. }
  127. return $_extra . '</' . $token->name . '>';
  128. } elseif ($token instanceof HTMLPurifier_Token_Empty) {
  129. if ($this->_flashCompat && $token->name == "param" && !empty($this->_flashStack)) {
  130. $this->_flashStack[count($this->_flashStack)-1]->param[$token->attr['name']] = $token->attr['value'];
  131. }
  132. $attr = $this->generateAttributes($token->attr, $token->name);
  133. return '<' . $token->name . ($attr ? ' ' : '') . $attr .
  134. ( $this->_xhtml ? ' /': '' ) // <br /> v. <br>
  135. . '>';
  136. } elseif ($token instanceof HTMLPurifier_Token_Text) {
  137. return $this->escape($token->data, ENT_NOQUOTES);
  138. } elseif ($token instanceof HTMLPurifier_Token_Comment) {
  139. return '<!--' . $token->data . '-->';
  140. } else {
  141. return '';
  142. }
  143. }
  144. /**
  145. * Special case processor for the contents of script tags
  146. * @warning This runs into problems if there's already a literal
  147. * --> somewhere inside the script contents.
  148. */
  149. public function generateScriptFromToken($token) {
  150. if (!$token instanceof HTMLPurifier_Token_Text) return $this->generateFromToken($token);
  151. // Thanks <http://lachy.id.au/log/2005/05/script-comments>
  152. $data = preg_replace('#//\s*$#', '', $token->data);
  153. return '<!--//--><![CDATA[//><!--' . "\n" . trim($data) . "\n" . '//--><!]]>';
  154. }
  155. /**
  156. * Generates attribute declarations from attribute array.
  157. * @note This does not include the leading or trailing space.
  158. * @param $assoc_array_of_attributes Attribute array
  159. * @param $element Name of element attributes are for, used to check
  160. * attribute minimization.
  161. * @return Generate HTML fragment for insertion.
  162. */
  163. public function generateAttributes($assoc_array_of_attributes, $element = false) {
  164. $html = '';
  165. if ($this->_sortAttr) ksort($assoc_array_of_attributes);
  166. foreach ($assoc_array_of_attributes as $key => $value) {
  167. if (!$this->_xhtml) {
  168. // Remove namespaced attributes
  169. if (strpos($key, ':') !== false) continue;
  170. // Check if we should minimize the attribute: val="val" -> val
  171. if ($element && !empty($this->_def->info[$element]->attr[$key]->minimized)) {
  172. $html .= $key . ' ';
  173. continue;
  174. }
  175. }
  176. // Workaround for Internet Explorer innerHTML bug.
  177. // Essentially, Internet Explorer, when calculating
  178. // innerHTML, omits quotes if there are no instances of
  179. // angled brackets, quotes or spaces. However, when parsing
  180. // HTML (for example, when you assign to innerHTML), it
  181. // treats backticks as quotes. Thus,
  182. // <img alt="``" />
  183. // becomes
  184. // <img alt=`` />
  185. // becomes
  186. // <img alt='' />
  187. // Fortunately, all we need to do is trigger an appropriate
  188. // quoting style, which we do by adding an extra space.
  189. // This also is consistent with the W3C spec, which states
  190. // that user agents may ignore leading or trailing
  191. // whitespace (in fact, most don't, at least for attributes
  192. // like alt, but an extra space at the end is barely
  193. // noticeable). Still, we have a configuration knob for
  194. // this, since this transformation is not necesary if you
  195. // don't process user input with innerHTML or you don't plan
  196. // on supporting Internet Explorer.
  197. if ($this->_innerHTMLFix) {
  198. if (strpos($value, '`') !== false) {
  199. // check if correct quoting style would not already be
  200. // triggered
  201. if (strcspn($value, '"\' <>') === strlen($value)) {
  202. // protect!
  203. $value .= ' ';
  204. }
  205. }
  206. }
  207. $html .= $key.'="'.$this->escape($value).'" ';
  208. }
  209. return rtrim($html);
  210. }
  211. /**
  212. * Escapes raw text data.
  213. * @todo This really ought to be protected, but until we have a facility
  214. * for properly generating HTML here w/o using tokens, it stays
  215. * public.
  216. * @param $string String data to escape for HTML.
  217. * @param $quote Quoting style, like htmlspecialchars. ENT_NOQUOTES is
  218. * permissible for non-attribute output.
  219. * @return String escaped data.
  220. */
  221. public function escape($string, $quote = null) {
  222. // Workaround for APC bug on Mac Leopard reported by sidepodcast
  223. // http://htmlpurifier.org/phorum/read.php?3,4823,4846
  224. if ($quote === null) $quote = ENT_COMPAT;
  225. return htmlspecialchars($string, $quote, 'UTF-8');
  226. }
  227. }
  228. // vim: et sw=4 sts=4