code:
<?php

/**
 * Abstract base node class that all others inherit from.
 *
 * Why do we not use the DOM extension?  (1) It is not always available,
 * (2) it has funny constraints on the data it can represent,
 * whereas we want a maximally flexible representation, and (3) its
 * interface is a bit cumbersome.
 */
abstract class HTMLPurifier_Node
{
    /**
     * Line number of the start token in the source document
     * @type int
     */
    public $line;

    /**
     * Column number of the start token in the source document. Null if unknown.
     * @type int
     */
    public $col;

    /**
     * Lookup array of processing that this token is exempt from.
     * Currently, valid values are "ValidateAttributes".
     * @type array
     */
    public $armor = array();

    /**
     * When true, this node should be ignored as non-existent.
     *
     * Who is responsible for ignoring dead nodes?  FixNesting is
     * responsible for removing them before passing on to child
     * validators.
     */
    public $dead = false;

    /**
     * Returns a pair of start and end tokens, where the end token
     * is null if it is not necessary. Does not include children.
     * @type array
     */
    abstract public function toTokenPair();
}

// vim: et sw=4 sts=4

repo_name: ksuudilla/gnu

license: mit


code:
<?php

/**
 * Concrete comment node class.
 */
class HTMLPurifier_Node_Comment extends HTMLPurifier_Node
{
    /**
     * Character data within comment.
     * @type string
     */
    public $data;

    /**
     * @type bool
     */
    public $is_whitespace = true;

    /**
     * Transparent constructor.
     *
     * @param string $data String comment data.
     * @param int $line
     * @param int $col
     */
    public function __construct($data, $line = null, $col = null)
    {
        $this->data = $data;
        $this->line = $line;
        $this->col = $col;
    }

    public function toTokenPair() {
        return array(new HTMLPurifier_Token_Comment($this->data, $this->line, $this->col), null);
    }
}


code:
<?php

/**
 * Concrete element node class.
 */
class HTMLPurifier_Node_Element extends HTMLPurifier_Node
{
    /**
     * The lower-case name of the tag, like 'a', 'b' or 'blockquote'.
     *
     * @note Strictly speaking, XML tags are case sensitive, so we shouldn't
     * be lower-casing them, but these tokens cater to HTML tags, which are
     * insensitive.
     * @type string
     */
    public $name;

    /**
     * Associative array of the node's attributes.
     * @type array
     */
    public $attr = array();

    /**
     * List of child elements.
     * @type array
     */
    public $children = array();

    /**
     * Does this use the  form or the  form, i.e.
     * is it a pair of start/end tokens or an empty token.
     * @bool
     */
    public $empty = false;

    public $endCol = null, $endLine = null, $endArmor = array();

    public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array()) {
        $this->name = $name;
        $this->attr = $attr;
        $this->line = $line;
        $this->col = $col;
        $this->armor = $armor;
    }

    public function toTokenPair() {
        // XXX inefficiency here, normalization is not necessary
        if ($this->empty) {
            return array(new HTMLPurifier_Token_Empty($this->name, $this->attr, $this->line, $this->col, $this->armor), null);
        } else {
            $start = new HTMLPurifier_Token_Start($this->name, $this->attr, $this->line, $this->col, $this->armor);
            $end = new HTMLPurifier_Token_End($this->name, array(), $this->endLine, $this->endCol, $this->endArmor);
            //$end->start = $start;
            return array($start, $end);
        }
    }
}


code:
<?php

/**
 * Concrete text token class.
 *
 * Text tokens comprise of regular parsed character data (PCDATA) and raw
 * character data (from the CDATA sections). Internally, their
 * data is parsed with all entities expanded. Surprisingly, the text token
 * does have a "tag name" called #PCDATA, which is how the DTD represents it
 * in permissible child nodes.
 */
class HTMLPurifier_Node_Text extends HTMLPurifier_Node
{

    /**
     * PCDATA tag name compatible with DTD, see
     * HTMLPurifier_ChildDef_Custom for details.
     * @type string
     */
    public $name = '#PCDATA';

    /**
     * @type string
     */
    public $data;
    /**< Parsed character data of text. */

    /**
     * @type bool
     */
    public $is_whitespace;

    /**< Bool indicating if node is whitespace. */

    /**
     * Constructor, accepts data and determines if it is whitespace.
     * @param string $data String parsed character data.
     * @param int $line
     * @param int $col
     */
    public function __construct($data, $is_whitespace, $line = null, $col = null)
    {
        $this->data = $data;
        $this->is_whitespace = $is_whitespace;
        $this->line = $line;
        $this->col = $col;
    }

    public function toTokenPair() {
        return array(new HTMLPurifier_Token_Text($this->data, $this->line, $this->col), null);
    }
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * Class that handles operations involving percent-encoding in URIs.
 *
 * @warning
 *      Be careful when reusing instances of PercentEncoder. The object
 *      you use for normalize() SHOULD NOT be used for encode(), or
 *      vice-versa.
 */
class HTMLPurifier_PercentEncoder
{

    /**
     * Reserved characters to preserve when using encode().
     * @type array
     */
    protected $preserve = array();

    /**
     * String of characters that should be preserved while using encode().
     * @param bool $preserve
     */
    public function __construct($preserve = false)
    {
        // unreserved letters, ought to const-ify
        for ($i = 48; $i <= 57; $i++) { // digits
            $this->preserve[$i] = true;
        }
        for ($i = 65; $i <= 90; $i++) { // upper-case
            $this->preserve[$i] = true;
        }
        for ($i = 97; $i <= 122; $i++) { // lower-case
            $this->preserve[$i] = true;
        }
        $this->preserve[45] = true; // Dash         -
        $this->preserve[46] = true; // Period       .
        $this->preserve[95] = true; // Underscore   _
        $this->preserve[126]= true; // Tilde        ~

        // extra letters not to escape
        if ($preserve !== false) {
            for ($i = 0, $c = strlen($preserve); $i < $c; $i++) {
                $this->preserve[ord($preserve[$i])] = true;
            }
        }
    }

    /**
     * Our replacement for urlencode, it encodes all non-reserved characters,
     * as well as any extra characters that were instructed to be preserved.
     * @note
     *      Assumes that the string has already been normalized, making any
     *      and all percent escape sequences valid. Percents will not be
     *      re-escaped, regardless of their status in $preserve
     * @param string $string String to be encoded
     * @return string Encoded string.
     */
    public function encode($string)
    {
        $ret = '';
        for ($i = 0, $c = strlen($string); $i < $c; $i++) {
            if ($string[$i] !== '%' && !isset($this->preserve[$int = ord($string[$i])])) {
                $ret .= '%' . sprintf('%02X', $int);
            } else {
                $ret .= $string[$i];
            }
        }
        return $ret;
    }

    /**
     * Fix up percent-encoding by decoding unreserved characters and normalizing.
     * @warning This function is affected by $preserve, even though the
     *          usual desired behavior is for this not to preserve those
     *          characters. Be careful when reusing instances of PercentEncoder!
     * @param string $string String to normalize
     * @return string
     */
    public function normalize($string)
    {
        if ($string == '') {
            return '';
        }
        $parts = explode('%', $string);
        $ret = array_shift($parts);
        foreach ($parts as $part) {
            $length = strlen($part);
            if ($length < 2) {
                $ret .= '%25' . $part;
                continue;
            }
            $encoding = substr($part, 0, 2);
            $text     = substr($part, 2);
            if (!ctype_xdigit($encoding)) {
                $ret .= '%25' . $part;
                continue;
            }
            $int = hexdec($encoding);
            if (isset($this->preserve[$int])) {
                $ret .= chr($int) . $text;
                continue;
            }
            $encoding = strtoupper($encoding);
            $ret .= '%' . $encoding . $text;
        }
        return $ret;
    }
}

// vim: et sw=4 sts=4


code:
<?php

// OUT OF DATE, NEEDS UPDATING!
// USE XMLWRITER!

class HTMLPurifier_Printer
{

    /**
     * For HTML generation convenience funcs.
     * @type HTMLPurifier_Generator
     */
    protected $generator;

    /**
     * For easy access.
     * @type HTMLPurifier_Config
     */
    protected $config;

    /**
     * Initialize $generator.
     */
    public function __construct()
    {
    }

    /**
     * Give generator necessary configuration if possible
     * @param HTMLPurifier_Config $config
     */
    public function prepareGenerator($config)
    {
        $all = $config->getAll();
        $context = new HTMLPurifier_Context();
        $this->generator = new HTMLPurifier_Generator($config, $context);
    }

    /**
     * Main function that renders object or aspect of that object
     * @note Parameters vary depending on printer
     */
    // function render() {}

    /**
     * Returns a start tag
     * @param string $tag Tag name
     * @param array $attr Attribute array
     * @return string
     */
    protected function start($tag, $attr = array())
    {
        return $this->generator->generateFromToken(
            new HTMLPurifier_Token_Start($tag, $attr ? $attr : array())
        );
    }

    /**
     * Returns an end tag
     * @param string $tag Tag name
     * @return string
     */
    protected function end($tag)
    {
        return $this->generator->generateFromToken(
            new HTMLPurifier_Token_End($tag)
        );
    }

    /**
     * Prints a complete element with content inside
     * @param string $tag Tag name
     * @param string $contents Element contents
     * @param array $attr Tag attributes
     * @param bool $escape whether or not to escape contents
     * @return string
     */
    protected function element($tag, $contents, $attr = array(), $escape = true)
    {
        return $this->start($tag, $attr) .
            ($escape ? $this->escape($contents) : $contents) .
            $this->end($tag);
    }

    /**
     * @param string $tag
     * @param array $attr
     * @return string
     */
    protected function elementEmpty($tag, $attr = array())
    {
        return $this->generator->generateFromToken(
            new HTMLPurifier_Token_Empty($tag, $attr)
        );
    }

    /**
     * @param string $text
     * @return string
     */
    protected function text($text)
    {
        return $this->generator->generateFromToken(
            new HTMLPurifier_Token_Text($text)
        );
    }

    /**
     * Prints a simple key/value row in a table.
     * @param string $name Key
     * @param mixed $value Value
     * @return string
     */
    protected function row($name, $value)
    {
        if (is_bool($value)) {
            $value = $value ? 'On' : 'Off';
        }
        return
            $this->start('tr') . "\n" .
            $this->element('th', $name) . "\n" .
            $this->element('td', $value) . "\n" .
            $this->end('tr');
    }

    /**
     * Escapes a string for HTML output.
     * @param string $string String to escape
     * @return string
     */
    protected function escape($string)
    {
        $string = HTMLPurifier_Encoder::cleanUTF8($string);
        $string = htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
        return $string;
    }

    /**
     * Takes a list of strings and turns them into a single list
     * @param string[] $array List of strings
     * @param bool $polite Bool whether or not to add an end before the last
     * @return string
     */
    protected function listify($array, $polite = false)
    {
        if (empty($array)) {
            return 'None';
        }
        $ret = '';
        $i = count($array);
        foreach ($array as $value) {
            $i--;
            $ret .= $value;
            if ($i > 0 && !($polite && $i == 1)) {
                $ret .= ', ';
            }
            if ($polite && $i == 1) {
                $ret .= 'and ';
            }
        }
        return $ret;
    }

    /**
     * Retrieves the class of an object without prefixes, as well as metadata
     * @param object $obj Object to determine class of
     * @param string $sec_prefix Further prefix to remove
     * @return string
     */
    protected function getClass($obj, $sec_prefix = '')
    {
        static $five = null;
        if ($five === null) {
            $five = version_compare(PHP_VERSION, '5', '>=');
        }
        $prefix = 'HTMLPurifier_' . $sec_prefix;
        if (!$five) {
            $prefix = strtolower($prefix);
        }
        $class = str_replace($prefix, '', get_class($obj));
        $lclass = strtolower($class);
        $class .= '(';
        switch ($lclass) {
            case 'enum':
                $values = array();
                foreach ($obj->valid_values as $value => $bool) {
                    $values[] = $value;
                }
                $class .= implode(', ', $values);
                break;
            case 'css_composite':
                $values = array();
                foreach ($obj->defs as $def) {
                    $values[] = $this->getClass($def, $sec_prefix);
                }
                $class .= implode(', ', $values);
                break;
            case 'css_multiple':
                $class .= $this->getClass($obj->single, $sec_prefix) . ', ';
                $class .= $obj->max;
                break;
            case 'css_denyelementdecorator':
                $class .= $this->getClass($obj->def, $sec_prefix) . ', ';
                $class .= $obj->element;
                break;
            case 'css_importantdecorator':
                $class .= $this->getClass($obj->def, $sec_prefix);
                if ($obj->allow) {
                    $class .= ', !important';
                }
                break;
        }
        $class .= ')';
        return $class;
    }
}

// vim: et sw=4 sts=4


code:
<?php

class HTMLPurifier_Printer_CSSDefinition extends HTMLPurifier_Printer
{
    /**
     * @type HTMLPurifier_CSSDefinition
     */
    protected $def;

    /**
     * @param HTMLPurifier_Config $config
     * @return string
     */
    public function render($config)
    {
        $this->def = $config->getCSSDefinition();
        $ret = '';

        $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer'));
        $ret .= $this->start('table');

        $ret .= $this->element('caption', 'Properties ($info)');

        $ret .= $this->start('thead');
        $ret .= $this->start('tr');
        $ret .= $this->element('th', 'Property', array('class' => 'heavy'));
        $ret .= $this->element('th', 'Definition', array('class' => 'heavy', 'style' => 'width:auto;'));
        $ret .= $this->end('tr');
        $ret .= $this->end('thead');

        ksort($this->def->info);
        foreach ($this->def->info as $property => $obj) {
            $name = $this->getClass($obj, 'AttrDef_');
            $ret .= $this->row($property, $name);
        }

        $ret .= $this->end('table');
        $ret .= $this->end('div');

        return $ret;
    }
}

// vim: et sw=4 sts=4


code:
.hp-config {}

.hp-config tbody th {text-align:right; padding-right:0.5em;}
.hp-config thead, .hp-config .namespace {background:#3C578C; color:#FFF;}
.hp-config .namespace th {text-align:center;}
.hp-config .verbose {display:none;}
.hp-config .controls {text-align:center;}

/* vim: et sw=4 sts=4 */


code:
function toggleWriteability(id_of_patient, checked) {
    document.getElementById(id_of_patient).disabled = checked;
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * @todo Rewrite to use Interchange objects
 */
class HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer
{

    /**
     * Printers for specific fields.
     * @type HTMLPurifier_Printer[]
     */
    protected $fields = array();

    /**
     * Documentation URL, can have fragment tagged on end.
     * @type string
     */
    protected $docURL;

    /**
     * Name of form element to stuff config in.
     * @type string
     */
    protected $name;

    /**
     * Whether or not to compress directive names, clipping them off
     * after a certain amount of letters. False to disable or integer letters
     * before clipping.
     * @type bool
     */
    protected $compress = false;

    /**
     * @param string $name Form element name for directives to be stuffed into
     * @param string $doc_url String documentation URL, will have fragment tagged on
     * @param bool $compress Integer max length before compressing a directive name, set to false to turn off
     */
    public function __construct(
        $name,
        $doc_url = null,
        $compress = false
    ) {
        parent::__construct();
        $this->docURL = $doc_url;
        $this->name = $name;
        $this->compress = $compress;
        // initialize sub-printers
        $this->fields[0] = new HTMLPurifier_Printer_ConfigForm_default();
        $this->fields[HTMLPurifier_VarParser::C_BOOL] = new HTMLPurifier_Printer_ConfigForm_bool();
    }

    /**
     * Sets default column and row size for textareas in sub-printers
     * @param $cols Integer columns of textarea, null to use default
     * @param $rows Integer rows of textarea, null to use default
     */
    public function setTextareaDimensions($cols = null, $rows = null)
    {
        if ($cols) {
            $this->fields['default']->cols = $cols;
        }
        if ($rows) {
            $this->fields['default']->rows = $rows;
        }
    }

    /**
     * Retrieves styling, in case it is not accessible by webserver
     */
    public static function getCSS()
    {
        return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.css');
    }

    /**
     * Retrieves JavaScript, in case it is not accessible by webserver
     */
    public static function getJavaScript()
    {
        return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.js');
    }

    /**
     * Returns HTML output for a configuration form
     * @param HTMLPurifier_Config|array $config Configuration object of current form state, or an array
     *        where [0] has an HTML namespace and [1] is being rendered.
     * @param array|bool $allowed Optional namespace(s) and directives to restrict form to.
     * @param bool $render_controls
     * @return string
     */
    public function render($config, $allowed = true, $render_controls = true)
    {
        if (is_array($config) && isset($config[0])) {
            $gen_config = $config[0];
            $config = $config[1];
        } else {
            $gen_config = $config;
        }

        $this->config = $config;
        $this->genConfig = $gen_config;
        $this->prepareGenerator($gen_config);

        $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $config->def);
        $all = array();
        foreach ($allowed as $key) {
            list($ns, $directive) = $key;
            $all[$ns][$directive] = $config->get($ns . '.' . $directive);
        }

        $ret = '';
        $ret .= $this->start('table', array('class' => 'hp-config'));
        $ret .= $this->start('thead');
        $ret .= $this->start('tr');
        $ret .= $this->element('th', 'Directive', array('class' => 'hp-directive'));
        $ret .= $this->element('th', 'Value', array('class' => 'hp-value'));
        $ret .= $this->end('tr');
        $ret .= $this->end('thead');
        foreach ($all as $ns => $directives) {
            $ret .= $this->renderNamespace($ns, $directives);
        }
        if ($render_controls) {
            $ret .= $this->start('tbody');
            $ret .= $this->start('tr');
            $ret .= $this->start('td', array('colspan' => 2, 'class' => 'controls'));
            $ret .= $this->elementEmpty('input', array('type' => 'submit', 'value' => 'Submit'));
            $ret .= '[Reset]';
            $ret .= $this->end('td');
            $ret .= $this->end('tr');
            $ret .= $this->end('tbody');
        }
        $ret .= $this->end('table');
        return $ret;
    }

    /**
     * Renders a single namespace
     * @param $ns String namespace name
     * @param array $directives array of directives to values
     * @return string
     */
    protected function renderNamespace($ns, $directives)
    {
        $ret = '';
        $ret .= $this->start('tbody', array('class' => 'namespace'));
        $ret .= $this->start('tr');
        $ret .= $this->element('th', $ns, array('colspan' => 2));
        $ret .= $this->end('tr');
        $ret .= $this->end('tbody');
        $ret .= $this->start('tbody');
        foreach ($directives as $directive => $value) {
            $ret .= $this->start('tr');
            $ret .= $this->start('th');
            if ($this->docURL) {
                $url = str_replace('%s', urlencode("$ns.$directive"), $this->docURL);
                $ret .= $this->start('a', array('href' => $url));
            }
            $attr = array('for' => "{$this->name}:$ns.$directive");

            // crop directive name if it's too long
            if (!$this->compress || (strlen($directive) < $this->compress)) {
                $directive_disp = $directive;
            } else {
                $directive_disp = substr($directive, 0, $this->compress - 2) . '...';
                $attr['title'] = $directive;
            }

            $ret .= $this->element(
                'label',
                $directive_disp,
                // component printers must create an element with this id
                $attr
            );
            if ($this->docURL) {
                $ret .= $this->end('a');
            }
            $ret .= $this->end('th');

            $ret .= $this->start('td');
            $def = $this->config->def->info["$ns.$directive"];
            if (is_int($def)) {
                $allow_null = $def < 0;
                $type = abs($def);
            } else {
                $type = $def->type;
                $allow_null = isset($def->allow_null);
            }
            if (!isset($this->fields[$type])) {
                $type = 0;
            } // default
            $type_obj = $this->fields[$type];
            if ($allow_null) {
                $type_obj = new HTMLPurifier_Printer_ConfigForm_NullDecorator($type_obj);
            }
            $ret .= $type_obj->render($ns, $directive, $value, $this->name, array($this->genConfig, $this->config));
            $ret .= $this->end('td');
            $ret .= $this->end('tr');
        }
        $ret .= $this->end('tbody');
        return $ret;
    }

}

/**
 * Printer decorator for directives that accept null
 */
class HTMLPurifier_Printer_ConfigForm_NullDecorator extends HTMLPurifier_Printer
{
    /**
     * Printer being decorated
     * @type HTMLPurifier_Printer
     */
    protected $obj;

    /**
     * @param HTMLPurifier_Printer $obj Printer to decorate
     */
    public function __construct($obj)
    {
        parent::__construct();
        $this->obj = $obj;
    }

    /**
     * @param string $ns
     * @param string $directive
     * @param string $value
     * @param string $name
     * @param HTMLPurifier_Config|array $config
     * @return string
     */
    public function render($ns, $directive, $value, $name, $config)
    {
        if (is_array($config) && isset($config[0])) {
            $gen_config = $config[0];
            $config = $config[1];
        } else {
            $gen_config = $config;
        }
        $this->prepareGenerator($gen_config);

        $ret = '';
        $ret .= $this->start('label', array('for' => "$name:Null_$ns.$directive"));
        $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));
        $ret .= $this->text(' Null/Disabled');
        $ret .= $this->end('label');
        $attr = array(
            'type' => 'checkbox',
            'value' => '1',
            'class' => 'null-toggle',
            'name' => "$name" . "[Null_$ns.$directive]",
            'id' => "$name:Null_$ns.$directive",
            'onclick' => "toggleWriteability('$name:$ns.$directive',checked)" // INLINE JAVASCRIPT!!!!
        );
        if ($this->obj instanceof HTMLPurifier_Printer_ConfigForm_bool) {
            // modify inline javascript slightly
            $attr['onclick'] =
                "toggleWriteability('$name:Yes_$ns.$directive',checked);" .
                "toggleWriteability('$name:No_$ns.$directive',checked)";
        }
        if ($value === null) {
            $attr['checked'] = 'checked';
        }
        $ret .= $this->elementEmpty('input', $attr);
        $ret .= $this->text(' or ');
        $ret .= $this->elementEmpty('br');
        $ret .= $this->obj->render($ns, $directive, $value, $name, array($gen_config, $config));
        return $ret;
    }
}

/**
 * Swiss-army knife configuration form field printer
 */
class HTMLPurifier_Printer_ConfigForm_default extends HTMLPurifier_Printer
{
    /**
     * @type int
     */
    public $cols = 18;

    /**
     * @type int
     */
    public $rows = 5;

    /**
     * @param string $ns
     * @param string $directive
     * @param string $value
     * @param string $name
     * @param HTMLPurifier_Config|array $config
     * @return string
     */
    public function render($ns, $directive, $value, $name, $config)
    {
        if (is_array($config) && isset($config[0])) {
            $gen_config = $config[0];
            $config = $config[1];
        } else {
            $gen_config = $config;
        }
        $this->prepareGenerator($gen_config);
        // this should probably be split up a little
        $ret = '';
        $def = $config->def->info["$ns.$directive"];
        if (is_int($def)) {
            $type = abs($def);
        } else {
            $type = $def->type;
        }
        if (is_array($value)) {
            switch ($type) {
                case HTMLPurifier_VarParser::LOOKUP:
                    $array = $value;
                    $value = array();
                    foreach ($array as $val => $b) {
                        $value[] = $val;
                    }
                    //TODO does this need a break?
                case HTMLPurifier_VarParser::ALIST:
                    $value = implode(PHP_EOL, $value);
                    break;
                case HTMLPurifier_VarParser::HASH:
                    $nvalue = '';
                    foreach ($value as $i => $v) {
                        if (is_array($v)) {
                            // HACK
                            $v = implode(";", $v);
                        }
                        $nvalue .= "$i:$v" . PHP_EOL;
                    }
                    $value = $nvalue;
                    break;
                default:
                    $value = '';
            }
        }
        if ($type === HTMLPurifier_VarParser::C_MIXED) {
            return 'Not supported';
            $value = serialize($value);
        }
        $attr = array(
            'name' => "$name" . "[$ns.$directive]",
            'id' => "$name:$ns.$directive"
        );
        if ($value === null) {
            $attr['disabled'] = 'disabled';
        }
        if (isset($def->allowed)) {
            $ret .= $this->start('select', $attr);
            foreach ($def->allowed as $val => $b) {
                $attr = array();
                if ($value == $val) {
                    $attr['selected'] = 'selected';
                }
                $ret .= $this->element('option', $val, $attr);
            }
            $ret .= $this->end('select');
        } elseif ($type === HTMLPurifier_VarParser::TEXT ||
                $type === HTMLPurifier_VarParser::ITEXT ||
                $type === HTMLPurifier_VarParser::ALIST ||
                $type === HTMLPurifier_VarParser::HASH ||
                $type === HTMLPurifier_VarParser::LOOKUP) {
            $attr['cols'] = $this->cols;
            $attr['rows'] = $this->rows;
            $ret .= $this->start('textarea', $attr);
            $ret .= $this->text($value);
            $ret .= $this->end('textarea');
        } else {
            $attr['value'] = $value;
            $attr['type'] = 'text';
            $ret .= $this->elementEmpty('input', $attr);
        }
        return $ret;
    }
}

/**
 * Bool form field printer
 */
class HTMLPurifier_Printer_ConfigForm_bool extends HTMLPurifier_Printer
{
    /**
     * @param string $ns
     * @param string $directive
     * @param string $value
     * @param string $name
     * @param HTMLPurifier_Config|array $config
     * @return string
     */
    public function render($ns, $directive, $value, $name, $config)
    {
        if (is_array($config) && isset($config[0])) {
            $gen_config = $config[0];
            $config = $config[1];
        } else {
            $gen_config = $config;
        }
        $this->prepareGenerator($gen_config);
        $ret = '';
        $ret .= $this->start('div', array('id' => "$name:$ns.$directive"));

        $ret .= $this->start('label', array('for' => "$name:Yes_$ns.$directive"));
        $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));
        $ret .= $this->text(' Yes');
        $ret .= $this->end('label');

        $attr = array(
            'type' => 'radio',
            'name' => "$name" . "[$ns.$directive]",
            'id' => "$name:Yes_$ns.$directive",
            'value' => '1'
        );
        if ($value === true) {
            $attr['checked'] = 'checked';
        }
        if ($value === null) {
            $attr['disabled'] = 'disabled';
        }
        $ret .= $this->elementEmpty('input', $attr);

        $ret .= $this->start('label', array('for' => "$name:No_$ns.$directive"));
        $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));
        $ret .= $this->text(' No');
        $ret .= $this->end('label');

        $attr = array(
            'type' => 'radio',
            'name' => "$name" . "[$ns.$directive]",
            'id' => "$name:No_$ns.$directive",
            'value' => '0'
        );
        if ($value === false) {
            $attr['checked'] = 'checked';
        }
        if ($value === null) {
            $attr['disabled'] = 'disabled';
        }
        $ret .= $this->elementEmpty('input', $attr);

        $ret .= $this->end('div');

        return $ret;
    }
}

// vim: et sw=4 sts=4


code:
<?php

class HTMLPurifier_Printer_HTMLDefinition extends HTMLPurifier_Printer
{

    /**
     * @type HTMLPurifier_HTMLDefinition, for easy access
     */
    protected $def;

    /**
     * @param HTMLPurifier_Config $config
     * @return string
     */
    public function render($config)
    {
        $ret = '';
        $this->config =& $config;

        $this->def = $config->getHTMLDefinition();

        $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer'));

        $ret .= $this->renderDoctype();
        $ret .= $this->renderEnvironment();
        $ret .= $this->renderContentSets();
        $ret .= $this->renderInfo();

        $ret .= $this->end('div');

        return $ret;
    }

    /**
     * Renders the Doctype table
     * @return string
     */
    protected function renderDoctype()
    {
        $doctype = $this->def->doctype;
        $ret = '';
        $ret .= $this->start('table');
        $ret .= $this->element('caption', 'Doctype');
        $ret .= $this->row('Name', $doctype->name);
        $ret .= $this->row('XML', $doctype->xml ? 'Yes' : 'No');
        $ret .= $this->row('Default Modules', implode($doctype->modules, ', '));
        $ret .= $this->row('Default Tidy Modules', implode($doctype->tidyModules, ', '));
        $ret .= $this->end('table');
        return $ret;
    }

    /**
     * Renders environment table, which is miscellaneous info
     * @return string
     */
    protected function renderEnvironment()
    {
        $def = $this->def;

        $ret = '';

        $ret .= $this->start('table');
        $ret .= $this->element('caption', 'Environment');

        $ret .= $this->row('Parent of fragment', $def->info_parent);
        $ret .= $this->renderChildren($def->info_parent_def->child);
        $ret .= $this->row('Block wrap name', $def->info_block_wrapper);

        $ret .= $this->start('tr');
        $ret .= $this->element('th', 'Global attributes');
        $ret .= $this->element('td', $this->listifyAttr($def->info_global_attr), null, 0);
        $ret .= $this->end('tr');

        $ret .= $this->start('tr');
        $ret .= $this->element('th', 'Tag transforms');
        $list = array();
        foreach ($def->info_tag_transform as $old => $new) {
            $new = $this->getClass($new, 'TagTransform_');
            $list[] = "<$old> with $new";
        }
        $ret .= $this->element('td', $this->listify($list));
        $ret .= $this->end('tr');

        $ret .= $this->start('tr');
        $ret .= $this->element('th', 'Pre-AttrTransform');
        $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_pre));
        $ret .= $this->end('tr');

        $ret .= $this->start('tr');
        $ret .= $this->element('th', 'Post-AttrTransform');
        $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_post));
        $ret .= $this->end('tr');

        $ret .= $this->end('table');
        return $ret;
    }

    /**
     * Renders the Content Sets table
     * @return string
     */
    protected function renderContentSets()
    {
        $ret = '';
        $ret .= $this->start('table');
        $ret .= $this->element('caption', 'Content Sets');
        foreach ($this->def->info_content_sets as $name => $lookup) {
            $ret .= $this->heavyHeader($name);
            $ret .= $this->start('tr');
            $ret .= $this->element('td', $this->listifyTagLookup($lookup));
            $ret .= $this->end('tr');
        }
        $ret .= $this->end('table');
        return $ret;
    }

    /**
     * Renders the Elements ($info) table
     * @return string
     */
    protected function renderInfo()
    {
        $ret = '';
        $ret .= $this->start('table');
        $ret .= $this->element('caption', 'Elements ($info)');
        ksort($this->def->info);
        $ret .= $this->heavyHeader('Allowed tags', 2);
        $ret .= $this->start('tr');
        $ret .= $this->element('td', $this->listifyTagLookup($this->def->info), array('colspan' => 2));
        $ret .= $this->end('tr');
        foreach ($this->def->info as $name => $def) {
            $ret .= $this->start('tr');
            $ret .= $this->element('th', "<$name>", array('class' => 'heavy', 'colspan' => 2));
            $ret .= $this->end('tr');
            $ret .= $this->start('tr');
            $ret .= $this->element('th', 'Inline content');
            $ret .= $this->element('td', $def->descendants_are_inline ? 'Yes' : 'No');
            $ret .= $this->end('tr');
            if (!empty($def->excludes)) {
                $ret .= $this->start('tr');
                $ret .= $this->element('th', 'Excludes');
                $ret .= $this->element('td', $this->listifyTagLookup($def->excludes));
                $ret .= $this->end('tr');
            }
            if (!empty($def->attr_transform_pre)) {
                $ret .= $this->start('tr');
                $ret .= $this->element('th', 'Pre-AttrTransform');
                $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_pre));
                $ret .= $this->end('tr');
            }
            if (!empty($def->attr_transform_post)) {
                $ret .= $this->start('tr');
                $ret .= $this->element('th', 'Post-AttrTransform');
                $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_post));
                $ret .= $this->end('tr');
            }
            if (!empty($def->auto_close)) {
                $ret .= $this->start('tr');
                $ret .= $this->element('th', 'Auto closed by');
                $ret .= $this->element('td', $this->listifyTagLookup($def->auto_close));
                $ret .= $this->end('tr');
            }
            $ret .= $this->start('tr');
            $ret .= $this->element('th', 'Allowed attributes');
            $ret .= $this->element('td', $this->listifyAttr($def->attr), array(), 0);
            $ret .= $this->end('tr');

            if (!empty($def->required_attr)) {
                $ret .= $this->row('Required attributes', $this->listify($def->required_attr));
            }

            $ret .= $this->renderChildren($def->child);
        }
        $ret .= $this->end('table');
        return $ret;
    }

    /**
     * Renders a row describing the allowed children of an element
     * @param HTMLPurifier_ChildDef $def HTMLPurifier_ChildDef of pertinent element
     * @return string
     */
    protected function renderChildren($def)
    {
        $context = new HTMLPurifier_Context();
        $ret = '';
        $ret .= $this->start('tr');
        $elements = array();
        $attr = array();
        if (isset($def->elements)) {
            if ($def->type == 'strictblockquote') {
                $def->validateChildren(array(), $this->config, $context);
            }
            $elements = $def->elements;
        }
        if ($def->type == 'chameleon') {
            $attr['rowspan'] = 2;
        } elseif ($def->type == 'empty') {
            $elements = array();
        } elseif ($def->type == 'table') {
            $elements = array_flip(
                array(
                    'col',
                    'caption',
                    'colgroup',
                    'thead',
                    'tfoot',
                    'tbody',
                    'tr'
                )
            );
        }
        $ret .= $this->element('th', 'Allowed children', $attr);

        if ($def->type == 'chameleon') {

            $ret .= $this->element(
                'td',
                'Block: ' .
                $this->escape($this->listifyTagLookup($def->block->elements)),
                null,
                0
            );
            $ret .= $this->end('tr');
            $ret .= $this->start('tr');
            $ret .= $this->element(
                'td',
                'Inline: ' .
                $this->escape($this->listifyTagLookup($def->inline->elements)),
                null,
                0
            );

        } elseif ($def->type == 'custom') {

            $ret .= $this->element(
                'td',
                '' . ucfirst($def->type) . ': ' .
                $def->dtd_regex
            );

        } else {
            $ret .= $this->element(
                'td',
                '' . ucfirst($def->type) . ': ' .
                $this->escape($this->listifyTagLookup($elements)),
                null,
                0
            );
        }
        $ret .= $this->end('tr');
        return $ret;
    }

    /**
     * Listifies a tag lookup table.
     * @param array $array Tag lookup array in form of array('tagname' => true)
     * @return string
     */
    protected function listifyTagLookup($array)
    {
        ksort($array);
        $list = array();
        foreach ($array as $name => $discard) {
            if ($name !== '#PCDATA' && !isset($this->def->info[$name])) {
                continue;
            }
            $list[] = $name;
        }
        return $this->listify($list);
    }

    /**
     * Listifies a list of objects by retrieving class names and internal state
     * @param array $array List of objects
     * @return string
     * @todo Also add information about internal state
     */
    protected function listifyObjectList($array)
    {
        ksort($array);
        $list = array();
        foreach ($array as $obj) {
            $list[] = $this->getClass($obj, 'AttrTransform_');
        }
        return $this->listify($list);
    }

    /**
     * Listifies a hash of attributes to AttrDef classes
     * @param array $array Array hash in form of array('attrname' => HTMLPurifier_AttrDef)
     * @return string
     */
    protected function listifyAttr($array)
    {
        ksort($array);
        $list = array();
        foreach ($array as $name => $obj) {
            if ($obj === false) {
                continue;
            }
            $list[] = "$name = " . $this->getClass($obj, 'AttrDef_') . '';
        }
        return $this->listify($list);
    }

    /**
     * Creates a heavy header row
     * @param string $text
     * @param int $num
     * @return string
     */
    protected function heavyHeader($text, $num = 1)
    {
        $ret = '';
        $ret .= $this->start('tr');
        $ret .= $this->element('th', $text, array('colspan' => $num, 'class' => 'heavy'));
        $ret .= $this->end('tr');
        return $ret;
    }
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * Generic property list implementation
 */
class HTMLPurifier_PropertyList
{
    /**
     * Internal data-structure for properties.
     * @type array
     */
    protected $data = array();

    /**
     * Parent plist.
     * @type HTMLPurifier_PropertyList
     */
    protected $parent;

    /**
     * Cache.
     * @type array
     */
    protected $cache;

    /**
     * @param HTMLPurifier_PropertyList $parent Parent plist
     */
    public function __construct($parent = null)
    {
        $this->parent = $parent;
    }

    /**
     * Recursively retrieves the value for a key
     * @param string $name
     * @throws HTMLPurifier_Exception
     */
    public function get($name)
    {
        if ($this->has($name)) {
            return $this->data[$name];
        }
        // possible performance bottleneck, convert to iterative if necessary
        if ($this->parent) {
            return $this->parent->get($name);
        }
        throw new HTMLPurifier_Exception("Key '$name' not found");
    }

    /**
     * Sets the value of a key, for this plist
     * @param string $name
     * @param mixed $value
     */
    public function set($name, $value)
    {
        $this->data[$name] = $value;
    }

    /**
     * Returns true if a given key exists
     * @param string $name
     * @return bool
     */
    public function has($name)
    {
        return array_key_exists($name, $this->data);
    }

    /**
     * Resets a value to the value of it's parent, usually the default. If
     * no value is specified, the entire plist is reset.
     * @param string $name
     */
    public function reset($name = null)
    {
        if ($name == null) {
            $this->data = array();
        } else {
            unset($this->data[$name]);
        }
    }

    /**
     * Squashes this property list and all of its property lists into a single
     * array, and returns the array. This value is cached by default.
     * @param bool $force If true, ignores the cache and regenerates the array.
     * @return array
     */
    public function squash($force = false)
    {
        if ($this->cache !== null && !$force) {
            return $this->cache;
        }
        if ($this->parent) {
            return $this->cache = array_merge($this->parent->squash($force), $this->data);
        } else {
            return $this->cache = $this->data;
        }
    }

    /**
     * Returns the parent plist.
     * @return HTMLPurifier_PropertyList
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Sets the parent plist.
     * @param HTMLPurifier_PropertyList $plist Parent plist
     */
    public function setParent($plist)
    {
        $this->parent = $plist;
    }
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * Property list iterator. Do not instantiate this class directly.
 */
class HTMLPurifier_PropertyListIterator extends FilterIterator
{

    /**
     * @type int
     */
    protected $l;
    /**
     * @type string
     */
    protected $filter;

    /**
     * @param Iterator $iterator Array of data to iterate over
     * @param string $filter Optional prefix to only allow values of
     */
    public function __construct(Iterator $iterator, $filter = null)
    {
        parent::__construct($iterator);
        $this->l = strlen($filter);
        $this->filter = $filter;
    }

    /**
     * @return bool
     */
    public function accept()
    {
        $key = $this->getInnerIterator()->key();
        if (strncmp($key, $this->filter, $this->l) !== 0) {
            return false;
        }
        return true;
    }
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * A simple array-backed queue, based off of the classic Okasaki
 * persistent amortized queue.  The basic idea is to maintain two
 * stacks: an input stack and an output stack.  When the output
 * stack runs out, reverse the input stack and use it as the output
 * stack.
 *
 * We don't use the SPL implementation because it's only supported
 * on PHP 5.3 and later.
 *
 * Exercise: Prove that push/pop on this queue take amortized O(1) time.
 *
 * Exercise: Extend this queue to be a deque, while preserving amortized
 * O(1) time.  Some care must be taken on rebalancing to avoid quadratic
 * behaviour caused by repeatedly shuffling data from the input stack
 * to the output stack and back.
 */
class HTMLPurifier_Queue {
    private $input;
    private $output;

    public function __construct($input = array()) {
        $this->input = $input;
        $this->output = array();
    }

    /**
     * Shifts an element off the front of the queue.
     */
    public function shift() {
        if (empty($this->output)) {
            $this->output = array_reverse($this->input);
            $this->input = array();
        }
        if (empty($this->output)) {
            return NULL;
        }
        return array_pop($this->output);
    }

    /**
     * Pushes an element onto the front of the queue.
     */
    public function push($x) {
        array_push($this->input, $x);
    }

    /**
     * Checks if it's empty.
     */
    public function isEmpty() {
        return empty($this->input) && empty($this->output);
    }
}


code:
<?php

/**
 * Supertype for classes that define a strategy for modifying/purifying tokens.
 *
 * While HTMLPurifier's core purpose is fixing HTML into something proper,
 * strategies provide plug points for extra configuration or even extra
 * features, such as custom tags, custom parsing of text, etc.
 */

abstract class HTMLPurifier_Strategy
{

    /**
     * Executes the strategy on the tokens.
     *
     * @param HTMLPurifier_Token[] $tokens Array of HTMLPurifier_Token objects to be operated on.
     * @param HTMLPurifier_Config $config
     * @param HTMLPurifier_Context $context
     * @return HTMLPurifier_Token[] Processed array of token objects.
     */
    abstract public function execute($tokens, $config, $context);
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * Composite strategy that runs multiple strategies on tokens.
 */
abstract class HTMLPurifier_Strategy_Composite extends HTMLPurifier_Strategy
{

    /**
     * List of strategies to run tokens through.
     * @type HTMLPurifier_Strategy[]
     */
    protected $strategies = array();

    /**
     * @param HTMLPurifier_Token[] $tokens
     * @param HTMLPurifier_Config $config
     * @param HTMLPurifier_Context $context
     * @return HTMLPurifier_Token[]
     */
    public function execute($tokens, $config, $context)
    {
        foreach ($this->strategies as $strategy) {
            $tokens = $strategy->execute($tokens, $config, $context);
        }
        return $tokens;
    }
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * Core strategy composed of the big four strategies.
 */
class HTMLPurifier_Strategy_Core extends HTMLPurifier_Strategy_Composite
{
    public function __construct()
    {
        $this->strategies[] = new HTMLPurifier_Strategy_RemoveForeignElements();
        $this->strategies[] = new HTMLPurifier_Strategy_MakeWellFormed();
        $this->strategies[] = new HTMLPurifier_Strategy_FixNesting();
        $this->strategies[] = new HTMLPurifier_Strategy_ValidateAttributes();
    }
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * Takes a well formed list of tokens and fixes their nesting.
 *
 * HTML elements dictate which elements are allowed to be their children,
 * for example, you can't have a p tag in a span tag.  Other elements have
 * much more rigorous definitions: tables, for instance, require a specific
 * order for their elements.  There are also constraints not expressible by
 * document type definitions, such as the chameleon nature of ins/del
 * tags and global child exclusions.
 *
 * The first major objective of this strategy is to iterate through all
 * the nodes and determine whether or not their children conform to the
 * element's definition.  If they do not, the child definition may
 * optionally supply an amended list of elements that is valid or
 * require that the entire node be deleted (and the previous node
 * rescanned).
 *
 * The second objective is to ensure that explicitly excluded elements of
 * an element do not appear in its children.  Code that accomplishes this
 * task is pervasive through the strategy, though the two are distinct tasks
 * and could, theoretically, be seperated (although it's not recommended).
 *
 * @note Whether or not unrecognized children are silently dropped or
 *       translated into text depends on the child definitions.
 *
 * @todo Enable nodes to be bubbled out of the structure.  This is
 *       easier with our new algorithm.
 */

class HTMLPurifier_Strategy_FixNesting extends HTMLPurifier_Strategy
{

    /**
     * @param HTMLPurifier_Token[] $tokens
     * @param HTMLPurifier_Config $config
     * @param HTMLPurifier_Context $context
     * @return array|HTMLPurifier_Token[]
     */
    public function execute($tokens, $config, $context)
    {

        //####################################################################//
        // Pre-processing

        // O(n) pass to convert to a tree, so that we can efficiently
        // refer to substrings
        $top_node = HTMLPurifier_Arborize::arborize($tokens, $config, $context);

        // get a copy of the HTML definition
        $definition = $config->getHTMLDefinition();

        $excludes_enabled = !$config->get('Core.DisableExcludes');

        // setup the context variable 'IsInline', for chameleon processing
        // is 'false' when we are not inline, 'true' when it must always
        // be inline, and an integer when it is inline for a certain
        // branch of the document tree
        $is_inline = $definition->info_parent_def->descendants_are_inline;
        $context->register('IsInline', $is_inline);

        // setup error collector
        $e =& $context->get('ErrorCollector', true);

        //####################################################################//
        // Loop initialization

        // stack that contains all elements that are excluded
        // it is organized by parent elements, similar to $stack,
        // but it is only populated when an element with exclusions is
        // processed, i.e. there won't be empty exclusions.
        $exclude_stack = array($definition->info_parent_def->excludes);

        // variable that contains the start token while we are processing
        // nodes. This enables error reporting to do its job
        $node = $top_node;
        // dummy token
        list($token, $d) = $node->toTokenPair();
        $context->register('CurrentNode', $node);
        $context->register('CurrentToken', $token);

        //####################################################################//
        // Loop

        // We need to implement a post-order traversal iteratively, to
        // avoid running into stack space limits.  This is pretty tricky
        // to reason about, so we just manually stack-ify the recursive
        // variant:
        //
        //  function f($node) {
        //      foreach ($node->children as $child) {
        //          f($child);
        //      }
        //      validate($node);
        //  }
        //
        // Thus, we will represent a stack frame as array($node,
        // $is_inline, stack of children)
        // e.g. array_reverse($node->children) - already processed
        // children.

        $parent_def = $definition->info_parent_def;
        $stack = array(
            array($top_node,
                  $parent_def->descendants_are_inline,
                  $parent_def->excludes, // exclusions
                  0)
            );

        while (!empty($stack)) {
            list($node, $is_inline, $excludes, $ix) = array_pop($stack);
            // recursive call
            $go = false;
            $def = empty($stack) ? $definition->info_parent_def : $definition->info[$node->name];
            while (isset($node->children[$ix])) {
                $child = $node->children[$ix++];
                if ($child instanceof HTMLPurifier_Node_Element) {
                    $go = true;
                    $stack[] = array($node, $is_inline, $excludes, $ix);
                    $stack[] = array($child,
                        // ToDo: I don't think it matters if it's def or
                        // child_def, but double check this...
                        $is_inline || $def->descendants_are_inline,
                        empty($def->excludes) ? $excludes
                                              : array_merge($excludes, $def->excludes),
                        0);
                    break;
                }
            };
            if ($go) continue;
            list($token, $d) = $node->toTokenPair();
            // base case
            if ($excludes_enabled && isset($excludes[$node->name])) {
                $node->dead = true;
                if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded');
            } else {
                // XXX I suppose it would be slightly more efficient to
                // avoid the allocation here and have children
                // strategies handle it
                $children = array();
                foreach ($node->children as $child) {
                    if (!$child->dead) $children[] = $child;
                }
                $result = $def->child->validateChildren($children, $config, $context);
                if ($result === true) {
                    // nop
                    $node->children = $children;
                } elseif ($result === false) {
                    $node->dead = true;
                    if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node removed');
                } else {
                    $node->children = $result;
                    if ($e) {
                        // XXX This will miss mutations of internal nodes. Perhaps defer to the child validators
                        if (empty($result) && !empty($children)) {
                            $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed');
                        } else if ($result != $children) {
                            $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized');
                        }
                    }
                }
            }
        }

        //####################################################################//
        // Post-processing

        // remove context variables
        $context->destroy('IsInline');
        $context->destroy('CurrentNode');
        $context->destroy('CurrentToken');

        //####################################################################//
        // Return

        return HTMLPurifier_Arborize::flatten($node, $config, $context);
    }
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * Takes tokens makes them well-formed (balance end tags, etc.)
 *
 * Specification of the armor attributes this strategy uses:
 *
 *      - MakeWellFormed_TagClosedError: This armor field is used to
 *        suppress tag closed errors for certain tokens [TagClosedSuppress],
 *        in particular, if a tag was generated automatically by HTML
 *        Purifier, we may rely on our infrastructure to close it for us
 *        and shouldn't report an error to the user [TagClosedAuto].
 */
class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
{

    /**
     * Array stream of tokens being processed.
     * @type HTMLPurifier_Token[]
     */
    protected $tokens;

    /**
     * Current token.
     * @type HTMLPurifier_Token
     */
    protected $token;

    /**
     * Zipper managing the true state.
     * @type HTMLPurifier_Zipper
     */
    protected $zipper;

    /**
     * Current nesting of elements.
     * @type array
     */
    protected $stack;

    /**
     * Injectors active in this stream processing.
     * @type HTMLPurifier_Injector[]
     */
    protected $injectors;

    /**
     * Current instance of HTMLPurifier_Config.
     * @type HTMLPurifier_Config
     */
    protected $config;

    /**
     * Current instance of HTMLPurifier_Context.
     * @type HTMLPurifier_Context
     */
    protected $context;

    /**
     * @param HTMLPurifier_Token[] $tokens
     * @param HTMLPurifier_Config $config
     * @param HTMLPurifier_Context $context
     * @return HTMLPurifier_Token[]
     * @throws HTMLPurifier_Exception
     */
    public function execute($tokens, $config, $context)
    {
        $definition = $config->getHTMLDefinition();

        // local variables
        $generator = new HTMLPurifier_Generator($config, $context);
        $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
        // used for autoclose early abortion
        $global_parent_allowed_elements = $definition->info_parent_def->child->getAllowedElements($config);
        $e = $context->get('ErrorCollector', true);
        $i = false; // injector index
        list($zipper, $token) = HTMLPurifier_Zipper::fromArray($tokens);
        if ($token === NULL) {
            return array();
        }
        $reprocess = false; // whether or not to reprocess the same token
        $stack = array();

        // member variables
        $this->stack =& $stack;
        $this->tokens =& $tokens;
        $this->token =& $token;
        $this->zipper =& $zipper;
        $this->config = $config;
        $this->context = $context;

        // context variables
        $context->register('CurrentNesting', $stack);
        $context->register('InputZipper', $zipper);
        $context->register('CurrentToken', $token);

        // -- begin INJECTOR --

        $this->injectors = array();

        $injectors = $config->getBatch('AutoFormat');
        $def_injectors = $definition->info_injector;
        $custom_injectors = $injectors['Custom'];
        unset($injectors['Custom']); // special case
        foreach ($injectors as $injector => $b) {
            // XXX: Fix with a legitimate lookup table of enabled filters
            if (strpos($injector, '.') !== false) {
                continue;
            }
            $injector = "HTMLPurifier_Injector_$injector";
            if (!$b) {
                continue;
            }
            $this->injectors[] = new $injector;
        }
        foreach ($def_injectors as $injector) {
            // assumed to be objects
            $this->injectors[] = $injector;
        }
        foreach ($custom_injectors as $injector) {
            if (!$injector) {
                continue;
            }
            if (is_string($injector)) {
                $injector = "HTMLPurifier_Injector_$injector";
                $injector = new $injector;
            }
            $this->injectors[] = $injector;
        }

        // give the injectors references to the definition and context
        // variables for performance reasons
        foreach ($this->injectors as $ix => $injector) {
            $error = $injector->prepare($config, $context);
            if (!$error) {
                continue;
            }
            array_splice($this->injectors, $ix, 1); // rm the injector
            trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING);
        }

        // -- end INJECTOR --

        // a note on reprocessing:
        //      In order to reduce code duplication, whenever some code needs
        //      to make HTML changes in order to make things "correct", the
        //      new HTML gets sent through the purifier, regardless of its
        //      status. This means that if we add a start token, because it
        //      was totally necessary, we don't have to update nesting; we just
        //      punt ($reprocess = true; continue;) and it does that for us.

        // isset is in loop because $tokens size changes during loop exec
        for (;;
             // only increment if we don't need to reprocess
             $reprocess ? $reprocess = false : $token = $zipper->next($token)) {

            // check for a rewind
            if (is_int($i)) {
                // possibility: disable rewinding if the current token has a
                // rewind set on it already. This would offer protection from
                // infinite loop, but might hinder some advanced rewinding.
                $rewind_offset = $this->injectors[$i]->getRewindOffset();
                if (is_int($rewind_offset)) {
                    for ($j = 0; $j < $rewind_offset; $j++) {
                        if (empty($zipper->front)) break;
                        $token = $zipper->prev($token);
                        // indicate that other injectors should not process this token,
                        // but we need to reprocess it.  See Note [Injector skips]
                        unset($token->skip[$i]);
                        $token->rewind = $i;
                        if ($token instanceof HTMLPurifier_Token_Start) {
                            array_pop($this->stack);
                        } elseif ($token instanceof HTMLPurifier_Token_End) {
                            $this->stack[] = $token->start;
                        }
                    }
                }
                $i = false;
            }

            // handle case of document end
            if ($token === NULL) {
                // kill processing if stack is empty
                if (empty($this->stack)) {
                    break;
                }

                // peek
                $top_nesting = array_pop($this->stack);
                $this->stack[] = $top_nesting;

                // send error [TagClosedSuppress]
                if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) {
                    $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting);
                }

                // append, don't splice, since this is the end
                $token = new HTMLPurifier_Token_End($top_nesting->name);

                // punt!
                $reprocess = true;
                continue;
            }

            //echo '
'; printZipper($zipper, $token);//printTokens($this->stack);
            //flush();

            // quick-check: if it's not a tag, no need to process
            if (empty($token->is_tag)) {
                if ($token instanceof HTMLPurifier_Token_Text) {
                    foreach ($this->injectors as $i => $injector) {
                        if (isset($token->skip[$i])) {
                            // See Note [Injector skips]
                            continue;
                        }
                        if ($token->rewind !== null && $token->rewind !== $i) {
                            continue;
                        }
                        // XXX fuckup
                        $r = $token;
                        $injector->handleText($r);
                        $token = $this->processToken($r, $i);
                        $reprocess = true;
                        break;
                    }
                }
                // another possibility is a comment
                continue;
            }

            if (isset($definition->info[$token->name])) {
                $type = $definition->info[$token->name]->child->type;
            } else {
                $type = false; // Type is unknown, treat accordingly
            }

            // quick tag checks: anything that's *not* an end tag
            $ok = false;
            if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) {
                // claims to be a start tag but is empty
                $token = new HTMLPurifier_Token_Empty(
                    $token->name,
                    $token->attr,
                    $token->line,
                    $token->col,
                    $token->armor
                );
                $ok = true;
            } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) {
                // claims to be empty but really is a start tag
                // NB: this assignment is required
                $old_token = $token;
                $token = new HTMLPurifier_Token_End($token->name);
                $token = $this->insertBefore(
                    new HTMLPurifier_Token_Start($old_token->name, $old_token->attr, $old_token->line, $old_token->col, $old_token->armor)
                );
                // punt (since we had to modify the input stream in a non-trivial way)
                $reprocess = true;
                continue;
            } elseif ($token instanceof HTMLPurifier_Token_Empty) {
                // real empty token
                $ok = true;
            } elseif ($token instanceof HTMLPurifier_Token_Start) {
                // start tag

                // ...unless they also have to close their parent
                if (!empty($this->stack)) {

                    // Performance note: you might think that it's rather
                    // inefficient, recalculating the autoclose information
                    // for every tag that a token closes (since when we
                    // do an autoclose, we push a new token into the
                    // stream and then /process/ that, before
                    // re-processing this token.)  But this is
                    // necessary, because an injector can make an
                    // arbitrary transformations to the autoclosing
                    // tokens we introduce, so things may have changed
                    // in the meantime.  Also, doing the inefficient thing is
                    // "easy" to reason about (for certain perverse definitions
                    // of "easy")

                    $parent = array_pop($this->stack);
                    $this->stack[] = $parent;

                    $parent_def = null;
                    $parent_elements = null;
                    $autoclose = false;
                    if (isset($definition->info[$parent->name])) {
                        $parent_def = $definition->info[$parent->name];
                        $parent_elements = $parent_def->child->getAllowedElements($config);
                        $autoclose = !isset($parent_elements[$token->name]);
                    }

                    if ($autoclose && $definition->info[$token->name]->wrap) {
                        // Check if an element can be wrapped by another
                        // element to make it valid in a context (for
                        // example,

 needs a
 in between)
                        $wrapname = $definition->info[$token->name]->wrap;
                        $wrapdef = $definition->info[$wrapname];
                        $elements = $wrapdef->child->getAllowedElements($config);
                        if (isset($elements[$token->name]) && isset($parent_elements[$wrapname])) {
                            $newtoken = new HTMLPurifier_Token_Start($wrapname);
                            $token = $this->insertBefore($newtoken);
                            $reprocess = true;
                            continue;
                        }
                    }

                    $carryover = false;
                    if ($autoclose && $parent_def->formatting) {
                        $carryover = true;
                    }

                    if ($autoclose) {
                        // check if this autoclose is doomed to fail
                        // (this rechecks $parent, which his harmless)
                        $autoclose_ok = isset($global_parent_allowed_elements[$token->name]);
                        if (!$autoclose_ok) {
                            foreach ($this->stack as $ancestor) {
                                $elements = $definition->info[$ancestor->name]->child->getAllowedElements($config);
                                if (isset($elements[$token->name])) {
                                    $autoclose_ok = true;
                                    break;
                                }
                                if ($definition->info[$token->name]->wrap) {
                                    $wrapname = $definition->info[$token->name]->wrap;
                                    $wrapdef = $definition->info[$wrapname];
                                    $wrap_elements = $wrapdef->child->getAllowedElements($config);
                                    if (isset($wrap_elements[$token->name]) && isset($elements[$wrapname])) {
                                        $autoclose_ok = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if ($autoclose_ok) {
                            // errors need to be updated
                            $new_token = new HTMLPurifier_Token_End($parent->name);
                            $new_token->start = $parent;
                            // [TagClosedSuppress]
                            if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) {
                                if (!$carryover) {
                                    $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);
                                } else {
                                    $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent);
                                }
                            }
                            if ($carryover) {
                                $element = clone $parent;
                                // [TagClosedAuto]
                                $element->armor['MakeWellFormed_TagClosedError'] = true;
                                $element->carryover = true;
                                $token = $this->processToken(array($new_token, $token, $element));
                            } else {
                                $token = $this->insertBefore($new_token);
                            }
                        } else {
                            $token = $this->remove();
                        }
                        $reprocess = true;
                        continue;
                    }

                }
                $ok = true;
            }

            if ($ok) {
                foreach ($this->injectors as $i => $injector) {
                    if (isset($token->skip[$i])) {
                        // See Note [Injector skips]
                        continue;
                    }
                    if ($token->rewind !== null && $token->rewind !== $i) {
                        continue;
                    }
                    $r = $token;
                    $injector->handleElement($r);
                    $token = $this->processToken($r, $i);
                    $reprocess = true;
                    break;
                }
                if (!$reprocess) {
                    // ah, nothing interesting happened; do normal processing
                    if ($token instanceof HTMLPurifier_Token_Start) {
                        $this->stack[] = $token;
                    } elseif ($token instanceof HTMLPurifier_Token_End) {
                        throw new HTMLPurifier_Exception(
                            'Improper handling of end tag in start code; possible error in MakeWellFormed'
                        );
                    }
                }
                continue;
            }

            // sanity check: we should be dealing with a closing tag
            if (!$token instanceof HTMLPurifier_Token_End) {
                throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier');
            }

            // make sure that we have something open
            if (empty($this->stack)) {
                if ($escape_invalid_tags) {
                    if ($e) {
                        $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text');
                    }
                    $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token));
                } else {
                    if ($e) {
                        $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed');
                    }
                    $token = $this->remove();
                }
                $reprocess = true;
                continue;
            }

            // first, check for the simplest case: everything closes neatly.
            // Eventually, everything passes through here; if there are problems
            // we modify the input stream accordingly and then punt, so that
            // the tokens get processed again.
            $current_parent = array_pop($this->stack);
            if ($current_parent->name == $token->name) {
                $token->start = $current_parent;
                foreach ($this->injectors as $i => $injector) {
                    if (isset($token->skip[$i])) {
                        // See Note [Injector skips]
                        continue;
                    }
                    if ($token->rewind !== null && $token->rewind !== $i) {
                        continue;
                    }
                    $r = $token;
                    $injector->handleEnd($r);
                    $token = $this->processToken($r, $i);
                    $this->stack[] = $current_parent;
                    $reprocess = true;
                    break;
                }
                continue;
            }

            // okay, so we're trying to close the wrong tag

            // undo the pop previous pop
            $this->stack[] = $current_parent;

            // scroll back the entire nest, trying to find our tag.
            // (feature could be to specify how far you'd like to go)
            $size = count($this->stack);
            // -2 because -1 is the last element, but we already checked that
            $skipped_tags = false;
            for ($j = $size - 2; $j >= 0; $j--) {
                if ($this->stack[$j]->name == $token->name) {
                    $skipped_tags = array_slice($this->stack, $j);
                    break;
                }
            }

            // we didn't find the tag, so remove
            if ($skipped_tags === false) {
                if ($escape_invalid_tags) {
                    if ($e) {
                        $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text');
                    }
                    $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token));
                } else {
                    if ($e) {
                        $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed');
                    }
                    $token = $this->remove();
                }
                $reprocess = true;
                continue;
            }

            // do errors, in REVERSE $j order: a,b,c with </c>
            $c = count($skipped_tags);
            if ($e) {
                for ($j = $c - 1; $j > 0; $j--) {
                    // notice we exclude $j == 0, i.e. the current ending tag, from
                    // the errors... [TagClosedSuppress]
                    if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) {
                        $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]);
                    }
                }
            }

            // insert tags, in FORWARD $j order: c,b,a with </c>
            $replace = array($token);
            for ($j = 1; $j < $c; $j++) {
                // ...as well as from the insertions
                $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name);
                $new_token->start = $skipped_tags[$j];
                array_unshift($replace, $new_token);
                if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) {
                    // [TagClosedAuto]
                    $element = clone $skipped_tags[$j];
                    $element->carryover = true;
                    $element->armor['MakeWellFormed_TagClosedError'] = true;
                    $replace[] = $element;
                }
            }
            $token = $this->processToken($replace);
            $reprocess = true;
            continue;
        }

        $context->destroy('CurrentToken');
        $context->destroy('CurrentNesting');
        $context->destroy('InputZipper');

        unset($this->injectors, $this->stack, $this->tokens);
        return $zipper->toArray($token);
    }

    /**
     * Processes arbitrary token values for complicated substitution patterns.
     * In general:
     *
     * If $token is an array, it is a list of tokens to substitute for the
     * current token. These tokens then get individually processed. If there
     * is a leading integer in the list, that integer determines how many
     * tokens from the stream should be removed.
     *
     * If $token is a regular token, it is swapped with the current token.
     *
     * If $token is false, the current token is deleted.
     *
     * If $token is an integer, that number of tokens (with the first token
     * being the current one) will be deleted.
     *
     * @param HTMLPurifier_Token|array|int|bool $token Token substitution value
     * @param HTMLPurifier_Injector|int $injector Injector that performed the substitution; default is if
     *        this is not an injector related operation.
     * @throws HTMLPurifier_Exception
     */
    protected function processToken($token, $injector = -1)
    {
        // Zend OpCache miscompiles $token = array($token), so
        // avoid this pattern.  See: https://github.com/ezyang/htmlpurifier/issues/108

        // normalize forms of token
        if (is_object($token)) {
            $tmp = $token;
            $token = array(1, $tmp);
        }
        if (is_int($token)) {
            $tmp = $token;
            $token = array($tmp);
        }
        if ($token === false) {
            $token = array(1);
        }
        if (!is_array($token)) {
            throw new HTMLPurifier_Exception('Invalid token type from injector');
        }
        if (!is_int($token[0])) {
            array_unshift($token, 1);
        }
        if ($token[0] === 0) {
            throw new HTMLPurifier_Exception('Deleting zero tokens is not valid');
        }

        // $token is now an array with the following form:
        // array(number nodes to delete, new node 1, new node 2, ...)

        $delete = array_shift($token);
        list($old, $r) = $this->zipper->splice($this->token, $delete, $token);

        if ($injector > -1) {
            // See Note [Injector skips]
            // Determine appropriate skips.  Here's what the code does:
            //  *If* we deleted one or more tokens, copy the skips
            //  of those tokens into the skips of the new tokens (in $token).
            //  Also, mark the newly inserted tokens as having come from
            //  $injector.
            $oldskip = isset($old[0]) ? $old[0]->skip : array();
            foreach ($token as $object) {
                $object->skip = $oldskip;
                $object->skip[$injector] = true;
            }
        }

        return $r;

    }

    /**
     * Inserts a token before the current token. Cursor now points to
     * this token.  You must reprocess after this.
     * @param HTMLPurifier_Token $token
     */
    private function insertBefore($token)
    {
        // NB not $this->zipper->insertBefore(), due to positioning
        // differences
        $splice = $this->zipper->splice($this->token, 0, array($token));

        return $splice[1];
    }

    /**
     * Removes current token. Cursor now points to new token occupying previously
     * occupied space.  You must reprocess after this.
     */
    private function remove()
    {
        return $this->zipper->delete();
    }
}

// Note [Injector skips]
// ~~~~~~~~~~~~~~~~~~~~~
// When I originally designed this class, the idea behind the 'skip'
// property of HTMLPurifier_Token was to help avoid infinite loops
// in injector processing.  For example, suppose you wrote an injector
// that bolded swear words.  Naively, you might write it so that
// whenever you saw ****, you replaced it with ****.
//
// When this happens, we will reprocess all of the tokens with the
// other injectors.  Now there is an opportunity for infinite loop:
// if we rerun the swear-word injector on these tokens, we might
// see **** and then reprocess again to get
// **** ad infinitum.
//
// Thus, the idea of a skip is that once we process a token with
// an injector, we mark all of those tokens as having "come from"
// the injector, and we never run the injector again on these
// tokens.
//
// There were two more complications, however:
//
//  - With HTMLPurifier_Injector_RemoveEmpty, we noticed that if
//    you had , after you removed the , you
//    really would like this injector to go back and reprocess
//    the  tag, discovering that it is now empty and can be
//    removed.  So we reintroduced the possibility of infinite looping
//    by adding a "rewind" function, which let you go back to an
//    earlier point in the token stream and reprocess it with injectors.
//    Needless to say, we need to UN-skip the token so it gets
//    reprocessed.
//
//  - Suppose that you successfuly process a token, replace it with
//    one with your skip mark, but now another injector wants to
//    process the skipped token with another token.  Should you continue
//    to skip that new token, or reprocess it?  If you reprocess,
//    you can end up with an infinite loop where one injector converts
//     to , and then another injector converts it back.  So
//    we inherit the skips, but for some reason, I thought that we
//    should inherit the skip from the first token of the token
//    that we deleted.  Why?  Well, it seems to work OK.
//
// If I were to redesign this functionality, I would absolutely not
// go about doing it this way: the semantics are just not very well
// defined, and in any case you probably wanted to operate on trees,
// not token streams.

// vim: et sw=4 sts=4


code:
<?php

/**
 * Removes all unrecognized tags from the list of tokens.
 *
 * This strategy iterates through all the tokens and removes unrecognized
 * tokens. If a token is not recognized but a TagTransform is defined for
 * that element, the element will be transformed accordingly.
 */

class HTMLPurifier_Strategy_RemoveForeignElements extends HTMLPurifier_Strategy
{

    /**
     * @param HTMLPurifier_Token[] $tokens
     * @param HTMLPurifier_Config $config
     * @param HTMLPurifier_Context $context
     * @return array|HTMLPurifier_Token[]
     */
    public function execute($tokens, $config, $context)
    {
        $definition = $config->getHTMLDefinition();
        $generator = new HTMLPurifier_Generator($config, $context);
        $result = array();

        $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
        $remove_invalid_img = $config->get('Core.RemoveInvalidImg');

        // currently only used to determine if comments should be kept
        $trusted = $config->get('HTML.Trusted');
        $comment_lookup = $config->get('HTML.AllowedComments');
        $comment_regexp = $config->get('HTML.AllowedCommentsRegexp');
        $check_comments = $comment_lookup !== array() || $comment_regexp !== null;

        $remove_script_contents = $config->get('Core.RemoveScriptContents');
        $hidden_elements = $config->get('Core.HiddenElements');

        // remove script contents compatibility
        if ($remove_script_contents === true) {
            $hidden_elements['script'] = true;
        } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) {
            unset($hidden_elements['script']);
        }

        $attr_validator = new HTMLPurifier_AttrValidator();

        // removes tokens until it reaches a closing tag with its value
        $remove_until = false;

        // converts comments into text tokens when this is equal to a tag name
        $textify_comments = false;

        $token = false;
        $context->register('CurrentToken', $token);

        $e = false;
        if ($config->get('Core.CollectErrors')) {
            $e =& $context->get('ErrorCollector');
        }

        foreach ($tokens as $token) {
            if ($remove_until) {
                if (empty($token->is_tag) || $token->name !== $remove_until) {
                    continue;
                }
            }
            if (!empty($token->is_tag)) {
                // DEFINITION CALL

                // before any processing, try to transform the element
                if (isset($definition->info_tag_transform[$token->name])) {
                    $original_name = $token->name;
                    // there is a transformation for this tag
                    // DEFINITION CALL
                    $token = $definition->
                        info_tag_transform[$token->name]->transform($token, $config, $context);
                    if ($e) {
                        $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name);
                    }
                }

                if (isset($definition->info[$token->name])) {
                    // mostly everything's good, but
                    // we need to make sure required attributes are in order
                    if (($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) &&
                        $definition->info[$token->name]->required_attr &&
                        ($token->name != 'img' || $remove_invalid_img) // ensure config option still works
                    ) {
                        $attr_validator->validateToken($token, $config, $context);
                        $ok = true;
                        foreach ($definition->info[$token->name]->required_attr as $name) {
                            if (!isset($token->attr[$name])) {
                                $ok = false;
                                break;
                            }
                        }
                        if (!$ok) {
                            if ($e) {
                                $e->send(
                                    E_ERROR,
                                    'Strategy_RemoveForeignElements: Missing required attribute',
                                    $name
                                );
                            }
                            continue;
                        }
                        $token->armor['ValidateAttributes'] = true;
                    }

                    if (isset($hidden_elements[$token->name]) && $token instanceof HTMLPurifier_Token_Start) {
                        $textify_comments = $token->name;
                    } elseif ($token->name === $textify_comments && $token instanceof HTMLPurifier_Token_End) {
                        $textify_comments = false;
                    }

                } elseif ($escape_invalid_tags) {
                    // invalid tag, generate HTML representation and insert in
                    if ($e) {
                        $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text');
                    }
                    $token = new HTMLPurifier_Token_Text(
                        $generator->generateFromToken($token)
                    );
                } else {
                    // check if we need to destroy all of the tag's children
                    // CAN BE GENERICIZED
                    if (isset($hidden_elements[$token->name])) {
                        if ($token instanceof HTMLPurifier_Token_Start) {
                            $remove_until = $token->name;
                        } elseif ($token instanceof HTMLPurifier_Token_Empty) {
                            // do nothing: we're still looking
                        } else {
                            $remove_until = false;
                        }
                        if ($e) {
                            $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed');
                        }
                    } else {
                        if ($e) {
                            $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign element removed');
                        }
                    }
                    continue;
                }
            } elseif ($token instanceof HTMLPurifier_Token_Comment) {
                // textify comments in script tags when they are allowed
                if ($textify_comments !== false) {
                    $data = $token->data;
                    $token = new HTMLPurifier_Token_Text($data);
                } elseif ($trusted || $check_comments) {
                    // always cleanup comments
                    $trailing_hyphen = false;
                    if ($e) {
                        // perform check whether or not there's a trailing hyphen
                        if (substr($token->data, -1) == '-') {
                            $trailing_hyphen = true;
                        }
                    }
                    $token->data = rtrim($token->data, '-');
                    $found_double_hyphen = false;
                    while (strpos($token->data, '--') !== false) {
                        $found_double_hyphen = true;
                        $token->data = str_replace('--', '-', $token->data);
                    }
                    if ($trusted || !empty($comment_lookup[trim($token->data)]) ||
                        ($comment_regexp !== null && preg_match($comment_regexp, trim($token->data)))) {
                        // OK good
                        if ($e) {
                            if ($trailing_hyphen) {
                                $e->send(
                                    E_NOTICE,
                                    'Strategy_RemoveForeignElements: Trailing hyphen in comment removed'
                                );
                            }
                            if ($found_double_hyphen) {
                                $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Hyphens in comment collapsed');
                            }
                        }
                    } else {
                        if ($e) {
                            $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed');
                        }
                        continue;
                    }
                } else {
                    // strip comments
                    if ($e) {
                        $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed');
                    }
                    continue;
                }
            } elseif ($token instanceof HTMLPurifier_Token_Text) {
            } else {
                continue;
            }
            $result[] = $token;
        }
        if ($remove_until && $e) {
            // we removed tokens until the end, throw error
            $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Token removed to end', $remove_until);
        }
        $context->destroy('CurrentToken');
        return $result;
    }
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * Validate all attributes in the tokens.
 */

class HTMLPurifier_Strategy_ValidateAttributes extends HTMLPurifier_Strategy
{

    /**
     * @param HTMLPurifier_Token[] $tokens
     * @param HTMLPurifier_Config $config
     * @param HTMLPurifier_Context $context
     * @return HTMLPurifier_Token[]
     */
    public function execute($tokens, $config, $context)
    {
        // setup validator
        $validator = new HTMLPurifier_AttrValidator();

        $token = false;
        $context->register('CurrentToken', $token);

        foreach ($tokens as $key => $token) {

            // only process tokens that have attributes,
            //   namely start and empty tags
            if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) {
                continue;
            }

            // skip tokens that are armored
            if (!empty($token->armor['ValidateAttributes'])) {
                continue;
            }

            // note that we have no facilities here for removing tokens
            $validator->validateToken($token, $config, $context);
        }
        $context->destroy('CurrentToken');
        return $tokens;
    }
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * This is in almost every respect equivalent to an array except
 * that it keeps track of which keys were accessed.
 *
 * @warning For the sake of backwards compatibility with early versions
 *     of PHP 5, you must not use the $hash[$key] syntax; if you do
 *     our version of offsetGet is never called.
 */
class HTMLPurifier_StringHash extends ArrayObject
{
    /**
     * @type array
     */
    protected $accessed = array();

    /**
     * Retrieves a value, and logs the access.
     * @param mixed $index
     * @return mixed
     */
    public function offsetGet($index)
    {
        $this->accessed[$index] = true;
        return parent::offsetGet($index);
    }

    /**
     * Returns a lookup array of all array indexes that have been accessed.
     * @return array in form array($index => true).
     */
    public function getAccessed()
    {
        return $this->accessed;
    }

    /**
     * Resets the access array.
     */
    public function resetAccessed()
    {
        $this->accessed = array();
    }
}

// vim: et sw=4 sts=4


code:
<?php

/**
 * Parses string hash files. File format is as such:
 *
 *      DefaultKeyValue
 *      KEY: Value
 *      KEY2: Value2
 *      --MULTILINE-KEY--
 *      Multiline
 *      value.
 *
 * Which would output something similar to:
 *
 *      array(
 *          'ID' => 'DefaultKeyValue',
 *          'KEY' => 'Value',
 *          'KEY2' => 'Value2',
 *          'MULTILINE-KEY' => "Multiline\nvalue.\n",
 *      )
 *
 * We use this as an easy to use file-format for configuration schema
 * files, but the class itself is usage agnostic.
 *
 * You can use ---- to forcibly terminate parsing of a single string-hash;
 * this marker is used in multi string-hashes to delimit boundaries.
 */
class HTMLPurifier_StringHashParser
{

    /**
     * @type string
     */
    public $default = 'ID';

    /**
     * Parses a file that contains a single string-hash.
     * @param string $file
     * @return array
     */
    public function parseFile($file)
    {
        if (!file_exists($file)) {
            return false;
        }
        $fh = fopen($file, 'r');
        if (!$fh) {
            return false;
        }
        $ret = $this->parseHandle($fh);
        fclose($fh);
        return $ret;
    }

    /**
     * Parses a file that contains multiple string-hashes delimited by '----'
     * @param string $file
     * @return array
     */
    public function parseMultiFile($file)
    {
        if (!file_exists($file)) {
            return false;
        }
        $ret = array();
        $fh = fopen($file, 'r');
        if (!$fh) {
            return false;
        }
        while (!feof($fh)) {
            $ret[] = $this->parseHandle($fh);
        }
        fclose($fh);
        return $ret;
    }

    /**
     * Internal parser that acepts a file handle.
     * @note While it's possible to simulate in-memory parsing by using
     *       custom stream wrappers, if such a use-case arises we should
     *       factor out the file handle into its own class.
     * @param resource $fh File handle with pointer at start of valid string-hash
     *            block.
     * @return array
     */
    protected function parseHandle($fh)
    {
        $state   = false;
        $single  = false;
        $ret     = array();
        do {
            $line = fgets($fh);
            if ($line === false) {
                break;
            }
            $line = rtrim($line, "\n\r");
            if (!$state && $line === '') {
                continue;
            }
            if ($line === '----') {
                break;
            }
            if (strncmp('--#', $line, 3) === 0) {
                // Comment
                continue;
            } elseif (strncmp('--', $line, 2) === 0) {
                // Multiline declaration
                $state = trim($line, '- ');
                if (!isset($ret[$state])) {
                    $ret[$state] = '';
                }
                continue;
            } elseif (!$state) {
                $single = true;
                if (strpos($line, ':') !== false) {
                    // Single-line declaration
                    list($state, $line) = explode(':', $line, 2);
                    $line = trim($line);
                } else {
                    // Use default declaration
                    $state  = $this->default;
                }
            }
            if ($single) {
                $ret[$state] = $line;
                $single = false;
                $state  = false;
            } else {
                $ret[$state] .= "$line\n";
            }
        } while (!feof($fh));
        return $ret;
    }
}

// vim: et sw=4 sts=4