File indexing completed on 2024-05-05 06:02:16

0001 <?php
0002 
0003 /**
0004  * Generates HTML from tokens.
0005  * @todo Refactor interface so that configuration/context is determined
0006  *       upon instantiation, no need for messy generateFromTokens() calls
0007  * @todo Make some of the more internal functions protected, and have
0008  *       unit tests work around that
0009  */
0010 class HTMLPurifier_Generator
0011 {
0012 
0013     /**
0014      * Whether or not generator should produce XML output.
0015      * @type bool
0016      */
0017     private $_xhtml = true;
0018 
0019     /**
0020      * :HACK: Whether or not generator should comment the insides of <script> tags.
0021      * @type bool
0022      */
0023     private $_scriptFix = false;
0024 
0025     /**
0026      * Cache of HTMLDefinition during HTML output to determine whether or
0027      * not attributes should be minimized.
0028      * @type HTMLPurifier_HTMLDefinition
0029      */
0030     private $_def;
0031 
0032     /**
0033      * Cache of %Output.SortAttr.
0034      * @type bool
0035      */
0036     private $_sortAttr;
0037 
0038     /**
0039      * Cache of %Output.FlashCompat.
0040      * @type bool
0041      */
0042     private $_flashCompat;
0043 
0044     /**
0045      * Cache of %Output.FixInnerHTML.
0046      * @type bool
0047      */
0048     private $_innerHTMLFix;
0049 
0050     /**
0051      * Stack for keeping track of object information when outputting IE
0052      * compatibility code.
0053      * @type array
0054      */
0055     private $_flashStack = array();
0056 
0057     /**
0058      * Configuration for the generator
0059      * @type HTMLPurifier_Config
0060      */
0061     protected $config;
0062 
0063     /**
0064      * @param HTMLPurifier_Config $config
0065      * @param HTMLPurifier_Context $context
0066      */
0067     public function __construct($config, $context)
0068     {
0069         $this->config = $config;
0070         $this->_scriptFix = $config->get('Output.CommentScriptContents');
0071         $this->_innerHTMLFix = $config->get('Output.FixInnerHTML');
0072         $this->_sortAttr = $config->get('Output.SortAttr');
0073         $this->_flashCompat = $config->get('Output.FlashCompat');
0074         $this->_def = $config->getHTMLDefinition();
0075         $this->_xhtml = $this->_def->doctype->xml;
0076     }
0077 
0078     /**
0079      * Generates HTML from an array of tokens.
0080      * @param HTMLPurifier_Token[] $tokens Array of HTMLPurifier_Token
0081      * @return string Generated HTML
0082      */
0083     public function generateFromTokens($tokens)
0084     {
0085         if (!$tokens) {
0086             return '';
0087         }
0088 
0089         // Basic algorithm
0090         $html = '';
0091         for ($i = 0, $size = count($tokens); $i < $size; $i++) {
0092             if ($this->_scriptFix && $tokens[$i]->name === 'script'
0093                 && $i + 2 < $size && $tokens[$i+2] instanceof HTMLPurifier_Token_End) {
0094                 // script special case
0095                 // the contents of the script block must be ONE token
0096                 // for this to work.
0097                 $html .= $this->generateFromToken($tokens[$i++]);
0098                 $html .= $this->generateScriptFromToken($tokens[$i++]);
0099             }
0100             $html .= $this->generateFromToken($tokens[$i]);
0101         }
0102 
0103         // Tidy cleanup
0104         if (extension_loaded('tidy') && $this->config->get('Output.TidyFormat')) {
0105             $tidy = new Tidy;
0106             $tidy->parseString(
0107                 $html,
0108                 array(
0109                    'indent'=> true,
0110                    'output-xhtml' => $this->_xhtml,
0111                    'show-body-only' => true,
0112                    'indent-spaces' => 2,
0113                    'wrap' => 68,
0114                 ),
0115                 'utf8'
0116             );
0117             $tidy->cleanRepair();
0118             $html = (string) $tidy; // explicit cast necessary
0119         }
0120 
0121         // Normalize newlines to system defined value
0122         if ($this->config->get('Core.NormalizeNewlines')) {
0123             $nl = $this->config->get('Output.Newline');
0124             if ($nl === null) {
0125                 $nl = PHP_EOL;
0126             }
0127             if ($nl !== "\n") {
0128                 $html = str_replace("\n", $nl, $html);
0129             }
0130         }
0131         return $html;
0132     }
0133 
0134     /**
0135      * Generates HTML from a single token.
0136      * @param HTMLPurifier_Token $token HTMLPurifier_Token object.
0137      * @return string Generated HTML
0138      */
0139     public function generateFromToken($token)
0140     {
0141         if (!$token instanceof HTMLPurifier_Token) {
0142             trigger_error('Cannot generate HTML from non-HTMLPurifier_Token object', E_USER_WARNING);
0143             return '';
0144 
0145         } elseif ($token instanceof HTMLPurifier_Token_Start) {
0146             $attr = $this->generateAttributes($token->attr, $token->name);
0147             if ($this->_flashCompat) {
0148                 if ($token->name == "object") {
0149                     $flash = new stdClass();
0150                     $flash->attr = $token->attr;
0151                     $flash->param = array();
0152                     $this->_flashStack[] = $flash;
0153                 }
0154             }
0155             return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';
0156 
0157         } elseif ($token instanceof HTMLPurifier_Token_End) {
0158             $_extra = '';
0159             if ($this->_flashCompat) {
0160                 if ($token->name == "object" && !empty($this->_flashStack)) {
0161                     // doesn't do anything for now
0162                 }
0163             }
0164             return $_extra . '</' . $token->name . '>';
0165 
0166         } elseif ($token instanceof HTMLPurifier_Token_Empty) {
0167             if ($this->_flashCompat && $token->name == "param" && !empty($this->_flashStack)) {
0168                 $this->_flashStack[count($this->_flashStack)-1]->param[$token->attr['name']] = $token->attr['value'];
0169             }
0170             $attr = $this->generateAttributes($token->attr, $token->name);
0171              return '<' . $token->name . ($attr ? ' ' : '') . $attr .
0172                 ( $this->_xhtml ? ' /': '' ) // <br /> v. <br>
0173                 . '>';
0174 
0175         } elseif ($token instanceof HTMLPurifier_Token_Text) {
0176             return $this->escape($token->data, ENT_NOQUOTES);
0177 
0178         } elseif ($token instanceof HTMLPurifier_Token_Comment) {
0179             return '<!--' . $token->data . '-->';
0180         } else {
0181             return '';
0182 
0183         }
0184     }
0185 
0186     /**
0187      * Special case processor for the contents of script tags
0188      * @param HTMLPurifier_Token $token HTMLPurifier_Token object.
0189      * @return string
0190      * @warning This runs into problems if there's already a literal
0191      *          --> somewhere inside the script contents.
0192      */
0193     public function generateScriptFromToken($token)
0194     {
0195         if (!$token instanceof HTMLPurifier_Token_Text) {
0196             return $this->generateFromToken($token);
0197         }
0198         // Thanks <http://lachy.id.au/log/2005/05/script-comments>
0199         $data = preg_replace('#//\s*$#', '', $token->data);
0200         return '<!--//--><![CDATA[//><!--' . "\n" . trim($data) . "\n" . '//--><!]]>';
0201     }
0202 
0203     /**
0204      * Generates attribute declarations from attribute array.
0205      * @note This does not include the leading or trailing space.
0206      * @param array $assoc_array_of_attributes Attribute array
0207      * @param string $element Name of element attributes are for, used to check
0208      *        attribute minimization.
0209      * @return string Generated HTML fragment for insertion.
0210      */
0211     public function generateAttributes($assoc_array_of_attributes, $element = '')
0212     {
0213         $html = '';
0214         if ($this->_sortAttr) {
0215             ksort($assoc_array_of_attributes);
0216         }
0217         foreach ($assoc_array_of_attributes as $key => $value) {
0218             if (!$this->_xhtml) {
0219                 // Remove namespaced attributes
0220                 if (strpos($key, ':') !== false) {
0221                     continue;
0222                 }
0223                 // Check if we should minimize the attribute: val="val" -> val
0224                 if ($element && !empty($this->_def->info[$element]->attr[$key]->minimized)) {
0225                     $html .= $key . ' ';
0226                     continue;
0227                 }
0228             }
0229             // Workaround for Internet Explorer innerHTML bug.
0230             // Essentially, Internet Explorer, when calculating
0231             // innerHTML, omits quotes if there are no instances of
0232             // angled brackets, quotes or spaces.  However, when parsing
0233             // HTML (for example, when you assign to innerHTML), it
0234             // treats backticks as quotes.  Thus,
0235             //      <img alt="``" />
0236             // becomes
0237             //      <img alt=`` />
0238             // becomes
0239             //      <img alt='' />
0240             // Fortunately, all we need to do is trigger an appropriate
0241             // quoting style, which we do by adding an extra space.
0242             // This also is consistent with the W3C spec, which states
0243             // that user agents may ignore leading or trailing
0244             // whitespace (in fact, most don't, at least for attributes
0245             // like alt, but an extra space at the end is barely
0246             // noticeable).  Still, we have a configuration knob for
0247             // this, since this transformation is not necesary if you
0248             // don't process user input with innerHTML or you don't plan
0249             // on supporting Internet Explorer.
0250             if ($this->_innerHTMLFix) {
0251                 if (strpos($value, '`') !== false) {
0252                     // check if correct quoting style would not already be
0253                     // triggered
0254                     if (strcspn($value, '"\' <>') === strlen($value)) {
0255                         // protect!
0256                         $value .= ' ';
0257                     }
0258                 }
0259             }
0260             $html .= $key.'="'.$this->escape($value).'" ';
0261         }
0262         return rtrim($html);
0263     }
0264 
0265     /**
0266      * Escapes raw text data.
0267      * @todo This really ought to be protected, but until we have a facility
0268      *       for properly generating HTML here w/o using tokens, it stays
0269      *       public.
0270      * @param string $string String data to escape for HTML.
0271      * @param int $quote Quoting style, like htmlspecialchars. ENT_NOQUOTES is
0272      *               permissible for non-attribute output.
0273      * @return string escaped data.
0274      */
0275     public function escape($string, $quote = null)
0276     {
0277         // Workaround for APC bug on Mac Leopard reported by sidepodcast
0278         // http://htmlpurifier.org/phorum/read.php?3,4823,4846
0279         if ($quote === null) {
0280             $quote = ENT_COMPAT;
0281         }
0282         return htmlspecialchars($string, $quote, 'UTF-8');
0283     }
0284 }
0285 
0286 // vim: et sw=4 sts=4