PageRenderTime 65ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/common/libraries/plugin/htmlpurifier/library/HTMLPurifier/Generator.php

https://bitbucket.org/chamilo/chamilo-dev/
PHP | 290 lines | 154 code | 28 blank | 108 comment | 33 complexity | fbea4a2e918e24789fe66c06b0e766c2 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, LGPL-2.1, LGPL-3.0, GPL-3.0, MIT
  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. {
  51. $this->config = $config;
  52. $this->_scriptFix = $config->get('Output.CommentScriptContents');
  53. $this->_innerHTMLFix = $config->get('Output.FixInnerHTML');
  54. $this->_sortAttr = $config->get('Output.SortAttr');
  55. $this->_flashCompat = $config->get('Output.FlashCompat');
  56. $this->_def = $config->getHTMLDefinition();
  57. $this->_xhtml = $this->_def->doctype->xml;
  58. }
  59. /**
  60. * Generates HTML from an array of tokens.
  61. * @param $tokens Array of HTMLPurifier_Token
  62. * @param $config HTMLPurifier_Config object
  63. * @return Generated HTML
  64. */
  65. public function generateFromTokens($tokens)
  66. {
  67. if (! $tokens)
  68. return '';
  69. // Basic algorithm
  70. $html = '';
  71. for($i = 0, $size = count($tokens); $i < $size; $i ++)
  72. {
  73. if ($this->_scriptFix && $tokens[$i]->name === 'script' && $i + 2 < $size && $tokens[$i + 2] instanceof HTMLPurifier_Token_End)
  74. {
  75. // script special case
  76. // the contents of the script block must be ONE token
  77. // for this to work.
  78. $html .= $this->generateFromToken($tokens[$i ++]);
  79. $html .= $this->generateScriptFromToken($tokens[$i ++]);
  80. }
  81. $html .= $this->generateFromToken($tokens[$i]);
  82. }
  83. // Tidy cleanup
  84. if (extension_loaded('tidy') && $this->config->get('Output.TidyFormat'))
  85. {
  86. $tidy = new Tidy();
  87. $tidy->parseString($html, array('indent' => true, 'output-xhtml' => $this->_xhtml,
  88. 'show-body-only' => true, 'indent-spaces' => 2, 'wrap' => 68), '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. {
  95. $nl = $this->config->get('Output.Newline');
  96. if ($nl === null)
  97. $nl = PHP_EOL;
  98. if ($nl !== "\n")
  99. $html = str_replace("\n", $nl, $html);
  100. }
  101. return $html;
  102. }
  103. /**
  104. * Generates HTML from a single token.
  105. * @param $token HTMLPurifier_Token object.
  106. * @return Generated HTML
  107. */
  108. public function generateFromToken($token)
  109. {
  110. if (! $token instanceof HTMLPurifier_Token)
  111. {
  112. trigger_error('Cannot generate HTML from non-HTMLPurifier_Token object', E_USER_WARNING);
  113. return '';
  114. }
  115. elseif ($token instanceof HTMLPurifier_Token_Start)
  116. {
  117. $attr = $this->generateAttributes($token->attr, $token->name);
  118. if ($this->_flashCompat)
  119. {
  120. if ($token->name == "object")
  121. {
  122. $flash = new stdclass();
  123. $flash->attr = $token->attr;
  124. $flash->param = array();
  125. $this->_flashStack[] = $flash;
  126. }
  127. }
  128. return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';
  129. }
  130. elseif ($token instanceof HTMLPurifier_Token_End)
  131. {
  132. $_extra = '';
  133. if ($this->_flashCompat)
  134. {
  135. if ($token->name == "object" && ! empty($this->_flashStack))
  136. {
  137. // doesn't do anything for now
  138. }
  139. }
  140. return $_extra . '</' . $token->name . '>';
  141. }
  142. elseif ($token instanceof HTMLPurifier_Token_Empty)
  143. {
  144. if ($this->_flashCompat && $token->name == "param" && ! empty($this->_flashStack))
  145. {
  146. $this->_flashStack[count($this->_flashStack) - 1]->param[$token->attr['name']] = $token->attr['value'];
  147. }
  148. $attr = $this->generateAttributes($token->attr, $token->name);
  149. return '<' . $token->name . ($attr ? ' ' : '') . $attr . ($this->_xhtml ? ' /' : '') . // <br /> v. <br>
  150. '>';
  151. }
  152. elseif ($token instanceof HTMLPurifier_Token_Text)
  153. {
  154. return $this->escape($token->data, ENT_NOQUOTES);
  155. }
  156. elseif ($token instanceof HTMLPurifier_Token_Comment)
  157. {
  158. return '<!--' . $token->data . '-->';
  159. }
  160. else
  161. {
  162. return '';
  163. }
  164. }
  165. /**
  166. * Special case processor for the contents of script tags
  167. * @warning This runs into problems if there's already a literal
  168. * --> somewhere inside the script contents.
  169. */
  170. public function generateScriptFromToken($token)
  171. {
  172. if (! $token instanceof HTMLPurifier_Token_Text)
  173. return $this->generateFromToken($token);
  174. // Thanks <http://lachy.id.au/log/2005/05/script-comments>
  175. $data = preg_replace('#//\s*$#', '', $token->data);
  176. return '<!--//--><![CDATA[//><!--' . "\n" . trim($data) . "\n" . '//--><!]]>';
  177. }
  178. /**
  179. * Generates attribute declarations from attribute array.
  180. * @note This does not include the leading or trailing space.
  181. * @param $assoc_array_of_attributes Attribute array
  182. * @param $element Name of element attributes are for, used to check
  183. * attribute minimization.
  184. * @return Generate HTML fragment for insertion.
  185. */
  186. public function generateAttributes($assoc_array_of_attributes, $element = false)
  187. {
  188. $html = '';
  189. if ($this->_sortAttr)
  190. ksort($assoc_array_of_attributes);
  191. foreach ($assoc_array_of_attributes as $key => $value)
  192. {
  193. if (! $this->_xhtml)
  194. {
  195. // Remove namespaced attributes
  196. if (strpos($key, ':') !== false)
  197. continue;
  198. // Check if we should minimize the attribute: val="val" -> val
  199. if ($element && ! empty($this->_def->info[$element]->attr[$key]->minimized))
  200. {
  201. $html .= $key . ' ';
  202. continue;
  203. }
  204. }
  205. // Workaround for Internet Explorer innerHTML bug.
  206. // Essentially, Internet Explorer, when calculating
  207. // innerHTML, omits quotes if there are no instances of
  208. // angled brackets, quotes or spaces. However, when parsing
  209. // HTML (for example, when you assign to innerHTML), it
  210. // treats backticks as quotes. Thus,
  211. // <img alt="``" />
  212. // becomes
  213. // <img alt=`` />
  214. // becomes
  215. // <img alt='' />
  216. // Fortunately, all we need to do is trigger an appropriate
  217. // quoting style, which we do by adding an extra space.
  218. // This also is consistent with the W3C spec, which states
  219. // that user agents may ignore leading or trailing
  220. // whitespace (in fact, most don't, at least for attributes
  221. // like alt, but an extra space at the end is barely
  222. // noticeable). Still, we have a configuration knob for
  223. // this, since this transformation is not necesary if you
  224. // don't process user input with innerHTML or you don't plan
  225. // on supporting Internet Explorer.
  226. if ($this->_innerHTMLFix)
  227. {
  228. if (strpos($value, '`') !== false)
  229. {
  230. // check if correct quoting style would not already be
  231. // triggered
  232. if (strcspn($value, '"\' <>') === strlen($value))
  233. {
  234. // protect!
  235. $value .= ' ';
  236. }
  237. }
  238. }
  239. $html .= $key . '="' . $this->escape($value) . '" ';
  240. }
  241. return rtrim($html);
  242. }
  243. /**
  244. * Escapes raw text data.
  245. * @todo This really ought to be protected, but until we have a facility
  246. * for properly generating HTML here w/o using tokens, it stays
  247. * public.
  248. * @param $string String data to escape for HTML.
  249. * @param $quote Quoting style, like htmlspecialchars. ENT_NOQUOTES is
  250. * permissible for non-attribute output.
  251. * @return String escaped data.
  252. */
  253. public function escape($string, $quote = null)
  254. {
  255. // Workaround for APC bug on Mac Leopard reported by sidepodcast
  256. // http://htmlpurifier.org/phorum/read.php?3,4823,4846
  257. if ($quote === null)
  258. $quote = ENT_COMPAT;
  259. return htmlspecialchars($string, $quote, 'UTF-8');
  260. }
  261. }
  262. // vim: et sw=4 sts=4