Planworld v3 Alpha "Gordon" 20191005
authorJohnnie Lamar Odom II <jlodom00@alumni.amherst.edu>
Sun, 6 Oct 2019 02:40:26 +0000 (21:40 -0500)
committerJohnnie Lamar Odom II <jlodom00@alumni.amherst.edu>
Sun, 6 Oct 2019 02:40:26 +0000 (21:40 -0500)
Interim release -- more detailed message in next commit.
This release adds basic watchlist and plan reading and writing functionality.
It builds on the infrastructure in previous releases.
Please see the setup document for information on the API calls that have been added.
With this release, there should be sufficient functionality to build real API clients
and to debate technical decisions going forward for things like blocklists.

162 files changed:
code/backend/HTMLPurifier.standalone.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/Builder/Xml.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/Exception.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/Interchange.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/Interchange/Directive.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/Interchange/Id.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/InterchangeBuilder.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/Validator.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/ValidatorAtom.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema.ser [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.Language.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Base.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Host.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/ConfigSchema/schema/info.ini [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/EntityLookup/entities.ser [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Filter/ExtractStyleBlocks.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Filter/YouTube.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Language/classes/en-x-test.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Language/messages/en-x-test.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Language/messages/en-x-testmini.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Language/messages/en.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Lexer/PH5P.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Printer.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Printer/CSSDefinition.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Printer/ConfigForm.css [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Printer/ConfigForm.js [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Printer/ConfigForm.php [new file with mode: 0644]
code/backend/standalone/HTMLPurifier/Printer/HTMLDefinition.php [new file with mode: 0644]
code/clientlib/3.00/plan.php [new file with mode: 0644]
code/clientlib/3.00/watchlist.php [new file with mode: 0644]
code/lib/Online.php [new file with mode: 0644]
code/lib/Planwatch.php [new file with mode: 0644]
code/lib/Planworld.php
code/lib/Snoop.php [new file with mode: 0644]
code/lib/User.php
code/scaffolding/debug_client.html
description [deleted file]
setup/readme.md

diff --git a/code/backend/HTMLPurifier.standalone.php b/code/backend/HTMLPurifier.standalone.php
new file mode 100644 (file)
index 0000000..598bbff
--- /dev/null
@@ -0,0 +1,22579 @@
+<?php\r
+\r
+/**\r
+ * @file\r
+ * This file was auto-generated by generate-includes.php and includes all of\r
+ * the core files required by HTML Purifier. Use this if performance is a\r
+ * primary concern and you are using an opcode cache. PLEASE DO NOT EDIT THIS\r
+ * FILE, changes will be overwritten the next time the script is run.\r
+ *\r
+ * @version 4.11.0\r
+ *\r
+ * @warning\r
+ *      You must *not* include any other HTML Purifier files before this file,\r
+ *      because 'require' not 'require_once' is used.\r
+ *\r
+ * @warning\r
+ *      This file requires that the include path contains the HTML Purifier\r
+ *      library directory; this is not auto-set.\r
+ */\r
+\r
+\r
+\r
+/*! @mainpage\r
+ *\r
+ * HTML Purifier is an HTML filter that will take an arbitrary snippet of\r
+ * HTML and rigorously test, validate and filter it into a version that\r
+ * is safe for output onto webpages. It achieves this by:\r
+ *\r
+ *  -# Lexing (parsing into tokens) the document,\r
+ *  -# Executing various strategies on the tokens:\r
+ *      -# Removing all elements not in the whitelist,\r
+ *      -# Making the tokens well-formed,\r
+ *      -# Fixing the nesting of the nodes, and\r
+ *      -# Validating attributes of the nodes; and\r
+ *  -# Generating HTML from the purified tokens.\r
+ *\r
+ * However, most users will only need to interface with the HTMLPurifier\r
+ * and HTMLPurifier_Config.\r
+ */\r
+\r
+/*\r
+    HTML Purifier 4.11.0 - Standards Compliant HTML Filtering\r
+    Copyright (C) 2006-2008 Edward Z. Yang\r
+\r
+    This library is free software; you can redistribute it and/or\r
+    modify it under the terms of the GNU Lesser General Public\r
+    License as published by the Free Software Foundation; either\r
+    version 2.1 of the License, or (at your option) any later version.\r
+\r
+    This library is distributed in the hope that it will be useful,\r
+    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
+    Lesser General Public License for more details.\r
+\r
+    You should have received a copy of the GNU Lesser General Public\r
+    License along with this library; if not, write to the Free Software\r
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\r
+ */\r
+\r
+/**\r
+ * Facade that coordinates HTML Purifier's subsystems in order to purify HTML.\r
+ *\r
+ * @note There are several points in which configuration can be specified\r
+ *       for HTML Purifier.  The precedence of these (from lowest to\r
+ *       highest) is as follows:\r
+ *          -# Instance: new HTMLPurifier($config)\r
+ *          -# Invocation: purify($html, $config)\r
+ *       These configurations are entirely independent of each other and\r
+ *       are *not* merged (this behavior may change in the future).\r
+ *\r
+ * @todo We need an easier way to inject strategies using the configuration\r
+ *       object.\r
+ */\r
+class HTMLPurifier\r
+{\r
+\r
+    /**\r
+     * Version of HTML Purifier.\r
+     * @type string\r
+     */\r
+    public $version = '4.11.0';\r
+\r
+    /**\r
+     * Constant with version of HTML Purifier.\r
+     */\r
+    const VERSION = '4.11.0';\r
+\r
+    /**\r
+     * Global configuration object.\r
+     * @type HTMLPurifier_Config\r
+     */\r
+    public $config;\r
+\r
+    /**\r
+     * Array of extra filter objects to run on HTML,\r
+     * for backwards compatibility.\r
+     * @type HTMLPurifier_Filter[]\r
+     */\r
+    private $filters = array();\r
+\r
+    /**\r
+     * Single instance of HTML Purifier.\r
+     * @type HTMLPurifier\r
+     */\r
+    private static $instance;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Strategy_Core\r
+     */\r
+    protected $strategy;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Generator\r
+     */\r
+    protected $generator;\r
+\r
+    /**\r
+     * Resultant context of last run purification.\r
+     * Is an array of contexts if the last called method was purifyArray().\r
+     * @type HTMLPurifier_Context\r
+     */\r
+    public $context;\r
+\r
+    /**\r
+     * Initializes the purifier.\r
+     *\r
+     * @param HTMLPurifier_Config|mixed $config Optional HTMLPurifier_Config object\r
+     *                for all instances of the purifier, if omitted, a default\r
+     *                configuration is supplied (which can be overridden on a\r
+     *                per-use basis).\r
+     *                The parameter can also be any type that\r
+     *                HTMLPurifier_Config::create() supports.\r
+     */\r
+    public function __construct($config = null)\r
+    {\r
+        $this->config = HTMLPurifier_Config::create($config);\r
+        $this->strategy = new HTMLPurifier_Strategy_Core();\r
+    }\r
+\r
+    /**\r
+     * Adds a filter to process the output. First come first serve\r
+     *\r
+     * @param HTMLPurifier_Filter $filter HTMLPurifier_Filter object\r
+     */\r
+    public function addFilter($filter)\r
+    {\r
+        trigger_error(\r
+            'HTMLPurifier->addFilter() is deprecated, use configuration directives' .\r
+            ' in the Filter namespace or Filter.Custom',\r
+            E_USER_WARNING\r
+        );\r
+        $this->filters[] = $filter;\r
+    }\r
+\r
+    /**\r
+     * Filters an HTML snippet/document to be XSS-free and standards-compliant.\r
+     *\r
+     * @param string $html String of HTML to purify\r
+     * @param HTMLPurifier_Config $config Config object for this operation,\r
+     *                if omitted, defaults to the config object specified during this\r
+     *                object's construction. The parameter can also be any type\r
+     *                that HTMLPurifier_Config::create() supports.\r
+     *\r
+     * @return string Purified HTML\r
+     */\r
+    public function purify($html, $config = null)\r
+    {\r
+        // :TODO: make the config merge in, instead of replace\r
+        $config = $config ? HTMLPurifier_Config::create($config) : $this->config;\r
+\r
+        // implementation is partially environment dependant, partially\r
+        // configuration dependant\r
+        $lexer = HTMLPurifier_Lexer::create($config);\r
+\r
+        $context = new HTMLPurifier_Context();\r
+\r
+        // setup HTML generator\r
+        $this->generator = new HTMLPurifier_Generator($config, $context);\r
+        $context->register('Generator', $this->generator);\r
+\r
+        // set up global context variables\r
+        if ($config->get('Core.CollectErrors')) {\r
+            // may get moved out if other facilities use it\r
+            $language_factory = HTMLPurifier_LanguageFactory::instance();\r
+            $language = $language_factory->create($config, $context);\r
+            $context->register('Locale', $language);\r
+\r
+            $error_collector = new HTMLPurifier_ErrorCollector($context);\r
+            $context->register('ErrorCollector', $error_collector);\r
+        }\r
+\r
+        // setup id_accumulator context, necessary due to the fact that\r
+        // AttrValidator can be called from many places\r
+        $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);\r
+        $context->register('IDAccumulator', $id_accumulator);\r
+\r
+        $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context);\r
+\r
+        // setup filters\r
+        $filter_flags = $config->getBatch('Filter');\r
+        $custom_filters = $filter_flags['Custom'];\r
+        unset($filter_flags['Custom']);\r
+        $filters = array();\r
+        foreach ($filter_flags as $filter => $flag) {\r
+            if (!$flag) {\r
+                continue;\r
+            }\r
+            if (strpos($filter, '.') !== false) {\r
+                continue;\r
+            }\r
+            $class = "HTMLPurifier_Filter_$filter";\r
+            $filters[] = new $class;\r
+        }\r
+        foreach ($custom_filters as $filter) {\r
+            // maybe "HTMLPurifier_Filter_$filter", but be consistent with AutoFormat\r
+            $filters[] = $filter;\r
+        }\r
+        $filters = array_merge($filters, $this->filters);\r
+        // maybe prepare(), but later\r
+\r
+        for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) {\r
+            $html = $filters[$i]->preFilter($html, $config, $context);\r
+        }\r
+\r
+        // purified HTML\r
+        $html =\r
+            $this->generator->generateFromTokens(\r
+                // list of tokens\r
+                $this->strategy->execute(\r
+                    // list of un-purified tokens\r
+                    $lexer->tokenizeHTML(\r
+                        // un-purified HTML\r
+                        $html,\r
+                        $config,\r
+                        $context\r
+                    ),\r
+                    $config,\r
+                    $context\r
+                )\r
+            );\r
+\r
+        for ($i = $filter_size - 1; $i >= 0; $i--) {\r
+            $html = $filters[$i]->postFilter($html, $config, $context);\r
+        }\r
+\r
+        $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context);\r
+        $this->context =& $context;\r
+        return $html;\r
+    }\r
+\r
+    /**\r
+     * Filters an array of HTML snippets\r
+     *\r
+     * @param string[] $array_of_html Array of html snippets\r
+     * @param HTMLPurifier_Config $config Optional config object for this operation.\r
+     *                See HTMLPurifier::purify() for more details.\r
+     *\r
+     * @return string[] Array of purified HTML\r
+     */\r
+    public function purifyArray($array_of_html, $config = null)\r
+    {\r
+        $context_array = array();\r
+        foreach($array_of_html as $key=>$value){\r
+            if (is_array($value)) {\r
+                $array[$key] = $this->purifyArray($value, $config);\r
+            } else {\r
+                $array[$key] = $this->purify($value, $config);\r
+            }\r
+            $context_array[$key] = $this->context;\r
+        }\r
+        $this->context = $context_array;\r
+        return $array;\r
+    }\r
+\r
+    /**\r
+     * Singleton for enforcing just one HTML Purifier in your system\r
+     *\r
+     * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype\r
+     *                   HTMLPurifier instance to overload singleton with,\r
+     *                   or HTMLPurifier_Config instance to configure the\r
+     *                   generated version with.\r
+     *\r
+     * @return HTMLPurifier\r
+     */\r
+    public static function instance($prototype = null)\r
+    {\r
+        if (!self::$instance || $prototype) {\r
+            if ($prototype instanceof HTMLPurifier) {\r
+                self::$instance = $prototype;\r
+            } elseif ($prototype) {\r
+                self::$instance = new HTMLPurifier($prototype);\r
+            } else {\r
+                self::$instance = new HTMLPurifier();\r
+            }\r
+        }\r
+        return self::$instance;\r
+    }\r
+\r
+    /**\r
+     * Singleton for enforcing just one HTML Purifier in your system\r
+     *\r
+     * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype\r
+     *                   HTMLPurifier instance to overload singleton with,\r
+     *                   or HTMLPurifier_Config instance to configure the\r
+     *                   generated version with.\r
+     *\r
+     * @return HTMLPurifier\r
+     * @note Backwards compatibility, see instance()\r
+     */\r
+    public static function getInstance($prototype = null)\r
+    {\r
+        return HTMLPurifier::instance($prototype);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Converts a stream of HTMLPurifier_Token into an HTMLPurifier_Node,\r
+ * and back again.\r
+ *\r
+ * @note This transformation is not an equivalence.  We mutate the input\r
+ * token stream to make it so; see all [MUT] markers in code.\r
+ */\r
+class HTMLPurifier_Arborize\r
+{\r
+    public static function arborize($tokens, $config, $context) {\r
+        $definition = $config->getHTMLDefinition();\r
+        $parent = new HTMLPurifier_Token_Start($definition->info_parent);\r
+        $stack = array($parent->toNode());\r
+        foreach ($tokens as $token) {\r
+            $token->skip = null; // [MUT]\r
+            $token->carryover = null; // [MUT]\r
+            if ($token instanceof HTMLPurifier_Token_End) {\r
+                $token->start = null; // [MUT]\r
+                $r = array_pop($stack);\r
+                //assert($r->name === $token->name);\r
+                //assert(empty($token->attr));\r
+                $r->endCol = $token->col;\r
+                $r->endLine = $token->line;\r
+                $r->endArmor = $token->armor;\r
+                continue;\r
+            }\r
+            $node = $token->toNode();\r
+            $stack[count($stack)-1]->children[] = $node;\r
+            if ($token instanceof HTMLPurifier_Token_Start) {\r
+                $stack[] = $node;\r
+            }\r
+        }\r
+        //assert(count($stack) == 1);\r
+        return $stack[0];\r
+    }\r
+\r
+    public static function flatten($node, $config, $context) {\r
+        $level = 0;\r
+        $nodes = array($level => new HTMLPurifier_Queue(array($node)));\r
+        $closingTokens = array();\r
+        $tokens = array();\r
+        do {\r
+            while (!$nodes[$level]->isEmpty()) {\r
+                $node = $nodes[$level]->shift(); // FIFO\r
+                list($start, $end) = $node->toTokenPair();\r
+                if ($level > 0) {\r
+                    $tokens[] = $start;\r
+                }\r
+                if ($end !== NULL) {\r
+                    $closingTokens[$level][] = $end;\r
+                }\r
+                if ($node instanceof HTMLPurifier_Node_Element) {\r
+                    $level++;\r
+                    $nodes[$level] = new HTMLPurifier_Queue();\r
+                    foreach ($node->children as $childNode) {\r
+                        $nodes[$level]->push($childNode);\r
+                    }\r
+                }\r
+            }\r
+            $level--;\r
+            if ($level && isset($closingTokens[$level])) {\r
+                while ($token = array_pop($closingTokens[$level])) {\r
+                    $tokens[] = $token;\r
+                }\r
+            }\r
+        } while ($level > 0);\r
+        return $tokens;\r
+    }\r
+}\r
+
+\r
+\r
+/**\r
+ * Defines common attribute collections that modules reference\r
+ */\r
+\r
+class HTMLPurifier_AttrCollections\r
+{\r
+\r
+    /**\r
+     * Associative array of attribute collections, indexed by name.\r
+     * @type array\r
+     */\r
+    public $info = array();\r
+\r
+    /**\r
+     * Performs all expansions on internal data for use by other inclusions\r
+     * It also collects all attribute collection extensions from\r
+     * modules\r
+     * @param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance\r
+     * @param HTMLPurifier_HTMLModule[] $modules Hash array of HTMLPurifier_HTMLModule members\r
+     */\r
+    public function __construct($attr_types, $modules)\r
+    {\r
+        $this->doConstruct($attr_types, $modules);\r
+    }\r
+\r
+    public function doConstruct($attr_types, $modules)\r
+    {\r
+        // load extensions from the modules\r
+        foreach ($modules as $module) {\r
+            foreach ($module->attr_collections as $coll_i => $coll) {\r
+                if (!isset($this->info[$coll_i])) {\r
+                    $this->info[$coll_i] = array();\r
+                }\r
+                foreach ($coll as $attr_i => $attr) {\r
+                    if ($attr_i === 0 && isset($this->info[$coll_i][$attr_i])) {\r
+                        // merge in includes\r
+                        $this->info[$coll_i][$attr_i] = array_merge(\r
+                            $this->info[$coll_i][$attr_i],\r
+                            $attr\r
+                        );\r
+                        continue;\r
+                    }\r
+                    $this->info[$coll_i][$attr_i] = $attr;\r
+                }\r
+            }\r
+        }\r
+        // perform internal expansions and inclusions\r
+        foreach ($this->info as $name => $attr) {\r
+            // merge attribute collections that include others\r
+            $this->performInclusions($this->info[$name]);\r
+            // replace string identifiers with actual attribute objects\r
+            $this->expandIdentifiers($this->info[$name], $attr_types);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Takes a reference to an attribute associative array and performs\r
+     * all inclusions specified by the zero index.\r
+     * @param array &$attr Reference to attribute array\r
+     */\r
+    public function performInclusions(&$attr)\r
+    {\r
+        if (!isset($attr[0])) {\r
+            return;\r
+        }\r
+        $merge = $attr[0];\r
+        $seen  = array(); // recursion guard\r
+        // loop through all the inclusions\r
+        for ($i = 0; isset($merge[$i]); $i++) {\r
+            if (isset($seen[$merge[$i]])) {\r
+                continue;\r
+            }\r
+            $seen[$merge[$i]] = true;\r
+            // foreach attribute of the inclusion, copy it over\r
+            if (!isset($this->info[$merge[$i]])) {\r
+                continue;\r
+            }\r
+            foreach ($this->info[$merge[$i]] as $key => $value) {\r
+                if (isset($attr[$key])) {\r
+                    continue;\r
+                } // also catches more inclusions\r
+                $attr[$key] = $value;\r
+            }\r
+            if (isset($this->info[$merge[$i]][0])) {\r
+                // recursion\r
+                $merge = array_merge($merge, $this->info[$merge[$i]][0]);\r
+            }\r
+        }\r
+        unset($attr[0]);\r
+    }\r
+\r
+    /**\r
+     * Expands all string identifiers in an attribute array by replacing\r
+     * them with the appropriate values inside HTMLPurifier_AttrTypes\r
+     * @param array &$attr Reference to attribute array\r
+     * @param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance\r
+     */\r
+    public function expandIdentifiers(&$attr, $attr_types)\r
+    {\r
+        // because foreach will process new elements we add, make sure we\r
+        // skip duplicates\r
+        $processed = array();\r
+\r
+        foreach ($attr as $def_i => $def) {\r
+            // skip inclusions\r
+            if ($def_i === 0) {\r
+                continue;\r
+            }\r
+\r
+            if (isset($processed[$def_i])) {\r
+                continue;\r
+            }\r
+\r
+            // determine whether or not attribute is required\r
+            if ($required = (strpos($def_i, '*') !== false)) {\r
+                // rename the definition\r
+                unset($attr[$def_i]);\r
+                $def_i = trim($def_i, '*');\r
+                $attr[$def_i] = $def;\r
+            }\r
+\r
+            $processed[$def_i] = true;\r
+\r
+            // if we've already got a literal object, move on\r
+            if (is_object($def)) {\r
+                // preserve previous required\r
+                $attr[$def_i]->required = ($required || $attr[$def_i]->required);\r
+                continue;\r
+            }\r
+\r
+            if ($def === false) {\r
+                unset($attr[$def_i]);\r
+                continue;\r
+            }\r
+\r
+            if ($t = $attr_types->get($def)) {\r
+                $attr[$def_i] = $t;\r
+                $attr[$def_i]->required = $required;\r
+            } else {\r
+                unset($attr[$def_i]);\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Base class for all validating attribute definitions.\r
+ *\r
+ * This family of classes forms the core for not only HTML attribute validation,\r
+ * but also any sort of string that needs to be validated or cleaned (which\r
+ * means CSS properties and composite definitions are defined here too).\r
+ * Besides defining (through code) what precisely makes the string valid,\r
+ * subclasses are also responsible for cleaning the code if possible.\r
+ */\r
+\r
+abstract class HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Tells us whether or not an HTML attribute is minimized.\r
+     * Has no meaning in other contexts.\r
+     * @type bool\r
+     */\r
+    public $minimized = false;\r
+\r
+    /**\r
+     * Tells us whether or not an HTML attribute is required.\r
+     * Has no meaning in other contexts\r
+     * @type bool\r
+     */\r
+    public $required = false;\r
+\r
+    /**\r
+     * Validates and cleans passed string according to a definition.\r
+     *\r
+     * @param string $string String to be validated and cleaned.\r
+     * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object.\r
+     * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object.\r
+     */\r
+    abstract public function validate($string, $config, $context);\r
+\r
+    /**\r
+     * Convenience method that parses a string as if it were CDATA.\r
+     *\r
+     * This method process a string in the manner specified at\r
+     * <http://www.w3.org/TR/html4/types.html#h-6.2> by removing\r
+     * leading and trailing whitespace, ignoring line feeds, and replacing\r
+     * carriage returns and tabs with spaces.  While most useful for HTML\r
+     * attributes specified as CDATA, it can also be applied to most CSS\r
+     * values.\r
+     *\r
+     * @note This method is not entirely standards compliant, as trim() removes\r
+     *       more types of whitespace than specified in the spec. In practice,\r
+     *       this is rarely a problem, as those extra characters usually have\r
+     *       already been removed by HTMLPurifier_Encoder.\r
+     *\r
+     * @warning This processing is inconsistent with XML's whitespace handling\r
+     *          as specified by section 3.3.3 and referenced XHTML 1.0 section\r
+     *          4.7.  However, note that we are NOT necessarily\r
+     *          parsing XML, thus, this behavior may still be correct. We\r
+     *          assume that newlines have been normalized.\r
+     */\r
+    public function parseCDATA($string)\r
+    {\r
+        $string = trim($string);\r
+        $string = str_replace(array("\n", "\t", "\r"), ' ', $string);\r
+        return $string;\r
+    }\r
+\r
+    /**\r
+     * Factory method for creating this class from a string.\r
+     * @param string $string String construction info\r
+     * @return HTMLPurifier_AttrDef Created AttrDef object corresponding to $string\r
+     */\r
+    public function make($string)\r
+    {\r
+        // default implementation, return a flyweight of this object.\r
+        // If $string has an effect on the returned object (i.e. you\r
+        // need to overload this method), it is best\r
+        // to clone or instantiate new copies. (Instantiation is safer.)\r
+        return $this;\r
+    }\r
+\r
+    /**\r
+     * Removes spaces from rgb(0, 0, 0) so that shorthand CSS properties work\r
+     * properly. THIS IS A HACK!\r
+     * @param string $string a CSS colour definition\r
+     * @return string\r
+     */\r
+    protected function mungeRgb($string)\r
+    {\r
+        $p = '\s*(\d+(\.\d+)?([%]?))\s*';\r
+\r
+        if (preg_match('/(rgba|hsla)\(/', $string)) {\r
+            return preg_replace('/(rgba|hsla)\('.$p.','.$p.','.$p.','.$p.'\)/', '\1(\2,\5,\8,\11)', $string);\r
+        }\r
+\r
+        return preg_replace('/(rgb|hsl)\('.$p.','.$p.','.$p.'\)/', '\1(\2,\5,\8)', $string);\r
+    }\r
+\r
+    /**\r
+     * Parses a possibly escaped CSS string and returns the "pure"\r
+     * version of it.\r
+     */\r
+    protected function expandCSSEscape($string)\r
+    {\r
+        // flexibly parse it\r
+        $ret = '';\r
+        for ($i = 0, $c = strlen($string); $i < $c; $i++) {\r
+            if ($string[$i] === '\\') {\r
+                $i++;\r
+                if ($i >= $c) {\r
+                    $ret .= '\\';\r
+                    break;\r
+                }\r
+                if (ctype_xdigit($string[$i])) {\r
+                    $code = $string[$i];\r
+                    for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) {\r
+                        if (!ctype_xdigit($string[$i])) {\r
+                            break;\r
+                        }\r
+                        $code .= $string[$i];\r
+                    }\r
+                    // We have to be extremely careful when adding\r
+                    // new characters, to make sure we're not breaking\r
+                    // the encoding.\r
+                    $char = HTMLPurifier_Encoder::unichr(hexdec($code));\r
+                    if (HTMLPurifier_Encoder::cleanUTF8($char) === '') {\r
+                        continue;\r
+                    }\r
+                    $ret .= $char;\r
+                    if ($i < $c && trim($string[$i]) !== '') {\r
+                        $i--;\r
+                    }\r
+                    continue;\r
+                }\r
+                if ($string[$i] === "\n") {\r
+                    continue;\r
+                }\r
+            }\r
+            $ret .= $string[$i];\r
+        }\r
+        return $ret;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Processes an entire attribute array for corrections needing multiple values.\r
+ *\r
+ * Occasionally, a certain attribute will need to be removed and popped onto\r
+ * another value.  Instead of creating a complex return syntax for\r
+ * HTMLPurifier_AttrDef, we just pass the whole attribute array to a\r
+ * specialized object and have that do the special work.  That is the\r
+ * family of HTMLPurifier_AttrTransform.\r
+ *\r
+ * An attribute transformation can be assigned to run before or after\r
+ * HTMLPurifier_AttrDef validation.  See HTMLPurifier_HTMLDefinition for\r
+ * more details.\r
+ */\r
+\r
+abstract class HTMLPurifier_AttrTransform\r
+{\r
+\r
+    /**\r
+     * Abstract: makes changes to the attributes dependent on multiple values.\r
+     *\r
+     * @param array $attr Assoc array of attributes, usually from\r
+     *              HTMLPurifier_Token_Tag::$attr\r
+     * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object.\r
+     * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object\r
+     * @return array Processed attribute array.\r
+     */\r
+    abstract public function transform($attr, $config, $context);\r
+\r
+    /**\r
+     * Prepends CSS properties to the style attribute, creating the\r
+     * attribute if it doesn't exist.\r
+     * @param array &$attr Attribute array to process (passed by reference)\r
+     * @param string $css CSS to prepend\r
+     */\r
+    public function prependCSS(&$attr, $css)\r
+    {\r
+        $attr['style'] = isset($attr['style']) ? $attr['style'] : '';\r
+        $attr['style'] = $css . $attr['style'];\r
+    }\r
+\r
+    /**\r
+     * Retrieves and removes an attribute\r
+     * @param array &$attr Attribute array to process (passed by reference)\r
+     * @param mixed $key Key of attribute to confiscate\r
+     * @return mixed\r
+     */\r
+    public function confiscateAttr(&$attr, $key)\r
+    {\r
+        if (!isset($attr[$key])) {\r
+            return null;\r
+        }\r
+        $value = $attr[$key];\r
+        unset($attr[$key]);\r
+        return $value;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Provides lookup array of attribute types to HTMLPurifier_AttrDef objects\r
+ */\r
+class HTMLPurifier_AttrTypes\r
+{\r
+    /**\r
+     * Lookup array of attribute string identifiers to concrete implementations.\r
+     * @type HTMLPurifier_AttrDef[]\r
+     */\r
+    protected $info = array();\r
+\r
+    /**\r
+     * Constructs the info array, supplying default implementations for attribute\r
+     * types.\r
+     */\r
+    public function __construct()\r
+    {\r
+        // XXX This is kind of poor, since we don't actually /clone/\r
+        // instances; instead, we use the supplied make() attribute. So,\r
+        // the underlying class must know how to deal with arguments.\r
+        // With the old implementation of Enum, that ignored its\r
+        // arguments when handling a make dispatch, the IAlign\r
+        // definition wouldn't work.\r
+\r
+        // pseudo-types, must be instantiated via shorthand\r
+        $this->info['Enum']    = new HTMLPurifier_AttrDef_Enum();\r
+        $this->info['Bool']    = new HTMLPurifier_AttrDef_HTML_Bool();\r
+\r
+        $this->info['CDATA']    = new HTMLPurifier_AttrDef_Text();\r
+        $this->info['ID']       = new HTMLPurifier_AttrDef_HTML_ID();\r
+        $this->info['Length']   = new HTMLPurifier_AttrDef_HTML_Length();\r
+        $this->info['MultiLength'] = new HTMLPurifier_AttrDef_HTML_MultiLength();\r
+        $this->info['NMTOKENS'] = new HTMLPurifier_AttrDef_HTML_Nmtokens();\r
+        $this->info['Pixels']   = new HTMLPurifier_AttrDef_HTML_Pixels();\r
+        $this->info['Text']     = new HTMLPurifier_AttrDef_Text();\r
+        $this->info['URI']      = new HTMLPurifier_AttrDef_URI();\r
+        $this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang();\r
+        $this->info['Color']    = new HTMLPurifier_AttrDef_HTML_Color();\r
+        $this->info['IAlign']   = self::makeEnum('top,middle,bottom,left,right');\r
+        $this->info['LAlign']   = self::makeEnum('top,bottom,left,right');\r
+        $this->info['FrameTarget'] = new HTMLPurifier_AttrDef_HTML_FrameTarget();\r
+\r
+        // unimplemented aliases\r
+        $this->info['ContentType'] = new HTMLPurifier_AttrDef_Text();\r
+        $this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text();\r
+        $this->info['Charsets'] = new HTMLPurifier_AttrDef_Text();\r
+        $this->info['Character'] = new HTMLPurifier_AttrDef_Text();\r
+\r
+        // "proprietary" types\r
+        $this->info['Class'] = new HTMLPurifier_AttrDef_HTML_Class();\r
+\r
+        // number is really a positive integer (one or more digits)\r
+        // FIXME: ^^ not always, see start and value of list items\r
+        $this->info['Number']   = new HTMLPurifier_AttrDef_Integer(false, false, true);\r
+    }\r
+\r
+    private static function makeEnum($in)\r
+    {\r
+        return new HTMLPurifier_AttrDef_Clone(new HTMLPurifier_AttrDef_Enum(explode(',', $in)));\r
+    }\r
+\r
+    /**\r
+     * Retrieves a type\r
+     * @param string $type String type name\r
+     * @return HTMLPurifier_AttrDef Object AttrDef for type\r
+     */\r
+    public function get($type)\r
+    {\r
+        // determine if there is any extra info tacked on\r
+        if (strpos($type, '#') !== false) {\r
+            list($type, $string) = explode('#', $type, 2);\r
+        } else {\r
+            $string = '';\r
+        }\r
+\r
+        if (!isset($this->info[$type])) {\r
+            trigger_error('Cannot retrieve undefined attribute type ' . $type, E_USER_ERROR);\r
+            return;\r
+        }\r
+        return $this->info[$type]->make($string);\r
+    }\r
+\r
+    /**\r
+     * Sets a new implementation for a type\r
+     * @param string $type String type name\r
+     * @param HTMLPurifier_AttrDef $impl Object AttrDef for type\r
+     */\r
+    public function set($type, $impl)\r
+    {\r
+        $this->info[$type] = $impl;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates the attributes of a token. Doesn't manage required attributes\r
+ * very well. The only reason we factored this out was because RemoveForeignElements\r
+ * also needed it besides ValidateAttributes.\r
+ */\r
+class HTMLPurifier_AttrValidator\r
+{\r
+\r
+    /**\r
+     * Validates the attributes of a token, mutating it as necessary.\r
+     * that has valid tokens\r
+     * @param HTMLPurifier_Token $token Token to validate.\r
+     * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config\r
+     * @param HTMLPurifier_Context $context Instance of HTMLPurifier_Context\r
+     */\r
+    public function validateToken($token, $config, $context)\r
+    {\r
+        $definition = $config->getHTMLDefinition();\r
+        $e =& $context->get('ErrorCollector', true);\r
+\r
+        // initialize IDAccumulator if necessary\r
+        $ok =& $context->get('IDAccumulator', true);\r
+        if (!$ok) {\r
+            $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);\r
+            $context->register('IDAccumulator', $id_accumulator);\r
+        }\r
+\r
+        // initialize CurrentToken if necessary\r
+        $current_token =& $context->get('CurrentToken', true);\r
+        if (!$current_token) {\r
+            $context->register('CurrentToken', $token);\r
+        }\r
+\r
+        if (!$token instanceof HTMLPurifier_Token_Start &&\r
+            !$token instanceof HTMLPurifier_Token_Empty\r
+        ) {\r
+            return;\r
+        }\r
+\r
+        // create alias to global definition array, see also $defs\r
+        // DEFINITION CALL\r
+        $d_defs = $definition->info_global_attr;\r
+\r
+        // don't update token until the very end, to ensure an atomic update\r
+        $attr = $token->attr;\r
+\r
+        // do global transformations (pre)\r
+        // nothing currently utilizes this\r
+        foreach ($definition->info_attr_transform_pre as $transform) {\r
+            $attr = $transform->transform($o = $attr, $config, $context);\r
+            if ($e) {\r
+                if ($attr != $o) {\r
+                    $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);\r
+                }\r
+            }\r
+        }\r
+\r
+        // do local transformations only applicable to this element (pre)\r
+        // ex. <p align="right"> to <p style="text-align:right;">\r
+        foreach ($definition->info[$token->name]->attr_transform_pre as $transform) {\r
+            $attr = $transform->transform($o = $attr, $config, $context);\r
+            if ($e) {\r
+                if ($attr != $o) {\r
+                    $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);\r
+                }\r
+            }\r
+        }\r
+\r
+        // create alias to this element's attribute definition array, see\r
+        // also $d_defs (global attribute definition array)\r
+        // DEFINITION CALL\r
+        $defs = $definition->info[$token->name]->attr;\r
+\r
+        $attr_key = false;\r
+        $context->register('CurrentAttr', $attr_key);\r
+\r
+        // iterate through all the attribute keypairs\r
+        // Watch out for name collisions: $key has previously been used\r
+        foreach ($attr as $attr_key => $value) {\r
+\r
+            // call the definition\r
+            if (isset($defs[$attr_key])) {\r
+                // there is a local definition defined\r
+                if ($defs[$attr_key] === false) {\r
+                    // We've explicitly been told not to allow this element.\r
+                    // This is usually when there's a global definition\r
+                    // that must be overridden.\r
+                    // Theoretically speaking, we could have a\r
+                    // AttrDef_DenyAll, but this is faster!\r
+                    $result = false;\r
+                } else {\r
+                    // validate according to the element's definition\r
+                    $result = $defs[$attr_key]->validate(\r
+                        $value,\r
+                        $config,\r
+                        $context\r
+                    );\r
+                }\r
+            } elseif (isset($d_defs[$attr_key])) {\r
+                // there is a global definition defined, validate according\r
+                // to the global definition\r
+                $result = $d_defs[$attr_key]->validate(\r
+                    $value,\r
+                    $config,\r
+                    $context\r
+                );\r
+            } else {\r
+                // system never heard of the attribute? DELETE!\r
+                $result = false;\r
+            }\r
+\r
+            // put the results into effect\r
+            if ($result === false || $result === null) {\r
+                // this is a generic error message that should replaced\r
+                // with more specific ones when possible\r
+                if ($e) {\r
+                    $e->send(E_ERROR, 'AttrValidator: Attribute removed');\r
+                }\r
+\r
+                // remove the attribute\r
+                unset($attr[$attr_key]);\r
+            } elseif (is_string($result)) {\r
+                // generally, if a substitution is happening, there\r
+                // was some sort of implicit correction going on. We'll\r
+                // delegate it to the attribute classes to say exactly what.\r
+\r
+                // simple substitution\r
+                $attr[$attr_key] = $result;\r
+            } else {\r
+                // nothing happens\r
+            }\r
+\r
+            // we'd also want slightly more complicated substitution\r
+            // involving an array as the return value,\r
+            // although we're not sure how colliding attributes would\r
+            // resolve (certain ones would be completely overriden,\r
+            // others would prepend themselves).\r
+        }\r
+\r
+        $context->destroy('CurrentAttr');\r
+\r
+        // post transforms\r
+\r
+        // global (error reporting untested)\r
+        foreach ($definition->info_attr_transform_post as $transform) {\r
+            $attr = $transform->transform($o = $attr, $config, $context);\r
+            if ($e) {\r
+                if ($attr != $o) {\r
+                    $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);\r
+                }\r
+            }\r
+        }\r
+\r
+        // local (error reporting untested)\r
+        foreach ($definition->info[$token->name]->attr_transform_post as $transform) {\r
+            $attr = $transform->transform($o = $attr, $config, $context);\r
+            if ($e) {\r
+                if ($attr != $o) {\r
+                    $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);\r
+                }\r
+            }\r
+        }\r
+\r
+        $token->attr = $attr;\r
+\r
+        // destroy CurrentToken if we made it ourselves\r
+        if (!$current_token) {\r
+            $context->destroy('CurrentToken');\r
+        }\r
+\r
+    }\r
+\r
+\r
+}\r
+\r
+
+
+\r
+\r
+// constants are slow, so we use as few as possible\r
+if (!defined('HTMLPURIFIER_PREFIX')) {\r
+    define('HTMLPURIFIER_PREFIX', dirname(__FILE__) . '/standalone');\r
+    set_include_path(HTMLPURIFIER_PREFIX . PATH_SEPARATOR . get_include_path());\r
+}\r
+\r
+// accomodations for versions earlier than 5.0.2\r
+// borrowed from PHP_Compat, LGPL licensed, by Aidan Lister <aidan@php.net>\r
+if (!defined('PHP_EOL')) {\r
+    switch (strtoupper(substr(PHP_OS, 0, 3))) {\r
+        case 'WIN':\r
+            define('PHP_EOL', "\r\n");\r
+            break;\r
+        case 'DAR':\r
+            define('PHP_EOL', "\r");\r
+            break;\r
+        default:\r
+            define('PHP_EOL', "\n");\r
+    }\r
+}\r
+\r
+/**\r
+ * Bootstrap class that contains meta-functionality for HTML Purifier such as\r
+ * the autoload function.\r
+ *\r
+ * @note\r
+ *      This class may be used without any other files from HTML Purifier.\r
+ */\r
+class HTMLPurifier_Bootstrap\r
+{\r
+\r
+    /**\r
+     * Autoload function for HTML Purifier\r
+     * @param string $class Class to load\r
+     * @return bool\r
+     */\r
+    public static function autoload($class)\r
+    {\r
+        $file = HTMLPurifier_Bootstrap::getPath($class);\r
+        if (!$file) {\r
+            return false;\r
+        }\r
+        // Technically speaking, it should be ok and more efficient to\r
+        // just do 'require', but Antonio Parraga reports that with\r
+        // Zend extensions such as Zend debugger and APC, this invariant\r
+        // may be broken.  Since we have efficient alternatives, pay\r
+        // the cost here and avoid the bug.\r
+        require_once HTMLPURIFIER_PREFIX . '/' . $file;\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Returns the path for a specific class.\r
+     * @param string $class Class path to get\r
+     * @return string\r
+     */\r
+    public static function getPath($class)\r
+    {\r
+        if (strncmp('HTMLPurifier', $class, 12) !== 0) {\r
+            return false;\r
+        }\r
+        // Custom implementations\r
+        if (strncmp('HTMLPurifier_Language_', $class, 22) === 0) {\r
+            $code = str_replace('_', '-', substr($class, 22));\r
+            $file = 'HTMLPurifier/Language/classes/' . $code . '.php';\r
+        } else {\r
+            $file = str_replace('_', '/', $class) . '.php';\r
+        }\r
+        if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) {\r
+            return false;\r
+        }\r
+        return $file;\r
+    }\r
+\r
+    /**\r
+     * "Pre-registers" our autoloader on the SPL stack.\r
+     */\r
+    public static function registerAutoload()\r
+    {\r
+        $autoload = array('HTMLPurifier_Bootstrap', 'autoload');\r
+        if (($funcs = spl_autoload_functions()) === false) {\r
+            spl_autoload_register($autoload);\r
+        } elseif (function_exists('spl_autoload_unregister')) {\r
+            if (version_compare(PHP_VERSION, '5.3.0', '>=')) {\r
+                // prepend flag exists, no need for shenanigans\r
+                spl_autoload_register($autoload, true, true);\r
+            } else {\r
+                $buggy  = version_compare(PHP_VERSION, '5.2.11', '<');\r
+                $compat = version_compare(PHP_VERSION, '5.1.2', '<=') &&\r
+                          version_compare(PHP_VERSION, '5.1.0', '>=');\r
+                foreach ($funcs as $func) {\r
+                    if ($buggy && is_array($func)) {\r
+                        // :TRICKY: There are some compatibility issues and some\r
+                        // places where we need to error out\r
+                        $reflector = new ReflectionMethod($func[0], $func[1]);\r
+                        if (!$reflector->isStatic()) {\r
+                            throw new Exception(\r
+                                'HTML Purifier autoloader registrar is not compatible\r
+                                with non-static object methods due to PHP Bug #44144;\r
+                                Please do not use HTMLPurifier.autoload.php (or any\r
+                                file that includes this file); instead, place the code:\r
+                                spl_autoload_register(array(\'HTMLPurifier_Bootstrap\', \'autoload\'))\r
+                                after your own autoloaders.'\r
+                            );\r
+                        }\r
+                        // Suprisingly, spl_autoload_register supports the\r
+                        // Class::staticMethod callback format, although call_user_func doesn't\r
+                        if ($compat) {\r
+                            $func = implode('::', $func);\r
+                        }\r
+                    }\r
+                    spl_autoload_unregister($func);\r
+                }\r
+                spl_autoload_register($autoload);\r
+                foreach ($funcs as $func) {\r
+                    spl_autoload_register($func);\r
+                }\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Super-class for definition datatype objects, implements serialization\r
+ * functions for the class.\r
+ */\r
+abstract class HTMLPurifier_Definition\r
+{\r
+\r
+    /**\r
+     * Has setup() been called yet?\r
+     * @type bool\r
+     */\r
+    public $setup = false;\r
+\r
+    /**\r
+     * If true, write out the final definition object to the cache after\r
+     * setup.  This will be true only if all invocations to get a raw\r
+     * definition object are also optimized.  This does not cause file\r
+     * system thrashing because on subsequent calls the cached object\r
+     * is used and any writes to the raw definition object are short\r
+     * circuited.  See enduser-customize.html for the high-level\r
+     * picture.\r
+     * @type bool\r
+     */\r
+    public $optimized = null;\r
+\r
+    /**\r
+     * What type of definition is it?\r
+     * @type string\r
+     */\r
+    public $type;\r
+\r
+    /**\r
+     * Sets up the definition object into the final form, something\r
+     * not done by the constructor\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    abstract protected function doSetup($config);\r
+\r
+    /**\r
+     * Setup function that aborts if already setup\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        if ($this->setup) {\r
+            return;\r
+        }\r
+        $this->setup = true;\r
+        $this->doSetup($config);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Defines allowed CSS attributes and what their values are.\r
+ * @see HTMLPurifier_HTMLDefinition\r
+ */\r
+class HTMLPurifier_CSSDefinition extends HTMLPurifier_Definition\r
+{\r
+\r
+    public $type = 'CSS';\r
+\r
+    /**\r
+     * Assoc array of attribute name to definition object.\r
+     * @type HTMLPurifier_AttrDef[]\r
+     */\r
+    public $info = array();\r
+\r
+    /**\r
+     * Constructs the info array.  The meat of this class.\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    protected function doSetup($config)\r
+    {\r
+        $this->info['text-align'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('left', 'right', 'center', 'justify'),\r
+            false\r
+        );\r
+\r
+        $border_style =\r
+            $this->info['border-bottom-style'] =\r
+            $this->info['border-right-style'] =\r
+            $this->info['border-left-style'] =\r
+            $this->info['border-top-style'] = new HTMLPurifier_AttrDef_Enum(\r
+                array(\r
+                    'none',\r
+                    'hidden',\r
+                    'dotted',\r
+                    'dashed',\r
+                    'solid',\r
+                    'double',\r
+                    'groove',\r
+                    'ridge',\r
+                    'inset',\r
+                    'outset'\r
+                ),\r
+                false\r
+            );\r
+\r
+        $this->info['border-style'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_style);\r
+\r
+        $this->info['clear'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('none', 'left', 'right', 'both'),\r
+            false\r
+        );\r
+        $this->info['float'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('none', 'left', 'right'),\r
+            false\r
+        );\r
+        $this->info['font-style'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('normal', 'italic', 'oblique'),\r
+            false\r
+        );\r
+        $this->info['font-variant'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('normal', 'small-caps'),\r
+            false\r
+        );\r
+\r
+        $uri_or_none = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_Enum(array('none')),\r
+                new HTMLPurifier_AttrDef_CSS_URI()\r
+            )\r
+        );\r
+\r
+        $this->info['list-style-position'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('inside', 'outside'),\r
+            false\r
+        );\r
+        $this->info['list-style-type'] = new HTMLPurifier_AttrDef_Enum(\r
+            array(\r
+                'disc',\r
+                'circle',\r
+                'square',\r
+                'decimal',\r
+                'lower-roman',\r
+                'upper-roman',\r
+                'lower-alpha',\r
+                'upper-alpha',\r
+                'none'\r
+            ),\r
+            false\r
+        );\r
+        $this->info['list-style-image'] = $uri_or_none;\r
+\r
+        $this->info['list-style'] = new HTMLPurifier_AttrDef_CSS_ListStyle($config);\r
+\r
+        $this->info['text-transform'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('capitalize', 'uppercase', 'lowercase', 'none'),\r
+            false\r
+        );\r
+        $this->info['color'] = new HTMLPurifier_AttrDef_CSS_Color();\r
+\r
+        $this->info['background-image'] = $uri_or_none;\r
+        $this->info['background-repeat'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('repeat', 'repeat-x', 'repeat-y', 'no-repeat')\r
+        );\r
+        $this->info['background-attachment'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('scroll', 'fixed')\r
+        );\r
+        $this->info['background-position'] = new HTMLPurifier_AttrDef_CSS_BackgroundPosition();\r
+\r
+        $border_color =\r
+            $this->info['border-top-color'] =\r
+            $this->info['border-bottom-color'] =\r
+            $this->info['border-left-color'] =\r
+            $this->info['border-right-color'] =\r
+            $this->info['background-color'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+                array(\r
+                    new HTMLPurifier_AttrDef_Enum(array('transparent')),\r
+                    new HTMLPurifier_AttrDef_CSS_Color()\r
+                )\r
+            );\r
+\r
+        $this->info['background'] = new HTMLPurifier_AttrDef_CSS_Background($config);\r
+\r
+        $this->info['border-color'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_color);\r
+\r
+        $border_width =\r
+            $this->info['border-top-width'] =\r
+            $this->info['border-bottom-width'] =\r
+            $this->info['border-left-width'] =\r
+            $this->info['border-right-width'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+                array(\r
+                    new HTMLPurifier_AttrDef_Enum(array('thin', 'medium', 'thick')),\r
+                    new HTMLPurifier_AttrDef_CSS_Length('0') //disallow negative\r
+                )\r
+            );\r
+\r
+        $this->info['border-width'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_width);\r
+\r
+        $this->info['letter-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_Enum(array('normal')),\r
+                new HTMLPurifier_AttrDef_CSS_Length()\r
+            )\r
+        );\r
+\r
+        $this->info['word-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_Enum(array('normal')),\r
+                new HTMLPurifier_AttrDef_CSS_Length()\r
+            )\r
+        );\r
+\r
+        $this->info['font-size'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_Enum(\r
+                    array(\r
+                        'xx-small',\r
+                        'x-small',\r
+                        'small',\r
+                        'medium',\r
+                        'large',\r
+                        'x-large',\r
+                        'xx-large',\r
+                        'larger',\r
+                        'smaller'\r
+                    )\r
+                ),\r
+                new HTMLPurifier_AttrDef_CSS_Percentage(),\r
+                new HTMLPurifier_AttrDef_CSS_Length()\r
+            )\r
+        );\r
+\r
+        $this->info['line-height'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_Enum(array('normal')),\r
+                new HTMLPurifier_AttrDef_CSS_Number(true), // no negatives\r
+                new HTMLPurifier_AttrDef_CSS_Length('0'),\r
+                new HTMLPurifier_AttrDef_CSS_Percentage(true)\r
+            )\r
+        );\r
+\r
+        $margin =\r
+            $this->info['margin-top'] =\r
+            $this->info['margin-bottom'] =\r
+            $this->info['margin-left'] =\r
+            $this->info['margin-right'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+                array(\r
+                    new HTMLPurifier_AttrDef_CSS_Length(),\r
+                    new HTMLPurifier_AttrDef_CSS_Percentage(),\r
+                    new HTMLPurifier_AttrDef_Enum(array('auto'))\r
+                )\r
+            );\r
+\r
+        $this->info['margin'] = new HTMLPurifier_AttrDef_CSS_Multiple($margin);\r
+\r
+        // non-negative\r
+        $padding =\r
+            $this->info['padding-top'] =\r
+            $this->info['padding-bottom'] =\r
+            $this->info['padding-left'] =\r
+            $this->info['padding-right'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+                array(\r
+                    new HTMLPurifier_AttrDef_CSS_Length('0'),\r
+                    new HTMLPurifier_AttrDef_CSS_Percentage(true)\r
+                )\r
+            );\r
+\r
+        $this->info['padding'] = new HTMLPurifier_AttrDef_CSS_Multiple($padding);\r
+\r
+        $this->info['text-indent'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_CSS_Length(),\r
+                new HTMLPurifier_AttrDef_CSS_Percentage()\r
+            )\r
+        );\r
+\r
+        $trusted_wh = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_CSS_Length('0'),\r
+                new HTMLPurifier_AttrDef_CSS_Percentage(true),\r
+                new HTMLPurifier_AttrDef_Enum(array('auto', 'initial', 'inherit'))\r
+            )\r
+        );\r
+        $trusted_min_wh = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_CSS_Length('0'),\r
+                new HTMLPurifier_AttrDef_CSS_Percentage(true),\r
+                new HTMLPurifier_AttrDef_Enum(array('initial', 'inherit'))\r
+            )\r
+        );\r
+        $trusted_max_wh = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_CSS_Length('0'),\r
+                new HTMLPurifier_AttrDef_CSS_Percentage(true),\r
+                new HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit'))\r
+            )\r
+        );\r
+        $max = $config->get('CSS.MaxImgLength');\r
+\r
+        $this->info['width'] =\r
+        $this->info['height'] =\r
+            $max === null ?\r
+                $trusted_wh :\r
+                new HTMLPurifier_AttrDef_Switch(\r
+                    'img',\r
+                    // For img tags:\r
+                    new HTMLPurifier_AttrDef_CSS_Composite(\r
+                        array(\r
+                            new HTMLPurifier_AttrDef_CSS_Length('0', $max),\r
+                            new HTMLPurifier_AttrDef_Enum(array('auto'))\r
+                        )\r
+                    ),\r
+                    // For everyone else:\r
+                    $trusted_wh\r
+                );\r
+        $this->info['min-width'] =\r
+        $this->info['min-height'] =\r
+            $max === null ?\r
+                $trusted_min_wh :\r
+                new HTMLPurifier_AttrDef_Switch(\r
+                    'img',\r
+                    // For img tags:\r
+                    new HTMLPurifier_AttrDef_CSS_Composite(\r
+                        array(\r
+                            new HTMLPurifier_AttrDef_CSS_Length('0', $max),\r
+                            new HTMLPurifier_AttrDef_Enum(array('initial', 'inherit'))\r
+                        )\r
+                    ),\r
+                    // For everyone else:\r
+                    $trusted_min_wh\r
+                );\r
+        $this->info['max-width'] =\r
+        $this->info['max-height'] =\r
+            $max === null ?\r
+                $trusted_max_wh :\r
+                new HTMLPurifier_AttrDef_Switch(\r
+                    'img',\r
+                    // For img tags:\r
+                    new HTMLPurifier_AttrDef_CSS_Composite(\r
+                        array(\r
+                            new HTMLPurifier_AttrDef_CSS_Length('0', $max),\r
+                            new HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit'))\r
+                        )\r
+                    ),\r
+                    // For everyone else:\r
+                    $trusted_max_wh\r
+                );\r
+\r
+        $this->info['text-decoration'] = new HTMLPurifier_AttrDef_CSS_TextDecoration();\r
+\r
+        $this->info['font-family'] = new HTMLPurifier_AttrDef_CSS_FontFamily();\r
+\r
+        // this could use specialized code\r
+        $this->info['font-weight'] = new HTMLPurifier_AttrDef_Enum(\r
+            array(\r
+                'normal',\r
+                'bold',\r
+                'bolder',\r
+                'lighter',\r
+                '100',\r
+                '200',\r
+                '300',\r
+                '400',\r
+                '500',\r
+                '600',\r
+                '700',\r
+                '800',\r
+                '900'\r
+            ),\r
+            false\r
+        );\r
+\r
+        // MUST be called after other font properties, as it references\r
+        // a CSSDefinition object\r
+        $this->info['font'] = new HTMLPurifier_AttrDef_CSS_Font($config);\r
+\r
+        // same here\r
+        $this->info['border'] =\r
+        $this->info['border-bottom'] =\r
+        $this->info['border-top'] =\r
+        $this->info['border-left'] =\r
+        $this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config);\r
+\r
+        $this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('collapse', 'separate')\r
+        );\r
+\r
+        $this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('top', 'bottom')\r
+        );\r
+\r
+        $this->info['table-layout'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('auto', 'fixed')\r
+        );\r
+\r
+        $this->info['vertical-align'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_Enum(\r
+                    array(\r
+                        'baseline',\r
+                        'sub',\r
+                        'super',\r
+                        'top',\r
+                        'text-top',\r
+                        'middle',\r
+                        'bottom',\r
+                        'text-bottom'\r
+                    )\r
+                ),\r
+                new HTMLPurifier_AttrDef_CSS_Length(),\r
+                new HTMLPurifier_AttrDef_CSS_Percentage()\r
+            )\r
+        );\r
+\r
+        $this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2);\r
+\r
+        // These CSS properties don't work on many browsers, but we live\r
+        // in THE FUTURE!\r
+        $this->info['white-space'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('nowrap', 'normal', 'pre', 'pre-wrap', 'pre-line')\r
+        );\r
+\r
+        if ($config->get('CSS.Proprietary')) {\r
+            $this->doSetupProprietary($config);\r
+        }\r
+\r
+        if ($config->get('CSS.AllowTricky')) {\r
+            $this->doSetupTricky($config);\r
+        }\r
+\r
+        if ($config->get('CSS.Trusted')) {\r
+            $this->doSetupTrusted($config);\r
+        }\r
+\r
+        $allow_important = $config->get('CSS.AllowImportant');\r
+        // wrap all attr-defs with decorator that handles !important\r
+        foreach ($this->info as $k => $v) {\r
+            $this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important);\r
+        }\r
+\r
+        $this->setupConfigStuff($config);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    protected function doSetupProprietary($config)\r
+    {\r
+        // Internet Explorer only scrollbar colors\r
+        $this->info['scrollbar-arrow-color'] = new HTMLPurifier_AttrDef_CSS_Color();\r
+        $this->info['scrollbar-base-color'] = new HTMLPurifier_AttrDef_CSS_Color();\r
+        $this->info['scrollbar-darkshadow-color'] = new HTMLPurifier_AttrDef_CSS_Color();\r
+        $this->info['scrollbar-face-color'] = new HTMLPurifier_AttrDef_CSS_Color();\r
+        $this->info['scrollbar-highlight-color'] = new HTMLPurifier_AttrDef_CSS_Color();\r
+        $this->info['scrollbar-shadow-color'] = new HTMLPurifier_AttrDef_CSS_Color();\r
+\r
+        // vendor specific prefixes of opacity\r
+        $this->info['-moz-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();\r
+        $this->info['-khtml-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();\r
+\r
+        // only opacity, for now\r
+        $this->info['filter'] = new HTMLPurifier_AttrDef_CSS_Filter();\r
+\r
+        // more CSS3\r
+        $this->info['page-break-after'] =\r
+        $this->info['page-break-before'] = new HTMLPurifier_AttrDef_Enum(\r
+            array(\r
+                'auto',\r
+                'always',\r
+                'avoid',\r
+                'left',\r
+                'right'\r
+            )\r
+        );\r
+        $this->info['page-break-inside'] = new HTMLPurifier_AttrDef_Enum(array('auto', 'avoid'));\r
+\r
+        $border_radius = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_CSS_Percentage(true), // disallow negative\r
+                new HTMLPurifier_AttrDef_CSS_Length('0') // disallow negative\r
+            ));\r
+\r
+        $this->info['border-top-left-radius'] =\r
+        $this->info['border-top-right-radius'] =\r
+        $this->info['border-bottom-right-radius'] =\r
+        $this->info['border-bottom-left-radius'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_radius, 2);\r
+        // TODO: support SLASH syntax\r
+        $this->info['border-radius'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_radius, 4);\r
+\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    protected function doSetupTricky($config)\r
+    {\r
+        $this->info['display'] = new HTMLPurifier_AttrDef_Enum(\r
+            array(\r
+                'inline',\r
+                'block',\r
+                'list-item',\r
+                'run-in',\r
+                'compact',\r
+                'marker',\r
+                'table',\r
+                'inline-block',\r
+                'inline-table',\r
+                'table-row-group',\r
+                'table-header-group',\r
+                'table-footer-group',\r
+                'table-row',\r
+                'table-column-group',\r
+                'table-column',\r
+                'table-cell',\r
+                'table-caption',\r
+                'none'\r
+            )\r
+        );\r
+        $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('visible', 'hidden', 'collapse')\r
+        );\r
+        $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll'));\r
+        $this->info['opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    protected function doSetupTrusted($config)\r
+    {\r
+        $this->info['position'] = new HTMLPurifier_AttrDef_Enum(\r
+            array('static', 'relative', 'absolute', 'fixed')\r
+        );\r
+        $this->info['top'] =\r
+        $this->info['left'] =\r
+        $this->info['right'] =\r
+        $this->info['bottom'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_CSS_Length(),\r
+                new HTMLPurifier_AttrDef_CSS_Percentage(),\r
+                new HTMLPurifier_AttrDef_Enum(array('auto')),\r
+            )\r
+        );\r
+        $this->info['z-index'] = new HTMLPurifier_AttrDef_CSS_Composite(\r
+            array(\r
+                new HTMLPurifier_AttrDef_Integer(),\r
+                new HTMLPurifier_AttrDef_Enum(array('auto')),\r
+            )\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Performs extra config-based processing. Based off of\r
+     * HTMLPurifier_HTMLDefinition.\r
+     * @param HTMLPurifier_Config $config\r
+     * @todo Refactor duplicate elements into common class (probably using\r
+     *       composition, not inheritance).\r
+     */\r
+    protected function setupConfigStuff($config)\r
+    {\r
+        // setup allowed elements\r
+        $support = "(for information on implementing this, see the " .\r
+            "support forums) ";\r
+        $allowed_properties = $config->get('CSS.AllowedProperties');\r
+        if ($allowed_properties !== null) {\r
+            foreach ($this->info as $name => $d) {\r
+                if (!isset($allowed_properties[$name])) {\r
+                    unset($this->info[$name]);\r
+                }\r
+                unset($allowed_properties[$name]);\r
+            }\r
+            // emit errors\r
+            foreach ($allowed_properties as $name => $d) {\r
+                // :TODO: Is this htmlspecialchars() call really necessary?\r
+                $name = htmlspecialchars($name);\r
+                trigger_error("Style attribute '$name' is not supported $support", E_USER_WARNING);\r
+            }\r
+        }\r
+\r
+        $forbidden_properties = $config->get('CSS.ForbiddenProperties');\r
+        if ($forbidden_properties !== null) {\r
+            foreach ($this->info as $name => $d) {\r
+                if (isset($forbidden_properties[$name])) {\r
+                    unset($this->info[$name]);\r
+                }\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Defines allowed child nodes and validates nodes against it.\r
+ */\r
+abstract class HTMLPurifier_ChildDef\r
+{\r
+    /**\r
+     * Type of child definition, usually right-most part of class name lowercase.\r
+     * Used occasionally in terms of context.\r
+     * @type string\r
+     */\r
+    public $type;\r
+\r
+    /**\r
+     * Indicates whether or not an empty array of children is okay.\r
+     *\r
+     * This is necessary for redundant checking when changes affecting\r
+     * a child node may cause a parent node to now be disallowed.\r
+     * @type bool\r
+     */\r
+    public $allow_empty;\r
+\r
+    /**\r
+     * Lookup array of all elements that this definition could possibly allow.\r
+     * @type array\r
+     */\r
+    public $elements = array();\r
+\r
+    /**\r
+     * Get lookup of tag names that should not close this element automatically.\r
+     * All other elements will do so.\r
+     * @param HTMLPurifier_Config $config HTMLPurifier_Config object\r
+     * @return array\r
+     */\r
+    public function getAllowedElements($config)\r
+    {\r
+        return $this->elements;\r
+    }\r
+\r
+    /**\r
+     * Validates nodes according to definition and returns modification.\r
+     *\r
+     * @param HTMLPurifier_Node[] $children Array of HTMLPurifier_Node\r
+     * @param HTMLPurifier_Config $config HTMLPurifier_Config object\r
+     * @param HTMLPurifier_Context $context HTMLPurifier_Context object\r
+     * @return bool|array true to leave nodes as is, false to remove parent node, array of replacement children\r
+     */\r
+    abstract public function validateChildren($children, $config, $context);\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Configuration object that triggers customizable behavior.\r
+ *\r
+ * @warning This class is strongly defined: that means that the class\r
+ *          will fail if an undefined directive is retrieved or set.\r
+ *\r
+ * @note Many classes that could (although many times don't) use the\r
+ *       configuration object make it a mandatory parameter.  This is\r
+ *       because a configuration object should always be forwarded,\r
+ *       otherwise, you run the risk of missing a parameter and then\r
+ *       being stumped when a configuration directive doesn't work.\r
+ *\r
+ * @todo Reconsider some of the public member variables\r
+ */\r
+class HTMLPurifier_Config\r
+{\r
+\r
+    /**\r
+     * HTML Purifier's version\r
+     * @type string\r
+     */\r
+    public $version = '4.11.0';\r
+\r
+    /**\r
+     * Whether or not to automatically finalize\r
+     * the object if a read operation is done.\r
+     * @type bool\r
+     */\r
+    public $autoFinalize = true;\r
+\r
+    // protected member variables\r
+\r
+    /**\r
+     * Namespace indexed array of serials for specific namespaces.\r
+     * @see getSerial() for more info.\r
+     * @type string[]\r
+     */\r
+    protected $serials = array();\r
+\r
+    /**\r
+     * Serial for entire configuration object.\r
+     * @type string\r
+     */\r
+    protected $serial;\r
+\r
+    /**\r
+     * Parser for variables.\r
+     * @type HTMLPurifier_VarParser_Flexible\r
+     */\r
+    protected $parser = null;\r
+\r
+    /**\r
+     * Reference HTMLPurifier_ConfigSchema for value checking.\r
+     * @type HTMLPurifier_ConfigSchema\r
+     * @note This is public for introspective purposes. Please don't\r
+     *       abuse!\r
+     */\r
+    public $def;\r
+\r
+    /**\r
+     * Indexed array of definitions.\r
+     * @type HTMLPurifier_Definition[]\r
+     */\r
+    protected $definitions;\r
+\r
+    /**\r
+     * Whether or not config is finalized.\r
+     * @type bool\r
+     */\r
+    protected $finalized = false;\r
+\r
+    /**\r
+     * Property list containing configuration directives.\r
+     * @type array\r
+     */\r
+    protected $plist;\r
+\r
+    /**\r
+     * Whether or not a set is taking place due to an alias lookup.\r
+     * @type bool\r
+     */\r
+    private $aliasMode;\r
+\r
+    /**\r
+     * Set to false if you do not want line and file numbers in errors.\r
+     * (useful when unit testing).  This will also compress some errors\r
+     * and exceptions.\r
+     * @type bool\r
+     */\r
+    public $chatty = true;\r
+\r
+    /**\r
+     * Current lock; only gets to this namespace are allowed.\r
+     * @type string\r
+     */\r
+    private $lock;\r
+\r
+    /**\r
+     * Constructor\r
+     * @param HTMLPurifier_ConfigSchema $definition ConfigSchema that defines\r
+     * what directives are allowed.\r
+     * @param HTMLPurifier_PropertyList $parent\r
+     */\r
+    public function __construct($definition, $parent = null)\r
+    {\r
+        $parent = $parent ? $parent : $definition->defaultPlist;\r
+        $this->plist = new HTMLPurifier_PropertyList($parent);\r
+        $this->def = $definition; // keep a copy around for checking\r
+        $this->parser = new HTMLPurifier_VarParser_Flexible();\r
+    }\r
+\r
+    /**\r
+     * Convenience constructor that creates a config object based on a mixed var\r
+     * @param mixed $config Variable that defines the state of the config\r
+     *                      object. Can be: a HTMLPurifier_Config() object,\r
+     *                      an array of directives based on loadArray(),\r
+     *                      or a string filename of an ini file.\r
+     * @param HTMLPurifier_ConfigSchema $schema Schema object\r
+     * @return HTMLPurifier_Config Configured object\r
+     */\r
+    public static function create($config, $schema = null)\r
+    {\r
+        if ($config instanceof HTMLPurifier_Config) {\r
+            // pass-through\r
+            return $config;\r
+        }\r
+        if (!$schema) {\r
+            $ret = HTMLPurifier_Config::createDefault();\r
+        } else {\r
+            $ret = new HTMLPurifier_Config($schema);\r
+        }\r
+        if (is_string($config)) {\r
+            $ret->loadIni($config);\r
+        } elseif (is_array($config)) $ret->loadArray($config);\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Creates a new config object that inherits from a previous one.\r
+     * @param HTMLPurifier_Config $config Configuration object to inherit from.\r
+     * @return HTMLPurifier_Config object with $config as its parent.\r
+     */\r
+    public static function inherit(HTMLPurifier_Config $config)\r
+    {\r
+        return new HTMLPurifier_Config($config->def, $config->plist);\r
+    }\r
+\r
+    /**\r
+     * Convenience constructor that creates a default configuration object.\r
+     * @return HTMLPurifier_Config default object.\r
+     */\r
+    public static function createDefault()\r
+    {\r
+        $definition = HTMLPurifier_ConfigSchema::instance();\r
+        $config = new HTMLPurifier_Config($definition);\r
+        return $config;\r
+    }\r
+\r
+    /**\r
+     * Retrieves a value from the configuration.\r
+     *\r
+     * @param string $key String key\r
+     * @param mixed $a\r
+     *\r
+     * @return mixed\r
+     */\r
+    public function get($key, $a = null)\r
+    {\r
+        if ($a !== null) {\r
+            $this->triggerError(\r
+                "Using deprecated API: use \$config->get('$key.$a') instead",\r
+                E_USER_WARNING\r
+            );\r
+            $key = "$key.$a";\r
+        }\r
+        if (!$this->finalized) {\r
+            $this->autoFinalize();\r
+        }\r
+        if (!isset($this->def->info[$key])) {\r
+            // can't add % due to SimpleTest bug\r
+            $this->triggerError(\r
+                'Cannot retrieve value of undefined directive ' . htmlspecialchars($key),\r
+                E_USER_WARNING\r
+            );\r
+            return;\r
+        }\r
+        if (isset($this->def->info[$key]->isAlias)) {\r
+            $d = $this->def->info[$key];\r
+            $this->triggerError(\r
+                'Cannot get value from aliased directive, use real name ' . $d->key,\r
+                E_USER_ERROR\r
+            );\r
+            return;\r
+        }\r
+        if ($this->lock) {\r
+            list($ns) = explode('.', $key);\r
+            if ($ns !== $this->lock) {\r
+                $this->triggerError(\r
+                    'Cannot get value of namespace ' . $ns . ' when lock for ' .\r
+                    $this->lock .\r
+                    ' is active, this probably indicates a Definition setup method ' .\r
+                    'is accessing directives that are not within its namespace',\r
+                    E_USER_ERROR\r
+                );\r
+                return;\r
+            }\r
+        }\r
+        return $this->plist->get($key);\r
+    }\r
+\r
+    /**\r
+     * Retrieves an array of directives to values from a given namespace\r
+     *\r
+     * @param string $namespace String namespace\r
+     *\r
+     * @return array\r
+     */\r
+    public function getBatch($namespace)\r
+    {\r
+        if (!$this->finalized) {\r
+            $this->autoFinalize();\r
+        }\r
+        $full = $this->getAll();\r
+        if (!isset($full[$namespace])) {\r
+            $this->triggerError(\r
+                'Cannot retrieve undefined namespace ' .\r
+                htmlspecialchars($namespace),\r
+                E_USER_WARNING\r
+            );\r
+            return;\r
+        }\r
+        return $full[$namespace];\r
+    }\r
+\r
+    /**\r
+     * Returns a SHA-1 signature of a segment of the configuration object\r
+     * that uniquely identifies that particular configuration\r
+     *\r
+     * @param string $namespace Namespace to get serial for\r
+     *\r
+     * @return string\r
+     * @note Revision is handled specially and is removed from the batch\r
+     *       before processing!\r
+     */\r
+    public function getBatchSerial($namespace)\r
+    {\r
+        if (empty($this->serials[$namespace])) {\r
+            $batch = $this->getBatch($namespace);\r
+            unset($batch['DefinitionRev']);\r
+            $this->serials[$namespace] = sha1(serialize($batch));\r
+        }\r
+        return $this->serials[$namespace];\r
+    }\r
+\r
+    /**\r
+     * Returns a SHA-1 signature for the entire configuration object\r
+     * that uniquely identifies that particular configuration\r
+     *\r
+     * @return string\r
+     */\r
+    public function getSerial()\r
+    {\r
+        if (empty($this->serial)) {\r
+            $this->serial = sha1(serialize($this->getAll()));\r
+        }\r
+        return $this->serial;\r
+    }\r
+\r
+    /**\r
+     * Retrieves all directives, organized by namespace\r
+     *\r
+     * @warning This is a pretty inefficient function, avoid if you can\r
+     */\r
+    public function getAll()\r
+    {\r
+        if (!$this->finalized) {\r
+            $this->autoFinalize();\r
+        }\r
+        $ret = array();\r
+        foreach ($this->plist->squash() as $name => $value) {\r
+            list($ns, $key) = explode('.', $name, 2);\r
+            $ret[$ns][$key] = $value;\r
+        }\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Sets a value to configuration.\r
+     *\r
+     * @param string $key key\r
+     * @param mixed $value value\r
+     * @param mixed $a\r
+     */\r
+    public function set($key, $value, $a = null)\r
+    {\r
+        if (strpos($key, '.') === false) {\r
+            $namespace = $key;\r
+            $directive = $value;\r
+            $value = $a;\r
+            $key = "$key.$directive";\r
+            $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE);\r
+        } else {\r
+            list($namespace) = explode('.', $key);\r
+        }\r
+        if ($this->isFinalized('Cannot set directive after finalization')) {\r
+            return;\r
+        }\r
+        if (!isset($this->def->info[$key])) {\r
+            $this->triggerError(\r
+                'Cannot set undefined directive ' . htmlspecialchars($key) . ' to value',\r
+                E_USER_WARNING\r
+            );\r
+            return;\r
+        }\r
+        $def = $this->def->info[$key];\r
+\r
+        if (isset($def->isAlias)) {\r
+            if ($this->aliasMode) {\r
+                $this->triggerError(\r
+                    'Double-aliases not allowed, please fix '.\r
+                    'ConfigSchema bug with' . $key,\r
+                    E_USER_ERROR\r
+                );\r
+                return;\r
+            }\r
+            $this->aliasMode = true;\r
+            $this->set($def->key, $value);\r
+            $this->aliasMode = false;\r
+            $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE);\r
+            return;\r
+        }\r
+\r
+        // Raw type might be negative when using the fully optimized form\r
+        // of stdClass, which indicates allow_null == true\r
+        $rtype = is_int($def) ? $def : $def->type;\r
+        if ($rtype < 0) {\r
+            $type = -$rtype;\r
+            $allow_null = true;\r
+        } else {\r
+            $type = $rtype;\r
+            $allow_null = isset($def->allow_null);\r
+        }\r
+\r
+        try {\r
+            $value = $this->parser->parse($value, $type, $allow_null);\r
+        } catch (HTMLPurifier_VarParserException $e) {\r
+            $this->triggerError(\r
+                'Value for ' . $key . ' is of invalid type, should be ' .\r
+                HTMLPurifier_VarParser::getTypeName($type),\r
+                E_USER_WARNING\r
+            );\r
+            return;\r
+        }\r
+        if (is_string($value) && is_object($def)) {\r
+            // resolve value alias if defined\r
+            if (isset($def->aliases[$value])) {\r
+                $value = $def->aliases[$value];\r
+            }\r
+            // check to see if the value is allowed\r
+            if (isset($def->allowed) && !isset($def->allowed[$value])) {\r
+                $this->triggerError(\r
+                    'Value not supported, valid values are: ' .\r
+                    $this->_listify($def->allowed),\r
+                    E_USER_WARNING\r
+                );\r
+                return;\r
+            }\r
+        }\r
+        $this->plist->set($key, $value);\r
+\r
+        // reset definitions if the directives they depend on changed\r
+        // this is a very costly process, so it's discouraged\r
+        // with finalization\r
+        if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') {\r
+            $this->definitions[$namespace] = null;\r
+        }\r
+\r
+        $this->serials[$namespace] = false;\r
+    }\r
+\r
+    /**\r
+     * Convenience function for error reporting\r
+     *\r
+     * @param array $lookup\r
+     *\r
+     * @return string\r
+     */\r
+    private function _listify($lookup)\r
+    {\r
+        $list = array();\r
+        foreach ($lookup as $name => $b) {\r
+            $list[] = $name;\r
+        }\r
+        return implode(', ', $list);\r
+    }\r
+\r
+    /**\r
+     * Retrieves object reference to the HTML definition.\r
+     *\r
+     * @param bool $raw Return a copy that has not been setup yet. Must be\r
+     *             called before it's been setup, otherwise won't work.\r
+     * @param bool $optimized If true, this method may return null, to\r
+     *             indicate that a cached version of the modified\r
+     *             definition object is available and no further edits\r
+     *             are necessary.  Consider using\r
+     *             maybeGetRawHTMLDefinition, which is more explicitly\r
+     *             named, instead.\r
+     *\r
+     * @return HTMLPurifier_HTMLDefinition\r
+     */\r
+    public function getHTMLDefinition($raw = false, $optimized = false)\r
+    {\r
+        return $this->getDefinition('HTML', $raw, $optimized);\r
+    }\r
+\r
+    /**\r
+     * Retrieves object reference to the CSS definition\r
+     *\r
+     * @param bool $raw Return a copy that has not been setup yet. Must be\r
+     *             called before it's been setup, otherwise won't work.\r
+     * @param bool $optimized If true, this method may return null, to\r
+     *             indicate that a cached version of the modified\r
+     *             definition object is available and no further edits\r
+     *             are necessary.  Consider using\r
+     *             maybeGetRawCSSDefinition, which is more explicitly\r
+     *             named, instead.\r
+     *\r
+     * @return HTMLPurifier_CSSDefinition\r
+     */\r
+    public function getCSSDefinition($raw = false, $optimized = false)\r
+    {\r
+        return $this->getDefinition('CSS', $raw, $optimized);\r
+    }\r
+\r
+    /**\r
+     * Retrieves object reference to the URI definition\r
+     *\r
+     * @param bool $raw Return a copy that has not been setup yet. Must be\r
+     *             called before it's been setup, otherwise won't work.\r
+     * @param bool $optimized If true, this method may return null, to\r
+     *             indicate that a cached version of the modified\r
+     *             definition object is available and no further edits\r
+     *             are necessary.  Consider using\r
+     *             maybeGetRawURIDefinition, which is more explicitly\r
+     *             named, instead.\r
+     *\r
+     * @return HTMLPurifier_URIDefinition\r
+     */\r
+    public function getURIDefinition($raw = false, $optimized = false)\r
+    {\r
+        return $this->getDefinition('URI', $raw, $optimized);\r
+    }\r
+\r
+    /**\r
+     * Retrieves a definition\r
+     *\r
+     * @param string $type Type of definition: HTML, CSS, etc\r
+     * @param bool $raw Whether or not definition should be returned raw\r
+     * @param bool $optimized Only has an effect when $raw is true.  Whether\r
+     *        or not to return null if the result is already present in\r
+     *        the cache.  This is off by default for backwards\r
+     *        compatibility reasons, but you need to do things this\r
+     *        way in order to ensure that caching is done properly.\r
+     *        Check out enduser-customize.html for more details.\r
+     *        We probably won't ever change this default, as much as the\r
+     *        maybe semantics is the "right thing to do."\r
+     *\r
+     * @throws HTMLPurifier_Exception\r
+     * @return HTMLPurifier_Definition\r
+     */\r
+    public function getDefinition($type, $raw = false, $optimized = false)\r
+    {\r
+        if ($optimized && !$raw) {\r
+            throw new HTMLPurifier_Exception("Cannot set optimized = true when raw = false");\r
+        }\r
+        if (!$this->finalized) {\r
+            $this->autoFinalize();\r
+        }\r
+        // temporarily suspend locks, so we can handle recursive definition calls\r
+        $lock = $this->lock;\r
+        $this->lock = null;\r
+        $factory = HTMLPurifier_DefinitionCacheFactory::instance();\r
+        $cache = $factory->create($type, $this);\r
+        $this->lock = $lock;\r
+        if (!$raw) {\r
+            // full definition\r
+            // ---------------\r
+            // check if definition is in memory\r
+            if (!empty($this->definitions[$type])) {\r
+                $def = $this->definitions[$type];\r
+                // check if the definition is setup\r
+                if ($def->setup) {\r
+                    return $def;\r
+                } else {\r
+                    $def->setup($this);\r
+                    if ($def->optimized) {\r
+                        $cache->add($def, $this);\r
+                    }\r
+                    return $def;\r
+                }\r
+            }\r
+            // check if definition is in cache\r
+            $def = $cache->get($this);\r
+            if ($def) {\r
+                // definition in cache, save to memory and return it\r
+                $this->definitions[$type] = $def;\r
+                return $def;\r
+            }\r
+            // initialize it\r
+            $def = $this->initDefinition($type);\r
+            // set it up\r
+            $this->lock = $type;\r
+            $def->setup($this);\r
+            $this->lock = null;\r
+            // save in cache\r
+            $cache->add($def, $this);\r
+            // return it\r
+            return $def;\r
+        } else {\r
+            // raw definition\r
+            // --------------\r
+            // check preconditions\r
+            $def = null;\r
+            if ($optimized) {\r
+                if (is_null($this->get($type . '.DefinitionID'))) {\r
+                    // fatally error out if definition ID not set\r
+                    throw new HTMLPurifier_Exception(\r
+                        "Cannot retrieve raw version without specifying %$type.DefinitionID"\r
+                    );\r
+                }\r
+            }\r
+            if (!empty($this->definitions[$type])) {\r
+                $def = $this->definitions[$type];\r
+                if ($def->setup && !$optimized) {\r
+                    $extra = $this->chatty ?\r
+                        " (try moving this code block earlier in your initialization)" :\r
+                        "";\r
+                    throw new HTMLPurifier_Exception(\r
+                        "Cannot retrieve raw definition after it has already been setup" .\r
+                        $extra\r
+                    );\r
+                }\r
+                if ($def->optimized === null) {\r
+                    $extra = $this->chatty ? " (try flushing your cache)" : "";\r
+                    throw new HTMLPurifier_Exception(\r
+                        "Optimization status of definition is unknown" . $extra\r
+                    );\r
+                }\r
+                if ($def->optimized !== $optimized) {\r
+                    $msg = $optimized ? "optimized" : "unoptimized";\r
+                    $extra = $this->chatty ?\r
+                        " (this backtrace is for the first inconsistent call, which was for a $msg raw definition)"\r
+                        : "";\r
+                    throw new HTMLPurifier_Exception(\r
+                        "Inconsistent use of optimized and unoptimized raw definition retrievals" . $extra\r
+                    );\r
+                }\r
+            }\r
+            // check if definition was in memory\r
+            if ($def) {\r
+                if ($def->setup) {\r
+                    // invariant: $optimized === true (checked above)\r
+                    return null;\r
+                } else {\r
+                    return $def;\r
+                }\r
+            }\r
+            // if optimized, check if definition was in cache\r
+            // (because we do the memory check first, this formulation\r
+            // is prone to cache slamming, but I think\r
+            // guaranteeing that either /all/ of the raw\r
+            // setup code or /none/ of it is run is more important.)\r
+            if ($optimized) {\r
+                // This code path only gets run once; once we put\r
+                // something in $definitions (which is guaranteed by the\r
+                // trailing code), we always short-circuit above.\r
+                $def = $cache->get($this);\r
+                if ($def) {\r
+                    // save the full definition for later, but don't\r
+                    // return it yet\r
+                    $this->definitions[$type] = $def;\r
+                    return null;\r
+                }\r
+            }\r
+            // check invariants for creation\r
+            if (!$optimized) {\r
+                if (!is_null($this->get($type . '.DefinitionID'))) {\r
+                    if ($this->chatty) {\r
+                        $this->triggerError(\r
+                            'Due to a documentation error in previous version of HTML Purifier, your ' .\r
+                            'definitions are not being cached.  If this is OK, you can remove the ' .\r
+                            '%$type.DefinitionRev and %$type.DefinitionID declaration.  Otherwise, ' .\r
+                            'modify your code to use maybeGetRawDefinition, and test if the returned ' .\r
+                            'value is null before making any edits (if it is null, that means that a ' .\r
+                            'cached version is available, and no raw operations are necessary).  See ' .\r
+                            '<a href="http://htmlpurifier.org/docs/enduser-customize.html#optimized">' .\r
+                            'Customize</a> for more details',\r
+                            E_USER_WARNING\r
+                        );\r
+                    } else {\r
+                        $this->triggerError(\r
+                            "Useless DefinitionID declaration",\r
+                            E_USER_WARNING\r
+                        );\r
+                    }\r
+                }\r
+            }\r
+            // initialize it\r
+            $def = $this->initDefinition($type);\r
+            $def->optimized = $optimized;\r
+            return $def;\r
+        }\r
+        throw new HTMLPurifier_Exception("The impossible happened!");\r
+    }\r
+\r
+    /**\r
+     * Initialise definition\r
+     *\r
+     * @param string $type What type of definition to create\r
+     *\r
+     * @return HTMLPurifier_CSSDefinition|HTMLPurifier_HTMLDefinition|HTMLPurifier_URIDefinition\r
+     * @throws HTMLPurifier_Exception\r
+     */\r
+    private function initDefinition($type)\r
+    {\r
+        // quick checks failed, let's create the object\r
+        if ($type == 'HTML') {\r
+            $def = new HTMLPurifier_HTMLDefinition();\r
+        } elseif ($type == 'CSS') {\r
+            $def = new HTMLPurifier_CSSDefinition();\r
+        } elseif ($type == 'URI') {\r
+            $def = new HTMLPurifier_URIDefinition();\r
+        } else {\r
+            throw new HTMLPurifier_Exception(\r
+                "Definition of $type type not supported"\r
+            );\r
+        }\r
+        $this->definitions[$type] = $def;\r
+        return $def;\r
+    }\r
+\r
+    public function maybeGetRawDefinition($name)\r
+    {\r
+        return $this->getDefinition($name, true, true);\r
+    }\r
+\r
+    /**\r
+     * @return HTMLPurifier_HTMLDefinition\r
+     */\r
+    public function maybeGetRawHTMLDefinition()\r
+    {\r
+        return $this->getDefinition('HTML', true, true);\r
+    }\r
+    \r
+    /**\r
+     * @return HTMLPurifier_CSSDefinition\r
+     */\r
+    public function maybeGetRawCSSDefinition()\r
+    {\r
+        return $this->getDefinition('CSS', true, true);\r
+    }\r
+    \r
+    /**\r
+     * @return HTMLPurifier_URIDefinition\r
+     */\r
+    public function maybeGetRawURIDefinition()\r
+    {\r
+        return $this->getDefinition('URI', true, true);\r
+    }\r
+\r
+    /**\r
+     * Loads configuration values from an array with the following structure:\r
+     * Namespace.Directive => Value\r
+     *\r
+     * @param array $config_array Configuration associative array\r
+     */\r
+    public function loadArray($config_array)\r
+    {\r
+        if ($this->isFinalized('Cannot load directives after finalization')) {\r
+            return;\r
+        }\r
+        foreach ($config_array as $key => $value) {\r
+            $key = str_replace('_', '.', $key);\r
+            if (strpos($key, '.') !== false) {\r
+                $this->set($key, $value);\r
+            } else {\r
+                $namespace = $key;\r
+                $namespace_values = $value;\r
+                foreach ($namespace_values as $directive => $value2) {\r
+                    $this->set($namespace .'.'. $directive, $value2);\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Returns a list of array(namespace, directive) for all directives\r
+     * that are allowed in a web-form context as per an allowed\r
+     * namespaces/directives list.\r
+     *\r
+     * @param array $allowed List of allowed namespaces/directives\r
+     * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy\r
+     *\r
+     * @return array\r
+     */\r
+    public static function getAllowedDirectivesForForm($allowed, $schema = null)\r
+    {\r
+        if (!$schema) {\r
+            $schema = HTMLPurifier_ConfigSchema::instance();\r
+        }\r
+        if ($allowed !== true) {\r
+            if (is_string($allowed)) {\r
+                $allowed = array($allowed);\r
+            }\r
+            $allowed_ns = array();\r
+            $allowed_directives = array();\r
+            $blacklisted_directives = array();\r
+            foreach ($allowed as $ns_or_directive) {\r
+                if (strpos($ns_or_directive, '.') !== false) {\r
+                    // directive\r
+                    if ($ns_or_directive[0] == '-') {\r
+                        $blacklisted_directives[substr($ns_or_directive, 1)] = true;\r
+                    } else {\r
+                        $allowed_directives[$ns_or_directive] = true;\r
+                    }\r
+                } else {\r
+                    // namespace\r
+                    $allowed_ns[$ns_or_directive] = true;\r
+                }\r
+            }\r
+        }\r
+        $ret = array();\r
+        foreach ($schema->info as $key => $def) {\r
+            list($ns, $directive) = explode('.', $key, 2);\r
+            if ($allowed !== true) {\r
+                if (isset($blacklisted_directives["$ns.$directive"])) {\r
+                    continue;\r
+                }\r
+                if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) {\r
+                    continue;\r
+                }\r
+            }\r
+            if (isset($def->isAlias)) {\r
+                continue;\r
+            }\r
+            if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') {\r
+                continue;\r
+            }\r
+            $ret[] = array($ns, $directive);\r
+        }\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Loads configuration values from $_GET/$_POST that were posted\r
+     * via ConfigForm\r
+     *\r
+     * @param array $array $_GET or $_POST array to import\r
+     * @param string|bool $index Index/name that the config variables are in\r
+     * @param array|bool $allowed List of allowed namespaces/directives\r
+     * @param bool $mq_fix Boolean whether or not to enable magic quotes fix\r
+     * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy\r
+     *\r
+     * @return mixed\r
+     */\r
+    public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null)\r
+    {\r
+        $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);\r
+        $config = HTMLPurifier_Config::create($ret, $schema);\r
+        return $config;\r
+    }\r
+\r
+    /**\r
+     * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.\r
+     *\r
+     * @param array $array $_GET or $_POST array to import\r
+     * @param string|bool $index Index/name that the config variables are in\r
+     * @param array|bool $allowed List of allowed namespaces/directives\r
+     * @param bool $mq_fix Boolean whether or not to enable magic quotes fix\r
+     */\r
+    public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true)\r
+    {\r
+         $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);\r
+         $this->loadArray($ret);\r
+    }\r
+\r
+    /**\r
+     * Prepares an array from a form into something usable for the more\r
+     * strict parts of HTMLPurifier_Config\r
+     *\r
+     * @param array $array $_GET or $_POST array to import\r
+     * @param string|bool $index Index/name that the config variables are in\r
+     * @param array|bool $allowed List of allowed namespaces/directives\r
+     * @param bool $mq_fix Boolean whether or not to enable magic quotes fix\r
+     * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy\r
+     *\r
+     * @return array\r
+     */\r
+    public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null)\r
+    {\r
+        if ($index !== false) {\r
+            $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();\r
+        }\r
+        $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();\r
+\r
+        $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);\r
+        $ret = array();\r
+        foreach ($allowed as $key) {\r
+            list($ns, $directive) = $key;\r
+            $skey = "$ns.$directive";\r
+            if (!empty($array["Null_$skey"])) {\r
+                $ret[$ns][$directive] = null;\r
+                continue;\r
+            }\r
+            if (!isset($array[$skey])) {\r
+                continue;\r
+            }\r
+            $value = $mq ? stripslashes($array[$skey]) : $array[$skey];\r
+            $ret[$ns][$directive] = $value;\r
+        }\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Loads configuration values from an ini file\r
+     *\r
+     * @param string $filename Name of ini file\r
+     */\r
+    public function loadIni($filename)\r
+    {\r
+        if ($this->isFinalized('Cannot load directives after finalization')) {\r
+            return;\r
+        }\r
+        $array = parse_ini_file($filename, true);\r
+        $this->loadArray($array);\r
+    }\r
+\r
+    /**\r
+     * Checks whether or not the configuration object is finalized.\r
+     *\r
+     * @param string|bool $error String error message, or false for no error\r
+     *\r
+     * @return bool\r
+     */\r
+    public function isFinalized($error = false)\r
+    {\r
+        if ($this->finalized && $error) {\r
+            $this->triggerError($error, E_USER_ERROR);\r
+        }\r
+        return $this->finalized;\r
+    }\r
+\r
+    /**\r
+     * Finalizes configuration only if auto finalize is on and not\r
+     * already finalized\r
+     */\r
+    public function autoFinalize()\r
+    {\r
+        if ($this->autoFinalize) {\r
+            $this->finalize();\r
+        } else {\r
+            $this->plist->squash(true);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Finalizes a configuration object, prohibiting further change\r
+     */\r
+    public function finalize()\r
+    {\r
+        $this->finalized = true;\r
+        $this->parser = null;\r
+    }\r
+\r
+    /**\r
+     * Produces a nicely formatted error message by supplying the\r
+     * stack frame information OUTSIDE of HTMLPurifier_Config.\r
+     *\r
+     * @param string $msg An error message\r
+     * @param int $no An error number\r
+     */\r
+    protected function triggerError($msg, $no)\r
+    {\r
+        // determine previous stack frame\r
+        $extra = '';\r
+        if ($this->chatty) {\r
+            $trace = debug_backtrace();\r
+            // zip(tail(trace), trace) -- but PHP is not Haskell har har\r
+            for ($i = 0, $c = count($trace); $i < $c - 1; $i++) {\r
+                // XXX this is not correct on some versions of HTML Purifier\r
+                if (isset($trace[$i + 1]['class']) && $trace[$i + 1]['class'] === 'HTMLPurifier_Config') {\r
+                    continue;\r
+                }\r
+                $frame = $trace[$i];\r
+                $extra = " invoked on line {$frame['line']} in file {$frame['file']}";\r
+                break;\r
+            }\r
+        }\r
+        trigger_error($msg . $extra, $no);\r
+    }\r
+\r
+    /**\r
+     * Returns a serialized form of the configuration object that can\r
+     * be reconstituted.\r
+     *\r
+     * @return string\r
+     */\r
+    public function serialize()\r
+    {\r
+        $this->getDefinition('HTML');\r
+        $this->getDefinition('CSS');\r
+        $this->getDefinition('URI');\r
+        return serialize($this);\r
+    }\r
+\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Configuration definition, defines directives and their defaults.\r
+ */\r
+class HTMLPurifier_ConfigSchema\r
+{\r
+    /**\r
+     * Defaults of the directives and namespaces.\r
+     * @type array\r
+     * @note This shares the exact same structure as HTMLPurifier_Config::$conf\r
+     */\r
+    public $defaults = array();\r
+\r
+    /**\r
+     * The default property list. Do not edit this property list.\r
+     * @type array\r
+     */\r
+    public $defaultPlist;\r
+\r
+    /**\r
+     * Definition of the directives.\r
+     * The structure of this is:\r
+     *\r
+     *  array(\r
+     *      'Namespace' => array(\r
+     *          'Directive' => new stdClass(),\r
+     *      )\r
+     *  )\r
+     *\r
+     * The stdClass may have the following properties:\r
+     *\r
+     *  - If isAlias isn't set:\r
+     *      - type: Integer type of directive, see HTMLPurifier_VarParser for definitions\r
+     *      - allow_null: If set, this directive allows null values\r
+     *      - aliases: If set, an associative array of value aliases to real values\r
+     *      - allowed: If set, a lookup array of allowed (string) values\r
+     *  - If isAlias is set:\r
+     *      - namespace: Namespace this directive aliases to\r
+     *      - name: Directive name this directive aliases to\r
+     *\r
+     * In certain degenerate cases, stdClass will actually be an integer. In\r
+     * that case, the value is equivalent to an stdClass with the type\r
+     * property set to the integer. If the integer is negative, type is\r
+     * equal to the absolute value of integer, and allow_null is true.\r
+     *\r
+     * This class is friendly with HTMLPurifier_Config. If you need introspection\r
+     * about the schema, you're better of using the ConfigSchema_Interchange,\r
+     * which uses more memory but has much richer information.\r
+     * @type array\r
+     */\r
+    public $info = array();\r
+\r
+    /**\r
+     * Application-wide singleton\r
+     * @type HTMLPurifier_ConfigSchema\r
+     */\r
+    protected static $singleton;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->defaultPlist = new HTMLPurifier_PropertyList();\r
+    }\r
+\r
+    /**\r
+     * Unserializes the default ConfigSchema.\r
+     * @return HTMLPurifier_ConfigSchema\r
+     */\r
+    public static function makeFromSerial()\r
+    {\r
+        $contents = file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema.ser');\r
+        $r = unserialize($contents);\r
+        if (!$r) {\r
+            $hash = sha1($contents);\r
+            trigger_error("Unserialization of configuration schema failed, sha1 of file was $hash", E_USER_ERROR);\r
+        }\r
+        return $r;\r
+    }\r
+\r
+    /**\r
+     * Retrieves an instance of the application-wide configuration definition.\r
+     * @param HTMLPurifier_ConfigSchema $prototype\r
+     * @return HTMLPurifier_ConfigSchema\r
+     */\r
+    public static function instance($prototype = null)\r
+    {\r
+        if ($prototype !== null) {\r
+            HTMLPurifier_ConfigSchema::$singleton = $prototype;\r
+        } elseif (HTMLPurifier_ConfigSchema::$singleton === null || $prototype === true) {\r
+            HTMLPurifier_ConfigSchema::$singleton = HTMLPurifier_ConfigSchema::makeFromSerial();\r
+        }\r
+        return HTMLPurifier_ConfigSchema::$singleton;\r
+    }\r
+\r
+    /**\r
+     * Defines a directive for configuration\r
+     * @warning Will fail of directive's namespace is defined.\r
+     * @warning This method's signature is slightly different from the legacy\r
+     *          define() static method! Beware!\r
+     * @param string $key Name of directive\r
+     * @param mixed $default Default value of directive\r
+     * @param string $type Allowed type of the directive. See\r
+     *      HTMLPurifier_VarParser::$types for allowed values\r
+     * @param bool $allow_null Whether or not to allow null values\r
+     */\r
+    public function add($key, $default, $type, $allow_null)\r
+    {\r
+        $obj = new stdClass();\r
+        $obj->type = is_int($type) ? $type : HTMLPurifier_VarParser::$types[$type];\r
+        if ($allow_null) {\r
+            $obj->allow_null = true;\r
+        }\r
+        $this->info[$key] = $obj;\r
+        $this->defaults[$key] = $default;\r
+        $this->defaultPlist->set($key, $default);\r
+    }\r
+\r
+    /**\r
+     * Defines a directive value alias.\r
+     *\r
+     * Directive value aliases are convenient for developers because it lets\r
+     * them set a directive to several values and get the same result.\r
+     * @param string $key Name of Directive\r
+     * @param array $aliases Hash of aliased values to the real alias\r
+     */\r
+    public function addValueAliases($key, $aliases)\r
+    {\r
+        if (!isset($this->info[$key]->aliases)) {\r
+            $this->info[$key]->aliases = array();\r
+        }\r
+        foreach ($aliases as $alias => $real) {\r
+            $this->info[$key]->aliases[$alias] = $real;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Defines a set of allowed values for a directive.\r
+     * @warning This is slightly different from the corresponding static\r
+     *          method definition.\r
+     * @param string $key Name of directive\r
+     * @param array $allowed Lookup array of allowed values\r
+     */\r
+    public function addAllowedValues($key, $allowed)\r
+    {\r
+        $this->info[$key]->allowed = $allowed;\r
+    }\r
+\r
+    /**\r
+     * Defines a directive alias for backwards compatibility\r
+     * @param string $key Directive that will be aliased\r
+     * @param string $new_key Directive that the alias will be to\r
+     */\r
+    public function addAlias($key, $new_key)\r
+    {\r
+        $obj = new stdClass;\r
+        $obj->key = $new_key;\r
+        $obj->isAlias = true;\r
+        $this->info[$key] = $obj;\r
+    }\r
+\r
+    /**\r
+     * Replaces any stdClass that only has the type property with type integer.\r
+     */\r
+    public function postProcess()\r
+    {\r
+        foreach ($this->info as $key => $v) {\r
+            if (count((array) $v) == 1) {\r
+                $this->info[$key] = $v->type;\r
+            } elseif (count((array) $v) == 2 && isset($v->allow_null)) {\r
+                $this->info[$key] = -$v->type;\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * @todo Unit test\r
+ */\r
+class HTMLPurifier_ContentSets\r
+{\r
+\r
+    /**\r
+     * List of content set strings (pipe separators) indexed by name.\r
+     * @type array\r
+     */\r
+    public $info = array();\r
+\r
+    /**\r
+     * List of content set lookups (element => true) indexed by name.\r
+     * @type array\r
+     * @note This is in HTMLPurifier_HTMLDefinition->info_content_sets\r
+     */\r
+    public $lookup = array();\r
+\r
+    /**\r
+     * Synchronized list of defined content sets (keys of info).\r
+     * @type array\r
+     */\r
+    protected $keys = array();\r
+    /**\r
+     * Synchronized list of defined content values (values of info).\r
+     * @type array\r
+     */\r
+    protected $values = array();\r
+\r
+    /**\r
+     * Merges in module's content sets, expands identifiers in the content\r
+     * sets and populates the keys, values and lookup member variables.\r
+     * @param HTMLPurifier_HTMLModule[] $modules List of HTMLPurifier_HTMLModule\r
+     */\r
+    public function __construct($modules)\r
+    {\r
+        if (!is_array($modules)) {\r
+            $modules = array($modules);\r
+        }\r
+        // populate content_sets based on module hints\r
+        // sorry, no way of overloading\r
+        foreach ($modules as $module) {\r
+            foreach ($module->content_sets as $key => $value) {\r
+                $temp = $this->convertToLookup($value);\r
+                if (isset($this->lookup[$key])) {\r
+                    // add it into the existing content set\r
+                    $this->lookup[$key] = array_merge($this->lookup[$key], $temp);\r
+                } else {\r
+                    $this->lookup[$key] = $temp;\r
+                }\r
+            }\r
+        }\r
+        $old_lookup = false;\r
+        while ($old_lookup !== $this->lookup) {\r
+            $old_lookup = $this->lookup;\r
+            foreach ($this->lookup as $i => $set) {\r
+                $add = array();\r
+                foreach ($set as $element => $x) {\r
+                    if (isset($this->lookup[$element])) {\r
+                        $add += $this->lookup[$element];\r
+                        unset($this->lookup[$i][$element]);\r
+                    }\r
+                }\r
+                $this->lookup[$i] += $add;\r
+            }\r
+        }\r
+\r
+        foreach ($this->lookup as $key => $lookup) {\r
+            $this->info[$key] = implode(' | ', array_keys($lookup));\r
+        }\r
+        $this->keys   = array_keys($this->info);\r
+        $this->values = array_values($this->info);\r
+    }\r
+\r
+    /**\r
+     * Accepts a definition; generates and assigns a ChildDef for it\r
+     * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef reference\r
+     * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef\r
+     */\r
+    public function generateChildDef(&$def, $module)\r
+    {\r
+        if (!empty($def->child)) { // already done!\r
+            return;\r
+        }\r
+        $content_model = $def->content_model;\r
+        if (is_string($content_model)) {\r
+            // Assume that $this->keys is alphanumeric\r
+            $def->content_model = preg_replace_callback(\r
+                '/\b(' . implode('|', $this->keys) . ')\b/',\r
+                array($this, 'generateChildDefCallback'),\r
+                $content_model\r
+            );\r
+            //$def->content_model = str_replace(\r
+            //    $this->keys, $this->values, $content_model);\r
+        }\r
+        $def->child = $this->getChildDef($def, $module);\r
+    }\r
+\r
+    public function generateChildDefCallback($matches)\r
+    {\r
+        return $this->info[$matches[0]];\r
+    }\r
+\r
+    /**\r
+     * Instantiates a ChildDef based on content_model and content_model_type\r
+     * member variables in HTMLPurifier_ElementDef\r
+     * @note This will also defer to modules for custom HTMLPurifier_ChildDef\r
+     *       subclasses that need content set expansion\r
+     * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef to have ChildDef extracted\r
+     * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef\r
+     * @return HTMLPurifier_ChildDef corresponding to ElementDef\r
+     */\r
+    public function getChildDef($def, $module)\r
+    {\r
+        $value = $def->content_model;\r
+        if (is_object($value)) {\r
+            trigger_error(\r
+                'Literal object child definitions should be stored in '.\r
+                'ElementDef->child not ElementDef->content_model',\r
+                E_USER_NOTICE\r
+            );\r
+            return $value;\r
+        }\r
+        switch ($def->content_model_type) {\r
+            case 'required':\r
+                return new HTMLPurifier_ChildDef_Required($value);\r
+            case 'optional':\r
+                return new HTMLPurifier_ChildDef_Optional($value);\r
+            case 'empty':\r
+                return new HTMLPurifier_ChildDef_Empty();\r
+            case 'custom':\r
+                return new HTMLPurifier_ChildDef_Custom($value);\r
+        }\r
+        // defer to its module\r
+        $return = false;\r
+        if ($module->defines_child_def) { // save a func call\r
+            $return = $module->getChildDef($def);\r
+        }\r
+        if ($return !== false) {\r
+            return $return;\r
+        }\r
+        // error-out\r
+        trigger_error(\r
+            'Could not determine which ChildDef class to instantiate',\r
+            E_USER_ERROR\r
+        );\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * Converts a string list of elements separated by pipes into\r
+     * a lookup array.\r
+     * @param string $string List of elements\r
+     * @return array Lookup array of elements\r
+     */\r
+    protected function convertToLookup($string)\r
+    {\r
+        $array = explode('|', str_replace(' ', '', $string));\r
+        $ret = array();\r
+        foreach ($array as $k) {\r
+            $ret[$k] = true;\r
+        }\r
+        return $ret;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Registry object that contains information about the current context.\r
+ * @warning Is a bit buggy when variables are set to null: it thinks\r
+ *          they don't exist! So use false instead, please.\r
+ * @note Since the variables Context deals with may not be objects,\r
+ *       references are very important here! Do not remove!\r
+ */\r
+class HTMLPurifier_Context\r
+{\r
+\r
+    /**\r
+     * Private array that stores the references.\r
+     * @type array\r
+     */\r
+    private $_storage = array();\r
+\r
+    /**\r
+     * Registers a variable into the context.\r
+     * @param string $name String name\r
+     * @param mixed $ref Reference to variable to be registered\r
+     */\r
+    public function register($name, &$ref)\r
+    {\r
+        if (array_key_exists($name, $this->_storage)) {\r
+            trigger_error(\r
+                "Name $name produces collision, cannot re-register",\r
+                E_USER_ERROR\r
+            );\r
+            return;\r
+        }\r
+        $this->_storage[$name] =& $ref;\r
+    }\r
+\r
+    /**\r
+     * Retrieves a variable reference from the context.\r
+     * @param string $name String name\r
+     * @param bool $ignore_error Boolean whether or not to ignore error\r
+     * @return mixed\r
+     */\r
+    public function &get($name, $ignore_error = false)\r
+    {\r
+        if (!array_key_exists($name, $this->_storage)) {\r
+            if (!$ignore_error) {\r
+                trigger_error(\r
+                    "Attempted to retrieve non-existent variable $name",\r
+                    E_USER_ERROR\r
+                );\r
+            }\r
+            $var = null; // so we can return by reference\r
+            return $var;\r
+        }\r
+        return $this->_storage[$name];\r
+    }\r
+\r
+    /**\r
+     * Destroys a variable in the context.\r
+     * @param string $name String name\r
+     */\r
+    public function destroy($name)\r
+    {\r
+        if (!array_key_exists($name, $this->_storage)) {\r
+            trigger_error(\r
+                "Attempted to destroy non-existent variable $name",\r
+                E_USER_ERROR\r
+            );\r
+            return;\r
+        }\r
+        unset($this->_storage[$name]);\r
+    }\r
+\r
+    /**\r
+     * Checks whether or not the variable exists.\r
+     * @param string $name String name\r
+     * @return bool\r
+     */\r
+    public function exists($name)\r
+    {\r
+        return array_key_exists($name, $this->_storage);\r
+    }\r
+\r
+    /**\r
+     * Loads a series of variables from an associative array\r
+     * @param array $context_array Assoc array of variables to load\r
+     */\r
+    public function loadArray($context_array)\r
+    {\r
+        foreach ($context_array as $key => $discard) {\r
+            $this->register($key, $context_array[$key]);\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Abstract class representing Definition cache managers that implements\r
+ * useful common methods and is a factory.\r
+ * @todo Create a separate maintenance file advanced users can use to\r
+ *       cache their custom HTMLDefinition, which can be loaded\r
+ *       via a configuration directive\r
+ * @todo Implement memcached\r
+ */\r
+abstract class HTMLPurifier_DefinitionCache\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $type;\r
+\r
+    /**\r
+     * @param string $type Type of definition objects this instance of the\r
+     *      cache will handle.\r
+     */\r
+    public function __construct($type)\r
+    {\r
+        $this->type = $type;\r
+    }\r
+\r
+    /**\r
+     * Generates a unique identifier for a particular configuration\r
+     * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config\r
+     * @return string\r
+     */\r
+    public function generateKey($config)\r
+    {\r
+        return $config->version . ',' . // possibly replace with function calls\r
+               $config->getBatchSerial($this->type) . ',' .\r
+               $config->get($this->type . '.DefinitionRev');\r
+    }\r
+\r
+    /**\r
+     * Tests whether or not a key is old with respect to the configuration's\r
+     * version and revision number.\r
+     * @param string $key Key to test\r
+     * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config to test against\r
+     * @return bool\r
+     */\r
+    public function isOld($key, $config)\r
+    {\r
+        if (substr_count($key, ',') < 2) {\r
+            return true;\r
+        }\r
+        list($version, $hash, $revision) = explode(',', $key, 3);\r
+        $compare = version_compare($version, $config->version);\r
+        // version mismatch, is always old\r
+        if ($compare != 0) {\r
+            return true;\r
+        }\r
+        // versions match, ids match, check revision number\r
+        if ($hash == $config->getBatchSerial($this->type) &&\r
+            $revision < $config->get($this->type . '.DefinitionRev')) {\r
+            return true;\r
+        }\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * Checks if a definition's type jives with the cache's type\r
+     * @note Throws an error on failure\r
+     * @param HTMLPurifier_Definition $def Definition object to check\r
+     * @return bool true if good, false if not\r
+     */\r
+    public function checkDefType($def)\r
+    {\r
+        if ($def->type !== $this->type) {\r
+            trigger_error("Cannot use definition of type {$def->type} in cache for {$this->type}");\r
+            return false;\r
+        }\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Adds a definition object to the cache\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    abstract public function add($def, $config);\r
+\r
+    /**\r
+     * Unconditionally saves a definition object to the cache\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    abstract public function set($def, $config);\r
+\r
+    /**\r
+     * Replace an object in the cache\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    abstract public function replace($def, $config);\r
+\r
+    /**\r
+     * Retrieves a definition object from the cache\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    abstract public function get($config);\r
+\r
+    /**\r
+     * Removes a definition object to the cache\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    abstract public function remove($config);\r
+\r
+    /**\r
+     * Clears all objects from cache\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    abstract public function flush($config);\r
+\r
+    /**\r
+     * Clears all expired (older version or revision) objects from cache\r
+     * @note Be careful implementing this method as flush. Flush must\r
+     *       not interfere with other Definition types, and cleanup()\r
+     *       should not be repeatedly called by userland code.\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    abstract public function cleanup($config);\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Responsible for creating definition caches.\r
+ */\r
+class HTMLPurifier_DefinitionCacheFactory\r
+{\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $caches = array('Serializer' => array());\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $implementations = array();\r
+\r
+    /**\r
+     * @type HTMLPurifier_DefinitionCache_Decorator[]\r
+     */\r
+    protected $decorators = array();\r
+\r
+    /**\r
+     * Initialize default decorators\r
+     */\r
+    public function setup()\r
+    {\r
+        $this->addDecorator('Cleanup');\r
+    }\r
+\r
+    /**\r
+     * Retrieves an instance of global definition cache factory.\r
+     * @param HTMLPurifier_DefinitionCacheFactory $prototype\r
+     * @return HTMLPurifier_DefinitionCacheFactory\r
+     */\r
+    public static function instance($prototype = null)\r
+    {\r
+        static $instance;\r
+        if ($prototype !== null) {\r
+            $instance = $prototype;\r
+        } elseif ($instance === null || $prototype === true) {\r
+            $instance = new HTMLPurifier_DefinitionCacheFactory();\r
+            $instance->setup();\r
+        }\r
+        return $instance;\r
+    }\r
+\r
+    /**\r
+     * Registers a new definition cache object\r
+     * @param string $short Short name of cache object, for reference\r
+     * @param string $long Full class name of cache object, for construction\r
+     */\r
+    public function register($short, $long)\r
+    {\r
+        $this->implementations[$short] = $long;\r
+    }\r
+\r
+    /**\r
+     * Factory method that creates a cache object based on configuration\r
+     * @param string $type Name of definitions handled by cache\r
+     * @param HTMLPurifier_Config $config Config instance\r
+     * @return mixed\r
+     */\r
+    public function create($type, $config)\r
+    {\r
+        $method = $config->get('Cache.DefinitionImpl');\r
+        if ($method === null) {\r
+            return new HTMLPurifier_DefinitionCache_Null($type);\r
+        }\r
+        if (!empty($this->caches[$method][$type])) {\r
+            return $this->caches[$method][$type];\r
+        }\r
+        if (isset($this->implementations[$method]) &&\r
+            class_exists($class = $this->implementations[$method], false)) {\r
+            $cache = new $class($type);\r
+        } else {\r
+            if ($method != 'Serializer') {\r
+                trigger_error("Unrecognized DefinitionCache $method, using Serializer instead", E_USER_WARNING);\r
+            }\r
+            $cache = new HTMLPurifier_DefinitionCache_Serializer($type);\r
+        }\r
+        foreach ($this->decorators as $decorator) {\r
+            $new_cache = $decorator->decorate($cache);\r
+            // prevent infinite recursion in PHP 4\r
+            unset($cache);\r
+            $cache = $new_cache;\r
+        }\r
+        $this->caches[$method][$type] = $cache;\r
+        return $this->caches[$method][$type];\r
+    }\r
+\r
+    /**\r
+     * Registers a decorator to add to all new cache objects\r
+     * @param HTMLPurifier_DefinitionCache_Decorator|string $decorator An instance or the name of a decorator\r
+     */\r
+    public function addDecorator($decorator)\r
+    {\r
+        if (is_string($decorator)) {\r
+            $class = "HTMLPurifier_DefinitionCache_Decorator_$decorator";\r
+            $decorator = new $class;\r
+        }\r
+        $this->decorators[$decorator->name] = $decorator;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Represents a document type, contains information on which modules\r
+ * need to be loaded.\r
+ * @note This class is inspected by Printer_HTMLDefinition->renderDoctype.\r
+ *       If structure changes, please update that function.\r
+ */\r
+class HTMLPurifier_Doctype\r
+{\r
+    /**\r
+     * Full name of doctype\r
+     * @type string\r
+     */\r
+    public $name;\r
+\r
+    /**\r
+     * List of standard modules (string identifiers or literal objects)\r
+     * that this doctype uses\r
+     * @type array\r
+     */\r
+    public $modules = array();\r
+\r
+    /**\r
+     * List of modules to use for tidying up code\r
+     * @type array\r
+     */\r
+    public $tidyModules = array();\r
+\r
+    /**\r
+     * Is the language derived from XML (i.e. XHTML)?\r
+     * @type bool\r
+     */\r
+    public $xml = true;\r
+\r
+    /**\r
+     * List of aliases for this doctype\r
+     * @type array\r
+     */\r
+    public $aliases = array();\r
+\r
+    /**\r
+     * Public DTD identifier\r
+     * @type string\r
+     */\r
+    public $dtdPublic;\r
+\r
+    /**\r
+     * System DTD identifier\r
+     * @type string\r
+     */\r
+    public $dtdSystem;\r
+\r
+    public function __construct(\r
+        $name = null,\r
+        $xml = true,\r
+        $modules = array(),\r
+        $tidyModules = array(),\r
+        $aliases = array(),\r
+        $dtd_public = null,\r
+        $dtd_system = null\r
+    ) {\r
+        $this->name         = $name;\r
+        $this->xml          = $xml;\r
+        $this->modules      = $modules;\r
+        $this->tidyModules  = $tidyModules;\r
+        $this->aliases      = $aliases;\r
+        $this->dtdPublic    = $dtd_public;\r
+        $this->dtdSystem    = $dtd_system;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_DoctypeRegistry\r
+{\r
+\r
+    /**\r
+     * Hash of doctype names to doctype objects.\r
+     * @type array\r
+     */\r
+    protected $doctypes;\r
+\r
+    /**\r
+     * Lookup table of aliases to real doctype names.\r
+     * @type array\r
+     */\r
+    protected $aliases;\r
+\r
+    /**\r
+     * Registers a doctype to the registry\r
+     * @note Accepts a fully-formed doctype object, or the\r
+     *       parameters for constructing a doctype object\r
+     * @param string $doctype Name of doctype or literal doctype object\r
+     * @param bool $xml\r
+     * @param array $modules Modules doctype will load\r
+     * @param array $tidy_modules Modules doctype will load for certain modes\r
+     * @param array $aliases Alias names for doctype\r
+     * @param string $dtd_public\r
+     * @param string $dtd_system\r
+     * @return HTMLPurifier_Doctype Editable registered doctype\r
+     */\r
+    public function register(\r
+        $doctype,\r
+        $xml = true,\r
+        $modules = array(),\r
+        $tidy_modules = array(),\r
+        $aliases = array(),\r
+        $dtd_public = null,\r
+        $dtd_system = null\r
+    ) {\r
+        if (!is_array($modules)) {\r
+            $modules = array($modules);\r
+        }\r
+        if (!is_array($tidy_modules)) {\r
+            $tidy_modules = array($tidy_modules);\r
+        }\r
+        if (!is_array($aliases)) {\r
+            $aliases = array($aliases);\r
+        }\r
+        if (!is_object($doctype)) {\r
+            $doctype = new HTMLPurifier_Doctype(\r
+                $doctype,\r
+                $xml,\r
+                $modules,\r
+                $tidy_modules,\r
+                $aliases,\r
+                $dtd_public,\r
+                $dtd_system\r
+            );\r
+        }\r
+        $this->doctypes[$doctype->name] = $doctype;\r
+        $name = $doctype->name;\r
+        // hookup aliases\r
+        foreach ($doctype->aliases as $alias) {\r
+            if (isset($this->doctypes[$alias])) {\r
+                continue;\r
+            }\r
+            $this->aliases[$alias] = $name;\r
+        }\r
+        // remove old aliases\r
+        if (isset($this->aliases[$name])) {\r
+            unset($this->aliases[$name]);\r
+        }\r
+        return $doctype;\r
+    }\r
+\r
+    /**\r
+     * Retrieves reference to a doctype of a certain name\r
+     * @note This function resolves aliases\r
+     * @note When possible, use the more fully-featured make()\r
+     * @param string $doctype Name of doctype\r
+     * @return HTMLPurifier_Doctype Editable doctype object\r
+     */\r
+    public function get($doctype)\r
+    {\r
+        if (isset($this->aliases[$doctype])) {\r
+            $doctype = $this->aliases[$doctype];\r
+        }\r
+        if (!isset($this->doctypes[$doctype])) {\r
+            trigger_error('Doctype ' . htmlspecialchars($doctype) . ' does not exist', E_USER_ERROR);\r
+            $anon = new HTMLPurifier_Doctype($doctype);\r
+            return $anon;\r
+        }\r
+        return $this->doctypes[$doctype];\r
+    }\r
+\r
+    /**\r
+     * Creates a doctype based on a configuration object,\r
+     * will perform initialization on the doctype\r
+     * @note Use this function to get a copy of doctype that config\r
+     *       can hold on to (this is necessary in order to tell\r
+     *       Generator whether or not the current document is XML\r
+     *       based or not).\r
+     * @param HTMLPurifier_Config $config\r
+     * @return HTMLPurifier_Doctype\r
+     */\r
+    public function make($config)\r
+    {\r
+        return clone $this->get($this->getDoctypeFromConfig($config));\r
+    }\r
+\r
+    /**\r
+     * Retrieves the doctype from the configuration object\r
+     * @param HTMLPurifier_Config $config\r
+     * @return string\r
+     */\r
+    public function getDoctypeFromConfig($config)\r
+    {\r
+        // recommended test\r
+        $doctype = $config->get('HTML.Doctype');\r
+        if (!empty($doctype)) {\r
+            return $doctype;\r
+        }\r
+        $doctype = $config->get('HTML.CustomDoctype');\r
+        if (!empty($doctype)) {\r
+            return $doctype;\r
+        }\r
+        // backwards-compatibility\r
+        if ($config->get('HTML.XHTML')) {\r
+            $doctype = 'XHTML 1.0';\r
+        } else {\r
+            $doctype = 'HTML 4.01';\r
+        }\r
+        if ($config->get('HTML.Strict')) {\r
+            $doctype .= ' Strict';\r
+        } else {\r
+            $doctype .= ' Transitional';\r
+        }\r
+        return $doctype;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Structure that stores an HTML element definition. Used by\r
+ * HTMLPurifier_HTMLDefinition and HTMLPurifier_HTMLModule.\r
+ * @note This class is inspected by HTMLPurifier_Printer_HTMLDefinition.\r
+ *       Please update that class too.\r
+ * @warning If you add new properties to this class, you MUST update\r
+ *          the mergeIn() method.\r
+ */\r
+class HTMLPurifier_ElementDef\r
+{\r
+    /**\r
+     * Does the definition work by itself, or is it created solely\r
+     * for the purpose of merging into another definition?\r
+     * @type bool\r
+     */\r
+    public $standalone = true;\r
+\r
+    /**\r
+     * Associative array of attribute name to HTMLPurifier_AttrDef.\r
+     * @type array\r
+     * @note Before being processed by HTMLPurifier_AttrCollections\r
+     *       when modules are finalized during\r
+     *       HTMLPurifier_HTMLDefinition->setup(), this array may also\r
+     *       contain an array at index 0 that indicates which attribute\r
+     *       collections to load into the full array. It may also\r
+     *       contain string indentifiers in lieu of HTMLPurifier_AttrDef,\r
+     *       see HTMLPurifier_AttrTypes on how they are expanded during\r
+     *       HTMLPurifier_HTMLDefinition->setup() processing.\r
+     */\r
+    public $attr = array();\r
+\r
+    // XXX: Design note: currently, it's not possible to override\r
+    // previously defined AttrTransforms without messing around with\r
+    // the final generated config. This is by design; a previous version\r
+    // used an associated list of attr_transform, but it was extremely\r
+    // easy to accidentally override other attribute transforms by\r
+    // forgetting to specify an index (and just using 0.)  While we\r
+    // could check this by checking the index number and complaining,\r
+    // there is a second problem which is that it is not at all easy to\r
+    // tell when something is getting overridden. Combine this with a\r
+    // codebase where this isn't really being used, and it's perfect for\r
+    // nuking.\r
+\r
+    /**\r
+     * List of tags HTMLPurifier_AttrTransform to be done before validation.\r
+     * @type array\r
+     */\r
+    public $attr_transform_pre = array();\r
+\r
+    /**\r
+     * List of tags HTMLPurifier_AttrTransform to be done after validation.\r
+     * @type array\r
+     */\r
+    public $attr_transform_post = array();\r
+\r
+    /**\r
+     * HTMLPurifier_ChildDef of this tag.\r
+     * @type HTMLPurifier_ChildDef\r
+     */\r
+    public $child;\r
+\r
+    /**\r
+     * Abstract string representation of internal ChildDef rules.\r
+     * @see HTMLPurifier_ContentSets for how this is parsed and then transformed\r
+     * into an HTMLPurifier_ChildDef.\r
+     * @warning This is a temporary variable that is not available after\r
+     *      being processed by HTMLDefinition\r
+     * @type string\r
+     */\r
+    public $content_model;\r
+\r
+    /**\r
+     * Value of $child->type, used to determine which ChildDef to use,\r
+     * used in combination with $content_model.\r
+     * @warning This must be lowercase\r
+     * @warning This is a temporary variable that is not available after\r
+     *      being processed by HTMLDefinition\r
+     * @type string\r
+     */\r
+    public $content_model_type;\r
+\r
+    /**\r
+     * Does the element have a content model (#PCDATA | Inline)*? This\r
+     * is important for chameleon ins and del processing in\r
+     * HTMLPurifier_ChildDef_Chameleon. Dynamically set: modules don't\r
+     * have to worry about this one.\r
+     * @type bool\r
+     */\r
+    public $descendants_are_inline = false;\r
+\r
+    /**\r
+     * List of the names of required attributes this element has.\r
+     * Dynamically populated by HTMLPurifier_HTMLDefinition::getElement()\r
+     * @type array\r
+     */\r
+    public $required_attr = array();\r
+\r
+    /**\r
+     * Lookup table of tags excluded from all descendants of this tag.\r
+     * @type array\r
+     * @note SGML permits exclusions for all descendants, but this is\r
+     *       not possible with DTDs or XML Schemas. W3C has elected to\r
+     *       use complicated compositions of content_models to simulate\r
+     *       exclusion for children, but we go the simpler, SGML-style\r
+     *       route of flat-out exclusions, which correctly apply to\r
+     *       all descendants and not just children. Note that the XHTML\r
+     *       Modularization Abstract Modules are blithely unaware of such\r
+     *       distinctions.\r
+     */\r
+    public $excludes = array();\r
+\r
+    /**\r
+     * This tag is explicitly auto-closed by the following tags.\r
+     * @type array\r
+     */\r
+    public $autoclose = array();\r
+\r
+    /**\r
+     * If a foreign element is found in this element, test if it is\r
+     * allowed by this sub-element; if it is, instead of closing the\r
+     * current element, place it inside this element.\r
+     * @type string\r
+     */\r
+    public $wrap;\r
+\r
+    /**\r
+     * Whether or not this is a formatting element affected by the\r
+     * "Active Formatting Elements" algorithm.\r
+     * @type bool\r
+     */\r
+    public $formatting;\r
+\r
+    /**\r
+     * Low-level factory constructor for creating new standalone element defs\r
+     */\r
+    public static function create($content_model, $content_model_type, $attr)\r
+    {\r
+        $def = new HTMLPurifier_ElementDef();\r
+        $def->content_model = $content_model;\r
+        $def->content_model_type = $content_model_type;\r
+        $def->attr = $attr;\r
+        return $def;\r
+    }\r
+\r
+    /**\r
+     * Merges the values of another element definition into this one.\r
+     * Values from the new element def take precedence if a value is\r
+     * not mergeable.\r
+     * @param HTMLPurifier_ElementDef $def\r
+     */\r
+    public function mergeIn($def)\r
+    {\r
+        // later keys takes precedence\r
+        foreach ($def->attr as $k => $v) {\r
+            if ($k === 0) {\r
+                // merge in the includes\r
+                // sorry, no way to override an include\r
+                foreach ($v as $v2) {\r
+                    $this->attr[0][] = $v2;\r
+                }\r
+                continue;\r
+            }\r
+            if ($v === false) {\r
+                if (isset($this->attr[$k])) {\r
+                    unset($this->attr[$k]);\r
+                }\r
+                continue;\r
+            }\r
+            $this->attr[$k] = $v;\r
+        }\r
+        $this->_mergeAssocArray($this->excludes, $def->excludes);\r
+        $this->attr_transform_pre = array_merge($this->attr_transform_pre, $def->attr_transform_pre);\r
+        $this->attr_transform_post = array_merge($this->attr_transform_post, $def->attr_transform_post);\r
+\r
+        if (!empty($def->content_model)) {\r
+            $this->content_model =\r
+                str_replace("#SUPER", $this->content_model, $def->content_model);\r
+            $this->child = false;\r
+        }\r
+        if (!empty($def->content_model_type)) {\r
+            $this->content_model_type = $def->content_model_type;\r
+            $this->child = false;\r
+        }\r
+        if (!is_null($def->child)) {\r
+            $this->child = $def->child;\r
+        }\r
+        if (!is_null($def->formatting)) {\r
+            $this->formatting = $def->formatting;\r
+        }\r
+        if ($def->descendants_are_inline) {\r
+            $this->descendants_are_inline = $def->descendants_are_inline;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Merges one array into another, removes values which equal false\r
+     * @param $a1 Array by reference that is merged into\r
+     * @param $a2 Array that merges into $a1\r
+     */\r
+    private function _mergeAssocArray(&$a1, $a2)\r
+    {\r
+        foreach ($a2 as $k => $v) {\r
+            if ($v === false) {\r
+                if (isset($a1[$k])) {\r
+                    unset($a1[$k]);\r
+                }\r
+                continue;\r
+            }\r
+            $a1[$k] = $v;\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * A UTF-8 specific character encoder that handles cleaning and transforming.\r
+ * @note All functions in this class should be static.\r
+ */\r
+class HTMLPurifier_Encoder\r
+{\r
+\r
+    /**\r
+     * Constructor throws fatal error if you attempt to instantiate class\r
+     */\r
+    private function __construct()\r
+    {\r
+        trigger_error('Cannot instantiate encoder, call methods statically', E_USER_ERROR);\r
+    }\r
+\r
+    /**\r
+     * Error-handler that mutes errors, alternative to shut-up operator.\r
+     */\r
+    public static function muteErrorHandler()\r
+    {\r
+    }\r
+\r
+    /**\r
+     * iconv wrapper which mutes errors, but doesn't work around bugs.\r
+     * @param string $in Input encoding\r
+     * @param string $out Output encoding\r
+     * @param string $text The text to convert\r
+     * @return string\r
+     */\r
+    public static function unsafeIconv($in, $out, $text)\r
+    {\r
+        set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));\r
+        $r = iconv($in, $out, $text);\r
+        restore_error_handler();\r
+        return $r;\r
+    }\r
+\r
+    /**\r
+     * iconv wrapper which mutes errors and works around bugs.\r
+     * @param string $in Input encoding\r
+     * @param string $out Output encoding\r
+     * @param string $text The text to convert\r
+     * @param int $max_chunk_size\r
+     * @return string\r
+     */\r
+    public static function iconv($in, $out, $text, $max_chunk_size = 8000)\r
+    {\r
+        $code = self::testIconvTruncateBug();\r
+        if ($code == self::ICONV_OK) {\r
+            return self::unsafeIconv($in, $out, $text);\r
+        } elseif ($code == self::ICONV_TRUNCATES) {\r
+            // we can only work around this if the input character set\r
+            // is utf-8\r
+            if ($in == 'utf-8') {\r
+                if ($max_chunk_size < 4) {\r
+                    trigger_error('max_chunk_size is too small', E_USER_WARNING);\r
+                    return false;\r
+                }\r
+                // split into 8000 byte chunks, but be careful to handle\r
+                // multibyte boundaries properly\r
+                if (($c = strlen($text)) <= $max_chunk_size) {\r
+                    return self::unsafeIconv($in, $out, $text);\r
+                }\r
+                $r = '';\r
+                $i = 0;\r
+                while (true) {\r
+                    if ($i + $max_chunk_size >= $c) {\r
+                        $r .= self::unsafeIconv($in, $out, substr($text, $i));\r
+                        break;\r
+                    }\r
+                    // wibble the boundary\r
+                    if (0x80 != (0xC0 & ord($text[$i + $max_chunk_size]))) {\r
+                        $chunk_size = $max_chunk_size;\r
+                    } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 1]))) {\r
+                        $chunk_size = $max_chunk_size - 1;\r
+                    } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 2]))) {\r
+                        $chunk_size = $max_chunk_size - 2;\r
+                    } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 3]))) {\r
+                        $chunk_size = $max_chunk_size - 3;\r
+                    } else {\r
+                        return false; // rather confusing UTF-8...\r
+                    }\r
+                    $chunk = substr($text, $i, $chunk_size); // substr doesn't mind overlong lengths\r
+                    $r .= self::unsafeIconv($in, $out, $chunk);\r
+                    $i += $chunk_size;\r
+                }\r
+                return $r;\r
+            } else {\r
+                return false;\r
+            }\r
+        } else {\r
+            return false;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Cleans a UTF-8 string for well-formedness and SGML validity\r
+     *\r
+     * It will parse according to UTF-8 and return a valid UTF8 string, with\r
+     * non-SGML codepoints excluded.\r
+     *\r
+     * Specifically, it will permit:\r
+     * \x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}\r
+     * Source: https://www.w3.org/TR/REC-xml/#NT-Char\r
+     * Arguably this function should be modernized to the HTML5 set\r
+     * of allowed characters:\r
+     * https://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream\r
+     * which simultaneously expand and restrict the set of allowed characters.\r
+     *\r
+     * @param string $str The string to clean\r
+     * @param bool $force_php\r
+     * @return string\r
+     *\r
+     * @note Just for reference, the non-SGML code points are 0 to 31 and\r
+     *       127 to 159, inclusive.  However, we allow code points 9, 10\r
+     *       and 13, which are the tab, line feed and carriage return\r
+     *       respectively. 128 and above the code points map to multibyte\r
+     *       UTF-8 representations.\r
+     *\r
+     * @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and\r
+     *       hsivonen@iki.fi at <http://iki.fi/hsivonen/php-utf8/> under the\r
+     *       LGPL license.  Notes on what changed are inside, but in general,\r
+     *       the original code transformed UTF-8 text into an array of integer\r
+     *       Unicode codepoints. Understandably, transforming that back to\r
+     *       a string would be somewhat expensive, so the function was modded to\r
+     *       directly operate on the string.  However, this discourages code\r
+     *       reuse, and the logic enumerated here would be useful for any\r
+     *       function that needs to be able to understand UTF-8 characters.\r
+     *       As of right now, only smart lossless character encoding converters\r
+     *       would need that, and I'm probably not going to implement them.\r
+     */\r
+    public static function cleanUTF8($str, $force_php = false)\r
+    {\r
+        // UTF-8 validity is checked since PHP 4.3.5\r
+        // This is an optimization: if the string is already valid UTF-8, no\r
+        // need to do PHP stuff. 99% of the time, this will be the case.\r
+        if (preg_match(\r
+            '/^[\x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]*$/Du',\r
+            $str\r
+        )) {\r
+            return $str;\r
+        }\r
+\r
+        $mState = 0; // cached expected number of octets after the current octet\r
+                     // until the beginning of the next UTF8 character sequence\r
+        $mUcs4  = 0; // cached Unicode character\r
+        $mBytes = 1; // cached expected number of octets in the current sequence\r
+\r
+        // original code involved an $out that was an array of Unicode\r
+        // codepoints.  Instead of having to convert back into UTF-8, we've\r
+        // decided to directly append valid UTF-8 characters onto a string\r
+        // $out once they're done.  $char accumulates raw bytes, while $mUcs4\r
+        // turns into the Unicode code point, so there's some redundancy.\r
+\r
+        $out = '';\r
+        $char = '';\r
+\r
+        $len = strlen($str);\r
+        for ($i = 0; $i < $len; $i++) {\r
+            $in = ord($str{$i});\r
+            $char .= $str[$i]; // append byte to char\r
+            if (0 == $mState) {\r
+                // When mState is zero we expect either a US-ASCII character\r
+                // or a multi-octet sequence.\r
+                if (0 == (0x80 & ($in))) {\r
+                    // US-ASCII, pass straight through.\r
+                    if (($in <= 31 || $in == 127) &&\r
+                        !($in == 9 || $in == 13 || $in == 10) // save \r\t\n\r
+                    ) {\r
+                        // control characters, remove\r
+                    } else {\r
+                        $out .= $char;\r
+                    }\r
+                    // reset\r
+                    $char = '';\r
+                    $mBytes = 1;\r
+                } elseif (0xC0 == (0xE0 & ($in))) {\r
+                    // First octet of 2 octet sequence\r
+                    $mUcs4 = ($in);\r
+                    $mUcs4 = ($mUcs4 & 0x1F) << 6;\r
+                    $mState = 1;\r
+                    $mBytes = 2;\r
+                } elseif (0xE0 == (0xF0 & ($in))) {\r
+                    // First octet of 3 octet sequence\r
+                    $mUcs4 = ($in);\r
+                    $mUcs4 = ($mUcs4 & 0x0F) << 12;\r
+                    $mState = 2;\r
+                    $mBytes = 3;\r
+                } elseif (0xF0 == (0xF8 & ($in))) {\r
+                    // First octet of 4 octet sequence\r
+                    $mUcs4 = ($in);\r
+                    $mUcs4 = ($mUcs4 & 0x07) << 18;\r
+                    $mState = 3;\r
+                    $mBytes = 4;\r
+                } elseif (0xF8 == (0xFC & ($in))) {\r
+                    // First octet of 5 octet sequence.\r
+                    //\r
+                    // This is illegal because the encoded codepoint must be\r
+                    // either:\r
+                    // (a) not the shortest form or\r
+                    // (b) outside the Unicode range of 0-0x10FFFF.\r
+                    // Rather than trying to resynchronize, we will carry on\r
+                    // until the end of the sequence and let the later error\r
+                    // handling code catch it.\r
+                    $mUcs4 = ($in);\r
+                    $mUcs4 = ($mUcs4 & 0x03) << 24;\r
+                    $mState = 4;\r
+                    $mBytes = 5;\r
+                } elseif (0xFC == (0xFE & ($in))) {\r
+                    // First octet of 6 octet sequence, see comments for 5\r
+                    // octet sequence.\r
+                    $mUcs4 = ($in);\r
+                    $mUcs4 = ($mUcs4 & 1) << 30;\r
+                    $mState = 5;\r
+                    $mBytes = 6;\r
+                } else {\r
+                    // Current octet is neither in the US-ASCII range nor a\r
+                    // legal first octet of a multi-octet sequence.\r
+                    $mState = 0;\r
+                    $mUcs4  = 0;\r
+                    $mBytes = 1;\r
+                    $char = '';\r
+                }\r
+            } else {\r
+                // When mState is non-zero, we expect a continuation of the\r
+                // multi-octet sequence\r
+                if (0x80 == (0xC0 & ($in))) {\r
+                    // Legal continuation.\r
+                    $shift = ($mState - 1) * 6;\r
+                    $tmp = $in;\r
+                    $tmp = ($tmp & 0x0000003F) << $shift;\r
+                    $mUcs4 |= $tmp;\r
+\r
+                    if (0 == --$mState) {\r
+                        // End of the multi-octet sequence. mUcs4 now contains\r
+                        // the final Unicode codepoint to be output\r
+\r
+                        // Check for illegal sequences and codepoints.\r
+\r
+                        // From Unicode 3.1, non-shortest form is illegal\r
+                        if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||\r
+                            ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||\r
+                            ((4 == $mBytes) && ($mUcs4 < 0x10000)) ||\r
+                            (4 < $mBytes) ||\r
+                            // From Unicode 3.2, surrogate characters = illegal\r
+                            (($mUcs4 & 0xFFFFF800) == 0xD800) ||\r
+                            // Codepoints outside the Unicode range are illegal\r
+                            ($mUcs4 > 0x10FFFF)\r
+                        ) {\r
+\r
+                        } elseif (0xFEFF != $mUcs4 && // omit BOM\r
+                            // check for valid Char unicode codepoints\r
+                            (\r
+                                0x9 == $mUcs4 ||\r
+                                0xA == $mUcs4 ||\r
+                                0xD == $mUcs4 ||\r
+                                (0x20 <= $mUcs4 && 0x7E >= $mUcs4) ||\r
+                                // 7F-9F is not strictly prohibited by XML,\r
+                                // but it is non-SGML, and thus we don't allow it\r
+                                (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) ||\r
+                                (0xE000 <= $mUcs4 && 0xFFFD >= $mUcs4) ||\r
+                                (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4)\r
+                            )\r
+                        ) {\r
+                            $out .= $char;\r
+                        }\r
+                        // initialize UTF8 cache (reset)\r
+                        $mState = 0;\r
+                        $mUcs4  = 0;\r
+                        $mBytes = 1;\r
+                        $char = '';\r
+                    }\r
+                } else {\r
+                    // ((0xC0 & (*in) != 0x80) && (mState != 0))\r
+                    // Incomplete multi-octet sequence.\r
+                    // used to result in complete fail, but we'll reset\r
+                    $mState = 0;\r
+                    $mUcs4  = 0;\r
+                    $mBytes = 1;\r
+                    $char ='';\r
+                }\r
+            }\r
+        }\r
+        return $out;\r
+    }\r
+\r
+    /**\r
+     * Translates a Unicode codepoint into its corresponding UTF-8 character.\r
+     * @note Based on Feyd's function at\r
+     *       <http://forums.devnetwork.net/viewtopic.php?p=191404#191404>,\r
+     *       which is in public domain.\r
+     * @note While we're going to do code point parsing anyway, a good\r
+     *       optimization would be to refuse to translate code points that\r
+     *       are non-SGML characters.  However, this could lead to duplication.\r
+     * @note This is very similar to the unichr function in\r
+     *       maintenance/generate-entity-file.php (although this is superior,\r
+     *       due to its sanity checks).\r
+     */\r
+\r
+    // +----------+----------+----------+----------+\r
+    // | 33222222 | 22221111 | 111111   |          |\r
+    // | 10987654 | 32109876 | 54321098 | 76543210 | bit\r
+    // +----------+----------+----------+----------+\r
+    // |          |          |          | 0xxxxxxx | 1 byte 0x00000000..0x0000007F\r
+    // |          |          | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF\r
+    // |          | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF\r
+    // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF\r
+    // +----------+----------+----------+----------+\r
+    // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF)\r
+    // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes\r
+    // +----------+----------+----------+----------+\r
+\r
+    public static function unichr($code)\r
+    {\r
+        if ($code > 1114111 or $code < 0 or\r
+          ($code >= 55296 and $code <= 57343) ) {\r
+            // bits are set outside the "valid" range as defined\r
+            // by UNICODE 4.1.0\r
+            return '';\r
+        }\r
+\r
+        $x = $y = $z = $w = 0;\r
+        if ($code < 128) {\r
+            // regular ASCII character\r
+            $x = $code;\r
+        } else {\r
+            // set up bits for UTF-8\r
+            $x = ($code & 63) | 128;\r
+            if ($code < 2048) {\r
+                $y = (($code & 2047) >> 6) | 192;\r
+            } else {\r
+                $y = (($code & 4032) >> 6) | 128;\r
+                if ($code < 65536) {\r
+                    $z = (($code >> 12) & 15) | 224;\r
+                } else {\r
+                    $z = (($code >> 12) & 63) | 128;\r
+                    $w = (($code >> 18) & 7)  | 240;\r
+                }\r
+            }\r
+        }\r
+        // set up the actual character\r
+        $ret = '';\r
+        if ($w) {\r
+            $ret .= chr($w);\r
+        }\r
+        if ($z) {\r
+            $ret .= chr($z);\r
+        }\r
+        if ($y) {\r
+            $ret .= chr($y);\r
+        }\r
+        $ret .= chr($x);\r
+\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * @return bool\r
+     */\r
+    public static function iconvAvailable()\r
+    {\r
+        static $iconv = null;\r
+        if ($iconv === null) {\r
+            $iconv = function_exists('iconv') && self::testIconvTruncateBug() != self::ICONV_UNUSABLE;\r
+        }\r
+        return $iconv;\r
+    }\r
+\r
+    /**\r
+     * Convert a string to UTF-8 based on configuration.\r
+     * @param string $str The string to convert\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     */\r
+    public static function convertToUTF8($str, $config, $context)\r
+    {\r
+        $encoding = $config->get('Core.Encoding');\r
+        if ($encoding === 'utf-8') {\r
+            return $str;\r
+        }\r
+        static $iconv = null;\r
+        if ($iconv === null) {\r
+            $iconv = self::iconvAvailable();\r
+        }\r
+        if ($iconv && !$config->get('Test.ForceNoIconv')) {\r
+            // unaffected by bugs, since UTF-8 support all characters\r
+            $str = self::unsafeIconv($encoding, 'utf-8//IGNORE', $str);\r
+            if ($str === false) {\r
+                // $encoding is not a valid encoding\r
+                trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR);\r
+                return '';\r
+            }\r
+            // If the string is bjorked by Shift_JIS or a similar encoding\r
+            // that doesn't support all of ASCII, convert the naughty\r
+            // characters to their true byte-wise ASCII/UTF-8 equivalents.\r
+            $str = strtr($str, self::testEncodingSupportsASCII($encoding));\r
+            return $str;\r
+        } elseif ($encoding === 'iso-8859-1') {\r
+            $str = utf8_encode($str);\r
+            return $str;\r
+        }\r
+        $bug = HTMLPurifier_Encoder::testIconvTruncateBug();\r
+        if ($bug == self::ICONV_OK) {\r
+            trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);\r
+        } else {\r
+            trigger_error(\r
+                'You have a buggy version of iconv, see https://bugs.php.net/bug.php?id=48147 ' .\r
+                'and http://sourceware.org/bugzilla/show_bug.cgi?id=13541',\r
+                E_USER_ERROR\r
+            );\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Converts a string from UTF-8 based on configuration.\r
+     * @param string $str The string to convert\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     * @note Currently, this is a lossy conversion, with unexpressable\r
+     *       characters being omitted.\r
+     */\r
+    public static function convertFromUTF8($str, $config, $context)\r
+    {\r
+        $encoding = $config->get('Core.Encoding');\r
+        if ($escape = $config->get('Core.EscapeNonASCIICharacters')) {\r
+            $str = self::convertToASCIIDumbLossless($str);\r
+        }\r
+        if ($encoding === 'utf-8') {\r
+            return $str;\r
+        }\r
+        static $iconv = null;\r
+        if ($iconv === null) {\r
+            $iconv = self::iconvAvailable();\r
+        }\r
+        if ($iconv && !$config->get('Test.ForceNoIconv')) {\r
+            // Undo our previous fix in convertToUTF8, otherwise iconv will barf\r
+            $ascii_fix = self::testEncodingSupportsASCII($encoding);\r
+            if (!$escape && !empty($ascii_fix)) {\r
+                $clear_fix = array();\r
+                foreach ($ascii_fix as $utf8 => $native) {\r
+                    $clear_fix[$utf8] = '';\r
+                }\r
+                $str = strtr($str, $clear_fix);\r
+            }\r
+            $str = strtr($str, array_flip($ascii_fix));\r
+            // Normal stuff\r
+            $str = self::iconv('utf-8', $encoding . '//IGNORE', $str);\r
+            return $str;\r
+        } elseif ($encoding === 'iso-8859-1') {\r
+            $str = utf8_decode($str);\r
+            return $str;\r
+        }\r
+        trigger_error('Encoding not supported', E_USER_ERROR);\r
+        // You might be tempted to assume that the ASCII representation\r
+        // might be OK, however, this is *not* universally true over all\r
+        // encodings.  So we take the conservative route here, rather\r
+        // than forcibly turn on %Core.EscapeNonASCIICharacters\r
+    }\r
+\r
+    /**\r
+     * Lossless (character-wise) conversion of HTML to ASCII\r
+     * @param string $str UTF-8 string to be converted to ASCII\r
+     * @return string ASCII encoded string with non-ASCII character entity-ized\r
+     * @warning Adapted from MediaWiki, claiming fair use: this is a common\r
+     *       algorithm. If you disagree with this license fudgery,\r
+     *       implement it yourself.\r
+     * @note Uses decimal numeric entities since they are best supported.\r
+     * @note This is a DUMB function: it has no concept of keeping\r
+     *       character entities that the projected character encoding\r
+     *       can allow. We could possibly implement a smart version\r
+     *       but that would require it to also know which Unicode\r
+     *       codepoints the charset supported (not an easy task).\r
+     * @note Sort of with cleanUTF8() but it assumes that $str is\r
+     *       well-formed UTF-8\r
+     */\r
+    public static function convertToASCIIDumbLossless($str)\r
+    {\r
+        $bytesleft = 0;\r
+        $result = '';\r
+        $working = 0;\r
+        $len = strlen($str);\r
+        for ($i = 0; $i < $len; $i++) {\r
+            $bytevalue = ord($str[$i]);\r
+            if ($bytevalue <= 0x7F) { //0xxx xxxx\r
+                $result .= chr($bytevalue);\r
+                $bytesleft = 0;\r
+            } elseif ($bytevalue <= 0xBF) { //10xx xxxx\r
+                $working = $working << 6;\r
+                $working += ($bytevalue & 0x3F);\r
+                $bytesleft--;\r
+                if ($bytesleft <= 0) {\r
+                    $result .= "&#" . $working . ";";\r
+                }\r
+            } elseif ($bytevalue <= 0xDF) { //110x xxxx\r
+                $working = $bytevalue & 0x1F;\r
+                $bytesleft = 1;\r
+            } elseif ($bytevalue <= 0xEF) { //1110 xxxx\r
+                $working = $bytevalue & 0x0F;\r
+                $bytesleft = 2;\r
+            } else { //1111 0xxx\r
+                $working = $bytevalue & 0x07;\r
+                $bytesleft = 3;\r
+            }\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    /** No bugs detected in iconv. */\r
+    const ICONV_OK = 0;\r
+\r
+    /** Iconv truncates output if converting from UTF-8 to another\r
+     *  character set with //IGNORE, and a non-encodable character is found */\r
+    const ICONV_TRUNCATES = 1;\r
+\r
+    /** Iconv does not support //IGNORE, making it unusable for\r
+     *  transcoding purposes */\r
+    const ICONV_UNUSABLE = 2;\r
+\r
+    /**\r
+     * glibc iconv has a known bug where it doesn't handle the magic\r
+     * //IGNORE stanza correctly.  In particular, rather than ignore\r
+     * characters, it will return an EILSEQ after consuming some number\r
+     * of characters, and expect you to restart iconv as if it were\r
+     * an E2BIG.  Old versions of PHP did not respect the errno, and\r
+     * returned the fragment, so as a result you would see iconv\r
+     * mysteriously truncating output. We can work around this by\r
+     * manually chopping our input into segments of about 8000\r
+     * characters, as long as PHP ignores the error code.  If PHP starts\r
+     * paying attention to the error code, iconv becomes unusable.\r
+     *\r
+     * @return int Error code indicating severity of bug.\r
+     */\r
+    public static function testIconvTruncateBug()\r
+    {\r
+        static $code = null;\r
+        if ($code === null) {\r
+            // better not use iconv, otherwise infinite loop!\r
+            $r = self::unsafeIconv('utf-8', 'ascii//IGNORE', "\xCE\xB1" . str_repeat('a', 9000));\r
+            if ($r === false) {\r
+                $code = self::ICONV_UNUSABLE;\r
+            } elseif (($c = strlen($r)) < 9000) {\r
+                $code = self::ICONV_TRUNCATES;\r
+            } elseif ($c > 9000) {\r
+                trigger_error(\r
+                    'Your copy of iconv is extremely buggy. Please notify HTML Purifier maintainers: ' .\r
+                    'include your iconv version as per phpversion()',\r
+                    E_USER_ERROR\r
+                );\r
+            } else {\r
+                $code = self::ICONV_OK;\r
+            }\r
+        }\r
+        return $code;\r
+    }\r
+\r
+    /**\r
+     * This expensive function tests whether or not a given character\r
+     * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will\r
+     * fail this test, and require special processing. Variable width\r
+     * encodings shouldn't ever fail.\r
+     *\r
+     * @param string $encoding Encoding name to test, as per iconv format\r
+     * @param bool $bypass Whether or not to bypass the precompiled arrays.\r
+     * @return Array of UTF-8 characters to their corresponding ASCII,\r
+     *      which can be used to "undo" any overzealous iconv action.\r
+     */\r
+    public static function testEncodingSupportsASCII($encoding, $bypass = false)\r
+    {\r
+        // All calls to iconv here are unsafe, proof by case analysis:\r
+        // If ICONV_OK, no difference.\r
+        // If ICONV_TRUNCATE, all calls involve one character inputs,\r
+        // so bug is not triggered.\r
+        // If ICONV_UNUSABLE, this call is irrelevant\r
+        static $encodings = array();\r
+        if (!$bypass) {\r
+            if (isset($encodings[$encoding])) {\r
+                return $encodings[$encoding];\r
+            }\r
+            $lenc = strtolower($encoding);\r
+            switch ($lenc) {\r
+                case 'shift_jis':\r
+                    return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~');\r
+                case 'johab':\r
+                    return array("\xE2\x82\xA9" => '\\');\r
+            }\r
+            if (strpos($lenc, 'iso-8859-') === 0) {\r
+                return array();\r
+            }\r
+        }\r
+        $ret = array();\r
+        if (self::unsafeIconv('UTF-8', $encoding, 'a') === false) {\r
+            return false;\r
+        }\r
+        for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars\r
+            $c = chr($i); // UTF-8 char\r
+            $r = self::unsafeIconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion\r
+            if ($r === '' ||\r
+                // This line is needed for iconv implementations that do not\r
+                // omit characters that do not exist in the target character set\r
+                ($r === $c && self::unsafeIconv($encoding, 'UTF-8//IGNORE', $r) !== $c)\r
+            ) {\r
+                // Reverse engineer: what's the UTF-8 equiv of this byte\r
+                // sequence? This assumes that there's no variable width\r
+                // encoding that doesn't support ASCII.\r
+                $ret[self::unsafeIconv($encoding, 'UTF-8//IGNORE', $c)] = $c;\r
+            }\r
+        }\r
+        $encodings[$encoding] = $ret;\r
+        return $ret;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Object that provides entity lookup table from entity name to character\r
+ */\r
+class HTMLPurifier_EntityLookup\r
+{\r
+    /**\r
+     * Assoc array of entity name to character represented.\r
+     * @type array\r
+     */\r
+    public $table;\r
+\r
+    /**\r
+     * Sets up the entity lookup table from the serialized file contents.\r
+     * @param bool $file\r
+     * @note The serialized contents are versioned, but were generated\r
+     *       using the maintenance script generate_entity_file.php\r
+     * @warning This is not in constructor to help enforce the Singleton\r
+     */\r
+    public function setup($file = false)\r
+    {\r
+        if (!$file) {\r
+            $file = HTMLPURIFIER_PREFIX . '/HTMLPurifier/EntityLookup/entities.ser';\r
+        }\r
+        $this->table = unserialize(file_get_contents($file));\r
+    }\r
+\r
+    /**\r
+     * Retrieves sole instance of the object.\r
+     * @param bool|HTMLPurifier_EntityLookup $prototype Optional prototype of custom lookup table to overload with.\r
+     * @return HTMLPurifier_EntityLookup\r
+     */\r
+    public static function instance($prototype = false)\r
+    {\r
+        // no references, since PHP doesn't copy unless modified\r
+        static $instance = null;\r
+        if ($prototype) {\r
+            $instance = $prototype;\r
+        } elseif (!$instance) {\r
+            $instance = new HTMLPurifier_EntityLookup();\r
+            $instance->setup();\r
+        }\r
+        return $instance;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+// if want to implement error collecting here, we'll need to use some sort\r
+// of global data (probably trigger_error) because it's impossible to pass\r
+// $config or $context to the callback functions.\r
+\r
+/**\r
+ * Handles referencing and derefencing character entities\r
+ */\r
+class HTMLPurifier_EntityParser\r
+{\r
+\r
+    /**\r
+     * Reference to entity lookup table.\r
+     * @type HTMLPurifier_EntityLookup\r
+     */\r
+    protected $_entity_lookup;\r
+\r
+    /**\r
+     * Callback regex string for entities in text.\r
+     * @type string\r
+     */\r
+    protected $_textEntitiesRegex;\r
+\r
+    /**\r
+     * Callback regex string for entities in attributes.\r
+     * @type string\r
+     */\r
+    protected $_attrEntitiesRegex;\r
+\r
+    /**\r
+     * Tests if the beginning of a string is a semi-optional regex\r
+     */\r
+    protected $_semiOptionalPrefixRegex;\r
+\r
+    public function __construct() {\r
+        // From\r
+        // http://stackoverflow.com/questions/15532252/why-is-reg-being-rendered-as-without-the-bounding-semicolon\r
+        $semi_optional = "quot|QUOT|lt|LT|gt|GT|amp|AMP|AElig|Aacute|Acirc|Agrave|Aring|Atilde|Auml|COPY|Ccedil|ETH|Eacute|Ecirc|Egrave|Euml|Iacute|Icirc|Igrave|Iuml|Ntilde|Oacute|Ocirc|Ograve|Oslash|Otilde|Ouml|REG|THORN|Uacute|Ucirc|Ugrave|Uuml|Yacute|aacute|acirc|acute|aelig|agrave|aring|atilde|auml|brvbar|ccedil|cedil|cent|copy|curren|deg|divide|eacute|ecirc|egrave|eth|euml|frac12|frac14|frac34|iacute|icirc|iexcl|igrave|iquest|iuml|laquo|macr|micro|middot|nbsp|not|ntilde|oacute|ocirc|ograve|ordf|ordm|oslash|otilde|ouml|para|plusmn|pound|raquo|reg|sect|shy|sup1|sup2|sup3|szlig|thorn|times|uacute|ucirc|ugrave|uml|uuml|yacute|yen|yuml";\r
+\r
+        // NB: three empty captures to put the fourth match in the right\r
+        // place\r
+        $this->_semiOptionalPrefixRegex = "/&()()()($semi_optional)/";\r
+\r
+        $this->_textEntitiesRegex =\r
+            '/&(?:'.\r
+            // hex\r
+            '[#]x([a-fA-F0-9]+);?|'.\r
+            // dec\r
+            '[#]0*(\d+);?|'.\r
+            // string (mandatory semicolon)\r
+            // NB: order matters: match semicolon preferentially\r
+            '([A-Za-z_:][A-Za-z0-9.\-_:]*);|'.\r
+            // string (optional semicolon)\r
+            "($semi_optional)".\r
+            ')/';\r
+\r
+        $this->_attrEntitiesRegex =\r
+            '/&(?:'.\r
+            // hex\r
+            '[#]x([a-fA-F0-9]+);?|'.\r
+            // dec\r
+            '[#]0*(\d+);?|'.\r
+            // string (mandatory semicolon)\r
+            // NB: order matters: match semicolon preferentially\r
+            '([A-Za-z_:][A-Za-z0-9.\-_:]*);|'.\r
+            // string (optional semicolon)\r
+            // don't match if trailing is equals or alphanumeric (URL\r
+            // like)\r
+            "($semi_optional)(?![=;A-Za-z0-9])".\r
+            ')/';\r
+\r
+    }\r
+\r
+    /**\r
+     * Substitute entities with the parsed equivalents.  Use this on\r
+     * textual data in an HTML document (as opposed to attributes.)\r
+     *\r
+     * @param string $string String to have entities parsed.\r
+     * @return string Parsed string.\r
+     */\r
+    public function substituteTextEntities($string)\r
+    {\r
+        return preg_replace_callback(\r
+            $this->_textEntitiesRegex,\r
+            array($this, 'entityCallback'),\r
+            $string\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Substitute entities with the parsed equivalents.  Use this on\r
+     * attribute contents in documents.\r
+     *\r
+     * @param string $string String to have entities parsed.\r
+     * @return string Parsed string.\r
+     */\r
+    public function substituteAttrEntities($string)\r
+    {\r
+        return preg_replace_callback(\r
+            $this->_attrEntitiesRegex,\r
+            array($this, 'entityCallback'),\r
+            $string\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Callback function for substituteNonSpecialEntities() that does the work.\r
+     *\r
+     * @param array $matches  PCRE matches array, with 0 the entire match, and\r
+     *                  either index 1, 2 or 3 set with a hex value, dec value,\r
+     *                  or string (respectively).\r
+     * @return string Replacement string.\r
+     */\r
+\r
+    protected function entityCallback($matches)\r
+    {\r
+        $entity = $matches[0];\r
+        $hex_part = @$matches[1];\r
+        $dec_part = @$matches[2];\r
+        $named_part = empty($matches[3]) ? (empty($matches[4]) ? "" : $matches[4]) : $matches[3];\r
+        if ($hex_part !== NULL && $hex_part !== "") {\r
+            return HTMLPurifier_Encoder::unichr(hexdec($hex_part));\r
+        } elseif ($dec_part !== NULL && $dec_part !== "") {\r
+            return HTMLPurifier_Encoder::unichr((int) $dec_part);\r
+        } else {\r
+            if (!$this->_entity_lookup) {\r
+                $this->_entity_lookup = HTMLPurifier_EntityLookup::instance();\r
+            }\r
+            if (isset($this->_entity_lookup->table[$named_part])) {\r
+                return $this->_entity_lookup->table[$named_part];\r
+            } else {\r
+                // exact match didn't match anything, so test if\r
+                // any of the semicolon optional match the prefix.\r
+                // Test that this is an EXACT match is important to\r
+                // prevent infinite loop\r
+                if (!empty($matches[3])) {\r
+                    return preg_replace_callback(\r
+                        $this->_semiOptionalPrefixRegex,\r
+                        array($this, 'entityCallback'),\r
+                        $entity\r
+                    );\r
+                }\r
+                return $entity;\r
+            }\r
+        }\r
+    }\r
+\r
+    // LEGACY CODE BELOW\r
+\r
+    /**\r
+     * Callback regex string for parsing entities.\r
+     * @type string\r
+     */\r
+    protected $_substituteEntitiesRegex =\r
+        '/&(?:[#]x([a-fA-F0-9]+)|[#]0*(\d+)|([A-Za-z_:][A-Za-z0-9.\-_:]*));?/';\r
+        //     1. hex             2. dec      3. string (XML style)\r
+\r
+    /**\r
+     * Decimal to parsed string conversion table for special entities.\r
+     * @type array\r
+     */\r
+    protected $_special_dec2str =\r
+            array(\r
+                    34 => '"',\r
+                    38 => '&',\r
+                    39 => "'",\r
+                    60 => '<',\r
+                    62 => '>'\r
+            );\r
+\r
+    /**\r
+     * Stripped entity names to decimal conversion table for special entities.\r
+     * @type array\r
+     */\r
+    protected $_special_ent2dec =\r
+            array(\r
+                    'quot' => 34,\r
+                    'amp'  => 38,\r
+                    'lt'   => 60,\r
+                    'gt'   => 62\r
+            );\r
+\r
+    /**\r
+     * Substitutes non-special entities with their parsed equivalents. Since\r
+     * running this whenever you have parsed character is t3h 5uck, we run\r
+     * it before everything else.\r
+     *\r
+     * @param string $string String to have non-special entities parsed.\r
+     * @return string Parsed string.\r
+     */\r
+    public function substituteNonSpecialEntities($string)\r
+    {\r
+        // it will try to detect missing semicolons, but don't rely on it\r
+        return preg_replace_callback(\r
+            $this->_substituteEntitiesRegex,\r
+            array($this, 'nonSpecialEntityCallback'),\r
+            $string\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Callback function for substituteNonSpecialEntities() that does the work.\r
+     *\r
+     * @param array $matches  PCRE matches array, with 0 the entire match, and\r
+     *                  either index 1, 2 or 3 set with a hex value, dec value,\r
+     *                  or string (respectively).\r
+     * @return string Replacement string.\r
+     */\r
+\r
+    protected function nonSpecialEntityCallback($matches)\r
+    {\r
+        // replaces all but big five\r
+        $entity = $matches[0];\r
+        $is_num = (@$matches[0][1] === '#');\r
+        if ($is_num) {\r
+            $is_hex = (@$entity[2] === 'x');\r
+            $code = $is_hex ? hexdec($matches[1]) : (int) $matches[2];\r
+            // abort for special characters\r
+            if (isset($this->_special_dec2str[$code])) {\r
+                return $entity;\r
+            }\r
+            return HTMLPurifier_Encoder::unichr($code);\r
+        } else {\r
+            if (isset($this->_special_ent2dec[$matches[3]])) {\r
+                return $entity;\r
+            }\r
+            if (!$this->_entity_lookup) {\r
+                $this->_entity_lookup = HTMLPurifier_EntityLookup::instance();\r
+            }\r
+            if (isset($this->_entity_lookup->table[$matches[3]])) {\r
+                return $this->_entity_lookup->table[$matches[3]];\r
+            } else {\r
+                return $entity;\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Substitutes only special entities with their parsed equivalents.\r
+     *\r
+     * @notice We try to avoid calling this function because otherwise, it\r
+     * would have to be called a lot (for every parsed section).\r
+     *\r
+     * @param string $string String to have non-special entities parsed.\r
+     * @return string Parsed string.\r
+     */\r
+    public function substituteSpecialEntities($string)\r
+    {\r
+        return preg_replace_callback(\r
+            $this->_substituteEntitiesRegex,\r
+            array($this, 'specialEntityCallback'),\r
+            $string\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Callback function for substituteSpecialEntities() that does the work.\r
+     *\r
+     * This callback has same syntax as nonSpecialEntityCallback().\r
+     *\r
+     * @param array $matches  PCRE-style matches array, with 0 the entire match, and\r
+     *                  either index 1, 2 or 3 set with a hex value, dec value,\r
+     *                  or string (respectively).\r
+     * @return string Replacement string.\r
+     */\r
+    protected function specialEntityCallback($matches)\r
+    {\r
+        $entity = $matches[0];\r
+        $is_num = (@$matches[0][1] === '#');\r
+        if ($is_num) {\r
+            $is_hex = (@$entity[2] === 'x');\r
+            $int = $is_hex ? hexdec($matches[1]) : (int) $matches[2];\r
+            return isset($this->_special_dec2str[$int]) ?\r
+                $this->_special_dec2str[$int] :\r
+                $entity;\r
+        } else {\r
+            return isset($this->_special_ent2dec[$matches[3]]) ?\r
+                $this->_special_dec2str[$this->_special_ent2dec[$matches[3]]] :\r
+                $entity;\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Error collection class that enables HTML Purifier to report HTML\r
+ * problems back to the user\r
+ */\r
+class HTMLPurifier_ErrorCollector\r
+{\r
+\r
+    /**\r
+     * Identifiers for the returned error array. These are purposely numeric\r
+     * so list() can be used.\r
+     */\r
+    const LINENO   = 0;\r
+    const SEVERITY = 1;\r
+    const MESSAGE  = 2;\r
+    const CHILDREN = 3;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $errors;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $_current;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $_stacks = array(array());\r
+\r
+    /**\r
+     * @type HTMLPurifier_Language\r
+     */\r
+    protected $locale;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Generator\r
+     */\r
+    protected $generator;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Context\r
+     */\r
+    protected $context;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $lines = array();\r
+\r
+    /**\r
+     * @param HTMLPurifier_Context $context\r
+     */\r
+    public function __construct($context)\r
+    {\r
+        $this->locale    =& $context->get('Locale');\r
+        $this->context   = $context;\r
+        $this->_current  =& $this->_stacks[0];\r
+        $this->errors    =& $this->_stacks[0];\r
+    }\r
+\r
+    /**\r
+     * Sends an error message to the collector for later use\r
+     * @param int $severity Error severity, PHP error style (don't use E_USER_)\r
+     * @param string $msg Error message text\r
+     */\r
+    public function send($severity, $msg)\r
+    {\r
+        $args = array();\r
+        if (func_num_args() > 2) {\r
+            $args = func_get_args();\r
+            array_shift($args);\r
+            unset($args[0]);\r
+        }\r
+\r
+        $token = $this->context->get('CurrentToken', true);\r
+        $line  = $token ? $token->line : $this->context->get('CurrentLine', true);\r
+        $col   = $token ? $token->col  : $this->context->get('CurrentCol', true);\r
+        $attr  = $this->context->get('CurrentAttr', true);\r
+\r
+        // perform special substitutions, also add custom parameters\r
+        $subst = array();\r
+        if (!is_null($token)) {\r
+            $args['CurrentToken'] = $token;\r
+        }\r
+        if (!is_null($attr)) {\r
+            $subst['$CurrentAttr.Name'] = $attr;\r
+            if (isset($token->attr[$attr])) {\r
+                $subst['$CurrentAttr.Value'] = $token->attr[$attr];\r
+            }\r
+        }\r
+\r
+        if (empty($args)) {\r
+            $msg = $this->locale->getMessage($msg);\r
+        } else {\r
+            $msg = $this->locale->formatMessage($msg, $args);\r
+        }\r
+\r
+        if (!empty($subst)) {\r
+            $msg = strtr($msg, $subst);\r
+        }\r
+\r
+        // (numerically indexed)\r
+        $error = array(\r
+            self::LINENO   => $line,\r
+            self::SEVERITY => $severity,\r
+            self::MESSAGE  => $msg,\r
+            self::CHILDREN => array()\r
+        );\r
+        $this->_current[] = $error;\r
+\r
+        // NEW CODE BELOW ...\r
+        // Top-level errors are either:\r
+        //  TOKEN type, if $value is set appropriately, or\r
+        //  "syntax" type, if $value is null\r
+        $new_struct = new HTMLPurifier_ErrorStruct();\r
+        $new_struct->type = HTMLPurifier_ErrorStruct::TOKEN;\r
+        if ($token) {\r
+            $new_struct->value = clone $token;\r
+        }\r
+        if (is_int($line) && is_int($col)) {\r
+            if (isset($this->lines[$line][$col])) {\r
+                $struct = $this->lines[$line][$col];\r
+            } else {\r
+                $struct = $this->lines[$line][$col] = $new_struct;\r
+            }\r
+            // These ksorts may present a performance problem\r
+            ksort($this->lines[$line], SORT_NUMERIC);\r
+        } else {\r
+            if (isset($this->lines[-1])) {\r
+                $struct = $this->lines[-1];\r
+            } else {\r
+                $struct = $this->lines[-1] = $new_struct;\r
+            }\r
+        }\r
+        ksort($this->lines, SORT_NUMERIC);\r
+\r
+        // Now, check if we need to operate on a lower structure\r
+        if (!empty($attr)) {\r
+            $struct = $struct->getChild(HTMLPurifier_ErrorStruct::ATTR, $attr);\r
+            if (!$struct->value) {\r
+                $struct->value = array($attr, 'PUT VALUE HERE');\r
+            }\r
+        }\r
+        if (!empty($cssprop)) {\r
+            $struct = $struct->getChild(HTMLPurifier_ErrorStruct::CSSPROP, $cssprop);\r
+            if (!$struct->value) {\r
+                // if we tokenize CSS this might be a little more difficult to do\r
+                $struct->value = array($cssprop, 'PUT VALUE HERE');\r
+            }\r
+        }\r
+\r
+        // Ok, structs are all setup, now time to register the error\r
+        $struct->addError($severity, $msg);\r
+    }\r
+\r
+    /**\r
+     * Retrieves raw error data for custom formatter to use\r
+     */\r
+    public function getRaw()\r
+    {\r
+        return $this->errors;\r
+    }\r
+\r
+    /**\r
+     * Default HTML formatting implementation for error messages\r
+     * @param HTMLPurifier_Config $config Configuration, vital for HTML output nature\r
+     * @param array $errors Errors array to display; used for recursion.\r
+     * @return string\r
+     */\r
+    public function getHTMLFormatted($config, $errors = null)\r
+    {\r
+        $ret = array();\r
+\r
+        $this->generator = new HTMLPurifier_Generator($config, $this->context);\r
+        if ($errors === null) {\r
+            $errors = $this->errors;\r
+        }\r
+\r
+        // 'At line' message needs to be removed\r
+\r
+        // generation code for new structure goes here. It needs to be recursive.\r
+        foreach ($this->lines as $line => $col_array) {\r
+            if ($line == -1) {\r
+                continue;\r
+            }\r
+            foreach ($col_array as $col => $struct) {\r
+                $this->_renderStruct($ret, $struct, $line, $col);\r
+            }\r
+        }\r
+        if (isset($this->lines[-1])) {\r
+            $this->_renderStruct($ret, $this->lines[-1]);\r
+        }\r
+\r
+        if (empty($errors)) {\r
+            return '<p>' . $this->locale->getMessage('ErrorCollector: No errors') . '</p>';\r
+        } else {\r
+            return '<ul><li>' . implode('</li><li>', $ret) . '</li></ul>';\r
+        }\r
+\r
+    }\r
+\r
+    private function _renderStruct(&$ret, $struct, $line = null, $col = null)\r
+    {\r
+        $stack = array($struct);\r
+        $context_stack = array(array());\r
+        while ($current = array_pop($stack)) {\r
+            $context = array_pop($context_stack);\r
+            foreach ($current->errors as $error) {\r
+                list($severity, $msg) = $error;\r
+                $string = '';\r
+                $string .= '<div>';\r
+                // W3C uses an icon to indicate the severity of the error.\r
+                $error = $this->locale->getErrorName($severity);\r
+                $string .= "<span class=\"error e$severity\"><strong>$error</strong></span> ";\r
+                if (!is_null($line) && !is_null($col)) {\r
+                    $string .= "<em class=\"location\">Line $line, Column $col: </em> ";\r
+                } else {\r
+                    $string .= '<em class="location">End of Document: </em> ';\r
+                }\r
+                $string .= '<strong class="description">' . $this->generator->escape($msg) . '</strong> ';\r
+                $string .= '</div>';\r
+                // Here, have a marker for the character on the column appropriate.\r
+                // Be sure to clip extremely long lines.\r
+                //$string .= '<pre>';\r
+                //$string .= '';\r
+                //$string .= '</pre>';\r
+                $ret[] = $string;\r
+            }\r
+            foreach ($current->children as $array) {\r
+                $context[] = $current;\r
+                $stack = array_merge($stack, array_reverse($array, true));\r
+                for ($i = count($array); $i > 0; $i--) {\r
+                    $context_stack[] = $context;\r
+                }\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Records errors for particular segments of an HTML document such as tokens,\r
+ * attributes or CSS properties. They can contain error structs (which apply\r
+ * to components of what they represent), but their main purpose is to hold\r
+ * errors applying to whatever struct is being used.\r
+ */\r
+class HTMLPurifier_ErrorStruct\r
+{\r
+\r
+    /**\r
+     * Possible values for $children first-key. Note that top-level structures\r
+     * are automatically token-level.\r
+     */\r
+    const TOKEN     = 0;\r
+    const ATTR      = 1;\r
+    const CSSPROP   = 2;\r
+\r
+    /**\r
+     * Type of this struct.\r
+     * @type string\r
+     */\r
+    public $type;\r
+\r
+    /**\r
+     * Value of the struct we are recording errors for. There are various\r
+     * values for this:\r
+     *  - TOKEN: Instance of HTMLPurifier_Token\r
+     *  - ATTR: array('attr-name', 'value')\r
+     *  - CSSPROP: array('prop-name', 'value')\r
+     * @type mixed\r
+     */\r
+    public $value;\r
+\r
+    /**\r
+     * Errors registered for this structure.\r
+     * @type array\r
+     */\r
+    public $errors = array();\r
+\r
+    /**\r
+     * Child ErrorStructs that are from this structure. For example, a TOKEN\r
+     * ErrorStruct would contain ATTR ErrorStructs. This is a multi-dimensional\r
+     * array in structure: [TYPE]['identifier']\r
+     * @type array\r
+     */\r
+    public $children = array();\r
+\r
+    /**\r
+     * @param string $type\r
+     * @param string $id\r
+     * @return mixed\r
+     */\r
+    public function getChild($type, $id)\r
+    {\r
+        if (!isset($this->children[$type][$id])) {\r
+            $this->children[$type][$id] = new HTMLPurifier_ErrorStruct();\r
+            $this->children[$type][$id]->type = $type;\r
+        }\r
+        return $this->children[$type][$id];\r
+    }\r
+\r
+    /**\r
+     * @param int $severity\r
+     * @param string $message\r
+     */\r
+    public function addError($severity, $message)\r
+    {\r
+        $this->errors[] = array($severity, $message);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Global exception class for HTML Purifier; any exceptions we throw\r
+ * are from here.\r
+ */\r
+class HTMLPurifier_Exception extends Exception\r
+{\r
+\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Represents a pre or post processing filter on HTML Purifier's output\r
+ *\r
+ * Sometimes, a little ad-hoc fixing of HTML has to be done before\r
+ * it gets sent through HTML Purifier: you can use filters to acheive\r
+ * this effect. For instance, YouTube videos can be preserved using\r
+ * this manner. You could have used a decorator for this task, but\r
+ * PHP's support for them is not terribly robust, so we're going\r
+ * to just loop through the filters.\r
+ *\r
+ * Filters should be exited first in, last out. If there are three filters,\r
+ * named 1, 2 and 3, the order of execution should go 1->preFilter,\r
+ * 2->preFilter, 3->preFilter, purify, 3->postFilter, 2->postFilter,\r
+ * 1->postFilter.\r
+ *\r
+ * @note Methods are not declared abstract as it is perfectly legitimate\r
+ *       for an implementation not to want anything to happen on a step\r
+ */\r
+\r
+class HTMLPurifier_Filter\r
+{\r
+\r
+    /**\r
+     * Name of the filter for identification purposes.\r
+     * @type string\r
+     */\r
+    public $name;\r
+\r
+    /**\r
+     * Pre-processor function, handles HTML before HTML Purifier\r
+     * @param string $html\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     */\r
+    public function preFilter($html, $config, $context)\r
+    {\r
+        return $html;\r
+    }\r
+\r
+    /**\r
+     * Post-processor function, handles HTML after HTML Purifier\r
+     * @param string $html\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     */\r
+    public function postFilter($html, $config, $context)\r
+    {\r
+        return $html;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Generates HTML from tokens.\r
+ * @todo Refactor interface so that configuration/context is determined\r
+ *       upon instantiation, no need for messy generateFromTokens() calls\r
+ * @todo Make some of the more internal functions protected, and have\r
+ *       unit tests work around that\r
+ */\r
+class HTMLPurifier_Generator\r
+{\r
+\r
+    /**\r
+     * Whether or not generator should produce XML output.\r
+     * @type bool\r
+     */\r
+    private $_xhtml = true;\r
+\r
+    /**\r
+     * :HACK: Whether or not generator should comment the insides of <script> tags.\r
+     * @type bool\r
+     */\r
+    private $_scriptFix = false;\r
+\r
+    /**\r
+     * Cache of HTMLDefinition during HTML output to determine whether or\r
+     * not attributes should be minimized.\r
+     * @type HTMLPurifier_HTMLDefinition\r
+     */\r
+    private $_def;\r
+\r
+    /**\r
+     * Cache of %Output.SortAttr.\r
+     * @type bool\r
+     */\r
+    private $_sortAttr;\r
+\r
+    /**\r
+     * Cache of %Output.FlashCompat.\r
+     * @type bool\r
+     */\r
+    private $_flashCompat;\r
+\r
+    /**\r
+     * Cache of %Output.FixInnerHTML.\r
+     * @type bool\r
+     */\r
+    private $_innerHTMLFix;\r
+\r
+    /**\r
+     * Stack for keeping track of object information when outputting IE\r
+     * compatibility code.\r
+     * @type array\r
+     */\r
+    private $_flashStack = array();\r
+\r
+    /**\r
+     * Configuration for the generator\r
+     * @type HTMLPurifier_Config\r
+     */\r
+    protected $config;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     */\r
+    public function __construct($config, $context)\r
+    {\r
+        $this->config = $config;\r
+        $this->_scriptFix = $config->get('Output.CommentScriptContents');\r
+        $this->_innerHTMLFix = $config->get('Output.FixInnerHTML');\r
+        $this->_sortAttr = $config->get('Output.SortAttr');\r
+        $this->_flashCompat = $config->get('Output.FlashCompat');\r
+        $this->_def = $config->getHTMLDefinition();\r
+        $this->_xhtml = $this->_def->doctype->xml;\r
+    }\r
+\r
+    /**\r
+     * Generates HTML from an array of tokens.\r
+     * @param HTMLPurifier_Token[] $tokens Array of HTMLPurifier_Token\r
+     * @return string Generated HTML\r
+     */\r
+    public function generateFromTokens($tokens)\r
+    {\r
+        if (!$tokens) {\r
+            return '';\r
+        }\r
+\r
+        // Basic algorithm\r
+        $html = '';\r
+        for ($i = 0, $size = count($tokens); $i < $size; $i++) {\r
+            if ($this->_scriptFix && $tokens[$i]->name === 'script'\r
+                && $i + 2 < $size && $tokens[$i+2] instanceof HTMLPurifier_Token_End) {\r
+                // script special case\r
+                // the contents of the script block must be ONE token\r
+                // for this to work.\r
+                $html .= $this->generateFromToken($tokens[$i++]);\r
+                $html .= $this->generateScriptFromToken($tokens[$i++]);\r
+            }\r
+            $html .= $this->generateFromToken($tokens[$i]);\r
+        }\r
+\r
+        // Tidy cleanup\r
+        if (extension_loaded('tidy') && $this->config->get('Output.TidyFormat')) {\r
+            $tidy = new Tidy;\r
+            $tidy->parseString(\r
+                $html,\r
+                array(\r
+                   'indent'=> true,\r
+                   'output-xhtml' => $this->_xhtml,\r
+                   'show-body-only' => true,\r
+                   'indent-spaces' => 2,\r
+                   'wrap' => 68,\r
+                ),\r
+                'utf8'\r
+            );\r
+            $tidy->cleanRepair();\r
+            $html = (string) $tidy; // explicit cast necessary\r
+        }\r
+\r
+        // Normalize newlines to system defined value\r
+        if ($this->config->get('Core.NormalizeNewlines')) {\r
+            $nl = $this->config->get('Output.Newline');\r
+            if ($nl === null) {\r
+                $nl = PHP_EOL;\r
+            }\r
+            if ($nl !== "\n") {\r
+                $html = str_replace("\n", $nl, $html);\r
+            }\r
+        }\r
+        return $html;\r
+    }\r
+\r
+    /**\r
+     * Generates HTML from a single token.\r
+     * @param HTMLPurifier_Token $token HTMLPurifier_Token object.\r
+     * @return string Generated HTML\r
+     */\r
+    public function generateFromToken($token)\r
+    {\r
+        if (!$token instanceof HTMLPurifier_Token) {\r
+            trigger_error('Cannot generate HTML from non-HTMLPurifier_Token object', E_USER_WARNING);\r
+            return '';\r
+\r
+        } elseif ($token instanceof HTMLPurifier_Token_Start) {\r
+            $attr = $this->generateAttributes($token->attr, $token->name);\r
+            if ($this->_flashCompat) {\r
+                if ($token->name == "object") {\r
+                    $flash = new stdClass();\r
+                    $flash->attr = $token->attr;\r
+                    $flash->param = array();\r
+                    $this->_flashStack[] = $flash;\r
+                }\r
+            }\r
+            return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';\r
+\r
+        } elseif ($token instanceof HTMLPurifier_Token_End) {\r
+            $_extra = '';\r
+            if ($this->_flashCompat) {\r
+                if ($token->name == "object" && !empty($this->_flashStack)) {\r
+                    // doesn't do anything for now\r
+                }\r
+            }\r
+            return $_extra . '</' . $token->name . '>';\r
+\r
+        } elseif ($token instanceof HTMLPurifier_Token_Empty) {\r
+            if ($this->_flashCompat && $token->name == "param" && !empty($this->_flashStack)) {\r
+                $this->_flashStack[count($this->_flashStack)-1]->param[$token->attr['name']] = $token->attr['value'];\r
+            }\r
+            $attr = $this->generateAttributes($token->attr, $token->name);\r
+             return '<' . $token->name . ($attr ? ' ' : '') . $attr .\r
+                ( $this->_xhtml ? ' /': '' ) // <br /> v. <br>\r
+                . '>';\r
+\r
+        } elseif ($token instanceof HTMLPurifier_Token_Text) {\r
+            return $this->escape($token->data, ENT_NOQUOTES);\r
+\r
+        } elseif ($token instanceof HTMLPurifier_Token_Comment) {\r
+            return '<!--' . $token->data . '-->';\r
+        } else {\r
+            return '';\r
+\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Special case processor for the contents of script tags\r
+     * @param HTMLPurifier_Token $token HTMLPurifier_Token object.\r
+     * @return string\r
+     * @warning This runs into problems if there's already a literal\r
+     *          --> somewhere inside the script contents.\r
+     */\r
+    public function generateScriptFromToken($token)\r
+    {\r
+        if (!$token instanceof HTMLPurifier_Token_Text) {\r
+            return $this->generateFromToken($token);\r
+        }\r
+        // Thanks <http://lachy.id.au/log/2005/05/script-comments>\r
+        $data = preg_replace('#//\s*$#', '', $token->data);\r
+        return '<!--//--><![CDATA[//><!--' . "\n" . trim($data) . "\n" . '//--><!]]>';\r
+    }\r
+\r
+    /**\r
+     * Generates attribute declarations from attribute array.\r
+     * @note This does not include the leading or trailing space.\r
+     * @param array $assoc_array_of_attributes Attribute array\r
+     * @param string $element Name of element attributes are for, used to check\r
+     *        attribute minimization.\r
+     * @return string Generated HTML fragment for insertion.\r
+     */\r
+    public function generateAttributes($assoc_array_of_attributes, $element = '')\r
+    {\r
+        $html = '';\r
+        if ($this->_sortAttr) {\r
+            ksort($assoc_array_of_attributes);\r
+        }\r
+        foreach ($assoc_array_of_attributes as $key => $value) {\r
+            if (!$this->_xhtml) {\r
+                // Remove namespaced attributes\r
+                if (strpos($key, ':') !== false) {\r
+                    continue;\r
+                }\r
+                // Check if we should minimize the attribute: val="val" -> val\r
+                if ($element && !empty($this->_def->info[$element]->attr[$key]->minimized)) {\r
+                    $html .= $key . ' ';\r
+                    continue;\r
+                }\r
+            }\r
+            // Workaround for Internet Explorer innerHTML bug.\r
+            // Essentially, Internet Explorer, when calculating\r
+            // innerHTML, omits quotes if there are no instances of\r
+            // angled brackets, quotes or spaces.  However, when parsing\r
+            // HTML (for example, when you assign to innerHTML), it\r
+            // treats backticks as quotes.  Thus,\r
+            //      <img alt="``" />\r
+            // becomes\r
+            //      <img alt=`` />\r
+            // becomes\r
+            //      <img alt='' />\r
+            // Fortunately, all we need to do is trigger an appropriate\r
+            // quoting style, which we do by adding an extra space.\r
+            // This also is consistent with the W3C spec, which states\r
+            // that user agents may ignore leading or trailing\r
+            // whitespace (in fact, most don't, at least for attributes\r
+            // like alt, but an extra space at the end is barely\r
+            // noticeable).  Still, we have a configuration knob for\r
+            // this, since this transformation is not necesary if you\r
+            // don't process user input with innerHTML or you don't plan\r
+            // on supporting Internet Explorer.\r
+            if ($this->_innerHTMLFix) {\r
+                if (strpos($value, '`') !== false) {\r
+                    // check if correct quoting style would not already be\r
+                    // triggered\r
+                    if (strcspn($value, '"\' <>') === strlen($value)) {\r
+                        // protect!\r
+                        $value .= ' ';\r
+                    }\r
+                }\r
+            }\r
+            $html .= $key.'="'.$this->escape($value).'" ';\r
+        }\r
+        return rtrim($html);\r
+    }\r
+\r
+    /**\r
+     * Escapes raw text data.\r
+     * @todo This really ought to be protected, but until we have a facility\r
+     *       for properly generating HTML here w/o using tokens, it stays\r
+     *       public.\r
+     * @param string $string String data to escape for HTML.\r
+     * @param int $quote Quoting style, like htmlspecialchars. ENT_NOQUOTES is\r
+     *               permissible for non-attribute output.\r
+     * @return string escaped data.\r
+     */\r
+    public function escape($string, $quote = null)\r
+    {\r
+        // Workaround for APC bug on Mac Leopard reported by sidepodcast\r
+        // http://htmlpurifier.org/phorum/read.php?3,4823,4846\r
+        if ($quote === null) {\r
+            $quote = ENT_COMPAT;\r
+        }\r
+        return htmlspecialchars($string, $quote, 'UTF-8');\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Definition of the purified HTML that describes allowed children,\r
+ * attributes, and many other things.\r
+ *\r
+ * Conventions:\r
+ *\r
+ * All member variables that are prefixed with info\r
+ * (including the main $info array) are used by HTML Purifier internals\r
+ * and should not be directly edited when customizing the HTMLDefinition.\r
+ * They can usually be set via configuration directives or custom\r
+ * modules.\r
+ *\r
+ * On the other hand, member variables without the info prefix are used\r
+ * internally by the HTMLDefinition and MUST NOT be used by other HTML\r
+ * Purifier internals. Many of them, however, are public, and may be\r
+ * edited by userspace code to tweak the behavior of HTMLDefinition.\r
+ *\r
+ * @note This class is inspected by Printer_HTMLDefinition; please\r
+ *       update that class if things here change.\r
+ *\r
+ * @warning Directives that change this object's structure must be in\r
+ *          the HTML or Attr namespace!\r
+ */\r
+class HTMLPurifier_HTMLDefinition extends HTMLPurifier_Definition\r
+{\r
+\r
+    // FULLY-PUBLIC VARIABLES ---------------------------------------------\r
+\r
+    /**\r
+     * Associative array of element names to HTMLPurifier_ElementDef.\r
+     * @type HTMLPurifier_ElementDef[]\r
+     */\r
+    public $info = array();\r
+\r
+    /**\r
+     * Associative array of global attribute name to attribute definition.\r
+     * @type array\r
+     */\r
+    public $info_global_attr = array();\r
+\r
+    /**\r
+     * String name of parent element HTML will be going into.\r
+     * @type string\r
+     */\r
+    public $info_parent = 'div';\r
+\r
+    /**\r
+     * Definition for parent element, allows parent element to be a\r
+     * tag that's not allowed inside the HTML fragment.\r
+     * @type HTMLPurifier_ElementDef\r
+     */\r
+    public $info_parent_def;\r
+\r
+    /**\r
+     * String name of element used to wrap inline elements in block context.\r
+     * @type string\r
+     * @note This is rarely used except for BLOCKQUOTEs in strict mode\r
+     */\r
+    public $info_block_wrapper = 'p';\r
+\r
+    /**\r
+     * Associative array of deprecated tag name to HTMLPurifier_TagTransform.\r
+     * @type array\r
+     */\r
+    public $info_tag_transform = array();\r
+\r
+    /**\r
+     * Indexed list of HTMLPurifier_AttrTransform to be performed before validation.\r
+     * @type HTMLPurifier_AttrTransform[]\r
+     */\r
+    public $info_attr_transform_pre = array();\r
+\r
+    /**\r
+     * Indexed list of HTMLPurifier_AttrTransform to be performed after validation.\r
+     * @type HTMLPurifier_AttrTransform[]\r
+     */\r
+    public $info_attr_transform_post = array();\r
+\r
+    /**\r
+     * Nested lookup array of content set name (Block, Inline) to\r
+     * element name to whether or not it belongs in that content set.\r
+     * @type array\r
+     */\r
+    public $info_content_sets = array();\r
+\r
+    /**\r
+     * Indexed list of HTMLPurifier_Injector to be used.\r
+     * @type HTMLPurifier_Injector[]\r
+     */\r
+    public $info_injector = array();\r
+\r
+    /**\r
+     * Doctype object\r
+     * @type HTMLPurifier_Doctype\r
+     */\r
+    public $doctype;\r
+\r
+\r
+\r
+    // RAW CUSTOMIZATION STUFF --------------------------------------------\r
+\r
+    /**\r
+     * Adds a custom attribute to a pre-existing element\r
+     * @note This is strictly convenience, and does not have a corresponding\r
+     *       method in HTMLPurifier_HTMLModule\r
+     * @param string $element_name Element name to add attribute to\r
+     * @param string $attr_name Name of attribute\r
+     * @param mixed $def Attribute definition, can be string or object, see\r
+     *             HTMLPurifier_AttrTypes for details\r
+     */\r
+    public function addAttribute($element_name, $attr_name, $def)\r
+    {\r
+        $module = $this->getAnonymousModule();\r
+        if (!isset($module->info[$element_name])) {\r
+            $element = $module->addBlankElement($element_name);\r
+        } else {\r
+            $element = $module->info[$element_name];\r
+        }\r
+        $element->attr[$attr_name] = $def;\r
+    }\r
+\r
+    /**\r
+     * Adds a custom element to your HTML definition\r
+     * @see HTMLPurifier_HTMLModule::addElement() for detailed\r
+     *       parameter and return value descriptions.\r
+     */\r
+    public function addElement($element_name, $type, $contents, $attr_collections, $attributes = array())\r
+    {\r
+        $module = $this->getAnonymousModule();\r
+        // assume that if the user is calling this, the element\r
+        // is safe. This may not be a good idea\r
+        $element = $module->addElement($element_name, $type, $contents, $attr_collections, $attributes);\r
+        return $element;\r
+    }\r
+\r
+    /**\r
+     * Adds a blank element to your HTML definition, for overriding\r
+     * existing behavior\r
+     * @param string $element_name\r
+     * @return HTMLPurifier_ElementDef\r
+     * @see HTMLPurifier_HTMLModule::addBlankElement() for detailed\r
+     *       parameter and return value descriptions.\r
+     */\r
+    public function addBlankElement($element_name)\r
+    {\r
+        $module  = $this->getAnonymousModule();\r
+        $element = $module->addBlankElement($element_name);\r
+        return $element;\r
+    }\r
+\r
+    /**\r
+     * Retrieves a reference to the anonymous module, so you can\r
+     * bust out advanced features without having to make your own\r
+     * module.\r
+     * @return HTMLPurifier_HTMLModule\r
+     */\r
+    public function getAnonymousModule()\r
+    {\r
+        if (!$this->_anonModule) {\r
+            $this->_anonModule = new HTMLPurifier_HTMLModule();\r
+            $this->_anonModule->name = 'Anonymous';\r
+        }\r
+        return $this->_anonModule;\r
+    }\r
+\r
+    private $_anonModule = null;\r
+\r
+    // PUBLIC BUT INTERNAL VARIABLES --------------------------------------\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $type = 'HTML';\r
+\r
+    /**\r
+     * @type HTMLPurifier_HTMLModuleManager\r
+     */\r
+    public $manager;\r
+\r
+    /**\r
+     * Performs low-cost, preliminary initialization.\r
+     */\r
+    public function __construct()\r
+    {\r
+        $this->manager = new HTMLPurifier_HTMLModuleManager();\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    protected function doSetup($config)\r
+    {\r
+        $this->processModules($config);\r
+        $this->setupConfigStuff($config);\r
+        unset($this->manager);\r
+\r
+        // cleanup some of the element definitions\r
+        foreach ($this->info as $k => $v) {\r
+            unset($this->info[$k]->content_model);\r
+            unset($this->info[$k]->content_model_type);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Extract out the information from the manager\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    protected function processModules($config)\r
+    {\r
+        if ($this->_anonModule) {\r
+            // for user specific changes\r
+            // this is late-loaded so we don't have to deal with PHP4\r
+            // reference wonky-ness\r
+            $this->manager->addModule($this->_anonModule);\r
+            unset($this->_anonModule);\r
+        }\r
+\r
+        $this->manager->setup($config);\r
+        $this->doctype = $this->manager->doctype;\r
+\r
+        foreach ($this->manager->modules as $module) {\r
+            foreach ($module->info_tag_transform as $k => $v) {\r
+                if ($v === false) {\r
+                    unset($this->info_tag_transform[$k]);\r
+                } else {\r
+                    $this->info_tag_transform[$k] = $v;\r
+                }\r
+            }\r
+            foreach ($module->info_attr_transform_pre as $k => $v) {\r
+                if ($v === false) {\r
+                    unset($this->info_attr_transform_pre[$k]);\r
+                } else {\r
+                    $this->info_attr_transform_pre[$k] = $v;\r
+                }\r
+            }\r
+            foreach ($module->info_attr_transform_post as $k => $v) {\r
+                if ($v === false) {\r
+                    unset($this->info_attr_transform_post[$k]);\r
+                } else {\r
+                    $this->info_attr_transform_post[$k] = $v;\r
+                }\r
+            }\r
+            foreach ($module->info_injector as $k => $v) {\r
+                if ($v === false) {\r
+                    unset($this->info_injector[$k]);\r
+                } else {\r
+                    $this->info_injector[$k] = $v;\r
+                }\r
+            }\r
+        }\r
+        $this->info = $this->manager->getElements();\r
+        $this->info_content_sets = $this->manager->contentSets->lookup;\r
+    }\r
+\r
+    /**\r
+     * Sets up stuff based on config. We need a better way of doing this.\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    protected function setupConfigStuff($config)\r
+    {\r
+        $block_wrapper = $config->get('HTML.BlockWrapper');\r
+        if (isset($this->info_content_sets['Block'][$block_wrapper])) {\r
+            $this->info_block_wrapper = $block_wrapper;\r
+        } else {\r
+            trigger_error(\r
+                'Cannot use non-block element as block wrapper',\r
+                E_USER_ERROR\r
+            );\r
+        }\r
+\r
+        $parent = $config->get('HTML.Parent');\r
+        $def = $this->manager->getElement($parent, true);\r
+        if ($def) {\r
+            $this->info_parent = $parent;\r
+            $this->info_parent_def = $def;\r
+        } else {\r
+            trigger_error(\r
+                'Cannot use unrecognized element as parent',\r
+                E_USER_ERROR\r
+            );\r
+            $this->info_parent_def = $this->manager->getElement($this->info_parent, true);\r
+        }\r
+\r
+        // support template text\r
+        $support = "(for information on implementing this, see the support forums) ";\r
+\r
+        // setup allowed elements -----------------------------------------\r
+\r
+        $allowed_elements = $config->get('HTML.AllowedElements');\r
+        $allowed_attributes = $config->get('HTML.AllowedAttributes'); // retrieve early\r
+\r
+        if (!is_array($allowed_elements) && !is_array($allowed_attributes)) {\r
+            $allowed = $config->get('HTML.Allowed');\r
+            if (is_string($allowed)) {\r
+                list($allowed_elements, $allowed_attributes) = $this->parseTinyMCEAllowedList($allowed);\r
+            }\r
+        }\r
+\r
+        if (is_array($allowed_elements)) {\r
+            foreach ($this->info as $name => $d) {\r
+                if (!isset($allowed_elements[$name])) {\r
+                    unset($this->info[$name]);\r
+                }\r
+                unset($allowed_elements[$name]);\r
+            }\r
+            // emit errors\r
+            foreach ($allowed_elements as $element => $d) {\r
+                $element = htmlspecialchars($element); // PHP doesn't escape errors, be careful!\r
+                trigger_error("Element '$element' is not supported $support", E_USER_WARNING);\r
+            }\r
+        }\r
+\r
+        // setup allowed attributes ---------------------------------------\r
+\r
+        $allowed_attributes_mutable = $allowed_attributes; // by copy!\r
+        if (is_array($allowed_attributes)) {\r
+            // This actually doesn't do anything, since we went away from\r
+            // global attributes. It's possible that userland code uses\r
+            // it, but HTMLModuleManager doesn't!\r
+            foreach ($this->info_global_attr as $attr => $x) {\r
+                $keys = array($attr, "*@$attr", "*.$attr");\r
+                $delete = true;\r
+                foreach ($keys as $key) {\r
+                    if ($delete && isset($allowed_attributes[$key])) {\r
+                        $delete = false;\r
+                    }\r
+                    if (isset($allowed_attributes_mutable[$key])) {\r
+                        unset($allowed_attributes_mutable[$key]);\r
+                    }\r
+                }\r
+                if ($delete) {\r
+                    unset($this->info_global_attr[$attr]);\r
+                }\r
+            }\r
+\r
+            foreach ($this->info as $tag => $info) {\r
+                foreach ($info->attr as $attr => $x) {\r
+                    $keys = array("$tag@$attr", $attr, "*@$attr", "$tag.$attr", "*.$attr");\r
+                    $delete = true;\r
+                    foreach ($keys as $key) {\r
+                        if ($delete && isset($allowed_attributes[$key])) {\r
+                            $delete = false;\r
+                        }\r
+                        if (isset($allowed_attributes_mutable[$key])) {\r
+                            unset($allowed_attributes_mutable[$key]);\r
+                        }\r
+                    }\r
+                    if ($delete) {\r
+                        if ($this->info[$tag]->attr[$attr]->required) {\r
+                            trigger_error(\r
+                                "Required attribute '$attr' in element '$tag' " .\r
+                                "was not allowed, which means '$tag' will not be allowed either",\r
+                                E_USER_WARNING\r
+                            );\r
+                        }\r
+                        unset($this->info[$tag]->attr[$attr]);\r
+                    }\r
+                }\r
+            }\r
+            // emit errors\r
+            foreach ($allowed_attributes_mutable as $elattr => $d) {\r
+                $bits = preg_split('/[.@]/', $elattr, 2);\r
+                $c = count($bits);\r
+                switch ($c) {\r
+                    case 2:\r
+                        if ($bits[0] !== '*') {\r
+                            $element = htmlspecialchars($bits[0]);\r
+                            $attribute = htmlspecialchars($bits[1]);\r
+                            if (!isset($this->info[$element])) {\r
+                                trigger_error(\r
+                                    "Cannot allow attribute '$attribute' if element " .\r
+                                    "'$element' is not allowed/supported $support"\r
+                                );\r
+                            } else {\r
+                                trigger_error(\r
+                                    "Attribute '$attribute' in element '$element' not supported $support",\r
+                                    E_USER_WARNING\r
+                                );\r
+                            }\r
+                            break;\r
+                        }\r
+                        // otherwise fall through\r
+                    case 1:\r
+                        $attribute = htmlspecialchars($bits[0]);\r
+                        trigger_error(\r
+                            "Global attribute '$attribute' is not ".\r
+                            "supported in any elements $support",\r
+                            E_USER_WARNING\r
+                        );\r
+                        break;\r
+                }\r
+            }\r
+        }\r
+\r
+        // setup forbidden elements ---------------------------------------\r
+\r
+        $forbidden_elements   = $config->get('HTML.ForbiddenElements');\r
+        $forbidden_attributes = $config->get('HTML.ForbiddenAttributes');\r
+\r
+        foreach ($this->info as $tag => $info) {\r
+            if (isset($forbidden_elements[$tag])) {\r
+                unset($this->info[$tag]);\r
+                continue;\r
+            }\r
+            foreach ($info->attr as $attr => $x) {\r
+                if (isset($forbidden_attributes["$tag@$attr"]) ||\r
+                    isset($forbidden_attributes["*@$attr"]) ||\r
+                    isset($forbidden_attributes[$attr])\r
+                ) {\r
+                    unset($this->info[$tag]->attr[$attr]);\r
+                    continue;\r
+                } elseif (isset($forbidden_attributes["$tag.$attr"])) { // this segment might get removed eventually\r
+                    // $tag.$attr are not user supplied, so no worries!\r
+                    trigger_error(\r
+                        "Error with $tag.$attr: tag.attr syntax not supported for " .\r
+                        "HTML.ForbiddenAttributes; use tag@attr instead",\r
+                        E_USER_WARNING\r
+                    );\r
+                }\r
+            }\r
+        }\r
+        foreach ($forbidden_attributes as $key => $v) {\r
+            if (strlen($key) < 2) {\r
+                continue;\r
+            }\r
+            if ($key[0] != '*') {\r
+                continue;\r
+            }\r
+            if ($key[1] == '.') {\r
+                trigger_error(\r
+                    "Error with $key: *.attr syntax not supported for HTML.ForbiddenAttributes; use attr instead",\r
+                    E_USER_WARNING\r
+                );\r
+            }\r
+        }\r
+\r
+        // setup injectors -----------------------------------------------------\r
+        foreach ($this->info_injector as $i => $injector) {\r
+            if ($injector->checkNeeded($config) !== false) {\r
+                // remove injector that does not have it's required\r
+                // elements/attributes present, and is thus not needed.\r
+                unset($this->info_injector[$i]);\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Parses a TinyMCE-flavored Allowed Elements and Attributes list into\r
+     * separate lists for processing. Format is element[attr1|attr2],element2...\r
+     * @warning Although it's largely drawn from TinyMCE's implementation,\r
+     *      it is different, and you'll probably have to modify your lists\r
+     * @param array $list String list to parse\r
+     * @return array\r
+     * @todo Give this its own class, probably static interface\r
+     */\r
+    public function parseTinyMCEAllowedList($list)\r
+    {\r
+        $list = str_replace(array(' ', "\t"), '', $list);\r
+\r
+        $elements = array();\r
+        $attributes = array();\r
+\r
+        $chunks = preg_split('/(,|[\n\r]+)/', $list);\r
+        foreach ($chunks as $chunk) {\r
+            if (empty($chunk)) {\r
+                continue;\r
+            }\r
+            // remove TinyMCE element control characters\r
+            if (!strpos($chunk, '[')) {\r
+                $element = $chunk;\r
+                $attr = false;\r
+            } else {\r
+                list($element, $attr) = explode('[', $chunk);\r
+            }\r
+            if ($element !== '*') {\r
+                $elements[$element] = true;\r
+            }\r
+            if (!$attr) {\r
+                continue;\r
+            }\r
+            $attr = substr($attr, 0, strlen($attr) - 1); // remove trailing ]\r
+            $attr = explode('|', $attr);\r
+            foreach ($attr as $key) {\r
+                $attributes["$element.$key"] = true;\r
+            }\r
+        }\r
+        return array($elements, $attributes);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Represents an XHTML 1.1 module, with information on elements, tags\r
+ * and attributes.\r
+ * @note Even though this is technically XHTML 1.1, it is also used for\r
+ *       regular HTML parsing. We are using modulization as a convenient\r
+ *       way to represent the internals of HTMLDefinition, and our\r
+ *       implementation is by no means conforming and does not directly\r
+ *       use the normative DTDs or XML schemas.\r
+ * @note The public variables in a module should almost directly\r
+ *       correspond to the variables in HTMLPurifier_HTMLDefinition.\r
+ *       However, the prefix info carries no special meaning in these\r
+ *       objects (include it anyway if that's the correspondence though).\r
+ * @todo Consider making some member functions protected\r
+ */\r
+\r
+class HTMLPurifier_HTMLModule\r
+{\r
+\r
+    // -- Overloadable ----------------------------------------------------\r
+\r
+    /**\r
+     * Short unique string identifier of the module.\r
+     * @type string\r
+     */\r
+    public $name;\r
+\r
+    /**\r
+     * Informally, a list of elements this module changes.\r
+     * Not used in any significant way.\r
+     * @type array\r
+     */\r
+    public $elements = array();\r
+\r
+    /**\r
+     * Associative array of element names to element definitions.\r
+     * Some definitions may be incomplete, to be merged in later\r
+     * with the full definition.\r
+     * @type array\r
+     */\r
+    public $info = array();\r
+\r
+    /**\r
+     * Associative array of content set names to content set additions.\r
+     * This is commonly used to, say, add an A element to the Inline\r
+     * content set. This corresponds to an internal variable $content_sets\r
+     * and NOT info_content_sets member variable of HTMLDefinition.\r
+     * @type array\r
+     */\r
+    public $content_sets = array();\r
+\r
+    /**\r
+     * Associative array of attribute collection names to attribute\r
+     * collection additions. More rarely used for adding attributes to\r
+     * the global collections. Example is the StyleAttribute module adding\r
+     * the style attribute to the Core. Corresponds to HTMLDefinition's\r
+     * attr_collections->info, since the object's data is only info,\r
+     * with extra behavior associated with it.\r
+     * @type array\r
+     */\r
+    public $attr_collections = array();\r
+\r
+    /**\r
+     * Associative array of deprecated tag name to HTMLPurifier_TagTransform.\r
+     * @type array\r
+     */\r
+    public $info_tag_transform = array();\r
+\r
+    /**\r
+     * List of HTMLPurifier_AttrTransform to be performed before validation.\r
+     * @type array\r
+     */\r
+    public $info_attr_transform_pre = array();\r
+\r
+    /**\r
+     * List of HTMLPurifier_AttrTransform to be performed after validation.\r
+     * @type array\r
+     */\r
+    public $info_attr_transform_post = array();\r
+\r
+    /**\r
+     * List of HTMLPurifier_Injector to be performed during well-formedness fixing.\r
+     * An injector will only be invoked if all of it's pre-requisites are met;\r
+     * if an injector fails setup, there will be no error; it will simply be\r
+     * silently disabled.\r
+     * @type array\r
+     */\r
+    public $info_injector = array();\r
+\r
+    /**\r
+     * Boolean flag that indicates whether or not getChildDef is implemented.\r
+     * For optimization reasons: may save a call to a function. Be sure\r
+     * to set it if you do implement getChildDef(), otherwise it will have\r
+     * no effect!\r
+     * @type bool\r
+     */\r
+    public $defines_child_def = false;\r
+\r
+    /**\r
+     * Boolean flag whether or not this module is safe. If it is not safe, all\r
+     * of its members are unsafe. Modules are safe by default (this might be\r
+     * slightly dangerous, but it doesn't make much sense to force HTML Purifier,\r
+     * which is based off of safe HTML, to explicitly say, "This is safe," even\r
+     * though there are modules which are "unsafe")\r
+     *\r
+     * @type bool\r
+     * @note Previously, safety could be applied at an element level granularity.\r
+     *       We've removed this ability, so in order to add "unsafe" elements\r
+     *       or attributes, a dedicated module with this property set to false\r
+     *       must be used.\r
+     */\r
+    public $safe = true;\r
+\r
+    /**\r
+     * Retrieves a proper HTMLPurifier_ChildDef subclass based on\r
+     * content_model and content_model_type member variables of\r
+     * the HTMLPurifier_ElementDef class. There is a similar function\r
+     * in HTMLPurifier_HTMLDefinition.\r
+     * @param HTMLPurifier_ElementDef $def\r
+     * @return HTMLPurifier_ChildDef subclass\r
+     */\r
+    public function getChildDef($def)\r
+    {\r
+        return false;\r
+    }\r
+\r
+    // -- Convenience -----------------------------------------------------\r
+\r
+    /**\r
+     * Convenience function that sets up a new element\r
+     * @param string $element Name of element to add\r
+     * @param string|bool $type What content set should element be registered to?\r
+     *              Set as false to skip this step.\r
+     * @param string $contents Allowed children in form of:\r
+     *              "$content_model_type: $content_model"\r
+     * @param array $attr_includes What attribute collections to register to\r
+     *              element?\r
+     * @param array $attr What unique attributes does the element define?\r
+     * @see HTMLPurifier_ElementDef:: for in-depth descriptions of these parameters.\r
+     * @return HTMLPurifier_ElementDef Created element definition object, so you\r
+     *         can set advanced parameters\r
+     */\r
+    public function addElement($element, $type, $contents, $attr_includes = array(), $attr = array())\r
+    {\r
+        $this->elements[] = $element;\r
+        // parse content_model\r
+        list($content_model_type, $content_model) = $this->parseContents($contents);\r
+        // merge in attribute inclusions\r
+        $this->mergeInAttrIncludes($attr, $attr_includes);\r
+        // add element to content sets\r
+        if ($type) {\r
+            $this->addElementToContentSet($element, $type);\r
+        }\r
+        // create element\r
+        $this->info[$element] = HTMLPurifier_ElementDef::create(\r
+            $content_model,\r
+            $content_model_type,\r
+            $attr\r
+        );\r
+        // literal object $contents means direct child manipulation\r
+        if (!is_string($contents)) {\r
+            $this->info[$element]->child = $contents;\r
+        }\r
+        return $this->info[$element];\r
+    }\r
+\r
+    /**\r
+     * Convenience function that creates a totally blank, non-standalone\r
+     * element.\r
+     * @param string $element Name of element to create\r
+     * @return HTMLPurifier_ElementDef Created element\r
+     */\r
+    public function addBlankElement($element)\r
+    {\r
+        if (!isset($this->info[$element])) {\r
+            $this->elements[] = $element;\r
+            $this->info[$element] = new HTMLPurifier_ElementDef();\r
+            $this->info[$element]->standalone = false;\r
+        } else {\r
+            trigger_error("Definition for $element already exists in module, cannot redefine");\r
+        }\r
+        return $this->info[$element];\r
+    }\r
+\r
+    /**\r
+     * Convenience function that registers an element to a content set\r
+     * @param string $element Element to register\r
+     * @param string $type Name content set (warning: case sensitive, usually upper-case\r
+     *        first letter)\r
+     */\r
+    public function addElementToContentSet($element, $type)\r
+    {\r
+        if (!isset($this->content_sets[$type])) {\r
+            $this->content_sets[$type] = '';\r
+        } else {\r
+            $this->content_sets[$type] .= ' | ';\r
+        }\r
+        $this->content_sets[$type] .= $element;\r
+    }\r
+\r
+    /**\r
+     * Convenience function that transforms single-string contents\r
+     * into separate content model and content model type\r
+     * @param string $contents Allowed children in form of:\r
+     *                  "$content_model_type: $content_model"\r
+     * @return array\r
+     * @note If contents is an object, an array of two nulls will be\r
+     *       returned, and the callee needs to take the original $contents\r
+     *       and use it directly.\r
+     */\r
+    public function parseContents($contents)\r
+    {\r
+        if (!is_string($contents)) {\r
+            return array(null, null);\r
+        } // defer\r
+        switch ($contents) {\r
+            // check for shorthand content model forms\r
+            case 'Empty':\r
+                return array('empty', '');\r
+            case 'Inline':\r
+                return array('optional', 'Inline | #PCDATA');\r
+            case 'Flow':\r
+                return array('optional', 'Flow | #PCDATA');\r
+        }\r
+        list($content_model_type, $content_model) = explode(':', $contents);\r
+        $content_model_type = strtolower(trim($content_model_type));\r
+        $content_model = trim($content_model);\r
+        return array($content_model_type, $content_model);\r
+    }\r
+\r
+    /**\r
+     * Convenience function that merges a list of attribute includes into\r
+     * an attribute array.\r
+     * @param array $attr Reference to attr array to modify\r
+     * @param array $attr_includes Array of includes / string include to merge in\r
+     */\r
+    public function mergeInAttrIncludes(&$attr, $attr_includes)\r
+    {\r
+        if (!is_array($attr_includes)) {\r
+            if (empty($attr_includes)) {\r
+                $attr_includes = array();\r
+            } else {\r
+                $attr_includes = array($attr_includes);\r
+            }\r
+        }\r
+        $attr[0] = $attr_includes;\r
+    }\r
+\r
+    /**\r
+     * Convenience function that generates a lookup table with boolean\r
+     * true as value.\r
+     * @param string $list List of values to turn into a lookup\r
+     * @note You can also pass an arbitrary number of arguments in\r
+     *       place of the regular argument\r
+     * @return array array equivalent of list\r
+     */\r
+    public function makeLookup($list)\r
+    {\r
+        if (is_string($list)) {\r
+            $list = func_get_args();\r
+        }\r
+        $ret = array();\r
+        foreach ($list as $value) {\r
+            if (is_null($value)) {\r
+                continue;\r
+            }\r
+            $ret[$value] = true;\r
+        }\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Lazy load construction of the module after determining whether\r
+     * or not it's needed, and also when a finalized configuration object\r
+     * is available.\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_HTMLModuleManager\r
+{\r
+\r
+    /**\r
+     * @type HTMLPurifier_DoctypeRegistry\r
+     */\r
+    public $doctypes;\r
+\r
+    /**\r
+     * Instance of current doctype.\r
+     * @type string\r
+     */\r
+    public $doctype;\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrTypes\r
+     */\r
+    public $attrTypes;\r
+\r
+    /**\r
+     * Active instances of modules for the specified doctype are\r
+     * indexed, by name, in this array.\r
+     * @type HTMLPurifier_HTMLModule[]\r
+     */\r
+    public $modules = array();\r
+\r
+    /**\r
+     * Array of recognized HTMLPurifier_HTMLModule instances,\r
+     * indexed by module's class name. This array is usually lazy loaded, but a\r
+     * user can overload a module by pre-emptively registering it.\r
+     * @type HTMLPurifier_HTMLModule[]\r
+     */\r
+    public $registeredModules = array();\r
+\r
+    /**\r
+     * List of extra modules that were added by the user\r
+     * using addModule(). These get unconditionally merged into the current doctype, whatever\r
+     * it may be.\r
+     * @type HTMLPurifier_HTMLModule[]\r
+     */\r
+    public $userModules = array();\r
+\r
+    /**\r
+     * Associative array of element name to list of modules that have\r
+     * definitions for the element; this array is dynamically filled.\r
+     * @type array\r
+     */\r
+    public $elementLookup = array();\r
+\r
+    /**\r
+     * List of prefixes we should use for registering small names.\r
+     * @type array\r
+     */\r
+    public $prefixes = array('HTMLPurifier_HTMLModule_');\r
+\r
+    /**\r
+     * @type HTMLPurifier_ContentSets\r
+     */\r
+    public $contentSets;\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrCollections\r
+     */\r
+    public $attrCollections;\r
+\r
+    /**\r
+     * If set to true, unsafe elements and attributes will be allowed.\r
+     * @type bool\r
+     */\r
+    public $trusted = false;\r
+\r
+    public function __construct()\r
+    {\r
+        // editable internal objects\r
+        $this->attrTypes = new HTMLPurifier_AttrTypes();\r
+        $this->doctypes  = new HTMLPurifier_DoctypeRegistry();\r
+\r
+        // setup basic modules\r
+        $common = array(\r
+            'CommonAttributes', 'Text', 'Hypertext', 'List',\r
+            'Presentation', 'Edit', 'Bdo', 'Tables', 'Image',\r
+            'StyleAttribute',\r
+            // Unsafe:\r
+            'Scripting', 'Object', 'Forms',\r
+            // Sorta legacy, but present in strict:\r
+            'Name',\r
+        );\r
+        $transitional = array('Legacy', 'Target', 'Iframe');\r
+        $xml = array('XMLCommonAttributes');\r
+        $non_xml = array('NonXMLCommonAttributes');\r
+\r
+        // setup basic doctypes\r
+        $this->doctypes->register(\r
+            'HTML 4.01 Transitional',\r
+            false,\r
+            array_merge($common, $transitional, $non_xml),\r
+            array('Tidy_Transitional', 'Tidy_Proprietary'),\r
+            array(),\r
+            '-//W3C//DTD HTML 4.01 Transitional//EN',\r
+            'http://www.w3.org/TR/html4/loose.dtd'\r
+        );\r
+\r
+        $this->doctypes->register(\r
+            'HTML 4.01 Strict',\r
+            false,\r
+            array_merge($common, $non_xml),\r
+            array('Tidy_Strict', 'Tidy_Proprietary', 'Tidy_Name'),\r
+            array(),\r
+            '-//W3C//DTD HTML 4.01//EN',\r
+            'http://www.w3.org/TR/html4/strict.dtd'\r
+        );\r
+\r
+        $this->doctypes->register(\r
+            'XHTML 1.0 Transitional',\r
+            true,\r
+            array_merge($common, $transitional, $xml, $non_xml),\r
+            array('Tidy_Transitional', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Name'),\r
+            array(),\r
+            '-//W3C//DTD XHTML 1.0 Transitional//EN',\r
+            'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'\r
+        );\r
+\r
+        $this->doctypes->register(\r
+            'XHTML 1.0 Strict',\r
+            true,\r
+            array_merge($common, $xml, $non_xml),\r
+            array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Strict', 'Tidy_Proprietary', 'Tidy_Name'),\r
+            array(),\r
+            '-//W3C//DTD XHTML 1.0 Strict//EN',\r
+            'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'\r
+        );\r
+\r
+        $this->doctypes->register(\r
+            'XHTML 1.1',\r
+            true,\r
+            // Iframe is a real XHTML 1.1 module, despite being\r
+            // "transitional"!\r
+            array_merge($common, $xml, array('Ruby', 'Iframe')),\r
+            array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Strict', 'Tidy_Name'), // Tidy_XHTML1_1\r
+            array(),\r
+            '-//W3C//DTD XHTML 1.1//EN',\r
+            'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'\r
+        );\r
+\r
+    }\r
+\r
+    /**\r
+     * Registers a module to the recognized module list, useful for\r
+     * overloading pre-existing modules.\r
+     * @param $module Mixed: string module name, with or without\r
+     *                HTMLPurifier_HTMLModule prefix, or instance of\r
+     *                subclass of HTMLPurifier_HTMLModule.\r
+     * @param $overload Boolean whether or not to overload previous modules.\r
+     *                  If this is not set, and you do overload a module,\r
+     *                  HTML Purifier will complain with a warning.\r
+     * @note This function will not call autoload, you must instantiate\r
+     *       (and thus invoke) autoload outside the method.\r
+     * @note If a string is passed as a module name, different variants\r
+     *       will be tested in this order:\r
+     *          - Check for HTMLPurifier_HTMLModule_$name\r
+     *          - Check all prefixes with $name in order they were added\r
+     *          - Check for literal object name\r
+     *          - Throw fatal error\r
+     *       If your object name collides with an internal class, specify\r
+     *       your module manually. All modules must have been included\r
+     *       externally: registerModule will not perform inclusions for you!\r
+     */\r
+    public function registerModule($module, $overload = false)\r
+    {\r
+        if (is_string($module)) {\r
+            // attempt to load the module\r
+            $original_module = $module;\r
+            $ok = false;\r
+            foreach ($this->prefixes as $prefix) {\r
+                $module = $prefix . $original_module;\r
+                if (class_exists($module)) {\r
+                    $ok = true;\r
+                    break;\r
+                }\r
+            }\r
+            if (!$ok) {\r
+                $module = $original_module;\r
+                if (!class_exists($module)) {\r
+                    trigger_error(\r
+                        $original_module . ' module does not exist',\r
+                        E_USER_ERROR\r
+                    );\r
+                    return;\r
+                }\r
+            }\r
+            $module = new $module();\r
+        }\r
+        if (empty($module->name)) {\r
+            trigger_error('Module instance of ' . get_class($module) . ' must have name');\r
+            return;\r
+        }\r
+        if (!$overload && isset($this->registeredModules[$module->name])) {\r
+            trigger_error('Overloading ' . $module->name . ' without explicit overload parameter', E_USER_WARNING);\r
+        }\r
+        $this->registeredModules[$module->name] = $module;\r
+    }\r
+\r
+    /**\r
+     * Adds a module to the current doctype by first registering it,\r
+     * and then tacking it on to the active doctype\r
+     */\r
+    public function addModule($module)\r
+    {\r
+        $this->registerModule($module);\r
+        if (is_object($module)) {\r
+            $module = $module->name;\r
+        }\r
+        $this->userModules[] = $module;\r
+    }\r
+\r
+    /**\r
+     * Adds a class prefix that registerModule() will use to resolve a\r
+     * string name to a concrete class\r
+     */\r
+    public function addPrefix($prefix)\r
+    {\r
+        $this->prefixes[] = $prefix;\r
+    }\r
+\r
+    /**\r
+     * Performs processing on modules, after being called you may\r
+     * use getElement() and getElements()\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $this->trusted = $config->get('HTML.Trusted');\r
+\r
+        // generate\r
+        $this->doctype = $this->doctypes->make($config);\r
+        $modules = $this->doctype->modules;\r
+\r
+        // take out the default modules that aren't allowed\r
+        $lookup = $config->get('HTML.AllowedModules');\r
+        $special_cases = $config->get('HTML.CoreModules');\r
+\r
+        if (is_array($lookup)) {\r
+            foreach ($modules as $k => $m) {\r
+                if (isset($special_cases[$m])) {\r
+                    continue;\r
+                }\r
+                if (!isset($lookup[$m])) {\r
+                    unset($modules[$k]);\r
+                }\r
+            }\r
+        }\r
+\r
+        // custom modules\r
+        if ($config->get('HTML.Proprietary')) {\r
+            $modules[] = 'Proprietary';\r
+        }\r
+        if ($config->get('HTML.SafeObject')) {\r
+            $modules[] = 'SafeObject';\r
+        }\r
+        if ($config->get('HTML.SafeEmbed')) {\r
+            $modules[] = 'SafeEmbed';\r
+        }\r
+        if ($config->get('HTML.SafeScripting') !== array()) {\r
+            $modules[] = 'SafeScripting';\r
+        }\r
+        if ($config->get('HTML.Nofollow')) {\r
+            $modules[] = 'Nofollow';\r
+        }\r
+        if ($config->get('HTML.TargetBlank')) {\r
+            $modules[] = 'TargetBlank';\r
+        }\r
+        // NB: HTML.TargetNoreferrer and HTML.TargetNoopener must be AFTER HTML.TargetBlank\r
+        // so that its post-attr-transform gets run afterwards.\r
+        if ($config->get('HTML.TargetNoreferrer')) {\r
+            $modules[] = 'TargetNoreferrer';\r
+        }\r
+        if ($config->get('HTML.TargetNoopener')) {\r
+            $modules[] = 'TargetNoopener';\r
+        }\r
+\r
+        // merge in custom modules\r
+        $modules = array_merge($modules, $this->userModules);\r
+\r
+        foreach ($modules as $module) {\r
+            $this->processModule($module);\r
+            $this->modules[$module]->setup($config);\r
+        }\r
+\r
+        foreach ($this->doctype->tidyModules as $module) {\r
+            $this->processModule($module);\r
+            $this->modules[$module]->setup($config);\r
+        }\r
+\r
+        // prepare any injectors\r
+        foreach ($this->modules as $module) {\r
+            $n = array();\r
+            foreach ($module->info_injector as $injector) {\r
+                if (!is_object($injector)) {\r
+                    $class = "HTMLPurifier_Injector_$injector";\r
+                    $injector = new $class;\r
+                }\r
+                $n[$injector->name] = $injector;\r
+            }\r
+            $module->info_injector = $n;\r
+        }\r
+\r
+        // setup lookup table based on all valid modules\r
+        foreach ($this->modules as $module) {\r
+            foreach ($module->info as $name => $def) {\r
+                if (!isset($this->elementLookup[$name])) {\r
+                    $this->elementLookup[$name] = array();\r
+                }\r
+                $this->elementLookup[$name][] = $module->name;\r
+            }\r
+        }\r
+\r
+        // note the different choice\r
+        $this->contentSets = new HTMLPurifier_ContentSets(\r
+            // content set assembly deals with all possible modules,\r
+            // not just ones deemed to be "safe"\r
+            $this->modules\r
+        );\r
+        $this->attrCollections = new HTMLPurifier_AttrCollections(\r
+            $this->attrTypes,\r
+            // there is no way to directly disable a global attribute,\r
+            // but using AllowedAttributes or simply not including\r
+            // the module in your custom doctype should be sufficient\r
+            $this->modules\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Takes a module and adds it to the active module collection,\r
+     * registering it if necessary.\r
+     */\r
+    public function processModule($module)\r
+    {\r
+        if (!isset($this->registeredModules[$module]) || is_object($module)) {\r
+            $this->registerModule($module);\r
+        }\r
+        $this->modules[$module] = $this->registeredModules[$module];\r
+    }\r
+\r
+    /**\r
+     * Retrieves merged element definitions.\r
+     * @return Array of HTMLPurifier_ElementDef\r
+     */\r
+    public function getElements()\r
+    {\r
+        $elements = array();\r
+        foreach ($this->modules as $module) {\r
+            if (!$this->trusted && !$module->safe) {\r
+                continue;\r
+            }\r
+            foreach ($module->info as $name => $v) {\r
+                if (isset($elements[$name])) {\r
+                    continue;\r
+                }\r
+                $elements[$name] = $this->getElement($name);\r
+            }\r
+        }\r
+\r
+        // remove dud elements, this happens when an element that\r
+        // appeared to be safe actually wasn't\r
+        foreach ($elements as $n => $v) {\r
+            if ($v === false) {\r
+                unset($elements[$n]);\r
+            }\r
+        }\r
+\r
+        return $elements;\r
+\r
+    }\r
+\r
+    /**\r
+     * Retrieves a single merged element definition\r
+     * @param string $name Name of element\r
+     * @param bool $trusted Boolean trusted overriding parameter: set to true\r
+     *                 if you want the full version of an element\r
+     * @return HTMLPurifier_ElementDef Merged HTMLPurifier_ElementDef\r
+     * @note You may notice that modules are getting iterated over twice (once\r
+     *       in getElements() and once here). This\r
+     *       is because\r
+     */\r
+    public function getElement($name, $trusted = null)\r
+    {\r
+        if (!isset($this->elementLookup[$name])) {\r
+            return false;\r
+        }\r
+\r
+        // setup global state variables\r
+        $def = false;\r
+        if ($trusted === null) {\r
+            $trusted = $this->trusted;\r
+        }\r
+\r
+        // iterate through each module that has registered itself to this\r
+        // element\r
+        foreach ($this->elementLookup[$name] as $module_name) {\r
+            $module = $this->modules[$module_name];\r
+\r
+            // refuse to create/merge from a module that is deemed unsafe--\r
+            // pretend the module doesn't exist--when trusted mode is not on.\r
+            if (!$trusted && !$module->safe) {\r
+                continue;\r
+            }\r
+\r
+            // clone is used because, ideally speaking, the original\r
+            // definition should not be modified. Usually, this will\r
+            // make no difference, but for consistency's sake\r
+            $new_def = clone $module->info[$name];\r
+\r
+            if (!$def && $new_def->standalone) {\r
+                $def = $new_def;\r
+            } elseif ($def) {\r
+                // This will occur even if $new_def is standalone. In practice,\r
+                // this will usually result in a full replacement.\r
+                $def->mergeIn($new_def);\r
+            } else {\r
+                // :TODO:\r
+                // non-standalone definitions that don't have a standalone\r
+                // to merge into could be deferred to the end\r
+                // HOWEVER, it is perfectly valid for a non-standalone\r
+                // definition to lack a standalone definition, even\r
+                // after all processing: this allows us to safely\r
+                // specify extra attributes for elements that may not be\r
+                // enabled all in one place.  In particular, this might\r
+                // be the case for trusted elements.  WARNING: care must\r
+                // be taken that the /extra/ definitions are all safe.\r
+                continue;\r
+            }\r
+\r
+            // attribute value expansions\r
+            $this->attrCollections->performInclusions($def->attr);\r
+            $this->attrCollections->expandIdentifiers($def->attr, $this->attrTypes);\r
+\r
+            // descendants_are_inline, for ChildDef_Chameleon\r
+            if (is_string($def->content_model) &&\r
+                strpos($def->content_model, 'Inline') !== false) {\r
+                if ($name != 'del' && $name != 'ins') {\r
+                    // this is for you, ins/del\r
+                    $def->descendants_are_inline = true;\r
+                }\r
+            }\r
+\r
+            $this->contentSets->generateChildDef($def, $module);\r
+        }\r
+\r
+        // This can occur if there is a blank definition, but no base to\r
+        // mix it in with\r
+        if (!$def) {\r
+            return false;\r
+        }\r
+\r
+        // add information on required attributes\r
+        foreach ($def->attr as $attr_name => $attr_def) {\r
+            if ($attr_def->required) {\r
+                $def->required_attr[] = $attr_name;\r
+            }\r
+        }\r
+        return $def;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Component of HTMLPurifier_AttrContext that accumulates IDs to prevent dupes\r
+ * @note In Slashdot-speak, dupe means duplicate.\r
+ * @note The default constructor does not accept $config or $context objects:\r
+ *       use must use the static build() factory method to perform initialization.\r
+ */\r
+class HTMLPurifier_IDAccumulator\r
+{\r
+\r
+    /**\r
+     * Lookup table of IDs we've accumulated.\r
+     * @public\r
+     */\r
+    public $ids = array();\r
+\r
+    /**\r
+     * Builds an IDAccumulator, also initializing the default blacklist\r
+     * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config\r
+     * @param HTMLPurifier_Context $context Instance of HTMLPurifier_Context\r
+     * @return HTMLPurifier_IDAccumulator Fully initialized HTMLPurifier_IDAccumulator\r
+     */\r
+    public static function build($config, $context)\r
+    {\r
+        $id_accumulator = new HTMLPurifier_IDAccumulator();\r
+        $id_accumulator->load($config->get('Attr.IDBlacklist'));\r
+        return $id_accumulator;\r
+    }\r
+\r
+    /**\r
+     * Add an ID to the lookup table.\r
+     * @param string $id ID to be added.\r
+     * @return bool status, true if success, false if there's a dupe\r
+     */\r
+    public function add($id)\r
+    {\r
+        if (isset($this->ids[$id])) {\r
+            return false;\r
+        }\r
+        return $this->ids[$id] = true;\r
+    }\r
+\r
+    /**\r
+     * Load a list of IDs into the lookup table\r
+     * @param $array_of_ids Array of IDs to load\r
+     * @note This function doesn't care about duplicates\r
+     */\r
+    public function load($array_of_ids)\r
+    {\r
+        foreach ($array_of_ids as $id) {\r
+            $this->ids[$id] = true;\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Injects tokens into the document while parsing for well-formedness.\r
+ * This enables "formatter-like" functionality such as auto-paragraphing,\r
+ * smiley-ification and linkification to take place.\r
+ *\r
+ * A note on how handlers create changes; this is done by assigning a new\r
+ * value to the $token reference. These values can take a variety of forms and\r
+ * are best described HTMLPurifier_Strategy_MakeWellFormed->processToken()\r
+ * documentation.\r
+ *\r
+ * @todo Allow injectors to request a re-run on their output. This\r
+ *       would help if an operation is recursive.\r
+ */\r
+abstract class HTMLPurifier_Injector\r
+{\r
+\r
+    /**\r
+     * Advisory name of injector, this is for friendly error messages.\r
+     * @type string\r
+     */\r
+    public $name;\r
+\r
+    /**\r
+     * @type HTMLPurifier_HTMLDefinition\r
+     */\r
+    protected $htmlDefinition;\r
+\r
+    /**\r
+     * Reference to CurrentNesting variable in Context. This is an array\r
+     * list of tokens that we are currently "inside"\r
+     * @type array\r
+     */\r
+    protected $currentNesting;\r
+\r
+    /**\r
+     * Reference to current token.\r
+     * @type HTMLPurifier_Token\r
+     */\r
+    protected $currentToken;\r
+\r
+    /**\r
+     * Reference to InputZipper variable in Context.\r
+     * @type HTMLPurifier_Zipper\r
+     */\r
+    protected $inputZipper;\r
+\r
+    /**\r
+     * Array of elements and attributes this injector creates and therefore\r
+     * need to be allowed by the definition. Takes form of\r
+     * array('element' => array('attr', 'attr2'), 'element2')\r
+     * @type array\r
+     */\r
+    public $needed = array();\r
+\r
+    /**\r
+     * Number of elements to rewind backwards (relative).\r
+     * @type bool|int\r
+     */\r
+    protected $rewindOffset = false;\r
+\r
+    /**\r
+     * Rewind to a spot to re-perform processing. This is useful if you\r
+     * deleted a node, and now need to see if this change affected any\r
+     * earlier nodes. Rewinding does not affect other injectors, and can\r
+     * result in infinite loops if not used carefully.\r
+     * @param bool|int $offset\r
+     * @warning HTML Purifier will prevent you from fast-forwarding with this\r
+     *          function.\r
+     */\r
+    public function rewindOffset($offset)\r
+    {\r
+        $this->rewindOffset = $offset;\r
+    }\r
+\r
+    /**\r
+     * Retrieves rewind offset, and then unsets it.\r
+     * @return bool|int\r
+     */\r
+    public function getRewindOffset()\r
+    {\r
+        $r = $this->rewindOffset;\r
+        $this->rewindOffset = false;\r
+        return $r;\r
+    }\r
+\r
+    /**\r
+     * Prepares the injector by giving it the config and context objects:\r
+     * this allows references to important variables to be made within\r
+     * the injector. This function also checks if the HTML environment\r
+     * will work with the Injector (see checkNeeded()).\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string Boolean false if success, string of missing needed element/attribute if failure\r
+     */\r
+    public function prepare($config, $context)\r
+    {\r
+        $this->htmlDefinition = $config->getHTMLDefinition();\r
+        // Even though this might fail, some unit tests ignore this and\r
+        // still test checkNeeded, so be careful. Maybe get rid of that\r
+        // dependency.\r
+        $result = $this->checkNeeded($config);\r
+        if ($result !== false) {\r
+            return $result;\r
+        }\r
+        $this->currentNesting =& $context->get('CurrentNesting');\r
+        $this->currentToken   =& $context->get('CurrentToken');\r
+        $this->inputZipper    =& $context->get('InputZipper');\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * This function checks if the HTML environment\r
+     * will work with the Injector: if p tags are not allowed, the\r
+     * Auto-Paragraphing injector should not be enabled.\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool|string Boolean false if success, string of missing needed element/attribute if failure\r
+     */\r
+    public function checkNeeded($config)\r
+    {\r
+        $def = $config->getHTMLDefinition();\r
+        foreach ($this->needed as $element => $attributes) {\r
+            if (is_int($element)) {\r
+                $element = $attributes;\r
+            }\r
+            if (!isset($def->info[$element])) {\r
+                return $element;\r
+            }\r
+            if (!is_array($attributes)) {\r
+                continue;\r
+            }\r
+            foreach ($attributes as $name) {\r
+                if (!isset($def->info[$element]->attr[$name])) {\r
+                    return "$element.$name";\r
+                }\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * Tests if the context node allows a certain element\r
+     * @param string $name Name of element to test for\r
+     * @return bool True if element is allowed, false if it is not\r
+     */\r
+    public function allowsElement($name)\r
+    {\r
+        if (!empty($this->currentNesting)) {\r
+            $parent_token = array_pop($this->currentNesting);\r
+            $this->currentNesting[] = $parent_token;\r
+            $parent = $this->htmlDefinition->info[$parent_token->name];\r
+        } else {\r
+            $parent = $this->htmlDefinition->info_parent_def;\r
+        }\r
+        if (!isset($parent->child->elements[$name]) || isset($parent->excludes[$name])) {\r
+            return false;\r
+        }\r
+        // check for exclusion\r
+        if (!empty($this->currentNesting)) {\r
+            for ($i = count($this->currentNesting) - 2; $i >= 0; $i--) {\r
+                $node = $this->currentNesting[$i];\r
+                $def  = $this->htmlDefinition->info[$node->name];\r
+                if (isset($def->excludes[$name])) {\r
+                    return false;\r
+                }\r
+            }\r
+        }\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Iterator function, which starts with the next token and continues until\r
+     * you reach the end of the input tokens.\r
+     * @warning Please prevent previous references from interfering with this\r
+     *          functions by setting $i = null beforehand!\r
+     * @param int $i Current integer index variable for inputTokens\r
+     * @param HTMLPurifier_Token $current Current token variable.\r
+     *          Do NOT use $token, as that variable is also a reference\r
+     * @return bool\r
+     */\r
+    protected function forward(&$i, &$current)\r
+    {\r
+        if ($i === null) {\r
+            $i = count($this->inputZipper->back) - 1;\r
+        } else {\r
+            $i--;\r
+        }\r
+        if ($i < 0) {\r
+            return false;\r
+        }\r
+        $current = $this->inputZipper->back[$i];\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Similar to _forward, but accepts a third parameter $nesting (which\r
+     * should be initialized at 0) and stops when we hit the end tag\r
+     * for the node $this->inputIndex starts in.\r
+     * @param int $i Current integer index variable for inputTokens\r
+     * @param HTMLPurifier_Token $current Current token variable.\r
+     *          Do NOT use $token, as that variable is also a reference\r
+     * @param int $nesting\r
+     * @return bool\r
+     */\r
+    protected function forwardUntilEndToken(&$i, &$current, &$nesting)\r
+    {\r
+        $result = $this->forward($i, $current);\r
+        if (!$result) {\r
+            return false;\r
+        }\r
+        if ($nesting === null) {\r
+            $nesting = 0;\r
+        }\r
+        if ($current instanceof HTMLPurifier_Token_Start) {\r
+            $nesting++;\r
+        } elseif ($current instanceof HTMLPurifier_Token_End) {\r
+            if ($nesting <= 0) {\r
+                return false;\r
+            }\r
+            $nesting--;\r
+        }\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Iterator function, starts with the previous token and continues until\r
+     * you reach the beginning of input tokens.\r
+     * @warning Please prevent previous references from interfering with this\r
+     *          functions by setting $i = null beforehand!\r
+     * @param int $i Current integer index variable for inputTokens\r
+     * @param HTMLPurifier_Token $current Current token variable.\r
+     *          Do NOT use $token, as that variable is also a reference\r
+     * @return bool\r
+     */\r
+    protected function backward(&$i, &$current)\r
+    {\r
+        if ($i === null) {\r
+            $i = count($this->inputZipper->front) - 1;\r
+        } else {\r
+            $i--;\r
+        }\r
+        if ($i < 0) {\r
+            return false;\r
+        }\r
+        $current = $this->inputZipper->front[$i];\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Handler that is called when a text token is processed\r
+     */\r
+    public function handleText(&$token)\r
+    {\r
+    }\r
+\r
+    /**\r
+     * Handler that is called when a start or empty token is processed\r
+     */\r
+    public function handleElement(&$token)\r
+    {\r
+    }\r
+\r
+    /**\r
+     * Handler that is called when an end token is processed\r
+     */\r
+    public function handleEnd(&$token)\r
+    {\r
+        $this->notifyEnd($token);\r
+    }\r
+\r
+    /**\r
+     * Notifier that is called when an end token is processed\r
+     * @param HTMLPurifier_Token $token Current token variable.\r
+     * @note This differs from handlers in that the token is read-only\r
+     * @deprecated\r
+     */\r
+    public function notifyEnd($token)\r
+    {\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Represents a language and defines localizable string formatting and\r
+ * other functions, as well as the localized messages for HTML Purifier.\r
+ */\r
+class HTMLPurifier_Language\r
+{\r
+\r
+    /**\r
+     * ISO 639 language code of language. Prefers shortest possible version.\r
+     * @type string\r
+     */\r
+    public $code = 'en';\r
+\r
+    /**\r
+     * Fallback language code.\r
+     * @type bool|string\r
+     */\r
+    public $fallback = false;\r
+\r
+    /**\r
+     * Array of localizable messages.\r
+     * @type array\r
+     */\r
+    public $messages = array();\r
+\r
+    /**\r
+     * Array of localizable error codes.\r
+     * @type array\r
+     */\r
+    public $errorNames = array();\r
+\r
+    /**\r
+     * True if no message file was found for this language, so English\r
+     * is being used instead. Check this if you'd like to notify the\r
+     * user that they've used a non-supported language.\r
+     * @type bool\r
+     */\r
+    public $error = false;\r
+\r
+    /**\r
+     * Has the language object been loaded yet?\r
+     * @type bool\r
+     * @todo Make it private, fix usage in HTMLPurifier_LanguageTest\r
+     */\r
+    public $_loaded = false;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Config\r
+     */\r
+    protected $config;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Context\r
+     */\r
+    protected $context;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     */\r
+    public function __construct($config, $context)\r
+    {\r
+        $this->config  = $config;\r
+        $this->context = $context;\r
+    }\r
+\r
+    /**\r
+     * Loads language object with necessary info from factory cache\r
+     * @note This is a lazy loader\r
+     */\r
+    public function load()\r
+    {\r
+        if ($this->_loaded) {\r
+            return;\r
+        }\r
+        $factory = HTMLPurifier_LanguageFactory::instance();\r
+        $factory->loadLanguage($this->code);\r
+        foreach ($factory->keys as $key) {\r
+            $this->$key = $factory->cache[$this->code][$key];\r
+        }\r
+        $this->_loaded = true;\r
+    }\r
+\r
+    /**\r
+     * Retrieves a localised message.\r
+     * @param string $key string identifier of message\r
+     * @return string localised message\r
+     */\r
+    public function getMessage($key)\r
+    {\r
+        if (!$this->_loaded) {\r
+            $this->load();\r
+        }\r
+        if (!isset($this->messages[$key])) {\r
+            return "[$key]";\r
+        }\r
+        return $this->messages[$key];\r
+    }\r
+\r
+    /**\r
+     * Retrieves a localised error name.\r
+     * @param int $int error number, corresponding to PHP's error reporting\r
+     * @return string localised message\r
+     */\r
+    public function getErrorName($int)\r
+    {\r
+        if (!$this->_loaded) {\r
+            $this->load();\r
+        }\r
+        if (!isset($this->errorNames[$int])) {\r
+            return "[Error: $int]";\r
+        }\r
+        return $this->errorNames[$int];\r
+    }\r
+\r
+    /**\r
+     * Converts an array list into a string readable representation\r
+     * @param array $array\r
+     * @return string\r
+     */\r
+    public function listify($array)\r
+    {\r
+        $sep      = $this->getMessage('Item separator');\r
+        $sep_last = $this->getMessage('Item separator last');\r
+        $ret = '';\r
+        for ($i = 0, $c = count($array); $i < $c; $i++) {\r
+            if ($i == 0) {\r
+            } elseif ($i + 1 < $c) {\r
+                $ret .= $sep;\r
+            } else {\r
+                $ret .= $sep_last;\r
+            }\r
+            $ret .= $array[$i];\r
+        }\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Formats a localised message with passed parameters\r
+     * @param string $key string identifier of message\r
+     * @param array $args Parameters to substitute in\r
+     * @return string localised message\r
+     * @todo Implement conditionals? Right now, some messages make\r
+     *     reference to line numbers, but those aren't always available\r
+     */\r
+    public function formatMessage($key, $args = array())\r
+    {\r
+        if (!$this->_loaded) {\r
+            $this->load();\r
+        }\r
+        if (!isset($this->messages[$key])) {\r
+            return "[$key]";\r
+        }\r
+        $raw = $this->messages[$key];\r
+        $subst = array();\r
+        $generator = false;\r
+        foreach ($args as $i => $value) {\r
+            if (is_object($value)) {\r
+                if ($value instanceof HTMLPurifier_Token) {\r
+                    // factor this out some time\r
+                    if (!$generator) {\r
+                        $generator = $this->context->get('Generator');\r
+                    }\r
+                    if (isset($value->name)) {\r
+                        $subst['$'.$i.'.Name'] = $value->name;\r
+                    }\r
+                    if (isset($value->data)) {\r
+                        $subst['$'.$i.'.Data'] = $value->data;\r
+                    }\r
+                    $subst['$'.$i.'.Compact'] =\r
+                    $subst['$'.$i.'.Serialized'] = $generator->generateFromToken($value);\r
+                    // a more complex algorithm for compact representation\r
+                    // could be introduced for all types of tokens. This\r
+                    // may need to be factored out into a dedicated class\r
+                    if (!empty($value->attr)) {\r
+                        $stripped_token = clone $value;\r
+                        $stripped_token->attr = array();\r
+                        $subst['$'.$i.'.Compact'] = $generator->generateFromToken($stripped_token);\r
+                    }\r
+                    $subst['$'.$i.'.Line'] = $value->line ? $value->line : 'unknown';\r
+                }\r
+                continue;\r
+            } elseif (is_array($value)) {\r
+                $keys = array_keys($value);\r
+                if (array_keys($keys) === $keys) {\r
+                    // list\r
+                    $subst['$'.$i] = $this->listify($value);\r
+                } else {\r
+                    // associative array\r
+                    // no $i implementation yet, sorry\r
+                    $subst['$'.$i.'.Keys'] = $this->listify($keys);\r
+                    $subst['$'.$i.'.Values'] = $this->listify(array_values($value));\r
+                }\r
+                continue;\r
+            }\r
+            $subst['$' . $i] = $value;\r
+        }\r
+        return strtr($raw, $subst);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Class responsible for generating HTMLPurifier_Language objects, managing\r
+ * caching and fallbacks.\r
+ * @note Thanks to MediaWiki for the general logic, although this version\r
+ *       has been entirely rewritten\r
+ * @todo Serialized cache for languages\r
+ */\r
+class HTMLPurifier_LanguageFactory\r
+{\r
+\r
+    /**\r
+     * Cache of language code information used to load HTMLPurifier_Language objects.\r
+     * Structure is: $factory->cache[$language_code][$key] = $value\r
+     * @type array\r
+     */\r
+    public $cache;\r
+\r
+    /**\r
+     * Valid keys in the HTMLPurifier_Language object. Designates which\r
+     * variables to slurp out of a message file.\r
+     * @type array\r
+     */\r
+    public $keys = array('fallback', 'messages', 'errorNames');\r
+\r
+    /**\r
+     * Instance to validate language codes.\r
+     * @type HTMLPurifier_AttrDef_Lang\r
+     *\r
+     */\r
+    protected $validator;\r
+\r
+    /**\r
+     * Cached copy of dirname(__FILE__), directory of current file without\r
+     * trailing slash.\r
+     * @type string\r
+     */\r
+    protected $dir;\r
+\r
+    /**\r
+     * Keys whose contents are a hash map and can be merged.\r
+     * @type array\r
+     */\r
+    protected $mergeable_keys_map = array('messages' => true, 'errorNames' => true);\r
+\r
+    /**\r
+     * Keys whose contents are a list and can be merged.\r
+     * @value array lookup\r
+     */\r
+    protected $mergeable_keys_list = array();\r
+\r
+    /**\r
+     * Retrieve sole instance of the factory.\r
+     * @param HTMLPurifier_LanguageFactory $prototype Optional prototype to overload sole instance with,\r
+     *                   or bool true to reset to default factory.\r
+     * @return HTMLPurifier_LanguageFactory\r
+     */\r
+    public static function instance($prototype = null)\r
+    {\r
+        static $instance = null;\r
+        if ($prototype !== null) {\r
+            $instance = $prototype;\r
+        } elseif ($instance === null || $prototype == true) {\r
+            $instance = new HTMLPurifier_LanguageFactory();\r
+            $instance->setup();\r
+        }\r
+        return $instance;\r
+    }\r
+\r
+    /**\r
+     * Sets up the singleton, much like a constructor\r
+     * @note Prevents people from getting this outside of the singleton\r
+     */\r
+    public function setup()\r
+    {\r
+        $this->validator = new HTMLPurifier_AttrDef_Lang();\r
+        $this->dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier';\r
+    }\r
+\r
+    /**\r
+     * Creates a language object, handles class fallbacks\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @param bool|string $code Code to override configuration with. Private parameter.\r
+     * @return HTMLPurifier_Language\r
+     */\r
+    public function create($config, $context, $code = false)\r
+    {\r
+        // validate language code\r
+        if ($code === false) {\r
+            $code = $this->validator->validate(\r
+                $config->get('Core.Language'),\r
+                $config,\r
+                $context\r
+            );\r
+        } else {\r
+            $code = $this->validator->validate($code, $config, $context);\r
+        }\r
+        if ($code === false) {\r
+            $code = 'en'; // malformed code becomes English\r
+        }\r
+\r
+        $pcode = str_replace('-', '_', $code); // make valid PHP classname\r
+        static $depth = 0; // recursion protection\r
+\r
+        if ($code == 'en') {\r
+            $lang = new HTMLPurifier_Language($config, $context);\r
+        } else {\r
+            $class = 'HTMLPurifier_Language_' . $pcode;\r
+            $file  = $this->dir . '/Language/classes/' . $code . '.php';\r
+            if (file_exists($file) || class_exists($class, false)) {\r
+                $lang = new $class($config, $context);\r
+            } else {\r
+                // Go fallback\r
+                $raw_fallback = $this->getFallbackFor($code);\r
+                $fallback = $raw_fallback ? $raw_fallback : 'en';\r
+                $depth++;\r
+                $lang = $this->create($config, $context, $fallback);\r
+                if (!$raw_fallback) {\r
+                    $lang->error = true;\r
+                }\r
+                $depth--;\r
+            }\r
+        }\r
+        $lang->code = $code;\r
+        return $lang;\r
+    }\r
+\r
+    /**\r
+     * Returns the fallback language for language\r
+     * @note Loads the original language into cache\r
+     * @param string $code language code\r
+     * @return string|bool\r
+     */\r
+    public function getFallbackFor($code)\r
+    {\r
+        $this->loadLanguage($code);\r
+        return $this->cache[$code]['fallback'];\r
+    }\r
+\r
+    /**\r
+     * Loads language into the cache, handles message file and fallbacks\r
+     * @param string $code language code\r
+     */\r
+    public function loadLanguage($code)\r
+    {\r
+        static $languages_seen = array(); // recursion guard\r
+\r
+        // abort if we've already loaded it\r
+        if (isset($this->cache[$code])) {\r
+            return;\r
+        }\r
+\r
+        // generate filename\r
+        $filename = $this->dir . '/Language/messages/' . $code . '.php';\r
+\r
+        // default fallback : may be overwritten by the ensuing include\r
+        $fallback = ($code != 'en') ? 'en' : false;\r
+\r
+        // load primary localisation\r
+        if (!file_exists($filename)) {\r
+            // skip the include: will rely solely on fallback\r
+            $filename = $this->dir . '/Language/messages/en.php';\r
+            $cache = array();\r
+        } else {\r
+            include $filename;\r
+            $cache = compact($this->keys);\r
+        }\r
+\r
+        // load fallback localisation\r
+        if (!empty($fallback)) {\r
+\r
+            // infinite recursion guard\r
+            if (isset($languages_seen[$code])) {\r
+                trigger_error(\r
+                    'Circular fallback reference in language ' .\r
+                    $code,\r
+                    E_USER_ERROR\r
+                );\r
+                $fallback = 'en';\r
+            }\r
+            $language_seen[$code] = true;\r
+\r
+            // load the fallback recursively\r
+            $this->loadLanguage($fallback);\r
+            $fallback_cache = $this->cache[$fallback];\r
+\r
+            // merge fallback with current language\r
+            foreach ($this->keys as $key) {\r
+                if (isset($cache[$key]) && isset($fallback_cache[$key])) {\r
+                    if (isset($this->mergeable_keys_map[$key])) {\r
+                        $cache[$key] = $cache[$key] + $fallback_cache[$key];\r
+                    } elseif (isset($this->mergeable_keys_list[$key])) {\r
+                        $cache[$key] = array_merge($fallback_cache[$key], $cache[$key]);\r
+                    }\r
+                } else {\r
+                    $cache[$key] = $fallback_cache[$key];\r
+                }\r
+            }\r
+        }\r
+\r
+        // save to cache for later retrieval\r
+        $this->cache[$code] = $cache;\r
+        return;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Represents a measurable length, with a string numeric magnitude\r
+ * and a unit. This object is immutable.\r
+ */\r
+class HTMLPurifier_Length\r
+{\r
+\r
+    /**\r
+     * String numeric magnitude.\r
+     * @type string\r
+     */\r
+    protected $n;\r
+\r
+    /**\r
+     * String unit. False is permitted if $n = 0.\r
+     * @type string|bool\r
+     */\r
+    protected $unit;\r
+\r
+    /**\r
+     * Whether or not this length is valid. Null if not calculated yet.\r
+     * @type bool\r
+     */\r
+    protected $isValid;\r
+\r
+    /**\r
+     * Array Lookup array of units recognized by CSS 3\r
+     * @type array\r
+     */\r
+    protected static $allowedUnits = array(\r
+        'em' => true, 'ex' => true, 'px' => true, 'in' => true,\r
+        'cm' => true, 'mm' => true, 'pt' => true, 'pc' => true,\r
+        'ch' => true, 'rem' => true, 'vw' => true, 'vh' => true,\r
+        'vmin' => true, 'vmax' => true\r
+    );\r
+\r
+    /**\r
+     * @param string $n Magnitude\r
+     * @param bool|string $u Unit\r
+     */\r
+    public function __construct($n = '0', $u = false)\r
+    {\r
+        $this->n = (string) $n;\r
+        $this->unit = $u !== false ? (string) $u : false;\r
+    }\r
+\r
+    /**\r
+     * @param string $s Unit string, like '2em' or '3.4in'\r
+     * @return HTMLPurifier_Length\r
+     * @warning Does not perform validation.\r
+     */\r
+    public static function make($s)\r
+    {\r
+        if ($s instanceof HTMLPurifier_Length) {\r
+            return $s;\r
+        }\r
+        $n_length = strspn($s, '1234567890.+-');\r
+        $n = substr($s, 0, $n_length);\r
+        $unit = substr($s, $n_length);\r
+        if ($unit === '') {\r
+            $unit = false;\r
+        }\r
+        return new HTMLPurifier_Length($n, $unit);\r
+    }\r
+\r
+    /**\r
+     * Validates the number and unit.\r
+     * @return bool\r
+     */\r
+    protected function validate()\r
+    {\r
+        // Special case:\r
+        if ($this->n === '+0' || $this->n === '-0') {\r
+            $this->n = '0';\r
+        }\r
+        if ($this->n === '0' && $this->unit === false) {\r
+            return true;\r
+        }\r
+        if (!ctype_lower($this->unit)) {\r
+            $this->unit = strtolower($this->unit);\r
+        }\r
+        if (!isset(HTMLPurifier_Length::$allowedUnits[$this->unit])) {\r
+            return false;\r
+        }\r
+        // Hack:\r
+        $def = new HTMLPurifier_AttrDef_CSS_Number();\r
+        $result = $def->validate($this->n, false, false);\r
+        if ($result === false) {\r
+            return false;\r
+        }\r
+        $this->n = $result;\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Returns string representation of number.\r
+     * @return string\r
+     */\r
+    public function toString()\r
+    {\r
+        if (!$this->isValid()) {\r
+            return false;\r
+        }\r
+        return $this->n . $this->unit;\r
+    }\r
+\r
+    /**\r
+     * Retrieves string numeric magnitude.\r
+     * @return string\r
+     */\r
+    public function getN()\r
+    {\r
+        return $this->n;\r
+    }\r
+\r
+    /**\r
+     * Retrieves string unit.\r
+     * @return string\r
+     */\r
+    public function getUnit()\r
+    {\r
+        return $this->unit;\r
+    }\r
+\r
+    /**\r
+     * Returns true if this length unit is valid.\r
+     * @return bool\r
+     */\r
+    public function isValid()\r
+    {\r
+        if ($this->isValid === null) {\r
+            $this->isValid = $this->validate();\r
+        }\r
+        return $this->isValid;\r
+    }\r
+\r
+    /**\r
+     * Compares two lengths, and returns 1 if greater, -1 if less and 0 if equal.\r
+     * @param HTMLPurifier_Length $l\r
+     * @return int\r
+     * @warning If both values are too large or small, this calculation will\r
+     *          not work properly\r
+     */\r
+    public function compareTo($l)\r
+    {\r
+        if ($l === false) {\r
+            return false;\r
+        }\r
+        if ($l->unit !== $this->unit) {\r
+            $converter = new HTMLPurifier_UnitConverter();\r
+            $l = $converter->convert($l, $this->unit);\r
+            if ($l === false) {\r
+                return false;\r
+            }\r
+        }\r
+        return $this->n - $l->n;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Forgivingly lexes HTML (SGML-style) markup into tokens.\r
+ *\r
+ * A lexer parses a string of SGML-style markup and converts them into\r
+ * corresponding tokens.  It doesn't check for well-formedness, although its\r
+ * internal mechanism may make this automatic (such as the case of\r
+ * HTMLPurifier_Lexer_DOMLex).  There are several implementations to choose\r
+ * from.\r
+ *\r
+ * A lexer is HTML-oriented: it might work with XML, but it's not\r
+ * recommended, as we adhere to a subset of the specification for optimization\r
+ * reasons. This might change in the future. Also, most tokenizers are not\r
+ * expected to handle DTDs or PIs.\r
+ *\r
+ * This class should not be directly instantiated, but you may use create() to\r
+ * retrieve a default copy of the lexer.  Being a supertype, this class\r
+ * does not actually define any implementation, but offers commonly used\r
+ * convenience functions for subclasses.\r
+ *\r
+ * @note The unit tests will instantiate this class for testing purposes, as\r
+ *       many of the utility functions require a class to be instantiated.\r
+ *       This means that, even though this class is not runnable, it will\r
+ *       not be declared abstract.\r
+ *\r
+ * @par\r
+ *\r
+ * @note\r
+ * We use tokens rather than create a DOM representation because DOM would:\r
+ *\r
+ * @par\r
+ *  -# Require more processing and memory to create,\r
+ *  -# Is not streamable, and\r
+ *  -# Has the entire document structure (html and body not needed).\r
+ *\r
+ * @par\r
+ * However, DOM is helpful in that it makes it easy to move around nodes\r
+ * without a lot of lookaheads to see when a tag is closed. This is a\r
+ * limitation of the token system and some workarounds would be nice.\r
+ */\r
+class HTMLPurifier_Lexer\r
+{\r
+\r
+    /**\r
+     * Whether or not this lexer implements line-number/column-number tracking.\r
+     * If it does, set to true.\r
+     */\r
+    public $tracksLineNumbers = false;\r
+\r
+    // -- STATIC ----------------------------------------------------------\r
+\r
+    /**\r
+     * Retrieves or sets the default Lexer as a Prototype Factory.\r
+     *\r
+     * By default HTMLPurifier_Lexer_DOMLex will be returned. There are\r
+     * a few exceptions involving special features that only DirectLex\r
+     * implements.\r
+     *\r
+     * @note The behavior of this class has changed, rather than accepting\r
+     *       a prototype object, it now accepts a configuration object.\r
+     *       To specify your own prototype, set %Core.LexerImpl to it.\r
+     *       This change in behavior de-singletonizes the lexer object.\r
+     *\r
+     * @param HTMLPurifier_Config $config\r
+     * @return HTMLPurifier_Lexer\r
+     * @throws HTMLPurifier_Exception\r
+     */\r
+    public static function create($config)\r
+    {\r
+        if (!($config instanceof HTMLPurifier_Config)) {\r
+            $lexer = $config;\r
+            trigger_error(\r
+                "Passing a prototype to\r
+                HTMLPurifier_Lexer::create() is deprecated, please instead\r
+                use %Core.LexerImpl",\r
+                E_USER_WARNING\r
+            );\r
+        } else {\r
+            $lexer = $config->get('Core.LexerImpl');\r
+        }\r
+\r
+        $needs_tracking =\r
+            $config->get('Core.MaintainLineNumbers') ||\r
+            $config->get('Core.CollectErrors');\r
+\r
+        $inst = null;\r
+        if (is_object($lexer)) {\r
+            $inst = $lexer;\r
+        } else {\r
+            if (is_null($lexer)) {\r
+                do {\r
+                    // auto-detection algorithm\r
+                    if ($needs_tracking) {\r
+                        $lexer = 'DirectLex';\r
+                        break;\r
+                    }\r
+\r
+                    if (class_exists('DOMDocument', false) &&\r
+                        method_exists('DOMDocument', 'loadHTML') &&\r
+                        !extension_loaded('domxml')\r
+                    ) {\r
+                        // check for DOM support, because while it's part of the\r
+                        // core, it can be disabled compile time. Also, the PECL\r
+                        // domxml extension overrides the default DOM, and is evil\r
+                        // and nasty and we shan't bother to support it\r
+                        $lexer = 'DOMLex';\r
+                    } else {\r
+                        $lexer = 'DirectLex';\r
+                    }\r
+                } while (0);\r
+            } // do..while so we can break\r
+\r
+            // instantiate recognized string names\r
+            switch ($lexer) {\r
+                case 'DOMLex':\r
+                    $inst = new HTMLPurifier_Lexer_DOMLex();\r
+                    break;\r
+                case 'DirectLex':\r
+                    $inst = new HTMLPurifier_Lexer_DirectLex();\r
+                    break;\r
+                case 'PH5P':\r
+                    $inst = new HTMLPurifier_Lexer_PH5P();\r
+                    break;\r
+                default:\r
+                    throw new HTMLPurifier_Exception(\r
+                        "Cannot instantiate unrecognized Lexer type " .\r
+                        htmlspecialchars($lexer)\r
+                    );\r
+            }\r
+        }\r
+\r
+        if (!$inst) {\r
+            throw new HTMLPurifier_Exception('No lexer was instantiated');\r
+        }\r
+\r
+        // once PHP DOM implements native line numbers, or we\r
+        // hack out something using XSLT, remove this stipulation\r
+        if ($needs_tracking && !$inst->tracksLineNumbers) {\r
+            throw new HTMLPurifier_Exception(\r
+                'Cannot use lexer that does not support line numbers with ' .\r
+                'Core.MaintainLineNumbers or Core.CollectErrors (use DirectLex instead)'\r
+            );\r
+        }\r
+\r
+        return $inst;\r
+\r
+    }\r
+\r
+    // -- CONVENIENCE MEMBERS ---------------------------------------------\r
+\r
+    public function __construct()\r
+    {\r
+        $this->_entity_parser = new HTMLPurifier_EntityParser();\r
+    }\r
+\r
+    /**\r
+     * Most common entity to raw value conversion table for special entities.\r
+     * @type array\r
+     */\r
+    protected $_special_entity2str =\r
+        array(\r
+            '&quot;' => '"',\r
+            '&amp;' => '&',\r
+            '&lt;' => '<',\r
+            '&gt;' => '>',\r
+            '&#39;' => "'",\r
+            '&#039;' => "'",\r
+            '&#x27;' => "'"\r
+        );\r
+\r
+    public function parseText($string, $config) {\r
+        return $this->parseData($string, false, $config);\r
+    }\r
+\r
+    public function parseAttr($string, $config) {\r
+        return $this->parseData($string, true, $config);\r
+    }\r
+\r
+    /**\r
+     * Parses special entities into the proper characters.\r
+     *\r
+     * This string will translate escaped versions of the special characters\r
+     * into the correct ones.\r
+     *\r
+     * @param string $string String character data to be parsed.\r
+     * @return string Parsed character data.\r
+     */\r
+    public function parseData($string, $is_attr, $config)\r
+    {\r
+        // following functions require at least one character\r
+        if ($string === '') {\r
+            return '';\r
+        }\r
+\r
+        // subtracts amps that cannot possibly be escaped\r
+        $num_amp = substr_count($string, '&') - substr_count($string, '& ') -\r
+            ($string[strlen($string) - 1] === '&' ? 1 : 0);\r
+\r
+        if (!$num_amp) {\r
+            return $string;\r
+        } // abort if no entities\r
+        $num_esc_amp = substr_count($string, '&amp;');\r
+        $string = strtr($string, $this->_special_entity2str);\r
+\r
+        // code duplication for sake of optimization, see above\r
+        $num_amp_2 = substr_count($string, '&') - substr_count($string, '& ') -\r
+            ($string[strlen($string) - 1] === '&' ? 1 : 0);\r
+\r
+        if ($num_amp_2 <= $num_esc_amp) {\r
+            return $string;\r
+        }\r
+\r
+        // hmm... now we have some uncommon entities. Use the callback.\r
+        if ($config->get('Core.LegacyEntityDecoder')) {\r
+            $string = $this->_entity_parser->substituteSpecialEntities($string);\r
+        } else {\r
+            if ($is_attr) {\r
+                $string = $this->_entity_parser->substituteAttrEntities($string);\r
+            } else {\r
+                $string = $this->_entity_parser->substituteTextEntities($string);\r
+            }\r
+        }\r
+        return $string;\r
+    }\r
+\r
+    /**\r
+     * Lexes an HTML string into tokens.\r
+     * @param $string String HTML.\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return HTMLPurifier_Token[] array representation of HTML.\r
+     */\r
+    public function tokenizeHTML($string, $config, $context)\r
+    {\r
+        trigger_error('Call to abstract class', E_USER_ERROR);\r
+    }\r
+\r
+    /**\r
+     * Translates CDATA sections into regular sections (through escaping).\r
+     * @param string $string HTML string to process.\r
+     * @return string HTML with CDATA sections escaped.\r
+     */\r
+    protected static function escapeCDATA($string)\r
+    {\r
+        return preg_replace_callback(\r
+            '/<!\[CDATA\[(.+?)\]\]>/s',\r
+            array('HTMLPurifier_Lexer', 'CDATACallback'),\r
+            $string\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Special CDATA case that is especially convoluted for <script>\r
+     * @param string $string HTML string to process.\r
+     * @return string HTML with CDATA sections escaped.\r
+     */\r
+    protected static function escapeCommentedCDATA($string)\r
+    {\r
+        return preg_replace_callback(\r
+            '#<!--//--><!\[CDATA\[//><!--(.+?)//--><!\]\]>#s',\r
+            array('HTMLPurifier_Lexer', 'CDATACallback'),\r
+            $string\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Special Internet Explorer conditional comments should be removed.\r
+     * @param string $string HTML string to process.\r
+     * @return string HTML with conditional comments removed.\r
+     */\r
+    protected static function removeIEConditional($string)\r
+    {\r
+        return preg_replace(\r
+            '#<!--\[if [^>]+\]>.*?<!\[endif\]-->#si', // probably should generalize for all strings\r
+            '',\r
+            $string\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Callback function for escapeCDATA() that does the work.\r
+     *\r
+     * @warning Though this is public in order to let the callback happen,\r
+     *          calling it directly is not recommended.\r
+     * @param array $matches PCRE matches array, with index 0 the entire match\r
+     *                  and 1 the inside of the CDATA section.\r
+     * @return string Escaped internals of the CDATA section.\r
+     */\r
+    protected static function CDATACallback($matches)\r
+    {\r
+        // not exactly sure why the character set is needed, but whatever\r
+        return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');\r
+    }\r
+\r
+    /**\r
+     * Takes a piece of HTML and normalizes it by converting entities, fixing\r
+     * encoding, extracting bits, and other good stuff.\r
+     * @param string $html HTML.\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     * @todo Consider making protected\r
+     */\r
+    public function normalize($html, $config, $context)\r
+    {\r
+        // normalize newlines to \n\r
+        if ($config->get('Core.NormalizeNewlines')) {\r
+            $html = str_replace("\r\n", "\n", $html);\r
+            $html = str_replace("\r", "\n", $html);\r
+        }\r
+\r
+        if ($config->get('HTML.Trusted')) {\r
+            // escape convoluted CDATA\r
+            $html = $this->escapeCommentedCDATA($html);\r
+        }\r
+\r
+        // escape CDATA\r
+        $html = $this->escapeCDATA($html);\r
+\r
+        $html = $this->removeIEConditional($html);\r
+\r
+        // extract body from document if applicable\r
+        if ($config->get('Core.ConvertDocumentToFragment')) {\r
+            $e = false;\r
+            if ($config->get('Core.CollectErrors')) {\r
+                $e =& $context->get('ErrorCollector');\r
+            }\r
+            $new_html = $this->extractBody($html);\r
+            if ($e && $new_html != $html) {\r
+                $e->send(E_WARNING, 'Lexer: Extracted body');\r
+            }\r
+            $html = $new_html;\r
+        }\r
+\r
+        // expand entities that aren't the big five\r
+        if ($config->get('Core.LegacyEntityDecoder')) {\r
+            $html = $this->_entity_parser->substituteNonSpecialEntities($html);\r
+        }\r
+\r
+        // clean into wellformed UTF-8 string for an SGML context: this has\r
+        // to be done after entity expansion because the entities sometimes\r
+        // represent non-SGML characters (horror, horror!)\r
+        $html = HTMLPurifier_Encoder::cleanUTF8($html);\r
+\r
+        // if processing instructions are to removed, remove them now\r
+        if ($config->get('Core.RemoveProcessingInstructions')) {\r
+            $html = preg_replace('#<\?.+?\?>#s', '', $html);\r
+        }\r
+\r
+        $hidden_elements = $config->get('Core.HiddenElements');\r
+        if ($config->get('Core.AggressivelyRemoveScript') &&\r
+            !($config->get('HTML.Trusted') || !$config->get('Core.RemoveScriptContents')\r
+            || empty($hidden_elements["script"]))) {\r
+            $html = preg_replace('#<script[^>]*>.*?</script>#i', '', $html);\r
+        }\r
+\r
+        return $html;\r
+    }\r
+\r
+    /**\r
+     * Takes a string of HTML (fragment or document) and returns the content\r
+     * @todo Consider making protected\r
+     */\r
+    public function extractBody($html)\r
+    {\r
+        $matches = array();\r
+        $result = preg_match('|(.*?)<body[^>]*>(.*)</body>|is', $html, $matches);\r
+        if ($result) {\r
+            // Make sure it's not in a comment\r
+            $comment_start = strrpos($matches[1], '<!--');\r
+            $comment_end   = strrpos($matches[1], '-->');\r
+            if ($comment_start === false ||\r
+                ($comment_end !== false && $comment_end > $comment_start)) {\r
+                return $matches[2];\r
+            }\r
+        }\r
+        return $html;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Abstract base node class that all others inherit from.\r
+ *\r
+ * Why do we not use the DOM extension?  (1) It is not always available,\r
+ * (2) it has funny constraints on the data it can represent,\r
+ * whereas we want a maximally flexible representation, and (3) its\r
+ * interface is a bit cumbersome.\r
+ */\r
+abstract class HTMLPurifier_Node\r
+{\r
+    /**\r
+     * Line number of the start token in the source document\r
+     * @type int\r
+     */\r
+    public $line;\r
+\r
+    /**\r
+     * Column number of the start token in the source document. Null if unknown.\r
+     * @type int\r
+     */\r
+    public $col;\r
+\r
+    /**\r
+     * Lookup array of processing that this token is exempt from.\r
+     * Currently, valid values are "ValidateAttributes".\r
+     * @type array\r
+     */\r
+    public $armor = array();\r
+\r
+    /**\r
+     * When true, this node should be ignored as non-existent.\r
+     *\r
+     * Who is responsible for ignoring dead nodes?  FixNesting is\r
+     * responsible for removing them before passing on to child\r
+     * validators.\r
+     */\r
+    public $dead = false;\r
+\r
+    /**\r
+     * Returns a pair of start and end tokens, where the end token\r
+     * is null if it is not necessary. Does not include children.\r
+     * @type array\r
+     */\r
+    abstract public function toTokenPair();\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Class that handles operations involving percent-encoding in URIs.\r
+ *\r
+ * @warning\r
+ *      Be careful when reusing instances of PercentEncoder. The object\r
+ *      you use for normalize() SHOULD NOT be used for encode(), or\r
+ *      vice-versa.\r
+ */\r
+class HTMLPurifier_PercentEncoder\r
+{\r
+\r
+    /**\r
+     * Reserved characters to preserve when using encode().\r
+     * @type array\r
+     */\r
+    protected $preserve = array();\r
+\r
+    /**\r
+     * String of characters that should be preserved while using encode().\r
+     * @param bool $preserve\r
+     */\r
+    public function __construct($preserve = false)\r
+    {\r
+        // unreserved letters, ought to const-ify\r
+        for ($i = 48; $i <= 57; $i++) { // digits\r
+            $this->preserve[$i] = true;\r
+        }\r
+        for ($i = 65; $i <= 90; $i++) { // upper-case\r
+            $this->preserve[$i] = true;\r
+        }\r
+        for ($i = 97; $i <= 122; $i++) { // lower-case\r
+            $this->preserve[$i] = true;\r
+        }\r
+        $this->preserve[45] = true; // Dash         -\r
+        $this->preserve[46] = true; // Period       .\r
+        $this->preserve[95] = true; // Underscore   _\r
+        $this->preserve[126]= true; // Tilde        ~\r
+\r
+        // extra letters not to escape\r
+        if ($preserve !== false) {\r
+            for ($i = 0, $c = strlen($preserve); $i < $c; $i++) {\r
+                $this->preserve[ord($preserve[$i])] = true;\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Our replacement for urlencode, it encodes all non-reserved characters,\r
+     * as well as any extra characters that were instructed to be preserved.\r
+     * @note\r
+     *      Assumes that the string has already been normalized, making any\r
+     *      and all percent escape sequences valid. Percents will not be\r
+     *      re-escaped, regardless of their status in $preserve\r
+     * @param string $string String to be encoded\r
+     * @return string Encoded string.\r
+     */\r
+    public function encode($string)\r
+    {\r
+        $ret = '';\r
+        for ($i = 0, $c = strlen($string); $i < $c; $i++) {\r
+            if ($string[$i] !== '%' && !isset($this->preserve[$int = ord($string[$i])])) {\r
+                $ret .= '%' . sprintf('%02X', $int);\r
+            } else {\r
+                $ret .= $string[$i];\r
+            }\r
+        }\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Fix up percent-encoding by decoding unreserved characters and normalizing.\r
+     * @warning This function is affected by $preserve, even though the\r
+     *          usual desired behavior is for this not to preserve those\r
+     *          characters. Be careful when reusing instances of PercentEncoder!\r
+     * @param string $string String to normalize\r
+     * @return string\r
+     */\r
+    public function normalize($string)\r
+    {\r
+        if ($string == '') {\r
+            return '';\r
+        }\r
+        $parts = explode('%', $string);\r
+        $ret = array_shift($parts);\r
+        foreach ($parts as $part) {\r
+            $length = strlen($part);\r
+            if ($length < 2) {\r
+                $ret .= '%25' . $part;\r
+                continue;\r
+            }\r
+            $encoding = substr($part, 0, 2);\r
+            $text     = substr($part, 2);\r
+            if (!ctype_xdigit($encoding)) {\r
+                $ret .= '%25' . $part;\r
+                continue;\r
+            }\r
+            $int = hexdec($encoding);\r
+            if (isset($this->preserve[$int])) {\r
+                $ret .= chr($int) . $text;\r
+                continue;\r
+            }\r
+            $encoding = strtoupper($encoding);\r
+            $ret .= '%' . $encoding . $text;\r
+        }\r
+        return $ret;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Generic property list implementation\r
+ */\r
+class HTMLPurifier_PropertyList\r
+{\r
+    /**\r
+     * Internal data-structure for properties.\r
+     * @type array\r
+     */\r
+    protected $data = array();\r
+\r
+    /**\r
+     * Parent plist.\r
+     * @type HTMLPurifier_PropertyList\r
+     */\r
+    protected $parent;\r
+\r
+    /**\r
+     * Cache.\r
+     * @type array\r
+     */\r
+    protected $cache;\r
+\r
+    /**\r
+     * @param HTMLPurifier_PropertyList $parent Parent plist\r
+     */\r
+    public function __construct($parent = null)\r
+    {\r
+        $this->parent = $parent;\r
+    }\r
+\r
+    /**\r
+     * Recursively retrieves the value for a key\r
+     * @param string $name\r
+     * @throws HTMLPurifier_Exception\r
+     */\r
+    public function get($name)\r
+    {\r
+        if ($this->has($name)) {\r
+            return $this->data[$name];\r
+        }\r
+        // possible performance bottleneck, convert to iterative if necessary\r
+        if ($this->parent) {\r
+            return $this->parent->get($name);\r
+        }\r
+        throw new HTMLPurifier_Exception("Key '$name' not found");\r
+    }\r
+\r
+    /**\r
+     * Sets the value of a key, for this plist\r
+     * @param string $name\r
+     * @param mixed $value\r
+     */\r
+    public function set($name, $value)\r
+    {\r
+        $this->data[$name] = $value;\r
+    }\r
+\r
+    /**\r
+     * Returns true if a given key exists\r
+     * @param string $name\r
+     * @return bool\r
+     */\r
+    public function has($name)\r
+    {\r
+        return array_key_exists($name, $this->data);\r
+    }\r
+\r
+    /**\r
+     * Resets a value to the value of it's parent, usually the default. If\r
+     * no value is specified, the entire plist is reset.\r
+     * @param string $name\r
+     */\r
+    public function reset($name = null)\r
+    {\r
+        if ($name == null) {\r
+            $this->data = array();\r
+        } else {\r
+            unset($this->data[$name]);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Squashes this property list and all of its property lists into a single\r
+     * array, and returns the array. This value is cached by default.\r
+     * @param bool $force If true, ignores the cache and regenerates the array.\r
+     * @return array\r
+     */\r
+    public function squash($force = false)\r
+    {\r
+        if ($this->cache !== null && !$force) {\r
+            return $this->cache;\r
+        }\r
+        if ($this->parent) {\r
+            return $this->cache = array_merge($this->parent->squash($force), $this->data);\r
+        } else {\r
+            return $this->cache = $this->data;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Returns the parent plist.\r
+     * @return HTMLPurifier_PropertyList\r
+     */\r
+    public function getParent()\r
+    {\r
+        return $this->parent;\r
+    }\r
+\r
+    /**\r
+     * Sets the parent plist.\r
+     * @param HTMLPurifier_PropertyList $plist Parent plist\r
+     */\r
+    public function setParent($plist)\r
+    {\r
+        $this->parent = $plist;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Property list iterator. Do not instantiate this class directly.\r
+ */\r
+class HTMLPurifier_PropertyListIterator extends FilterIterator\r
+{\r
+\r
+    /**\r
+     * @type int\r
+     */\r
+    protected $l;\r
+    /**\r
+     * @type string\r
+     */\r
+    protected $filter;\r
+\r
+    /**\r
+     * @param Iterator $iterator Array of data to iterate over\r
+     * @param string $filter Optional prefix to only allow values of\r
+     */\r
+    public function __construct(Iterator $iterator, $filter = null)\r
+    {\r
+        parent::__construct($iterator);\r
+        $this->l = strlen($filter);\r
+        $this->filter = $filter;\r
+    }\r
+\r
+    /**\r
+     * @return bool\r
+     */\r
+    public function accept()\r
+    {\r
+        $key = $this->getInnerIterator()->key();\r
+        if (strncmp($key, $this->filter, $this->l) !== 0) {\r
+            return false;\r
+        }\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * A simple array-backed queue, based off of the classic Okasaki\r
+ * persistent amortized queue.  The basic idea is to maintain two\r
+ * stacks: an input stack and an output stack.  When the output\r
+ * stack runs out, reverse the input stack and use it as the output\r
+ * stack.\r
+ *\r
+ * We don't use the SPL implementation because it's only supported\r
+ * on PHP 5.3 and later.\r
+ *\r
+ * Exercise: Prove that push/pop on this queue take amortized O(1) time.\r
+ *\r
+ * Exercise: Extend this queue to be a deque, while preserving amortized\r
+ * O(1) time.  Some care must be taken on rebalancing to avoid quadratic\r
+ * behaviour caused by repeatedly shuffling data from the input stack\r
+ * to the output stack and back.\r
+ */\r
+class HTMLPurifier_Queue {\r
+    private $input;\r
+    private $output;\r
+\r
+    public function __construct($input = array()) {\r
+        $this->input = $input;\r
+        $this->output = array();\r
+    }\r
+\r
+    /**\r
+     * Shifts an element off the front of the queue.\r
+     */\r
+    public function shift() {\r
+        if (empty($this->output)) {\r
+            $this->output = array_reverse($this->input);\r
+            $this->input = array();\r
+        }\r
+        if (empty($this->output)) {\r
+            return NULL;\r
+        }\r
+        return array_pop($this->output);\r
+    }\r
+\r
+    /**\r
+     * Pushes an element onto the front of the queue.\r
+     */\r
+    public function push($x) {\r
+        array_push($this->input, $x);\r
+    }\r
+\r
+    /**\r
+     * Checks if it's empty.\r
+     */\r
+    public function isEmpty() {\r
+        return empty($this->input) && empty($this->output);\r
+    }\r
+}\r
+
+\r
+\r
+/**\r
+ * Supertype for classes that define a strategy for modifying/purifying tokens.\r
+ *\r
+ * While HTMLPurifier's core purpose is fixing HTML into something proper,\r
+ * strategies provide plug points for extra configuration or even extra\r
+ * features, such as custom tags, custom parsing of text, etc.\r
+ */\r
+\r
+\r
+abstract class HTMLPurifier_Strategy\r
+{\r
+\r
+    /**\r
+     * Executes the strategy on the tokens.\r
+     *\r
+     * @param HTMLPurifier_Token[] $tokens Array of HTMLPurifier_Token objects to be operated on.\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return HTMLPurifier_Token[] Processed array of token objects.\r
+     */\r
+    abstract public function execute($tokens, $config, $context);\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * This is in almost every respect equivalent to an array except\r
+ * that it keeps track of which keys were accessed.\r
+ *\r
+ * @warning For the sake of backwards compatibility with early versions\r
+ *     of PHP 5, you must not use the $hash[$key] syntax; if you do\r
+ *     our version of offsetGet is never called.\r
+ */\r
+class HTMLPurifier_StringHash extends ArrayObject\r
+{\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $accessed = array();\r
+\r
+    /**\r
+     * Retrieves a value, and logs the access.\r
+     * @param mixed $index\r
+     * @return mixed\r
+     */\r
+    public function offsetGet($index)\r
+    {\r
+        $this->accessed[$index] = true;\r
+        return parent::offsetGet($index);\r
+    }\r
+\r
+    /**\r
+     * Returns a lookup array of all array indexes that have been accessed.\r
+     * @return array in form array($index => true).\r
+     */\r
+    public function getAccessed()\r
+    {\r
+        return $this->accessed;\r
+    }\r
+\r
+    /**\r
+     * Resets the access array.\r
+     */\r
+    public function resetAccessed()\r
+    {\r
+        $this->accessed = array();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Parses string hash files. File format is as such:\r
+ *\r
+ *      DefaultKeyValue\r
+ *      KEY: Value\r
+ *      KEY2: Value2\r
+ *      --MULTILINE-KEY--\r
+ *      Multiline\r
+ *      value.\r
+ *\r
+ * Which would output something similar to:\r
+ *\r
+ *      array(\r
+ *          'ID' => 'DefaultKeyValue',\r
+ *          'KEY' => 'Value',\r
+ *          'KEY2' => 'Value2',\r
+ *          'MULTILINE-KEY' => "Multiline\nvalue.\n",\r
+ *      )\r
+ *\r
+ * We use this as an easy to use file-format for configuration schema\r
+ * files, but the class itself is usage agnostic.\r
+ *\r
+ * You can use ---- to forcibly terminate parsing of a single string-hash;\r
+ * this marker is used in multi string-hashes to delimit boundaries.\r
+ */\r
+class HTMLPurifier_StringHashParser\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $default = 'ID';\r
+\r
+    /**\r
+     * Parses a file that contains a single string-hash.\r
+     * @param string $file\r
+     * @return array\r
+     */\r
+    public function parseFile($file)\r
+    {\r
+        if (!file_exists($file)) {\r
+            return false;\r
+        }\r
+        $fh = fopen($file, 'r');\r
+        if (!$fh) {\r
+            return false;\r
+        }\r
+        $ret = $this->parseHandle($fh);\r
+        fclose($fh);\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Parses a file that contains multiple string-hashes delimited by '----'\r
+     * @param string $file\r
+     * @return array\r
+     */\r
+    public function parseMultiFile($file)\r
+    {\r
+        if (!file_exists($file)) {\r
+            return false;\r
+        }\r
+        $ret = array();\r
+        $fh = fopen($file, 'r');\r
+        if (!$fh) {\r
+            return false;\r
+        }\r
+        while (!feof($fh)) {\r
+            $ret[] = $this->parseHandle($fh);\r
+        }\r
+        fclose($fh);\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Internal parser that acepts a file handle.\r
+     * @note While it's possible to simulate in-memory parsing by using\r
+     *       custom stream wrappers, if such a use-case arises we should\r
+     *       factor out the file handle into its own class.\r
+     * @param resource $fh File handle with pointer at start of valid string-hash\r
+     *            block.\r
+     * @return array\r
+     */\r
+    protected function parseHandle($fh)\r
+    {\r
+        $state   = false;\r
+        $single  = false;\r
+        $ret     = array();\r
+        do {\r
+            $line = fgets($fh);\r
+            if ($line === false) {\r
+                break;\r
+            }\r
+            $line = rtrim($line, "\n\r");\r
+            if (!$state && $line === '') {\r
+                continue;\r
+            }\r
+            if ($line === '----') {\r
+                break;\r
+            }\r
+            if (strncmp('--#', $line, 3) === 0) {\r
+                // Comment\r
+                continue;\r
+            } elseif (strncmp('--', $line, 2) === 0) {\r
+                // Multiline declaration\r
+                $state = trim($line, '- ');\r
+                if (!isset($ret[$state])) {\r
+                    $ret[$state] = '';\r
+                }\r
+                continue;\r
+            } elseif (!$state) {\r
+                $single = true;\r
+                if (strpos($line, ':') !== false) {\r
+                    // Single-line declaration\r
+                    list($state, $line) = explode(':', $line, 2);\r
+                    $line = trim($line);\r
+                } else {\r
+                    // Use default declaration\r
+                    $state  = $this->default;\r
+                }\r
+            }\r
+            if ($single) {\r
+                $ret[$state] = $line;\r
+                $single = false;\r
+                $state  = false;\r
+            } else {\r
+                $ret[$state] .= "$line\n";\r
+            }\r
+        } while (!feof($fh));\r
+        return $ret;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Defines a mutation of an obsolete tag into a valid tag.\r
+ */\r
+abstract class HTMLPurifier_TagTransform\r
+{\r
+\r
+    /**\r
+     * Tag name to transform the tag to.\r
+     * @type string\r
+     */\r
+    public $transform_to;\r
+\r
+    /**\r
+     * Transforms the obsolete tag into the valid tag.\r
+     * @param HTMLPurifier_Token_Tag $tag Tag to be transformed.\r
+     * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object\r
+     * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object\r
+     */\r
+    abstract public function transform($tag, $config, $context);\r
+\r
+    /**\r
+     * Prepends CSS properties to the style attribute, creating the\r
+     * attribute if it doesn't exist.\r
+     * @warning Copied over from AttrTransform, be sure to keep in sync\r
+     * @param array $attr Attribute array to process (passed by reference)\r
+     * @param string $css CSS to prepend\r
+     */\r
+    protected function prependCSS(&$attr, $css)\r
+    {\r
+        $attr['style'] = isset($attr['style']) ? $attr['style'] : '';\r
+        $attr['style'] = $css . $attr['style'];\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Abstract base token class that all others inherit from.\r
+ */\r
+abstract class HTMLPurifier_Token\r
+{\r
+    /**\r
+     * Line number node was on in source document. Null if unknown.\r
+     * @type int\r
+     */\r
+    public $line;\r
+\r
+    /**\r
+     * Column of line node was on in source document. Null if unknown.\r
+     * @type int\r
+     */\r
+    public $col;\r
+\r
+    /**\r
+     * Lookup array of processing that this token is exempt from.\r
+     * Currently, valid values are "ValidateAttributes" and\r
+     * "MakeWellFormed_TagClosedError"\r
+     * @type array\r
+     */\r
+    public $armor = array();\r
+\r
+    /**\r
+     * Used during MakeWellFormed.  See Note [Injector skips]\r
+     * @type\r
+     */\r
+    public $skip;\r
+\r
+    /**\r
+     * @type\r
+     */\r
+    public $rewind;\r
+\r
+    /**\r
+     * @type\r
+     */\r
+    public $carryover;\r
+\r
+    /**\r
+     * @param string $n\r
+     * @return null|string\r
+     */\r
+    public function __get($n)\r
+    {\r
+        if ($n === 'type') {\r
+            trigger_error('Deprecated type property called; use instanceof', E_USER_NOTICE);\r
+            switch (get_class($this)) {\r
+                case 'HTMLPurifier_Token_Start':\r
+                    return 'start';\r
+                case 'HTMLPurifier_Token_Empty':\r
+                    return 'empty';\r
+                case 'HTMLPurifier_Token_End':\r
+                    return 'end';\r
+                case 'HTMLPurifier_Token_Text':\r
+                    return 'text';\r
+                case 'HTMLPurifier_Token_Comment':\r
+                    return 'comment';\r
+                default:\r
+                    return null;\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Sets the position of the token in the source document.\r
+     * @param int $l\r
+     * @param int $c\r
+     */\r
+    public function position($l = null, $c = null)\r
+    {\r
+        $this->line = $l;\r
+        $this->col = $c;\r
+    }\r
+\r
+    /**\r
+     * Convenience function for DirectLex settings line/col position.\r
+     * @param int $l\r
+     * @param int $c\r
+     */\r
+    public function rawPosition($l, $c)\r
+    {\r
+        if ($c === -1) {\r
+            $l++;\r
+        }\r
+        $this->line = $l;\r
+        $this->col = $c;\r
+    }\r
+\r
+    /**\r
+     * Converts a token into its corresponding node.\r
+     */\r
+    abstract public function toNode();\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Factory for token generation.\r
+ *\r
+ * @note Doing some benchmarking indicates that the new operator is much\r
+ *       slower than the clone operator (even discounting the cost of the\r
+ *       constructor).  This class is for that optimization.\r
+ *       Other then that, there's not much point as we don't\r
+ *       maintain parallel HTMLPurifier_Token hierarchies (the main reason why\r
+ *       you'd want to use an abstract factory).\r
+ * @todo Port DirectLex to use this\r
+ */\r
+class HTMLPurifier_TokenFactory\r
+{\r
+    // p stands for prototype\r
+\r
+    /**\r
+     * @type HTMLPurifier_Token_Start\r
+     */\r
+    private $p_start;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Token_End\r
+     */\r
+    private $p_end;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Token_Empty\r
+     */\r
+    private $p_empty;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Token_Text\r
+     */\r
+    private $p_text;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Token_Comment\r
+     */\r
+    private $p_comment;\r
+\r
+    /**\r
+     * Generates blank prototypes for cloning.\r
+     */\r
+    public function __construct()\r
+    {\r
+        $this->p_start = new HTMLPurifier_Token_Start('', array());\r
+        $this->p_end = new HTMLPurifier_Token_End('');\r
+        $this->p_empty = new HTMLPurifier_Token_Empty('', array());\r
+        $this->p_text = new HTMLPurifier_Token_Text('');\r
+        $this->p_comment = new HTMLPurifier_Token_Comment('');\r
+    }\r
+\r
+    /**\r
+     * Creates a HTMLPurifier_Token_Start.\r
+     * @param string $name Tag name\r
+     * @param array $attr Associative array of attributes\r
+     * @return HTMLPurifier_Token_Start Generated HTMLPurifier_Token_Start\r
+     */\r
+    public function createStart($name, $attr = array())\r
+    {\r
+        $p = clone $this->p_start;\r
+        $p->__construct($name, $attr);\r
+        return $p;\r
+    }\r
+\r
+    /**\r
+     * Creates a HTMLPurifier_Token_End.\r
+     * @param string $name Tag name\r
+     * @return HTMLPurifier_Token_End Generated HTMLPurifier_Token_End\r
+     */\r
+    public function createEnd($name)\r
+    {\r
+        $p = clone $this->p_end;\r
+        $p->__construct($name);\r
+        return $p;\r
+    }\r
+\r
+    /**\r
+     * Creates a HTMLPurifier_Token_Empty.\r
+     * @param string $name Tag name\r
+     * @param array $attr Associative array of attributes\r
+     * @return HTMLPurifier_Token_Empty Generated HTMLPurifier_Token_Empty\r
+     */\r
+    public function createEmpty($name, $attr = array())\r
+    {\r
+        $p = clone $this->p_empty;\r
+        $p->__construct($name, $attr);\r
+        return $p;\r
+    }\r
+\r
+    /**\r
+     * Creates a HTMLPurifier_Token_Text.\r
+     * @param string $data Data of text token\r
+     * @return HTMLPurifier_Token_Text Generated HTMLPurifier_Token_Text\r
+     */\r
+    public function createText($data)\r
+    {\r
+        $p = clone $this->p_text;\r
+        $p->__construct($data);\r
+        return $p;\r
+    }\r
+\r
+    /**\r
+     * Creates a HTMLPurifier_Token_Comment.\r
+     * @param string $data Data of comment token\r
+     * @return HTMLPurifier_Token_Comment Generated HTMLPurifier_Token_Comment\r
+     */\r
+    public function createComment($data)\r
+    {\r
+        $p = clone $this->p_comment;\r
+        $p->__construct($data);\r
+        return $p;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * HTML Purifier's internal representation of a URI.\r
+ * @note\r
+ *      Internal data-structures are completely escaped. If the data needs\r
+ *      to be used in a non-URI context (which is very unlikely), be sure\r
+ *      to decode it first. The URI may not necessarily be well-formed until\r
+ *      validate() is called.\r
+ */\r
+class HTMLPurifier_URI\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $scheme;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $userinfo;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $host;\r
+\r
+    /**\r
+     * @type int\r
+     */\r
+    public $port;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $path;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $query;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $fragment;\r
+\r
+    /**\r
+     * @param string $scheme\r
+     * @param string $userinfo\r
+     * @param string $host\r
+     * @param int $port\r
+     * @param string $path\r
+     * @param string $query\r
+     * @param string $fragment\r
+     * @note Automatically normalizes scheme and port\r
+     */\r
+    public function __construct($scheme, $userinfo, $host, $port, $path, $query, $fragment)\r
+    {\r
+        $this->scheme = is_null($scheme) || ctype_lower($scheme) ? $scheme : strtolower($scheme);\r
+        $this->userinfo = $userinfo;\r
+        $this->host = $host;\r
+        $this->port = is_null($port) ? $port : (int)$port;\r
+        $this->path = $path;\r
+        $this->query = $query;\r
+        $this->fragment = $fragment;\r
+    }\r
+\r
+    /**\r
+     * Retrieves a scheme object corresponding to the URI's scheme/default\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return HTMLPurifier_URIScheme Scheme object appropriate for validating this URI\r
+     */\r
+    public function getSchemeObj($config, $context)\r
+    {\r
+        $registry = HTMLPurifier_URISchemeRegistry::instance();\r
+        if ($this->scheme !== null) {\r
+            $scheme_obj = $registry->getScheme($this->scheme, $config, $context);\r
+            if (!$scheme_obj) {\r
+                return false;\r
+            } // invalid scheme, clean it out\r
+        } else {\r
+            // no scheme: retrieve the default one\r
+            $def = $config->getDefinition('URI');\r
+            $scheme_obj = $def->getDefaultScheme($config, $context);\r
+            if (!$scheme_obj) {\r
+                if ($def->defaultScheme !== null) {\r
+                    // something funky happened to the default scheme object\r
+                    trigger_error(\r
+                        'Default scheme object "' . $def->defaultScheme . '" was not readable',\r
+                        E_USER_WARNING\r
+                    );\r
+                } // suppress error if it's null\r
+                return false;\r
+            }\r
+        }\r
+        return $scheme_obj;\r
+    }\r
+\r
+    /**\r
+     * Generic validation method applicable for all schemes. May modify\r
+     * this URI in order to get it into a compliant form.\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool True if validation/filtering succeeds, false if failure\r
+     */\r
+    public function validate($config, $context)\r
+    {\r
+        // ABNF definitions from RFC 3986\r
+        $chars_sub_delims = '!$&\'()*+,;=';\r
+        $chars_gen_delims = ':/?#[]@';\r
+        $chars_pchar = $chars_sub_delims . ':@';\r
+\r
+        // validate host\r
+        if (!is_null($this->host)) {\r
+            $host_def = new HTMLPurifier_AttrDef_URI_Host();\r
+            $this->host = $host_def->validate($this->host, $config, $context);\r
+            if ($this->host === false) {\r
+                $this->host = null;\r
+            }\r
+        }\r
+\r
+        // validate scheme\r
+        // NOTE: It's not appropriate to check whether or not this\r
+        // scheme is in our registry, since a URIFilter may convert a\r
+        // URI that we don't allow into one we do.  So instead, we just\r
+        // check if the scheme can be dropped because there is no host\r
+        // and it is our default scheme.\r
+        if (!is_null($this->scheme) && is_null($this->host) || $this->host === '') {\r
+            // support for relative paths is pretty abysmal when the\r
+            // scheme is present, so axe it when possible\r
+            $def = $config->getDefinition('URI');\r
+            if ($def->defaultScheme === $this->scheme) {\r
+                $this->scheme = null;\r
+            }\r
+        }\r
+\r
+        // validate username\r
+        if (!is_null($this->userinfo)) {\r
+            $encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . ':');\r
+            $this->userinfo = $encoder->encode($this->userinfo);\r
+        }\r
+\r
+        // validate port\r
+        if (!is_null($this->port)) {\r
+            if ($this->port < 1 || $this->port > 65535) {\r
+                $this->port = null;\r
+            }\r
+        }\r
+\r
+        // validate path\r
+        $segments_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/');\r
+        if (!is_null($this->host)) { // this catches $this->host === ''\r
+            // path-abempty (hier and relative)\r
+            // http://www.example.com/my/path\r
+            // //www.example.com/my/path (looks odd, but works, and\r
+            //                            recognized by most browsers)\r
+            // (this set is valid or invalid on a scheme by scheme\r
+            // basis, so we'll deal with it later)\r
+            // file:///my/path\r
+            // ///my/path\r
+            $this->path = $segments_encoder->encode($this->path);\r
+        } elseif ($this->path !== '') {\r
+            if ($this->path[0] === '/') {\r
+                // path-absolute (hier and relative)\r
+                // http:/my/path\r
+                // /my/path\r
+                if (strlen($this->path) >= 2 && $this->path[1] === '/') {\r
+                    // This could happen if both the host gets stripped\r
+                    // out\r
+                    // http://my/path\r
+                    // //my/path\r
+                    $this->path = '';\r
+                } else {\r
+                    $this->path = $segments_encoder->encode($this->path);\r
+                }\r
+            } elseif (!is_null($this->scheme)) {\r
+                // path-rootless (hier)\r
+                // http:my/path\r
+                // Short circuit evaluation means we don't need to check nz\r
+                $this->path = $segments_encoder->encode($this->path);\r
+            } else {\r
+                // path-noscheme (relative)\r
+                // my/path\r
+                // (once again, not checking nz)\r
+                $segment_nc_encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . '@');\r
+                $c = strpos($this->path, '/');\r
+                if ($c !== false) {\r
+                    $this->path =\r
+                        $segment_nc_encoder->encode(substr($this->path, 0, $c)) .\r
+                        $segments_encoder->encode(substr($this->path, $c));\r
+                } else {\r
+                    $this->path = $segment_nc_encoder->encode($this->path);\r
+                }\r
+            }\r
+        } else {\r
+            // path-empty (hier and relative)\r
+            $this->path = ''; // just to be safe\r
+        }\r
+\r
+        // qf = query and fragment\r
+        $qf_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/?');\r
+\r
+        if (!is_null($this->query)) {\r
+            $this->query = $qf_encoder->encode($this->query);\r
+        }\r
+\r
+        if (!is_null($this->fragment)) {\r
+            $this->fragment = $qf_encoder->encode($this->fragment);\r
+        }\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Convert URI back to string\r
+     * @return string URI appropriate for output\r
+     */\r
+    public function toString()\r
+    {\r
+        // reconstruct authority\r
+        $authority = null;\r
+        // there is a rendering difference between a null authority\r
+        // (http:foo-bar) and an empty string authority\r
+        // (http:///foo-bar).\r
+        if (!is_null($this->host)) {\r
+            $authority = '';\r
+            if (!is_null($this->userinfo)) {\r
+                $authority .= $this->userinfo . '@';\r
+            }\r
+            $authority .= $this->host;\r
+            if (!is_null($this->port)) {\r
+                $authority .= ':' . $this->port;\r
+            }\r
+        }\r
+\r
+        // Reconstruct the result\r
+        // One might wonder about parsing quirks from browsers after\r
+        // this reconstruction.  Unfortunately, parsing behavior depends\r
+        // on what *scheme* was employed (file:///foo is handled *very*\r
+        // differently than http:///foo), so unfortunately we have to\r
+        // defer to the schemes to do the right thing.\r
+        $result = '';\r
+        if (!is_null($this->scheme)) {\r
+            $result .= $this->scheme . ':';\r
+        }\r
+        if (!is_null($authority)) {\r
+            $result .= '//' . $authority;\r
+        }\r
+        $result .= $this->path;\r
+        if (!is_null($this->query)) {\r
+            $result .= '?' . $this->query;\r
+        }\r
+        if (!is_null($this->fragment)) {\r
+            $result .= '#' . $this->fragment;\r
+        }\r
+\r
+        return $result;\r
+    }\r
+\r
+    /**\r
+     * Returns true if this URL might be considered a 'local' URL given\r
+     * the current context.  This is true when the host is null, or\r
+     * when it matches the host supplied to the configuration.\r
+     *\r
+     * Note that this does not do any scheme checking, so it is mostly\r
+     * only appropriate for metadata that doesn't care about protocol\r
+     * security.  isBenign is probably what you actually want.\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function isLocal($config, $context)\r
+    {\r
+        if ($this->host === null) {\r
+            return true;\r
+        }\r
+        $uri_def = $config->getDefinition('URI');\r
+        if ($uri_def->host === $this->host) {\r
+            return true;\r
+        }\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * Returns true if this URL should be considered a 'benign' URL,\r
+     * that is:\r
+     *\r
+     *      - It is a local URL (isLocal), and\r
+     *      - It has a equal or better level of security\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function isBenign($config, $context)\r
+    {\r
+        if (!$this->isLocal($config, $context)) {\r
+            return false;\r
+        }\r
+\r
+        $scheme_obj = $this->getSchemeObj($config, $context);\r
+        if (!$scheme_obj) {\r
+            return false;\r
+        } // conservative approach\r
+\r
+        $current_scheme_obj = $config->getDefinition('URI')->getDefaultScheme($config, $context);\r
+        if ($current_scheme_obj->secure) {\r
+            if (!$scheme_obj->secure) {\r
+                return false;\r
+            }\r
+        }\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_URIDefinition extends HTMLPurifier_Definition\r
+{\r
+\r
+    public $type = 'URI';\r
+    protected $filters = array();\r
+    protected $postFilters = array();\r
+    protected $registeredFilters = array();\r
+\r
+    /**\r
+     * HTMLPurifier_URI object of the base specified at %URI.Base\r
+     */\r
+    public $base;\r
+\r
+    /**\r
+     * String host to consider "home" base, derived off of $base\r
+     */\r
+    public $host;\r
+\r
+    /**\r
+     * Name of default scheme based on %URI.DefaultScheme and %URI.Base\r
+     */\r
+    public $defaultScheme;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternal());\r
+        $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternalResources());\r
+        $this->registerFilter(new HTMLPurifier_URIFilter_DisableResources());\r
+        $this->registerFilter(new HTMLPurifier_URIFilter_HostBlacklist());\r
+        $this->registerFilter(new HTMLPurifier_URIFilter_SafeIframe());\r
+        $this->registerFilter(new HTMLPurifier_URIFilter_MakeAbsolute());\r
+        $this->registerFilter(new HTMLPurifier_URIFilter_Munge());\r
+    }\r
+\r
+    public function registerFilter($filter)\r
+    {\r
+        $this->registeredFilters[$filter->name] = $filter;\r
+    }\r
+\r
+    public function addFilter($filter, $config)\r
+    {\r
+        $r = $filter->prepare($config);\r
+        if ($r === false) return; // null is ok, for backwards compat\r
+        if ($filter->post) {\r
+            $this->postFilters[$filter->name] = $filter;\r
+        } else {\r
+            $this->filters[$filter->name] = $filter;\r
+        }\r
+    }\r
+\r
+    protected function doSetup($config)\r
+    {\r
+        $this->setupMemberVariables($config);\r
+        $this->setupFilters($config);\r
+    }\r
+\r
+    protected function setupFilters($config)\r
+    {\r
+        foreach ($this->registeredFilters as $name => $filter) {\r
+            if ($filter->always_load) {\r
+                $this->addFilter($filter, $config);\r
+            } else {\r
+                $conf = $config->get('URI.' . $name);\r
+                if ($conf !== false && $conf !== null) {\r
+                    $this->addFilter($filter, $config);\r
+                }\r
+            }\r
+        }\r
+        unset($this->registeredFilters);\r
+    }\r
+\r
+    protected function setupMemberVariables($config)\r
+    {\r
+        $this->host = $config->get('URI.Host');\r
+        $base_uri = $config->get('URI.Base');\r
+        if (!is_null($base_uri)) {\r
+            $parser = new HTMLPurifier_URIParser();\r
+            $this->base = $parser->parse($base_uri);\r
+            $this->defaultScheme = $this->base->scheme;\r
+            if (is_null($this->host)) $this->host = $this->base->host;\r
+        }\r
+        if (is_null($this->defaultScheme)) $this->defaultScheme = $config->get('URI.DefaultScheme');\r
+    }\r
+\r
+    public function getDefaultScheme($config, $context)\r
+    {\r
+        return HTMLPurifier_URISchemeRegistry::instance()->getScheme($this->defaultScheme, $config, $context);\r
+    }\r
+\r
+    public function filter(&$uri, $config, $context)\r
+    {\r
+        foreach ($this->filters as $name => $f) {\r
+            $result = $f->filter($uri, $config, $context);\r
+            if (!$result) return false;\r
+        }\r
+        return true;\r
+    }\r
+\r
+    public function postFilter(&$uri, $config, $context)\r
+    {\r
+        foreach ($this->postFilters as $name => $f) {\r
+            $result = $f->filter($uri, $config, $context);\r
+            if (!$result) return false;\r
+        }\r
+        return true;\r
+    }\r
+\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Chainable filters for custom URI processing.\r
+ *\r
+ * These filters can perform custom actions on a URI filter object,\r
+ * including transformation or blacklisting.  A filter named Foo\r
+ * must have a corresponding configuration directive %URI.Foo,\r
+ * unless always_load is specified to be true.\r
+ *\r
+ * The following contexts may be available while URIFilters are being\r
+ * processed:\r
+ *\r
+ *      - EmbeddedURI: true if URI is an embedded resource that will\r
+ *        be loaded automatically on page load\r
+ *      - CurrentToken: a reference to the token that is currently\r
+ *        being processed\r
+ *      - CurrentAttr: the name of the attribute that is currently being\r
+ *        processed\r
+ *      - CurrentCSSProperty: the name of the CSS property that is\r
+ *        currently being processed (if applicable)\r
+ *\r
+ * @warning This filter is called before scheme object validation occurs.\r
+ *          Make sure, if you require a specific scheme object, you\r
+ *          you check that it exists. This allows filters to convert\r
+ *          proprietary URI schemes into regular ones.\r
+ */\r
+abstract class HTMLPurifier_URIFilter\r
+{\r
+\r
+    /**\r
+     * Unique identifier of filter.\r
+     * @type string\r
+     */\r
+    public $name;\r
+\r
+    /**\r
+     * True if this filter should be run after scheme validation.\r
+     * @type bool\r
+     */\r
+    public $post = false;\r
+\r
+    /**\r
+     * True if this filter should always be loaded.\r
+     * This permits a filter to be named Foo without the corresponding\r
+     * %URI.Foo directive existing.\r
+     * @type bool\r
+     */\r
+    public $always_load = false;\r
+\r
+    /**\r
+     * Performs initialization for the filter.  If the filter returns\r
+     * false, this means that it shouldn't be considered active.\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function prepare($config)\r
+    {\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Filter a URI object\r
+     * @param HTMLPurifier_URI $uri Reference to URI object variable\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool Whether or not to continue processing: false indicates\r
+     *         URL is no good, true indicates continue processing. Note that\r
+     *         all changes are committed directly on the URI object\r
+     */\r
+    abstract public function filter(&$uri, $config, $context);\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Parses a URI into the components and fragment identifier as specified\r
+ * by RFC 3986.\r
+ */\r
+class HTMLPurifier_URIParser\r
+{\r
+\r
+    /**\r
+     * Instance of HTMLPurifier_PercentEncoder to do normalization with.\r
+     */\r
+    protected $percentEncoder;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->percentEncoder = new HTMLPurifier_PercentEncoder();\r
+    }\r
+\r
+    /**\r
+     * Parses a URI.\r
+     * @param $uri string URI to parse\r
+     * @return HTMLPurifier_URI representation of URI. This representation has\r
+     *         not been validated yet and may not conform to RFC.\r
+     */\r
+    public function parse($uri)\r
+    {\r
+        $uri = $this->percentEncoder->normalize($uri);\r
+\r
+        // Regexp is as per Appendix B.\r
+        // Note that ["<>] are an addition to the RFC's recommended\r
+        // characters, because they represent external delimeters.\r
+        $r_URI = '!'.\r
+            '(([a-zA-Z0-9\.\+\-]+):)?'. // 2. Scheme\r
+            '(//([^/?#"<>]*))?'. // 4. Authority\r
+            '([^?#"<>]*)'.       // 5. Path\r
+            '(\?([^#"<>]*))?'.   // 7. Query\r
+            '(#([^"<>]*))?'.     // 8. Fragment\r
+            '!';\r
+\r
+        $matches = array();\r
+        $result = preg_match($r_URI, $uri, $matches);\r
+\r
+        if (!$result) return false; // *really* invalid URI\r
+\r
+        // seperate out parts\r
+        $scheme     = !empty($matches[1]) ? $matches[2] : null;\r
+        $authority  = !empty($matches[3]) ? $matches[4] : null;\r
+        $path       = $matches[5]; // always present, can be empty\r
+        $query      = !empty($matches[6]) ? $matches[7] : null;\r
+        $fragment   = !empty($matches[8]) ? $matches[9] : null;\r
+\r
+        // further parse authority\r
+        if ($authority !== null) {\r
+            $r_authority = "/^((.+?)@)?(\[[^\]]+\]|[^:]*)(:(\d*))?/";\r
+            $matches = array();\r
+            preg_match($r_authority, $authority, $matches);\r
+            $userinfo   = !empty($matches[1]) ? $matches[2] : null;\r
+            $host       = !empty($matches[3]) ? $matches[3] : '';\r
+            $port       = !empty($matches[4]) ? (int) $matches[5] : null;\r
+        } else {\r
+            $port = $host = $userinfo = null;\r
+        }\r
+\r
+        return new HTMLPurifier_URI(\r
+            $scheme, $userinfo, $host, $port, $path, $query, $fragment);\r
+    }\r
+\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validator for the components of a URI for a specific scheme\r
+ */\r
+abstract class HTMLPurifier_URIScheme\r
+{\r
+\r
+    /**\r
+     * Scheme's default port (integer). If an explicit port number is\r
+     * specified that coincides with the default port, it will be\r
+     * elided.\r
+     * @type int\r
+     */\r
+    public $default_port = null;\r
+\r
+    /**\r
+     * Whether or not URIs of this scheme are locatable by a browser\r
+     * http and ftp are accessible, while mailto and news are not.\r
+     * @type bool\r
+     */\r
+    public $browsable = false;\r
+\r
+    /**\r
+     * Whether or not data transmitted over this scheme is encrypted.\r
+     * https is secure, http is not.\r
+     * @type bool\r
+     */\r
+    public $secure = false;\r
+\r
+    /**\r
+     * Whether or not the URI always uses <hier_part>, resolves edge cases\r
+     * with making relative URIs absolute\r
+     * @type bool\r
+     */\r
+    public $hierarchical = false;\r
+\r
+    /**\r
+     * Whether or not the URI may omit a hostname when the scheme is\r
+     * explicitly specified, ala file:///path/to/file. As of writing,\r
+     * 'file' is the only scheme that browsers support his properly.\r
+     * @type bool\r
+     */\r
+    public $may_omit_host = false;\r
+\r
+    /**\r
+     * Validates the components of a URI for a specific scheme.\r
+     * @param HTMLPurifier_URI $uri Reference to a HTMLPurifier_URI object\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool success or failure\r
+     */\r
+    abstract public function doValidate(&$uri, $config, $context);\r
+\r
+    /**\r
+     * Public interface for validating components of a URI.  Performs a\r
+     * bunch of default actions. Don't overload this method.\r
+     * @param HTMLPurifier_URI $uri Reference to a HTMLPurifier_URI object\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool success or failure\r
+     */\r
+    public function validate(&$uri, $config, $context)\r
+    {\r
+        if ($this->default_port == $uri->port) {\r
+            $uri->port = null;\r
+        }\r
+        // kludge: browsers do funny things when the scheme but not the\r
+        // authority is set\r
+        if (!$this->may_omit_host &&\r
+            // if the scheme is present, a missing host is always in error\r
+            (!is_null($uri->scheme) && ($uri->host === '' || is_null($uri->host))) ||\r
+            // if the scheme is not present, a *blank* host is in error,\r
+            // since this translates into '///path' which most browsers\r
+            // interpret as being 'http://path'.\r
+            (is_null($uri->scheme) && $uri->host === '')\r
+        ) {\r
+            do {\r
+                if (is_null($uri->scheme)) {\r
+                    if (substr($uri->path, 0, 2) != '//') {\r
+                        $uri->host = null;\r
+                        break;\r
+                    }\r
+                    // URI is '////path', so we cannot nullify the\r
+                    // host to preserve semantics.  Try expanding the\r
+                    // hostname instead (fall through)\r
+                }\r
+                // first see if we can manually insert a hostname\r
+                $host = $config->get('URI.Host');\r
+                if (!is_null($host)) {\r
+                    $uri->host = $host;\r
+                } else {\r
+                    // we can't do anything sensible, reject the URL.\r
+                    return false;\r
+                }\r
+            } while (false);\r
+        }\r
+        return $this->doValidate($uri, $config, $context);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Registry for retrieving specific URI scheme validator objects.\r
+ */\r
+class HTMLPurifier_URISchemeRegistry\r
+{\r
+\r
+    /**\r
+     * Retrieve sole instance of the registry.\r
+     * @param HTMLPurifier_URISchemeRegistry $prototype Optional prototype to overload sole instance with,\r
+     *                   or bool true to reset to default registry.\r
+     * @return HTMLPurifier_URISchemeRegistry\r
+     * @note Pass a registry object $prototype with a compatible interface and\r
+     *       the function will copy it and return it all further times.\r
+     */\r
+    public static function instance($prototype = null)\r
+    {\r
+        static $instance = null;\r
+        if ($prototype !== null) {\r
+            $instance = $prototype;\r
+        } elseif ($instance === null || $prototype == true) {\r
+            $instance = new HTMLPurifier_URISchemeRegistry();\r
+        }\r
+        return $instance;\r
+    }\r
+\r
+    /**\r
+     * Cache of retrieved schemes.\r
+     * @type HTMLPurifier_URIScheme[]\r
+     */\r
+    protected $schemes = array();\r
+\r
+    /**\r
+     * Retrieves a scheme validator object\r
+     * @param string $scheme String scheme name like http or mailto\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return HTMLPurifier_URIScheme\r
+     */\r
+    public function getScheme($scheme, $config, $context)\r
+    {\r
+        if (!$config) {\r
+            $config = HTMLPurifier_Config::createDefault();\r
+        }\r
+\r
+        // important, otherwise attacker could include arbitrary file\r
+        $allowed_schemes = $config->get('URI.AllowedSchemes');\r
+        if (!$config->get('URI.OverrideAllowedSchemes') &&\r
+            !isset($allowed_schemes[$scheme])\r
+        ) {\r
+            return;\r
+        }\r
+\r
+        if (isset($this->schemes[$scheme])) {\r
+            return $this->schemes[$scheme];\r
+        }\r
+        if (!isset($allowed_schemes[$scheme])) {\r
+            return;\r
+        }\r
+\r
+        $class = 'HTMLPurifier_URIScheme_' . $scheme;\r
+        if (!class_exists($class)) {\r
+            return;\r
+        }\r
+        $this->schemes[$scheme] = new $class();\r
+        return $this->schemes[$scheme];\r
+    }\r
+\r
+    /**\r
+     * Registers a custom scheme to the cache, bypassing reflection.\r
+     * @param string $scheme Scheme name\r
+     * @param HTMLPurifier_URIScheme $scheme_obj\r
+     */\r
+    public function register($scheme, $scheme_obj)\r
+    {\r
+        $this->schemes[$scheme] = $scheme_obj;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Class for converting between different unit-lengths as specified by\r
+ * CSS.\r
+ */\r
+class HTMLPurifier_UnitConverter\r
+{\r
+\r
+    const ENGLISH = 1;\r
+    const METRIC = 2;\r
+    const DIGITAL = 3;\r
+\r
+    /**\r
+     * Units information array. Units are grouped into measuring systems\r
+     * (English, Metric), and are assigned an integer representing\r
+     * the conversion factor between that unit and the smallest unit in\r
+     * the system. Numeric indexes are actually magical constants that\r
+     * encode conversion data from one system to the next, with a O(n^2)\r
+     * constraint on memory (this is generally not a problem, since\r
+     * the number of measuring systems is small.)\r
+     */\r
+    protected static $units = array(\r
+        self::ENGLISH => array(\r
+            'px' => 3, // This is as per CSS 2.1 and Firefox. Your mileage may vary\r
+            'pt' => 4,\r
+            'pc' => 48,\r
+            'in' => 288,\r
+            self::METRIC => array('pt', '0.352777778', 'mm'),\r
+        ),\r
+        self::METRIC => array(\r
+            'mm' => 1,\r
+            'cm' => 10,\r
+            self::ENGLISH => array('mm', '2.83464567', 'pt'),\r
+        ),\r
+    );\r
+\r
+    /**\r
+     * Minimum bcmath precision for output.\r
+     * @type int\r
+     */\r
+    protected $outputPrecision;\r
+\r
+    /**\r
+     * Bcmath precision for internal calculations.\r
+     * @type int\r
+     */\r
+    protected $internalPrecision;\r
+\r
+    /**\r
+     * Whether or not BCMath is available.\r
+     * @type bool\r
+     */\r
+    private $bcmath;\r
+\r
+    public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false)\r
+    {\r
+        $this->outputPrecision = $output_precision;\r
+        $this->internalPrecision = $internal_precision;\r
+        $this->bcmath = !$force_no_bcmath && function_exists('bcmul');\r
+    }\r
+\r
+    /**\r
+     * Converts a length object of one unit into another unit.\r
+     * @param HTMLPurifier_Length $length\r
+     *      Instance of HTMLPurifier_Length to convert. You must validate()\r
+     *      it before passing it here!\r
+     * @param string $to_unit\r
+     *      Unit to convert to.\r
+     * @return HTMLPurifier_Length|bool\r
+     * @note\r
+     *      About precision: This conversion function pays very special\r
+     *      attention to the incoming precision of values and attempts\r
+     *      to maintain a number of significant figure. Results are\r
+     *      fairly accurate up to nine digits. Some caveats:\r
+     *          - If a number is zero-padded as a result of this significant\r
+     *            figure tracking, the zeroes will be eliminated.\r
+     *          - If a number contains less than four sigfigs ($outputPrecision)\r
+     *            and this causes some decimals to be excluded, those\r
+     *            decimals will be added on.\r
+     */\r
+    public function convert($length, $to_unit)\r
+    {\r
+        if (!$length->isValid()) {\r
+            return false;\r
+        }\r
+\r
+        $n = $length->getN();\r
+        $unit = $length->getUnit();\r
+\r
+        if ($n === '0' || $unit === false) {\r
+            return new HTMLPurifier_Length('0', false);\r
+        }\r
+\r
+        $state = $dest_state = false;\r
+        foreach (self::$units as $k => $x) {\r
+            if (isset($x[$unit])) {\r
+                $state = $k;\r
+            }\r
+            if (isset($x[$to_unit])) {\r
+                $dest_state = $k;\r
+            }\r
+        }\r
+        if (!$state || !$dest_state) {\r
+            return false;\r
+        }\r
+\r
+        // Some calculations about the initial precision of the number;\r
+        // this will be useful when we need to do final rounding.\r
+        $sigfigs = $this->getSigFigs($n);\r
+        if ($sigfigs < $this->outputPrecision) {\r
+            $sigfigs = $this->outputPrecision;\r
+        }\r
+\r
+        // BCMath's internal precision deals only with decimals. Use\r
+        // our default if the initial number has no decimals, or increase\r
+        // it by how ever many decimals, thus, the number of guard digits\r
+        // will always be greater than or equal to internalPrecision.\r
+        $log = (int)floor(log(abs($n), 10));\r
+        $cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision\r
+\r
+        for ($i = 0; $i < 2; $i++) {\r
+\r
+            // Determine what unit IN THIS SYSTEM we need to convert to\r
+            if ($dest_state === $state) {\r
+                // Simple conversion\r
+                $dest_unit = $to_unit;\r
+            } else {\r
+                // Convert to the smallest unit, pending a system shift\r
+                $dest_unit = self::$units[$state][$dest_state][0];\r
+            }\r
+\r
+            // Do the conversion if necessary\r
+            if ($dest_unit !== $unit) {\r
+                $factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp);\r
+                $n = $this->mul($n, $factor, $cp);\r
+                $unit = $dest_unit;\r
+            }\r
+\r
+            // Output was zero, so bail out early. Shouldn't ever happen.\r
+            if ($n === '') {\r
+                $n = '0';\r
+                $unit = $to_unit;\r
+                break;\r
+            }\r
+\r
+            // It was a simple conversion, so bail out\r
+            if ($dest_state === $state) {\r
+                break;\r
+            }\r
+\r
+            if ($i !== 0) {\r
+                // Conversion failed! Apparently, the system we forwarded\r
+                // to didn't have this unit. This should never happen!\r
+                return false;\r
+            }\r
+\r
+            // Pre-condition: $i == 0\r
+\r
+            // Perform conversion to next system of units\r
+            $n = $this->mul($n, self::$units[$state][$dest_state][1], $cp);\r
+            $unit = self::$units[$state][$dest_state][2];\r
+            $state = $dest_state;\r
+\r
+            // One more loop around to convert the unit in the new system.\r
+\r
+        }\r
+\r
+        // Post-condition: $unit == $to_unit\r
+        if ($unit !== $to_unit) {\r
+            return false;\r
+        }\r
+\r
+        // Useful for debugging:\r
+        //echo "<pre>n";\r
+        //echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n</pre>\n";\r
+\r
+        $n = $this->round($n, $sigfigs);\r
+        if (strpos($n, '.') !== false) {\r
+            $n = rtrim($n, '0');\r
+        }\r
+        $n = rtrim($n, '.');\r
+\r
+        return new HTMLPurifier_Length($n, $unit);\r
+    }\r
+\r
+    /**\r
+     * Returns the number of significant figures in a string number.\r
+     * @param string $n Decimal number\r
+     * @return int number of sigfigs\r
+     */\r
+    public function getSigFigs($n)\r
+    {\r
+        $n = ltrim($n, '0+-');\r
+        $dp = strpos($n, '.'); // decimal position\r
+        if ($dp === false) {\r
+            $sigfigs = strlen(rtrim($n, '0'));\r
+        } else {\r
+            $sigfigs = strlen(ltrim($n, '0.')); // eliminate extra decimal character\r
+            if ($dp !== 0) {\r
+                $sigfigs--;\r
+            }\r
+        }\r
+        return $sigfigs;\r
+    }\r
+\r
+    /**\r
+     * Adds two numbers, using arbitrary precision when available.\r
+     * @param string $s1\r
+     * @param string $s2\r
+     * @param int $scale\r
+     * @return string\r
+     */\r
+    private function add($s1, $s2, $scale)\r
+    {\r
+        if ($this->bcmath) {\r
+            return bcadd($s1, $s2, $scale);\r
+        } else {\r
+            return $this->scale((float)$s1 + (float)$s2, $scale);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Multiples two numbers, using arbitrary precision when available.\r
+     * @param string $s1\r
+     * @param string $s2\r
+     * @param int $scale\r
+     * @return string\r
+     */\r
+    private function mul($s1, $s2, $scale)\r
+    {\r
+        if ($this->bcmath) {\r
+            return bcmul($s1, $s2, $scale);\r
+        } else {\r
+            return $this->scale((float)$s1 * (float)$s2, $scale);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Divides two numbers, using arbitrary precision when available.\r
+     * @param string $s1\r
+     * @param string $s2\r
+     * @param int $scale\r
+     * @return string\r
+     */\r
+    private function div($s1, $s2, $scale)\r
+    {\r
+        if ($this->bcmath) {\r
+            return bcdiv($s1, $s2, $scale);\r
+        } else {\r
+            return $this->scale((float)$s1 / (float)$s2, $scale);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Rounds a number according to the number of sigfigs it should have,\r
+     * using arbitrary precision when available.\r
+     * @param float $n\r
+     * @param int $sigfigs\r
+     * @return string\r
+     */\r
+    private function round($n, $sigfigs)\r
+    {\r
+        $new_log = (int)floor(log(abs($n), 10)); // Number of digits left of decimal - 1\r
+        $rp = $sigfigs - $new_log - 1; // Number of decimal places needed\r
+        $neg = $n < 0 ? '-' : ''; // Negative sign\r
+        if ($this->bcmath) {\r
+            if ($rp >= 0) {\r
+                $n = bcadd($n, $neg . '0.' . str_repeat('0', $rp) . '5', $rp + 1);\r
+                $n = bcdiv($n, '1', $rp);\r
+            } else {\r
+                // This algorithm partially depends on the standardized\r
+                // form of numbers that comes out of bcmath.\r
+                $n = bcadd($n, $neg . '5' . str_repeat('0', $new_log - $sigfigs), 0);\r
+                $n = substr($n, 0, $sigfigs + strlen($neg)) . str_repeat('0', $new_log - $sigfigs + 1);\r
+            }\r
+            return $n;\r
+        } else {\r
+            return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Scales a float to $scale digits right of decimal point, like BCMath.\r
+     * @param float $r\r
+     * @param int $scale\r
+     * @return string\r
+     */\r
+    private function scale($r, $scale)\r
+    {\r
+        if ($scale < 0) {\r
+            // The f sprintf type doesn't support negative numbers, so we\r
+            // need to cludge things manually. First get the string.\r
+            $r = sprintf('%.0f', (float)$r);\r
+            // Due to floating point precision loss, $r will more than likely\r
+            // look something like 4652999999999.9234. We grab one more digit\r
+            // than we need to precise from $r and then use that to round\r
+            // appropriately.\r
+            $precise = (string)round(substr($r, 0, strlen($r) + $scale), -1);\r
+            // Now we return it, truncating the zero that was rounded off.\r
+            return substr($precise, 0, -1) . str_repeat('0', -$scale + 1);\r
+        }\r
+        return sprintf('%.' . $scale . 'f', (float)$r);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Parses string representations into their corresponding native PHP\r
+ * variable type. The base implementation does a simple type-check.\r
+ */\r
+class HTMLPurifier_VarParser\r
+{\r
+\r
+    const C_STRING = 1;\r
+    const ISTRING = 2;\r
+    const TEXT = 3;\r
+    const ITEXT = 4;\r
+    const C_INT = 5;\r
+    const C_FLOAT = 6;\r
+    const C_BOOL = 7;\r
+    const LOOKUP = 8;\r
+    const ALIST = 9;\r
+    const HASH = 10;\r
+    const C_MIXED = 11;\r
+\r
+    /**\r
+     * Lookup table of allowed types. Mainly for backwards compatibility, but\r
+     * also convenient for transforming string type names to the integer constants.\r
+     */\r
+    public static $types = array(\r
+        'string' => self::C_STRING,\r
+        'istring' => self::ISTRING,\r
+        'text' => self::TEXT,\r
+        'itext' => self::ITEXT,\r
+        'int' => self::C_INT,\r
+        'float' => self::C_FLOAT,\r
+        'bool' => self::C_BOOL,\r
+        'lookup' => self::LOOKUP,\r
+        'list' => self::ALIST,\r
+        'hash' => self::HASH,\r
+        'mixed' => self::C_MIXED\r
+    );\r
+\r
+    /**\r
+     * Lookup table of types that are string, and can have aliases or\r
+     * allowed value lists.\r
+     */\r
+    public static $stringTypes = array(\r
+        self::C_STRING => true,\r
+        self::ISTRING => true,\r
+        self::TEXT => true,\r
+        self::ITEXT => true,\r
+    );\r
+\r
+    /**\r
+     * Validate a variable according to type.\r
+     * It may return NULL as a valid type if $allow_null is true.\r
+     *\r
+     * @param mixed $var Variable to validate\r
+     * @param int $type Type of variable, see HTMLPurifier_VarParser->types\r
+     * @param bool $allow_null Whether or not to permit null as a value\r
+     * @return string Validated and type-coerced variable\r
+     * @throws HTMLPurifier_VarParserException\r
+     */\r
+    final public function parse($var, $type, $allow_null = false)\r
+    {\r
+        if (is_string($type)) {\r
+            if (!isset(HTMLPurifier_VarParser::$types[$type])) {\r
+                throw new HTMLPurifier_VarParserException("Invalid type '$type'");\r
+            } else {\r
+                $type = HTMLPurifier_VarParser::$types[$type];\r
+            }\r
+        }\r
+        $var = $this->parseImplementation($var, $type, $allow_null);\r
+        if ($allow_null && $var === null) {\r
+            return null;\r
+        }\r
+        // These are basic checks, to make sure nothing horribly wrong\r
+        // happened in our implementations.\r
+        switch ($type) {\r
+            case (self::C_STRING):\r
+            case (self::ISTRING):\r
+            case (self::TEXT):\r
+            case (self::ITEXT):\r
+                if (!is_string($var)) {\r
+                    break;\r
+                }\r
+                if ($type == self::ISTRING || $type == self::ITEXT) {\r
+                    $var = strtolower($var);\r
+                }\r
+                return $var;\r
+            case (self::C_INT):\r
+                if (!is_int($var)) {\r
+                    break;\r
+                }\r
+                return $var;\r
+            case (self::C_FLOAT):\r
+                if (!is_float($var)) {\r
+                    break;\r
+                }\r
+                return $var;\r
+            case (self::C_BOOL):\r
+                if (!is_bool($var)) {\r
+                    break;\r
+                }\r
+                return $var;\r
+            case (self::LOOKUP):\r
+            case (self::ALIST):\r
+            case (self::HASH):\r
+                if (!is_array($var)) {\r
+                    break;\r
+                }\r
+                if ($type === self::LOOKUP) {\r
+                    foreach ($var as $k) {\r
+                        if ($k !== true) {\r
+                            $this->error('Lookup table contains value other than true');\r
+                        }\r
+                    }\r
+                } elseif ($type === self::ALIST) {\r
+                    $keys = array_keys($var);\r
+                    if (array_keys($keys) !== $keys) {\r
+                        $this->error('Indices for list are not uniform');\r
+                    }\r
+                }\r
+                return $var;\r
+            case (self::C_MIXED):\r
+                return $var;\r
+            default:\r
+                $this->errorInconsistent(get_class($this), $type);\r
+        }\r
+        $this->errorGeneric($var, $type);\r
+    }\r
+\r
+    /**\r
+     * Actually implements the parsing. Base implementation does not\r
+     * do anything to $var. Subclasses should overload this!\r
+     * @param mixed $var\r
+     * @param int $type\r
+     * @param bool $allow_null\r
+     * @return string\r
+     */\r
+    protected function parseImplementation($var, $type, $allow_null)\r
+    {\r
+        return $var;\r
+    }\r
+\r
+    /**\r
+     * Throws an exception.\r
+     * @throws HTMLPurifier_VarParserException\r
+     */\r
+    protected function error($msg)\r
+    {\r
+        throw new HTMLPurifier_VarParserException($msg);\r
+    }\r
+\r
+    /**\r
+     * Throws an inconsistency exception.\r
+     * @note This should not ever be called. It would be called if we\r
+     *       extend the allowed values of HTMLPurifier_VarParser without\r
+     *       updating subclasses.\r
+     * @param string $class\r
+     * @param int $type\r
+     * @throws HTMLPurifier_Exception\r
+     */\r
+    protected function errorInconsistent($class, $type)\r
+    {\r
+        throw new HTMLPurifier_Exception(\r
+            "Inconsistency in $class: " . HTMLPurifier_VarParser::getTypeName($type) .\r
+            " not implemented"\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Generic error for if a type didn't work.\r
+     * @param mixed $var\r
+     * @param int $type\r
+     */\r
+    protected function errorGeneric($var, $type)\r
+    {\r
+        $vtype = gettype($var);\r
+        $this->error("Expected type " . HTMLPurifier_VarParser::getTypeName($type) . ", got $vtype");\r
+    }\r
+\r
+    /**\r
+     * @param int $type\r
+     * @return string\r
+     */\r
+    public static function getTypeName($type)\r
+    {\r
+        static $lookup;\r
+        if (!$lookup) {\r
+            // Lazy load the alternative lookup table\r
+            $lookup = array_flip(HTMLPurifier_VarParser::$types);\r
+        }\r
+        if (!isset($lookup[$type])) {\r
+            return 'unknown';\r
+        }\r
+        return $lookup[$type];\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Exception type for HTMLPurifier_VarParser\r
+ */\r
+class HTMLPurifier_VarParserException extends HTMLPurifier_Exception\r
+{\r
+\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * A zipper is a purely-functional data structure which contains\r
+ * a focus that can be efficiently manipulated.  It is known as\r
+ * a "one-hole context".  This mutable variant implements a zipper\r
+ * for a list as a pair of two arrays, laid out as follows:\r
+ *\r
+ *      Base list: 1 2 3 4 [ ] 6 7 8 9\r
+ *      Front list: 1 2 3 4\r
+ *      Back list: 9 8 7 6\r
+ *\r
+ * User is expected to keep track of the "current element" and properly\r
+ * fill it back in as necessary.  (ToDo: Maybe it's more user friendly\r
+ * to implicitly track the current element?)\r
+ *\r
+ * Nota bene: the current class gets confused if you try to store NULLs\r
+ * in the list.\r
+ */\r
+\r
+class HTMLPurifier_Zipper\r
+{\r
+    public $front, $back;\r
+\r
+    public function __construct($front, $back) {\r
+        $this->front = $front;\r
+        $this->back = $back;\r
+    }\r
+\r
+    /**\r
+     * Creates a zipper from an array, with a hole in the\r
+     * 0-index position.\r
+     * @param Array to zipper-ify.\r
+     * @return Tuple of zipper and element of first position.\r
+     */\r
+    static public function fromArray($array) {\r
+        $z = new self(array(), array_reverse($array));\r
+        $t = $z->delete(); // delete the "dummy hole"\r
+        return array($z, $t);\r
+    }\r
+\r
+    /**\r
+     * Convert zipper back into a normal array, optionally filling in\r
+     * the hole with a value. (Usually you should supply a $t, unless you\r
+     * are at the end of the array.)\r
+     */\r
+    public function toArray($t = NULL) {\r
+        $a = $this->front;\r
+        if ($t !== NULL) $a[] = $t;\r
+        for ($i = count($this->back)-1; $i >= 0; $i--) {\r
+            $a[] = $this->back[$i];\r
+        }\r
+        return $a;\r
+    }\r
+\r
+    /**\r
+     * Move hole to the next element.\r
+     * @param $t Element to fill hole with\r
+     * @return Original contents of new hole.\r
+     */\r
+    public function next($t) {\r
+        if ($t !== NULL) array_push($this->front, $t);\r
+        return empty($this->back) ? NULL : array_pop($this->back);\r
+    }\r
+\r
+    /**\r
+     * Iterated hole advancement.\r
+     * @param $t Element to fill hole with\r
+     * @param $i How many forward to advance hole\r
+     * @return Original contents of new hole, i away\r
+     */\r
+    public function advance($t, $n) {\r
+        for ($i = 0; $i < $n; $i++) {\r
+            $t = $this->next($t);\r
+        }\r
+        return $t;\r
+    }\r
+\r
+    /**\r
+     * Move hole to the previous element\r
+     * @param $t Element to fill hole with\r
+     * @return Original contents of new hole.\r
+     */\r
+    public function prev($t) {\r
+        if ($t !== NULL) array_push($this->back, $t);\r
+        return empty($this->front) ? NULL : array_pop($this->front);\r
+    }\r
+\r
+    /**\r
+     * Delete contents of current hole, shifting hole to\r
+     * next element.\r
+     * @return Original contents of new hole.\r
+     */\r
+    public function delete() {\r
+        return empty($this->back) ? NULL : array_pop($this->back);\r
+    }\r
+\r
+    /**\r
+     * Returns true if we are at the end of the list.\r
+     * @return bool\r
+     */\r
+    public function done() {\r
+        return empty($this->back);\r
+    }\r
+\r
+    /**\r
+     * Insert element before hole.\r
+     * @param Element to insert\r
+     */\r
+    public function insertBefore($t) {\r
+        if ($t !== NULL) array_push($this->front, $t);\r
+    }\r
+\r
+    /**\r
+     * Insert element after hole.\r
+     * @param Element to insert\r
+     */\r
+    public function insertAfter($t) {\r
+        if ($t !== NULL) array_push($this->back, $t);\r
+    }\r
+\r
+    /**\r
+     * Splice in multiple elements at hole.  Functional specification\r
+     * in terms of array_splice:\r
+     *\r
+     *      $arr1 = $arr;\r
+     *      $old1 = array_splice($arr1, $i, $delete, $replacement);\r
+     *\r
+     *      list($z, $t) = HTMLPurifier_Zipper::fromArray($arr);\r
+     *      $t = $z->advance($t, $i);\r
+     *      list($old2, $t) = $z->splice($t, $delete, $replacement);\r
+     *      $arr2 = $z->toArray($t);\r
+     *\r
+     *      assert($old1 === $old2);\r
+     *      assert($arr1 === $arr2);\r
+     *\r
+     * NB: the absolute index location after this operation is\r
+     * *unchanged!*\r
+     *\r
+     * @param Current contents of hole.\r
+     */\r
+    public function splice($t, $delete, $replacement) {\r
+        // delete\r
+        $old = array();\r
+        $r = $t;\r
+        for ($i = $delete; $i > 0; $i--) {\r
+            $old[] = $r;\r
+            $r = $this->delete();\r
+        }\r
+        // insert\r
+        for ($i = count($replacement)-1; $i >= 0; $i--) {\r
+            $this->insertAfter($r);\r
+            $r = $replacement[$i];\r
+        }\r
+        return array($old, $r);\r
+    }\r
+}\r
+
+\r
+\r
+/**\r
+ * Validates the HTML attribute style, otherwise known as CSS.\r
+ * @note We don't implement the whole CSS specification, so it might be\r
+ *       difficult to reuse this component in the context of validating\r
+ *       actual stylesheet declarations.\r
+ * @note If we were really serious about validating the CSS, we would\r
+ *       tokenize the styles and then parse the tokens. Obviously, we\r
+ *       are not doing that. Doing that could seriously harm performance,\r
+ *       but would make these components a lot more viable for a CSS\r
+ *       filtering solution.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @param string $css\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($css, $config, $context)\r
+    {\r
+        $css = $this->parseCDATA($css);\r
+\r
+        $definition = $config->getCSSDefinition();\r
+        $allow_duplicates = $config->get("CSS.AllowDuplicates");\r
+\r
+\r
+        // According to the CSS2.1 spec, the places where a\r
+        // non-delimiting semicolon can appear are in strings\r
+        // escape sequences.   So here is some dumb hack to\r
+        // handle quotes.\r
+        $len = strlen($css);\r
+        $accum = "";\r
+        $declarations = array();\r
+        $quoted = false;\r
+        for ($i = 0; $i < $len; $i++) {\r
+            $c = strcspn($css, ";'\"", $i);\r
+            $accum .= substr($css, $i, $c);\r
+            $i += $c;\r
+            if ($i == $len) break;\r
+            $d = $css[$i];\r
+            if ($quoted) {\r
+                $accum .= $d;\r
+                if ($d == $quoted) {\r
+                    $quoted = false;\r
+                }\r
+            } else {\r
+                if ($d == ";") {\r
+                    $declarations[] = $accum;\r
+                    $accum = "";\r
+                } else {\r
+                    $accum .= $d;\r
+                    $quoted = $d;\r
+                }\r
+            }\r
+        }\r
+        if ($accum != "") $declarations[] = $accum;\r
+\r
+        $propvalues = array();\r
+        $new_declarations = '';\r
+\r
+        /**\r
+         * Name of the current CSS property being validated.\r
+         */\r
+        $property = false;\r
+        $context->register('CurrentCSSProperty', $property);\r
+\r
+        foreach ($declarations as $declaration) {\r
+            if (!$declaration) {\r
+                continue;\r
+            }\r
+            if (!strpos($declaration, ':')) {\r
+                continue;\r
+            }\r
+            list($property, $value) = explode(':', $declaration, 2);\r
+            $property = trim($property);\r
+            $value = trim($value);\r
+            $ok = false;\r
+            do {\r
+                if (isset($definition->info[$property])) {\r
+                    $ok = true;\r
+                    break;\r
+                }\r
+                if (ctype_lower($property)) {\r
+                    break;\r
+                }\r
+                $property = strtolower($property);\r
+                if (isset($definition->info[$property])) {\r
+                    $ok = true;\r
+                    break;\r
+                }\r
+            } while (0);\r
+            if (!$ok) {\r
+                continue;\r
+            }\r
+            // inefficient call, since the validator will do this again\r
+            if (strtolower(trim($value)) !== 'inherit') {\r
+                // inherit works for everything (but only on the base property)\r
+                $result = $definition->info[$property]->validate(\r
+                    $value,\r
+                    $config,\r
+                    $context\r
+                );\r
+            } else {\r
+                $result = 'inherit';\r
+            }\r
+            if ($result === false) {\r
+                continue;\r
+            }\r
+            if ($allow_duplicates) {\r
+                $new_declarations .= "$property:$result;";\r
+            } else {\r
+                $propvalues[$property] = $result;\r
+            }\r
+        }\r
+\r
+        $context->destroy('CurrentCSSProperty');\r
+\r
+        // procedure does not write the new CSS simultaneously, so it's\r
+        // slightly inefficient, but it's the only way of getting rid of\r
+        // duplicates. Perhaps config to optimize it, but not now.\r
+\r
+        foreach ($propvalues as $prop => $value) {\r
+            $new_declarations .= "$prop:$value;";\r
+        }\r
+\r
+        return $new_declarations ? $new_declarations : false;\r
+\r
+    }\r
+\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Dummy AttrDef that mimics another AttrDef, BUT it generates clones\r
+ * with make.\r
+ */\r
+class HTMLPurifier_AttrDef_Clone extends HTMLPurifier_AttrDef\r
+{\r
+    /**\r
+     * What we're cloning.\r
+     * @type HTMLPurifier_AttrDef\r
+     */\r
+    protected $clone;\r
+\r
+    /**\r
+     * @param HTMLPurifier_AttrDef $clone\r
+     */\r
+    public function __construct($clone)\r
+    {\r
+        $this->clone = $clone;\r
+    }\r
+\r
+    /**\r
+     * @param string $v\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($v, $config, $context)\r
+    {\r
+        return $this->clone->validate($v, $config, $context);\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @return HTMLPurifier_AttrDef\r
+     */\r
+    public function make($string)\r
+    {\r
+        return clone $this->clone;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+// Enum = Enumerated\r
+/**\r
+ * Validates a keyword against a list of valid values.\r
+ * @warning The case-insensitive compare of this function uses PHP's\r
+ *          built-in strtolower and ctype_lower functions, which may\r
+ *          cause problems with international comparisons\r
+ */\r
+class HTMLPurifier_AttrDef_Enum extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Lookup table of valid values.\r
+     * @type array\r
+     * @todo Make protected\r
+     */\r
+    public $valid_values = array();\r
+\r
+    /**\r
+     * Bool indicating whether or not enumeration is case sensitive.\r
+     * @note In general this is always case insensitive.\r
+     */\r
+    protected $case_sensitive = false; // values according to W3C spec\r
+\r
+    /**\r
+     * @param array $valid_values List of valid values\r
+     * @param bool $case_sensitive Whether or not case sensitive\r
+     */\r
+    public function __construct($valid_values = array(), $case_sensitive = false)\r
+    {\r
+        $this->valid_values = array_flip($valid_values);\r
+        $this->case_sensitive = $case_sensitive;\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = trim($string);\r
+        if (!$this->case_sensitive) {\r
+            // we may want to do full case-insensitive libraries\r
+            $string = ctype_lower($string) ? $string : strtolower($string);\r
+        }\r
+        $result = isset($this->valid_values[$string]);\r
+\r
+        return $result ? $string : false;\r
+    }\r
+\r
+    /**\r
+     * @param string $string In form of comma-delimited list of case-insensitive\r
+     *      valid values. Example: "foo,bar,baz". Prepend "s:" to make\r
+     *      case sensitive\r
+     * @return HTMLPurifier_AttrDef_Enum\r
+     */\r
+    public function make($string)\r
+    {\r
+        if (strlen($string) > 2 && $string[0] == 's' && $string[1] == ':') {\r
+            $string = substr($string, 2);\r
+            $sensitive = true;\r
+        } else {\r
+            $sensitive = false;\r
+        }\r
+        $values = explode(',', $string);\r
+        return new HTMLPurifier_AttrDef_Enum($values, $sensitive);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates an integer.\r
+ * @note While this class was modeled off the CSS definition, no currently\r
+ *       allowed CSS uses this type.  The properties that do are: widows,\r
+ *       orphans, z-index, counter-increment, counter-reset.  Some of the\r
+ *       HTML attributes, however, find use for a non-negative version of this.\r
+ */\r
+class HTMLPurifier_AttrDef_Integer extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Whether or not negative values are allowed.\r
+     * @type bool\r
+     */\r
+    protected $negative = true;\r
+\r
+    /**\r
+     * Whether or not zero is allowed.\r
+     * @type bool\r
+     */\r
+    protected $zero = true;\r
+\r
+    /**\r
+     * Whether or not positive values are allowed.\r
+     * @type bool\r
+     */\r
+    protected $positive = true;\r
+\r
+    /**\r
+     * @param $negative Bool indicating whether or not negative values are allowed\r
+     * @param $zero Bool indicating whether or not zero is allowed\r
+     * @param $positive Bool indicating whether or not positive values are allowed\r
+     */\r
+    public function __construct($negative = true, $zero = true, $positive = true)\r
+    {\r
+        $this->negative = $negative;\r
+        $this->zero = $zero;\r
+        $this->positive = $positive;\r
+    }\r
+\r
+    /**\r
+     * @param string $integer\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($integer, $config, $context)\r
+    {\r
+        $integer = $this->parseCDATA($integer);\r
+        if ($integer === '') {\r
+            return false;\r
+        }\r
+\r
+        // we could possibly simply typecast it to integer, but there are\r
+        // certain fringe cases that must not return an integer.\r
+\r
+        // clip leading sign\r
+        if ($this->negative && $integer[0] === '-') {\r
+            $digits = substr($integer, 1);\r
+            if ($digits === '0') {\r
+                $integer = '0';\r
+            } // rm minus sign for zero\r
+        } elseif ($this->positive && $integer[0] === '+') {\r
+            $digits = $integer = substr($integer, 1); // rm unnecessary plus\r
+        } else {\r
+            $digits = $integer;\r
+        }\r
+\r
+        // test if it's numeric\r
+        if (!ctype_digit($digits)) {\r
+            return false;\r
+        }\r
+\r
+        // perform scope tests\r
+        if (!$this->zero && $integer == 0) {\r
+            return false;\r
+        }\r
+        if (!$this->positive && $integer > 0) {\r
+            return false;\r
+        }\r
+        if (!$this->negative && $integer < 0) {\r
+            return false;\r
+        }\r
+\r
+        return $integer;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates the HTML attribute lang, effectively a language code.\r
+ * @note Built according to RFC 3066, which obsoleted RFC 1766\r
+ */\r
+class HTMLPurifier_AttrDef_Lang extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = trim($string);\r
+        if (!$string) {\r
+            return false;\r
+        }\r
+\r
+        $subtags = explode('-', $string);\r
+        $num_subtags = count($subtags);\r
+\r
+        if ($num_subtags == 0) { // sanity check\r
+            return false;\r
+        }\r
+\r
+        // process primary subtag : $subtags[0]\r
+        $length = strlen($subtags[0]);\r
+        switch ($length) {\r
+            case 0:\r
+                return false;\r
+            case 1:\r
+                if (!($subtags[0] == 'x' || $subtags[0] == 'i')) {\r
+                    return false;\r
+                }\r
+                break;\r
+            case 2:\r
+            case 3:\r
+                if (!ctype_alpha($subtags[0])) {\r
+                    return false;\r
+                } elseif (!ctype_lower($subtags[0])) {\r
+                    $subtags[0] = strtolower($subtags[0]);\r
+                }\r
+                break;\r
+            default:\r
+                return false;\r
+        }\r
+\r
+        $new_string = $subtags[0];\r
+        if ($num_subtags == 1) {\r
+            return $new_string;\r
+        }\r
+\r
+        // process second subtag : $subtags[1]\r
+        $length = strlen($subtags[1]);\r
+        if ($length == 0 || ($length == 1 && $subtags[1] != 'x') || $length > 8 || !ctype_alnum($subtags[1])) {\r
+            return $new_string;\r
+        }\r
+        if (!ctype_lower($subtags[1])) {\r
+            $subtags[1] = strtolower($subtags[1]);\r
+        }\r
+\r
+        $new_string .= '-' . $subtags[1];\r
+        if ($num_subtags == 2) {\r
+            return $new_string;\r
+        }\r
+\r
+        // process all other subtags, index 2 and up\r
+        for ($i = 2; $i < $num_subtags; $i++) {\r
+            $length = strlen($subtags[$i]);\r
+            if ($length == 0 || $length > 8 || !ctype_alnum($subtags[$i])) {\r
+                return $new_string;\r
+            }\r
+            if (!ctype_lower($subtags[$i])) {\r
+                $subtags[$i] = strtolower($subtags[$i]);\r
+            }\r
+            $new_string .= '-' . $subtags[$i];\r
+        }\r
+        return $new_string;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Decorator that, depending on a token, switches between two definitions.\r
+ */\r
+class HTMLPurifier_AttrDef_Switch\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    protected $tag;\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrDef\r
+     */\r
+    protected $withTag;\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrDef\r
+     */\r
+    protected $withoutTag;\r
+\r
+    /**\r
+     * @param string $tag Tag name to switch upon\r
+     * @param HTMLPurifier_AttrDef $with_tag Call if token matches tag\r
+     * @param HTMLPurifier_AttrDef $without_tag Call if token doesn't match, or there is no token\r
+     */\r
+    public function __construct($tag, $with_tag, $without_tag)\r
+    {\r
+        $this->tag = $tag;\r
+        $this->withTag = $with_tag;\r
+        $this->withoutTag = $without_tag;\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $token = $context->get('CurrentToken', true);\r
+        if (!$token || $token->name !== $this->tag) {\r
+            return $this->withoutTag->validate($string, $config, $context);\r
+        } else {\r
+            return $this->withTag->validate($string, $config, $context);\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates arbitrary text according to the HTML spec.\r
+ */\r
+class HTMLPurifier_AttrDef_Text extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        return $this->parseCDATA($string);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates a URI as defined by RFC 3986.\r
+ * @note Scheme-specific mechanics deferred to HTMLPurifier_URIScheme\r
+ */\r
+class HTMLPurifier_AttrDef_URI extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @type HTMLPurifier_URIParser\r
+     */\r
+    protected $parser;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    protected $embedsResource;\r
+\r
+    /**\r
+     * @param bool $embeds_resource Does the URI here result in an extra HTTP request?\r
+     */\r
+    public function __construct($embeds_resource = false)\r
+    {\r
+        $this->parser = new HTMLPurifier_URIParser();\r
+        $this->embedsResource = (bool)$embeds_resource;\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @return HTMLPurifier_AttrDef_URI\r
+     */\r
+    public function make($string)\r
+    {\r
+        $embeds = ($string === 'embedded');\r
+        return new HTMLPurifier_AttrDef_URI($embeds);\r
+    }\r
+\r
+    /**\r
+     * @param string $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($uri, $config, $context)\r
+    {\r
+        if ($config->get('URI.Disable')) {\r
+            return false;\r
+        }\r
+\r
+        $uri = $this->parseCDATA($uri);\r
+\r
+        // parse the URI\r
+        $uri = $this->parser->parse($uri);\r
+        if ($uri === false) {\r
+            return false;\r
+        }\r
+\r
+        // add embedded flag to context for validators\r
+        $context->register('EmbeddedURI', $this->embedsResource);\r
+\r
+        $ok = false;\r
+        do {\r
+\r
+            // generic validation\r
+            $result = $uri->validate($config, $context);\r
+            if (!$result) {\r
+                break;\r
+            }\r
+\r
+            // chained filtering\r
+            $uri_def = $config->getDefinition('URI');\r
+            $result = $uri_def->filter($uri, $config, $context);\r
+            if (!$result) {\r
+                break;\r
+            }\r
+\r
+            // scheme-specific validation\r
+            $scheme_obj = $uri->getSchemeObj($config, $context);\r
+            if (!$scheme_obj) {\r
+                break;\r
+            }\r
+            if ($this->embedsResource && !$scheme_obj->browsable) {\r
+                break;\r
+            }\r
+            $result = $scheme_obj->validate($uri, $config, $context);\r
+            if (!$result) {\r
+                break;\r
+            }\r
+\r
+            // Post chained filtering\r
+            $result = $uri_def->postFilter($uri, $config, $context);\r
+            if (!$result) {\r
+                break;\r
+            }\r
+\r
+            // survived gauntlet\r
+            $ok = true;\r
+\r
+        } while (false);\r
+\r
+        $context->destroy('EmbeddedURI');\r
+        if (!$ok) {\r
+            return false;\r
+        }\r
+        // back to string\r
+        return $uri->toString();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates a number as defined by the CSS spec.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Number extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Indicates whether or not only positive values are allowed.\r
+     * @type bool\r
+     */\r
+    protected $non_negative = false;\r
+\r
+    /**\r
+     * @param bool $non_negative indicates whether negatives are forbidden\r
+     */\r
+    public function __construct($non_negative = false)\r
+    {\r
+        $this->non_negative = $non_negative;\r
+    }\r
+\r
+    /**\r
+     * @param string $number\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string|bool\r
+     * @warning Some contexts do not pass $config, $context. These\r
+     *          variables should not be used without checking HTMLPurifier_Length\r
+     */\r
+    public function validate($number, $config, $context)\r
+    {\r
+        $number = $this->parseCDATA($number);\r
+\r
+        if ($number === '') {\r
+            return false;\r
+        }\r
+        if ($number === '0') {\r
+            return '0';\r
+        }\r
+\r
+        $sign = '';\r
+        switch ($number[0]) {\r
+            case '-':\r
+                if ($this->non_negative) {\r
+                    return false;\r
+                }\r
+                $sign = '-';\r
+            case '+':\r
+                $number = substr($number, 1);\r
+        }\r
+\r
+        if (ctype_digit($number)) {\r
+            $number = ltrim($number, '0');\r
+            return $number ? $sign . $number : '0';\r
+        }\r
+\r
+        // Period is the only non-numeric character allowed\r
+        if (strpos($number, '.') === false) {\r
+            return false;\r
+        }\r
+\r
+        list($left, $right) = explode('.', $number, 2);\r
+\r
+        if ($left === '' && $right === '') {\r
+            return false;\r
+        }\r
+        if ($left !== '' && !ctype_digit($left)) {\r
+            return false;\r
+        }\r
+\r
+        $left = ltrim($left, '0');\r
+        $right = rtrim($right, '0');\r
+\r
+        if ($right === '') {\r
+            return $left ? $sign . $left : '0';\r
+        } elseif (!ctype_digit($right)) {\r
+            return false;\r
+        }\r
+        return $sign . $left . '.' . $right;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_AttrDef_CSS_AlphaValue extends HTMLPurifier_AttrDef_CSS_Number\r
+{\r
+\r
+    public function __construct()\r
+    {\r
+        parent::__construct(false); // opacity is non-negative, but we will clamp it\r
+    }\r
+\r
+    /**\r
+     * @param string $number\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     */\r
+    public function validate($number, $config, $context)\r
+    {\r
+        $result = parent::validate($number, $config, $context);\r
+        if ($result === false) {\r
+            return $result;\r
+        }\r
+        $float = (float)$result;\r
+        if ($float < 0.0) {\r
+            $result = '0';\r
+        }\r
+        if ($float > 1.0) {\r
+            $result = '1';\r
+        }\r
+        return $result;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates shorthand CSS property background.\r
+ * @warning Does not support url tokens that have internal spaces.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Background extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Local copy of component validators.\r
+     * @type HTMLPurifier_AttrDef[]\r
+     * @note See HTMLPurifier_AttrDef_Font::$info for a similar impl.\r
+     */\r
+    protected $info;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function __construct($config)\r
+    {\r
+        $def = $config->getCSSDefinition();\r
+        $this->info['background-color'] = $def->info['background-color'];\r
+        $this->info['background-image'] = $def->info['background-image'];\r
+        $this->info['background-repeat'] = $def->info['background-repeat'];\r
+        $this->info['background-attachment'] = $def->info['background-attachment'];\r
+        $this->info['background-position'] = $def->info['background-position'];\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        // regular pre-processing\r
+        $string = $this->parseCDATA($string);\r
+        if ($string === '') {\r
+            return false;\r
+        }\r
+\r
+        // munge rgb() decl if necessary\r
+        $string = $this->mungeRgb($string);\r
+\r
+        // assumes URI doesn't have spaces in it\r
+        $bits = explode(' ', $string); // bits to process\r
+\r
+        $caught = array();\r
+        $caught['color'] = false;\r
+        $caught['image'] = false;\r
+        $caught['repeat'] = false;\r
+        $caught['attachment'] = false;\r
+        $caught['position'] = false;\r
+\r
+        $i = 0; // number of catches\r
+\r
+        foreach ($bits as $bit) {\r
+            if ($bit === '') {\r
+                continue;\r
+            }\r
+            foreach ($caught as $key => $status) {\r
+                if ($key != 'position') {\r
+                    if ($status !== false) {\r
+                        continue;\r
+                    }\r
+                    $r = $this->info['background-' . $key]->validate($bit, $config, $context);\r
+                } else {\r
+                    $r = $bit;\r
+                }\r
+                if ($r === false) {\r
+                    continue;\r
+                }\r
+                if ($key == 'position') {\r
+                    if ($caught[$key] === false) {\r
+                        $caught[$key] = '';\r
+                    }\r
+                    $caught[$key] .= $r . ' ';\r
+                } else {\r
+                    $caught[$key] = $r;\r
+                }\r
+                $i++;\r
+                break;\r
+            }\r
+        }\r
+\r
+        if (!$i) {\r
+            return false;\r
+        }\r
+        if ($caught['position'] !== false) {\r
+            $caught['position'] = $this->info['background-position']->\r
+                validate($caught['position'], $config, $context);\r
+        }\r
+\r
+        $ret = array();\r
+        foreach ($caught as $value) {\r
+            if ($value === false) {\r
+                continue;\r
+            }\r
+            $ret[] = $value;\r
+        }\r
+\r
+        if (empty($ret)) {\r
+            return false;\r
+        }\r
+        return implode(' ', $ret);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/* W3C says:\r
+    [ // adjective and number must be in correct order, even if\r
+      // you could switch them without introducing ambiguity.\r
+      // some browsers support that syntax\r
+        [\r
+            <percentage> | <length> | left | center | right\r
+        ]\r
+        [\r
+            <percentage> | <length> | top | center | bottom\r
+        ]?\r
+    ] |\r
+    [ // this signifies that the vertical and horizontal adjectives\r
+      // can be arbitrarily ordered, however, there can only be two,\r
+      // one of each, or none at all\r
+        [\r
+            left | center | right\r
+        ] ||\r
+        [\r
+            top | center | bottom\r
+        ]\r
+    ]\r
+    top, left = 0%\r
+    center, (none) = 50%\r
+    bottom, right = 100%\r
+*/\r
+\r
+/* QuirksMode says:\r
+    keyword + length/percentage must be ordered correctly, as per W3C\r
+\r
+    Internet Explorer and Opera, however, support arbitrary ordering. We\r
+    should fix it up.\r
+\r
+    Minor issue though, not strictly necessary.\r
+*/\r
+\r
+// control freaks may appreciate the ability to convert these to\r
+// percentages or something, but it's not necessary\r
+\r
+/**\r
+ * Validates the value of background-position.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_BackgroundPosition extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrDef_CSS_Length\r
+     */\r
+    protected $length;\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrDef_CSS_Percentage\r
+     */\r
+    protected $percentage;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->length = new HTMLPurifier_AttrDef_CSS_Length();\r
+        $this->percentage = new HTMLPurifier_AttrDef_CSS_Percentage();\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = $this->parseCDATA($string);\r
+        $bits = explode(' ', $string);\r
+\r
+        $keywords = array();\r
+        $keywords['h'] = false; // left, right\r
+        $keywords['v'] = false; // top, bottom\r
+        $keywords['ch'] = false; // center (first word)\r
+        $keywords['cv'] = false; // center (second word)\r
+        $measures = array();\r
+\r
+        $i = 0;\r
+\r
+        $lookup = array(\r
+            'top' => 'v',\r
+            'bottom' => 'v',\r
+            'left' => 'h',\r
+            'right' => 'h',\r
+            'center' => 'c'\r
+        );\r
+\r
+        foreach ($bits as $bit) {\r
+            if ($bit === '') {\r
+                continue;\r
+            }\r
+\r
+            // test for keyword\r
+            $lbit = ctype_lower($bit) ? $bit : strtolower($bit);\r
+            if (isset($lookup[$lbit])) {\r
+                $status = $lookup[$lbit];\r
+                if ($status == 'c') {\r
+                    if ($i == 0) {\r
+                        $status = 'ch';\r
+                    } else {\r
+                        $status = 'cv';\r
+                    }\r
+                }\r
+                $keywords[$status] = $lbit;\r
+                $i++;\r
+            }\r
+\r
+            // test for length\r
+            $r = $this->length->validate($bit, $config, $context);\r
+            if ($r !== false) {\r
+                $measures[] = $r;\r
+                $i++;\r
+            }\r
+\r
+            // test for percentage\r
+            $r = $this->percentage->validate($bit, $config, $context);\r
+            if ($r !== false) {\r
+                $measures[] = $r;\r
+                $i++;\r
+            }\r
+        }\r
+\r
+        if (!$i) {\r
+            return false;\r
+        } // no valid values were caught\r
+\r
+        $ret = array();\r
+\r
+        // first keyword\r
+        if ($keywords['h']) {\r
+            $ret[] = $keywords['h'];\r
+        } elseif ($keywords['ch']) {\r
+            $ret[] = $keywords['ch'];\r
+            $keywords['cv'] = false; // prevent re-use: center = center center\r
+        } elseif (count($measures)) {\r
+            $ret[] = array_shift($measures);\r
+        }\r
+\r
+        if ($keywords['v']) {\r
+            $ret[] = $keywords['v'];\r
+        } elseif ($keywords['cv']) {\r
+            $ret[] = $keywords['cv'];\r
+        } elseif (count($measures)) {\r
+            $ret[] = array_shift($measures);\r
+        }\r
+\r
+        if (empty($ret)) {\r
+            return false;\r
+        }\r
+        return implode(' ', $ret);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates the border property as defined by CSS.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Border extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Local copy of properties this property is shorthand for.\r
+     * @type HTMLPurifier_AttrDef[]\r
+     */\r
+    protected $info = array();\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function __construct($config)\r
+    {\r
+        $def = $config->getCSSDefinition();\r
+        $this->info['border-width'] = $def->info['border-width'];\r
+        $this->info['border-style'] = $def->info['border-style'];\r
+        $this->info['border-top-color'] = $def->info['border-top-color'];\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = $this->parseCDATA($string);\r
+        $string = $this->mungeRgb($string);\r
+        $bits = explode(' ', $string);\r
+        $done = array(); // segments we've finished\r
+        $ret = ''; // return value\r
+        foreach ($bits as $bit) {\r
+            foreach ($this->info as $propname => $validator) {\r
+                if (isset($done[$propname])) {\r
+                    continue;\r
+                }\r
+                $r = $validator->validate($bit, $config, $context);\r
+                if ($r !== false) {\r
+                    $ret .= $r . ' ';\r
+                    $done[$propname] = true;\r
+                    break;\r
+                }\r
+            }\r
+        }\r
+        return rtrim($ret);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates Color as defined by CSS.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Color extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrDef_CSS_AlphaValue\r
+     */\r
+    protected $alpha;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->alpha = new HTMLPurifier_AttrDef_CSS_AlphaValue();\r
+    }\r
+\r
+    /**\r
+     * @param string $color\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($color, $config, $context)\r
+    {\r
+        static $colors = null;\r
+        if ($colors === null) {\r
+            $colors = $config->get('Core.ColorKeywords');\r
+        }\r
+\r
+        $color = trim($color);\r
+        if ($color === '') {\r
+            return false;\r
+        }\r
+\r
+        $lower = strtolower($color);\r
+        if (isset($colors[$lower])) {\r
+            return $colors[$lower];\r
+        }\r
+\r
+        if (preg_match('#(rgb|rgba|hsl|hsla)\(#', $color, $matches) === 1) {\r
+            $length = strlen($color);\r
+            if (strpos($color, ')') !== $length - 1) {\r
+                return false;\r
+            }\r
+\r
+            // get used function : rgb, rgba, hsl or hsla\r
+            $function = $matches[1];\r
+\r
+            $parameters_size = 3;\r
+            $alpha_channel = false;\r
+            if (substr($function, -1) === 'a') {\r
+                $parameters_size = 4;\r
+                $alpha_channel = true;\r
+            }\r
+\r
+            /*\r
+             * Allowed types for values :\r
+             * parameter_position => [type => max_value]\r
+             */\r
+            $allowed_types = array(\r
+                1 => array('percentage' => 100, 'integer' => 255),\r
+                2 => array('percentage' => 100, 'integer' => 255),\r
+                3 => array('percentage' => 100, 'integer' => 255),\r
+            );\r
+            $allow_different_types = false;\r
+\r
+            if (strpos($function, 'hsl') !== false) {\r
+                $allowed_types = array(\r
+                    1 => array('integer' => 360),\r
+                    2 => array('percentage' => 100),\r
+                    3 => array('percentage' => 100),\r
+                );\r
+                $allow_different_types = true;\r
+            }\r
+\r
+            $values = trim(str_replace($function, '', $color), ' ()');\r
+\r
+            $parts = explode(',', $values);\r
+            if (count($parts) !== $parameters_size) {\r
+                return false;\r
+            }\r
+\r
+            $type = false;\r
+            $new_parts = array();\r
+            $i = 0;\r
+\r
+            foreach ($parts as $part) {\r
+                $i++;\r
+                $part = trim($part);\r
+\r
+                if ($part === '') {\r
+                    return false;\r
+                }\r
+\r
+                // different check for alpha channel\r
+                if ($alpha_channel === true && $i === count($parts)) {\r
+                    $result = $this->alpha->validate($part, $config, $context);\r
+\r
+                    if ($result === false) {\r
+                        return false;\r
+                    }\r
+\r
+                    $new_parts[] = (string)$result;\r
+                    continue;\r
+                }\r
+\r
+                if (substr($part, -1) === '%') {\r
+                    $current_type = 'percentage';\r
+                } else {\r
+                    $current_type = 'integer';\r
+                }\r
+\r
+                if (!array_key_exists($current_type, $allowed_types[$i])) {\r
+                    return false;\r
+                }\r
+\r
+                if (!$type) {\r
+                    $type = $current_type;\r
+                }\r
+\r
+                if ($allow_different_types === false && $type != $current_type) {\r
+                    return false;\r
+                }\r
+\r
+                $max_value = $allowed_types[$i][$current_type];\r
+\r
+                if ($current_type == 'integer') {\r
+                    // Return value between range 0 -> $max_value\r
+                    $new_parts[] = (int)max(min($part, $max_value), 0);\r
+                } elseif ($current_type == 'percentage') {\r
+                    $new_parts[] = (float)max(min(rtrim($part, '%'), $max_value), 0) . '%';\r
+                }\r
+            }\r
+\r
+            $new_values = implode(',', $new_parts);\r
+\r
+            $color = $function . '(' . $new_values . ')';\r
+        } else {\r
+            // hexadecimal handling\r
+            if ($color[0] === '#') {\r
+                $hex = substr($color, 1);\r
+            } else {\r
+                $hex = $color;\r
+                $color = '#' . $color;\r
+            }\r
+            $length = strlen($hex);\r
+            if ($length !== 3 && $length !== 6) {\r
+                return false;\r
+            }\r
+            if (!ctype_xdigit($hex)) {\r
+                return false;\r
+            }\r
+        }\r
+        return $color;\r
+    }\r
+\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Allows multiple validators to attempt to validate attribute.\r
+ *\r
+ * Composite is just what it sounds like: a composite of many validators.\r
+ * This means that multiple HTMLPurifier_AttrDef objects will have a whack\r
+ * at the string.  If one of them passes, that's what is returned.  This is\r
+ * especially useful for CSS values, which often are a choice between\r
+ * an enumerated set of predefined values or a flexible data type.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Composite extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * List of objects that may process strings.\r
+     * @type HTMLPurifier_AttrDef[]\r
+     * @todo Make protected\r
+     */\r
+    public $defs;\r
+\r
+    /**\r
+     * @param HTMLPurifier_AttrDef[] $defs List of HTMLPurifier_AttrDef objects\r
+     */\r
+    public function __construct($defs)\r
+    {\r
+        $this->defs = $defs;\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        foreach ($this->defs as $i => $def) {\r
+            $result = $this->defs[$i]->validate($string, $config, $context);\r
+            if ($result !== false) {\r
+                return $result;\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Decorator which enables CSS properties to be disabled for specific elements.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_DenyElementDecorator extends HTMLPurifier_AttrDef\r
+{\r
+    /**\r
+     * @type HTMLPurifier_AttrDef\r
+     */\r
+    public $def;\r
+    /**\r
+     * @type string\r
+     */\r
+    public $element;\r
+\r
+    /**\r
+     * @param HTMLPurifier_AttrDef $def Definition to wrap\r
+     * @param string $element Element to deny\r
+     */\r
+    public function __construct($def, $element)\r
+    {\r
+        $this->def = $def;\r
+        $this->element = $element;\r
+    }\r
+\r
+    /**\r
+     * Checks if CurrentToken is set and equal to $this->element\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $token = $context->get('CurrentToken', true);\r
+        if ($token && $token->name == $this->element) {\r
+            return false;\r
+        }\r
+        return $this->def->validate($string, $config, $context);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Microsoft's proprietary filter: CSS property\r
+ * @note Currently supports the alpha filter. In the future, this will\r
+ *       probably need an extensible framework\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Filter extends HTMLPurifier_AttrDef\r
+{\r
+    /**\r
+     * @type HTMLPurifier_AttrDef_Integer\r
+     */\r
+    protected $intValidator;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->intValidator = new HTMLPurifier_AttrDef_Integer();\r
+    }\r
+\r
+    /**\r
+     * @param string $value\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($value, $config, $context)\r
+    {\r
+        $value = $this->parseCDATA($value);\r
+        if ($value === 'none') {\r
+            return $value;\r
+        }\r
+        // if we looped this we could support multiple filters\r
+        $function_length = strcspn($value, '(');\r
+        $function = trim(substr($value, 0, $function_length));\r
+        if ($function !== 'alpha' &&\r
+            $function !== 'Alpha' &&\r
+            $function !== 'progid:DXImageTransform.Microsoft.Alpha'\r
+        ) {\r
+            return false;\r
+        }\r
+        $cursor = $function_length + 1;\r
+        $parameters_length = strcspn($value, ')', $cursor);\r
+        $parameters = substr($value, $cursor, $parameters_length);\r
+        $params = explode(',', $parameters);\r
+        $ret_params = array();\r
+        $lookup = array();\r
+        foreach ($params as $param) {\r
+            list($key, $value) = explode('=', $param);\r
+            $key = trim($key);\r
+            $value = trim($value);\r
+            if (isset($lookup[$key])) {\r
+                continue;\r
+            }\r
+            if ($key !== 'opacity') {\r
+                continue;\r
+            }\r
+            $value = $this->intValidator->validate($value, $config, $context);\r
+            if ($value === false) {\r
+                continue;\r
+            }\r
+            $int = (int)$value;\r
+            if ($int > 100) {\r
+                $value = '100';\r
+            }\r
+            if ($int < 0) {\r
+                $value = '0';\r
+            }\r
+            $ret_params[] = "$key=$value";\r
+            $lookup[$key] = true;\r
+        }\r
+        $ret_parameters = implode(',', $ret_params);\r
+        $ret_function = "$function($ret_parameters)";\r
+        return $ret_function;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates shorthand CSS property font.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Font extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Local copy of validators\r
+     * @type HTMLPurifier_AttrDef[]\r
+     * @note If we moved specific CSS property definitions to their own\r
+     *       classes instead of having them be assembled at run time by\r
+     *       CSSDefinition, this wouldn't be necessary.  We'd instantiate\r
+     *       our own copies.\r
+     */\r
+    protected $info = array();\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function __construct($config)\r
+    {\r
+        $def = $config->getCSSDefinition();\r
+        $this->info['font-style'] = $def->info['font-style'];\r
+        $this->info['font-variant'] = $def->info['font-variant'];\r
+        $this->info['font-weight'] = $def->info['font-weight'];\r
+        $this->info['font-size'] = $def->info['font-size'];\r
+        $this->info['line-height'] = $def->info['line-height'];\r
+        $this->info['font-family'] = $def->info['font-family'];\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        static $system_fonts = array(\r
+            'caption' => true,\r
+            'icon' => true,\r
+            'menu' => true,\r
+            'message-box' => true,\r
+            'small-caption' => true,\r
+            'status-bar' => true\r
+        );\r
+\r
+        // regular pre-processing\r
+        $string = $this->parseCDATA($string);\r
+        if ($string === '') {\r
+            return false;\r
+        }\r
+\r
+        // check if it's one of the keywords\r
+        $lowercase_string = strtolower($string);\r
+        if (isset($system_fonts[$lowercase_string])) {\r
+            return $lowercase_string;\r
+        }\r
+\r
+        $bits = explode(' ', $string); // bits to process\r
+        $stage = 0; // this indicates what we're looking for\r
+        $caught = array(); // which stage 0 properties have we caught?\r
+        $stage_1 = array('font-style', 'font-variant', 'font-weight');\r
+        $final = ''; // output\r
+\r
+        for ($i = 0, $size = count($bits); $i < $size; $i++) {\r
+            if ($bits[$i] === '') {\r
+                continue;\r
+            }\r
+            switch ($stage) {\r
+                case 0: // attempting to catch font-style, font-variant or font-weight\r
+                    foreach ($stage_1 as $validator_name) {\r
+                        if (isset($caught[$validator_name])) {\r
+                            continue;\r
+                        }\r
+                        $r = $this->info[$validator_name]->validate(\r
+                            $bits[$i],\r
+                            $config,\r
+                            $context\r
+                        );\r
+                        if ($r !== false) {\r
+                            $final .= $r . ' ';\r
+                            $caught[$validator_name] = true;\r
+                            break;\r
+                        }\r
+                    }\r
+                    // all three caught, continue on\r
+                    if (count($caught) >= 3) {\r
+                        $stage = 1;\r
+                    }\r
+                    if ($r !== false) {\r
+                        break;\r
+                    }\r
+                case 1: // attempting to catch font-size and perhaps line-height\r
+                    $found_slash = false;\r
+                    if (strpos($bits[$i], '/') !== false) {\r
+                        list($font_size, $line_height) =\r
+                            explode('/', $bits[$i]);\r
+                        if ($line_height === '') {\r
+                            // ooh, there's a space after the slash!\r
+                            $line_height = false;\r
+                            $found_slash = true;\r
+                        }\r
+                    } else {\r
+                        $font_size = $bits[$i];\r
+                        $line_height = false;\r
+                    }\r
+                    $r = $this->info['font-size']->validate(\r
+                        $font_size,\r
+                        $config,\r
+                        $context\r
+                    );\r
+                    if ($r !== false) {\r
+                        $final .= $r;\r
+                        // attempt to catch line-height\r
+                        if ($line_height === false) {\r
+                            // we need to scroll forward\r
+                            for ($j = $i + 1; $j < $size; $j++) {\r
+                                if ($bits[$j] === '') {\r
+                                    continue;\r
+                                }\r
+                                if ($bits[$j] === '/') {\r
+                                    if ($found_slash) {\r
+                                        return false;\r
+                                    } else {\r
+                                        $found_slash = true;\r
+                                        continue;\r
+                                    }\r
+                                }\r
+                                $line_height = $bits[$j];\r
+                                break;\r
+                            }\r
+                        } else {\r
+                            // slash already found\r
+                            $found_slash = true;\r
+                            $j = $i;\r
+                        }\r
+                        if ($found_slash) {\r
+                            $i = $j;\r
+                            $r = $this->info['line-height']->validate(\r
+                                $line_height,\r
+                                $config,\r
+                                $context\r
+                            );\r
+                            if ($r !== false) {\r
+                                $final .= '/' . $r;\r
+                            }\r
+                        }\r
+                        $final .= ' ';\r
+                        $stage = 2;\r
+                        break;\r
+                    }\r
+                    return false;\r
+                case 2: // attempting to catch font-family\r
+                    $font_family =\r
+                        implode(' ', array_slice($bits, $i, $size - $i));\r
+                    $r = $this->info['font-family']->validate(\r
+                        $font_family,\r
+                        $config,\r
+                        $context\r
+                    );\r
+                    if ($r !== false) {\r
+                        $final .= $r . ' ';\r
+                        // processing completed successfully\r
+                        return rtrim($final);\r
+                    }\r
+                    return false;\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates a font family list according to CSS spec\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_FontFamily extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    protected $mask = null;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->mask = '_- ';\r
+        for ($c = 'a'; $c <= 'z'; $c++) {\r
+            $this->mask .= $c;\r
+        }\r
+        for ($c = 'A'; $c <= 'Z'; $c++) {\r
+            $this->mask .= $c;\r
+        }\r
+        for ($c = '0'; $c <= '9'; $c++) {\r
+            $this->mask .= $c;\r
+        } // cast-y, but should be fine\r
+        // special bytes used by UTF-8\r
+        for ($i = 0x80; $i <= 0xFF; $i++) {\r
+            // We don't bother excluding invalid bytes in this range,\r
+            // because the our restriction of well-formed UTF-8 will\r
+            // prevent these from ever occurring.\r
+            $this->mask .= chr($i);\r
+        }\r
+\r
+        /*\r
+            PHP's internal strcspn implementation is\r
+            O(length of string * length of mask), making it inefficient\r
+            for large masks.  However, it's still faster than\r
+            preg_match 8)\r
+          for (p = s1;;) {\r
+            spanp = s2;\r
+            do {\r
+              if (*spanp == c || p == s1_end) {\r
+                return p - s1;\r
+              }\r
+            } while (spanp++ < (s2_end - 1));\r
+            c = *++p;\r
+          }\r
+         */\r
+        // possible optimization: invert the mask.\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        static $generic_names = array(\r
+            'serif' => true,\r
+            'sans-serif' => true,\r
+            'monospace' => true,\r
+            'fantasy' => true,\r
+            'cursive' => true\r
+        );\r
+        $allowed_fonts = $config->get('CSS.AllowedFonts');\r
+\r
+        // assume that no font names contain commas in them\r
+        $fonts = explode(',', $string);\r
+        $final = '';\r
+        foreach ($fonts as $font) {\r
+            $font = trim($font);\r
+            if ($font === '') {\r
+                continue;\r
+            }\r
+            // match a generic name\r
+            if (isset($generic_names[$font])) {\r
+                if ($allowed_fonts === null || isset($allowed_fonts[$font])) {\r
+                    $final .= $font . ', ';\r
+                }\r
+                continue;\r
+            }\r
+            // match a quoted name\r
+            if ($font[0] === '"' || $font[0] === "'") {\r
+                $length = strlen($font);\r
+                if ($length <= 2) {\r
+                    continue;\r
+                }\r
+                $quote = $font[0];\r
+                if ($font[$length - 1] !== $quote) {\r
+                    continue;\r
+                }\r
+                $font = substr($font, 1, $length - 2);\r
+            }\r
+\r
+            $font = $this->expandCSSEscape($font);\r
+\r
+            // $font is a pure representation of the font name\r
+\r
+            if ($allowed_fonts !== null && !isset($allowed_fonts[$font])) {\r
+                continue;\r
+            }\r
+\r
+            if (ctype_alnum($font) && $font !== '') {\r
+                // very simple font, allow it in unharmed\r
+                $final .= $font . ', ';\r
+                continue;\r
+            }\r
+\r
+            // bugger out on whitespace.  form feed (0C) really\r
+            // shouldn't show up regardless\r
+            $font = str_replace(array("\n", "\t", "\r", "\x0C"), ' ', $font);\r
+\r
+            // Here, there are various classes of characters which need\r
+            // to be treated differently:\r
+            //  - Alphanumeric characters are essentially safe.  We\r
+            //    handled these above.\r
+            //  - Spaces require quoting, though most parsers will do\r
+            //    the right thing if there aren't any characters that\r
+            //    can be misinterpreted\r
+            //  - Dashes rarely occur, but they fairly unproblematic\r
+            //    for parsing/rendering purposes.\r
+            //  The above characters cover the majority of Western font\r
+            //  names.\r
+            //  - Arbitrary Unicode characters not in ASCII.  Because\r
+            //    most parsers give little thought to Unicode, treatment\r
+            //    of these codepoints is basically uniform, even for\r
+            //    punctuation-like codepoints.  These characters can\r
+            //    show up in non-Western pages and are supported by most\r
+            //    major browsers, for example: "MS 明朝" is a\r
+            //    legitimate font-name\r
+            //    <http://ja.wikipedia.org/wiki/MS_明朝>.  See\r
+            //    the CSS3 spec for more examples:\r
+            //    <http://www.w3.org/TR/2011/WD-css3-fonts-20110324/localizedfamilynames.png>\r
+            //    You can see live samples of these on the Internet:\r
+            //    <http://www.google.co.jp/search?q=font-family+MS+明朝|ゴシック>\r
+            //    However, most of these fonts have ASCII equivalents:\r
+            //    for example, 'MS Mincho', and it's considered\r
+            //    professional to use ASCII font names instead of\r
+            //    Unicode font names.  Thanks Takeshi Terada for\r
+            //    providing this information.\r
+            //  The following characters, to my knowledge, have not been\r
+            //  used to name font names.\r
+            //  - Single quote.  While theoretically you might find a\r
+            //    font name that has a single quote in its name (serving\r
+            //    as an apostrophe, e.g. Dave's Scribble), I haven't\r
+            //    been able to find any actual examples of this.\r
+            //    Internet Explorer's cssText translation (which I\r
+            //    believe is invoked by innerHTML) normalizes any\r
+            //    quoting to single quotes, and fails to escape single\r
+            //    quotes.  (Note that this is not IE's behavior for all\r
+            //    CSS properties, just some sort of special casing for\r
+            //    font-family).  So a single quote *cannot* be used\r
+            //    safely in the font-family context if there will be an\r
+            //    innerHTML/cssText translation.  Note that Firefox 3.x\r
+            //    does this too.\r
+            //  - Double quote.  In IE, these get normalized to\r
+            //    single-quotes, no matter what the encoding.  (Fun\r
+            //    fact, in IE8, the 'content' CSS property gained\r
+            //    support, where they special cased to preserve encoded\r
+            //    double quotes, but still translate unadorned double\r
+            //    quotes into single quotes.)  So, because their\r
+            //    fixpoint behavior is identical to single quotes, they\r
+            //    cannot be allowed either.  Firefox 3.x displays\r
+            //    single-quote style behavior.\r
+            //  - Backslashes are reduced by one (so \\ -> \) every\r
+            //    iteration, so they cannot be used safely.  This shows\r
+            //    up in IE7, IE8 and FF3\r
+            //  - Semicolons, commas and backticks are handled properly.\r
+            //  - The rest of the ASCII punctuation is handled properly.\r
+            // We haven't checked what browsers do to unadorned\r
+            // versions, but this is not important as long as the\r
+            // browser doesn't /remove/ surrounding quotes (as IE does\r
+            // for HTML).\r
+            //\r
+            // With these results in hand, we conclude that there are\r
+            // various levels of safety:\r
+            //  - Paranoid: alphanumeric, spaces and dashes(?)\r
+            //  - International: Paranoid + non-ASCII Unicode\r
+            //  - Edgy: Everything except quotes, backslashes\r
+            //  - NoJS: Standards compliance, e.g. sod IE. Note that\r
+            //    with some judicious character escaping (since certain\r
+            //    types of escaping doesn't work) this is theoretically\r
+            //    OK as long as innerHTML/cssText is not called.\r
+            // We believe that international is a reasonable default\r
+            // (that we will implement now), and once we do more\r
+            // extensive research, we may feel comfortable with dropping\r
+            // it down to edgy.\r
+\r
+            // Edgy: alphanumeric, spaces, dashes, underscores and Unicode.  Use of\r
+            // str(c)spn assumes that the string was already well formed\r
+            // Unicode (which of course it is).\r
+            if (strspn($font, $this->mask) !== strlen($font)) {\r
+                continue;\r
+            }\r
+\r
+            // Historical:\r
+            // In the absence of innerHTML/cssText, these ugly\r
+            // transforms don't pose a security risk (as \\ and \"\r
+            // might--these escapes are not supported by most browsers).\r
+            // We could try to be clever and use single-quote wrapping\r
+            // when there is a double quote present, but I have choosen\r
+            // not to implement that.  (NOTE: you can reduce the amount\r
+            // of escapes by one depending on what quoting style you use)\r
+            // $font = str_replace('\\', '\\5C ', $font);\r
+            // $font = str_replace('"',  '\\22 ', $font);\r
+            // $font = str_replace("'",  '\\27 ', $font);\r
+\r
+            // font possibly with spaces, requires quoting\r
+            $final .= "'$font', ";\r
+        }\r
+        $final = rtrim($final, ', ');\r
+        if ($final === '') {\r
+            return false;\r
+        }\r
+        return $final;\r
+    }\r
+\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates based on {ident} CSS grammar production\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Ident extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = trim($string);\r
+\r
+        // early abort: '' and '0' (strings that convert to false) are invalid\r
+        if (!$string) {\r
+            return false;\r
+        }\r
+\r
+        $pattern = '/^(-?[A-Za-z_][A-Za-z_\-0-9]*)$/';\r
+        if (!preg_match($pattern, $string)) {\r
+            return false;\r
+        }\r
+        return $string;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Decorator which enables !important to be used in CSS values.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_ImportantDecorator extends HTMLPurifier_AttrDef\r
+{\r
+    /**\r
+     * @type HTMLPurifier_AttrDef\r
+     */\r
+    public $def;\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $allow;\r
+\r
+    /**\r
+     * @param HTMLPurifier_AttrDef $def Definition to wrap\r
+     * @param bool $allow Whether or not to allow !important\r
+     */\r
+    public function __construct($def, $allow = false)\r
+    {\r
+        $this->def = $def;\r
+        $this->allow = $allow;\r
+    }\r
+\r
+    /**\r
+     * Intercepts and removes !important if necessary\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        // test for ! and important tokens\r
+        $string = trim($string);\r
+        $is_important = false;\r
+        // :TODO: optimization: test directly for !important and ! important\r
+        if (strlen($string) >= 9 && substr($string, -9) === 'important') {\r
+            $temp = rtrim(substr($string, 0, -9));\r
+            // use a temp, because we might want to restore important\r
+            if (strlen($temp) >= 1 && substr($temp, -1) === '!') {\r
+                $string = rtrim(substr($temp, 0, -1));\r
+                $is_important = true;\r
+            }\r
+        }\r
+        $string = $this->def->validate($string, $config, $context);\r
+        if ($this->allow && $is_important) {\r
+            $string .= ' !important';\r
+        }\r
+        return $string;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Represents a Length as defined by CSS.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Length extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @type HTMLPurifier_Length|string\r
+     */\r
+    protected $min;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Length|string\r
+     */\r
+    protected $max;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Length|string $min Minimum length, or null for no bound. String is also acceptable.\r
+     * @param HTMLPurifier_Length|string $max Maximum length, or null for no bound. String is also acceptable.\r
+     */\r
+    public function __construct($min = null, $max = null)\r
+    {\r
+        $this->min = $min !== null ? HTMLPurifier_Length::make($min) : null;\r
+        $this->max = $max !== null ? HTMLPurifier_Length::make($max) : null;\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = $this->parseCDATA($string);\r
+\r
+        // Optimizations\r
+        if ($string === '') {\r
+            return false;\r
+        }\r
+        if ($string === '0') {\r
+            return '0';\r
+        }\r
+        if (strlen($string) === 1) {\r
+            return false;\r
+        }\r
+\r
+        $length = HTMLPurifier_Length::make($string);\r
+        if (!$length->isValid()) {\r
+            return false;\r
+        }\r
+\r
+        if ($this->min) {\r
+            $c = $length->compareTo($this->min);\r
+            if ($c === false) {\r
+                return false;\r
+            }\r
+            if ($c < 0) {\r
+                return false;\r
+            }\r
+        }\r
+        if ($this->max) {\r
+            $c = $length->compareTo($this->max);\r
+            if ($c === false) {\r
+                return false;\r
+            }\r
+            if ($c > 0) {\r
+                return false;\r
+            }\r
+        }\r
+        return $length->toString();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates shorthand CSS property list-style.\r
+ * @warning Does not support url tokens that have internal spaces.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_ListStyle extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Local copy of validators.\r
+     * @type HTMLPurifier_AttrDef[]\r
+     * @note See HTMLPurifier_AttrDef_CSS_Font::$info for a similar impl.\r
+     */\r
+    protected $info;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function __construct($config)\r
+    {\r
+        $def = $config->getCSSDefinition();\r
+        $this->info['list-style-type'] = $def->info['list-style-type'];\r
+        $this->info['list-style-position'] = $def->info['list-style-position'];\r
+        $this->info['list-style-image'] = $def->info['list-style-image'];\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        // regular pre-processing\r
+        $string = $this->parseCDATA($string);\r
+        if ($string === '') {\r
+            return false;\r
+        }\r
+\r
+        // assumes URI doesn't have spaces in it\r
+        $bits = explode(' ', strtolower($string)); // bits to process\r
+\r
+        $caught = array();\r
+        $caught['type'] = false;\r
+        $caught['position'] = false;\r
+        $caught['image'] = false;\r
+\r
+        $i = 0; // number of catches\r
+        $none = false;\r
+\r
+        foreach ($bits as $bit) {\r
+            if ($i >= 3) {\r
+                return;\r
+            } // optimization bit\r
+            if ($bit === '') {\r
+                continue;\r
+            }\r
+            foreach ($caught as $key => $status) {\r
+                if ($status !== false) {\r
+                    continue;\r
+                }\r
+                $r = $this->info['list-style-' . $key]->validate($bit, $config, $context);\r
+                if ($r === false) {\r
+                    continue;\r
+                }\r
+                if ($r === 'none') {\r
+                    if ($none) {\r
+                        continue;\r
+                    } else {\r
+                        $none = true;\r
+                    }\r
+                    if ($key == 'image') {\r
+                        continue;\r
+                    }\r
+                }\r
+                $caught[$key] = $r;\r
+                $i++;\r
+                break;\r
+            }\r
+        }\r
+\r
+        if (!$i) {\r
+            return false;\r
+        }\r
+\r
+        $ret = array();\r
+\r
+        // construct type\r
+        if ($caught['type']) {\r
+            $ret[] = $caught['type'];\r
+        }\r
+\r
+        // construct image\r
+        if ($caught['image']) {\r
+            $ret[] = $caught['image'];\r
+        }\r
+\r
+        // construct position\r
+        if ($caught['position']) {\r
+            $ret[] = $caught['position'];\r
+        }\r
+\r
+        if (empty($ret)) {\r
+            return false;\r
+        }\r
+        return implode(' ', $ret);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Framework class for strings that involve multiple values.\r
+ *\r
+ * Certain CSS properties such as border-width and margin allow multiple\r
+ * lengths to be specified.  This class can take a vanilla border-width\r
+ * definition and multiply it, usually into a max of four.\r
+ *\r
+ * @note Even though the CSS specification isn't clear about it, inherit\r
+ *       can only be used alone: it will never manifest as part of a multi\r
+ *       shorthand declaration.  Thus, this class does not allow inherit.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Multiple extends HTMLPurifier_AttrDef\r
+{\r
+    /**\r
+     * Instance of component definition to defer validation to.\r
+     * @type HTMLPurifier_AttrDef\r
+     * @todo Make protected\r
+     */\r
+    public $single;\r
+\r
+    /**\r
+     * Max number of values allowed.\r
+     * @todo Make protected\r
+     */\r
+    public $max;\r
+\r
+    /**\r
+     * @param HTMLPurifier_AttrDef $single HTMLPurifier_AttrDef to multiply\r
+     * @param int $max Max number of values allowed (usually four)\r
+     */\r
+    public function __construct($single, $max = 4)\r
+    {\r
+        $this->single = $single;\r
+        $this->max = $max;\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = $this->mungeRgb($this->parseCDATA($string));\r
+        if ($string === '') {\r
+            return false;\r
+        }\r
+        $parts = explode(' ', $string); // parseCDATA replaced \r, \t and \n\r
+        $length = count($parts);\r
+        $final = '';\r
+        for ($i = 0, $num = 0; $i < $length && $num < $this->max; $i++) {\r
+            if (ctype_space($parts[$i])) {\r
+                continue;\r
+            }\r
+            $result = $this->single->validate($parts[$i], $config, $context);\r
+            if ($result !== false) {\r
+                $final .= $result . ' ';\r
+                $num++;\r
+            }\r
+        }\r
+        if ($final === '') {\r
+            return false;\r
+        }\r
+        return rtrim($final);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates a Percentage as defined by the CSS spec.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_Percentage extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Instance to defer number validation to.\r
+     * @type HTMLPurifier_AttrDef_CSS_Number\r
+     */\r
+    protected $number_def;\r
+\r
+    /**\r
+     * @param bool $non_negative Whether to forbid negative values\r
+     */\r
+    public function __construct($non_negative = false)\r
+    {\r
+        $this->number_def = new HTMLPurifier_AttrDef_CSS_Number($non_negative);\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = $this->parseCDATA($string);\r
+\r
+        if ($string === '') {\r
+            return false;\r
+        }\r
+        $length = strlen($string);\r
+        if ($length === 1) {\r
+            return false;\r
+        }\r
+        if ($string[$length - 1] !== '%') {\r
+            return false;\r
+        }\r
+\r
+        $number = substr($string, 0, $length - 1);\r
+        $number = $this->number_def->validate($number, $config, $context);\r
+\r
+        if ($number === false) {\r
+            return false;\r
+        }\r
+        return "$number%";\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates the value for the CSS property text-decoration\r
+ * @note This class could be generalized into a version that acts sort of\r
+ *       like Enum except you can compound the allowed values.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_TextDecoration extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        static $allowed_values = array(\r
+            'line-through' => true,\r
+            'overline' => true,\r
+            'underline' => true,\r
+        );\r
+\r
+        $string = strtolower($this->parseCDATA($string));\r
+\r
+        if ($string === 'none') {\r
+            return $string;\r
+        }\r
+\r
+        $parts = explode(' ', $string);\r
+        $final = '';\r
+        foreach ($parts as $part) {\r
+            if (isset($allowed_values[$part])) {\r
+                $final .= $part . ' ';\r
+            }\r
+        }\r
+        $final = rtrim($final);\r
+        if ($final === '') {\r
+            return false;\r
+        }\r
+        return $final;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates a URI in CSS syntax, which uses url('http://example.com')\r
+ * @note While theoretically speaking a URI in a CSS document could\r
+ *       be non-embedded, as of CSS2 there is no such usage so we're\r
+ *       generalizing it. This may need to be changed in the future.\r
+ * @warning Since HTMLPurifier_AttrDef_CSS blindly uses semicolons as\r
+ *          the separator, you cannot put a literal semicolon in\r
+ *          in the URI. Try percent encoding it, in that case.\r
+ */\r
+class HTMLPurifier_AttrDef_CSS_URI extends HTMLPurifier_AttrDef_URI\r
+{\r
+\r
+    public function __construct()\r
+    {\r
+        parent::__construct(true); // always embedded\r
+    }\r
+\r
+    /**\r
+     * @param string $uri_string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($uri_string, $config, $context)\r
+    {\r
+        // parse the URI out of the string and then pass it onto\r
+        // the parent object\r
+\r
+        $uri_string = $this->parseCDATA($uri_string);\r
+        if (strpos($uri_string, 'url(') !== 0) {\r
+            return false;\r
+        }\r
+        $uri_string = substr($uri_string, 4);\r
+        if (strlen($uri_string) == 0) {\r
+            return false;\r
+        }\r
+        $new_length = strlen($uri_string) - 1;\r
+        if ($uri_string[$new_length] != ')') {\r
+            return false;\r
+        }\r
+        $uri = trim(substr($uri_string, 0, $new_length));\r
+\r
+        if (!empty($uri) && ($uri[0] == "'" || $uri[0] == '"')) {\r
+            $quote = $uri[0];\r
+            $new_length = strlen($uri) - 1;\r
+            if ($uri[$new_length] !== $quote) {\r
+                return false;\r
+            }\r
+            $uri = substr($uri, 1, $new_length - 1);\r
+        }\r
+\r
+        $uri = $this->expandCSSEscape($uri);\r
+\r
+        $result = parent::validate($uri, $config, $context);\r
+\r
+        if ($result === false) {\r
+            return false;\r
+        }\r
+\r
+        // extra sanity check; should have been done by URI\r
+        $result = str_replace(array('"', "\\", "\n", "\x0c", "\r"), "", $result);\r
+\r
+        // suspicious characters are ()'; we're going to percent encode\r
+        // them for safety.\r
+        $result = str_replace(array('(', ')', "'"), array('%28', '%29', '%27'), $result);\r
+\r
+        // there's an extra bug where ampersands lose their escaping on\r
+        // an innerHTML cycle, so a very unlucky query parameter could\r
+        // then change the meaning of the URL.  Unfortunately, there's\r
+        // not much we can do about that...\r
+        return "url(\"$result\")";\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates a boolean attribute\r
+ */\r
+class HTMLPurifier_AttrDef_HTML_Bool extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    protected $name;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $minimized = true;\r
+\r
+    /**\r
+     * @param bool $name\r
+     */\r
+    public function __construct($name = false)\r
+    {\r
+        $this->name = $name;\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        return $this->name;\r
+    }\r
+\r
+    /**\r
+     * @param string $string Name of attribute\r
+     * @return HTMLPurifier_AttrDef_HTML_Bool\r
+     */\r
+    public function make($string)\r
+    {\r
+        return new HTMLPurifier_AttrDef_HTML_Bool($string);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates contents based on NMTOKENS attribute type.\r
+ */\r
+class HTMLPurifier_AttrDef_HTML_Nmtokens extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = trim($string);\r
+\r
+        // early abort: '' and '0' (strings that convert to false) are invalid\r
+        if (!$string) {\r
+            return false;\r
+        }\r
+\r
+        $tokens = $this->split($string, $config, $context);\r
+        $tokens = $this->filter($tokens, $config, $context);\r
+        if (empty($tokens)) {\r
+            return false;\r
+        }\r
+        return implode(' ', $tokens);\r
+    }\r
+\r
+    /**\r
+     * Splits a space separated list of tokens into its constituent parts.\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    protected function split($string, $config, $context)\r
+    {\r
+        // OPTIMIZABLE!\r
+        // do the preg_match, capture all subpatterns for reformulation\r
+\r
+        // we don't support U+00A1 and up codepoints or\r
+        // escaping because I don't know how to do that with regexps\r
+        // and plus it would complicate optimization efforts (you never\r
+        // see that anyway).\r
+        $pattern = '/(?:(?<=\s)|\A)' . // look behind for space or string start\r
+            '((?:--|-?[A-Za-z_])[A-Za-z_\-0-9]*)' .\r
+            '(?:(?=\s)|\z)/'; // look ahead for space or string end\r
+        preg_match_all($pattern, $string, $matches);\r
+        return $matches[1];\r
+    }\r
+\r
+    /**\r
+     * Template method for removing certain tokens based on arbitrary criteria.\r
+     * @note If we wanted to be really functional, we'd do an array_filter\r
+     *       with a callback. But... we're not.\r
+     * @param array $tokens\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    protected function filter($tokens, $config, $context)\r
+    {\r
+        return $tokens;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Implements special behavior for class attribute (normally NMTOKENS)\r
+ */\r
+class HTMLPurifier_AttrDef_HTML_Class extends HTMLPurifier_AttrDef_HTML_Nmtokens\r
+{\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    protected function split($string, $config, $context)\r
+    {\r
+        // really, this twiddle should be lazy loaded\r
+        $name = $config->getDefinition('HTML')->doctype->name;\r
+        if ($name == "XHTML 1.1" || $name == "XHTML 2.0") {\r
+            return parent::split($string, $config, $context);\r
+        } else {\r
+            return preg_split('/\s+/', $string);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * @param array $tokens\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    protected function filter($tokens, $config, $context)\r
+    {\r
+        $allowed = $config->get('Attr.AllowedClasses');\r
+        $forbidden = $config->get('Attr.ForbiddenClasses');\r
+        $ret = array();\r
+        foreach ($tokens as $token) {\r
+            if (($allowed === null || isset($allowed[$token])) &&\r
+                !isset($forbidden[$token]) &&\r
+                // We need this O(n) check because of PHP's array\r
+                // implementation that casts -0 to 0.\r
+                !in_array($token, $ret, true)\r
+            ) {\r
+                $ret[] = $token;\r
+            }\r
+        }\r
+        return $ret;\r
+    }\r
+}\r
+
+\r
+\r
+/**\r
+ * Validates a color according to the HTML spec.\r
+ */\r
+class HTMLPurifier_AttrDef_HTML_Color extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        static $colors = null;\r
+        if ($colors === null) {\r
+            $colors = $config->get('Core.ColorKeywords');\r
+        }\r
+\r
+        $string = trim($string);\r
+\r
+        if (empty($string)) {\r
+            return false;\r
+        }\r
+        $lower = strtolower($string);\r
+        if (isset($colors[$lower])) {\r
+            return $colors[$lower];\r
+        }\r
+        if ($string[0] === '#') {\r
+            $hex = substr($string, 1);\r
+        } else {\r
+            $hex = $string;\r
+        }\r
+\r
+        $length = strlen($hex);\r
+        if ($length !== 3 && $length !== 6) {\r
+            return false;\r
+        }\r
+        if (!ctype_xdigit($hex)) {\r
+            return false;\r
+        }\r
+        if ($length === 3) {\r
+            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];\r
+        }\r
+        return "#$hex";\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Special-case enum attribute definition that lazy loads allowed frame targets\r
+ */\r
+class HTMLPurifier_AttrDef_HTML_FrameTarget extends HTMLPurifier_AttrDef_Enum\r
+{\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $valid_values = false; // uninitialized value\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    protected $case_sensitive = false;\r
+\r
+    public function __construct()\r
+    {\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        if ($this->valid_values === false) {\r
+            $this->valid_values = $config->get('Attr.AllowedFrameTargets');\r
+        }\r
+        return parent::validate($string, $config, $context);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates the HTML attribute ID.\r
+ * @warning Even though this is the id processor, it\r
+ *          will ignore the directive Attr:IDBlacklist, since it will only\r
+ *          go according to the ID accumulator. Since the accumulator is\r
+ *          automatically generated, it will have already absorbed the\r
+ *          blacklist. If you're hacking around, make sure you use load()!\r
+ */\r
+\r
+class HTMLPurifier_AttrDef_HTML_ID extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    // selector is NOT a valid thing to use for IDREFs, because IDREFs\r
+    // *must* target IDs that exist, whereas selector #ids do not.\r
+\r
+    /**\r
+     * Determines whether or not we're validating an ID in a CSS\r
+     * selector context.\r
+     * @type bool\r
+     */\r
+    protected $selector;\r
+\r
+    /**\r
+     * @param bool $selector\r
+     */\r
+    public function __construct($selector = false)\r
+    {\r
+        $this->selector = $selector;\r
+    }\r
+\r
+    /**\r
+     * @param string $id\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($id, $config, $context)\r
+    {\r
+        if (!$this->selector && !$config->get('Attr.EnableID')) {\r
+            return false;\r
+        }\r
+\r
+        $id = trim($id); // trim it first\r
+\r
+        if ($id === '') {\r
+            return false;\r
+        }\r
+\r
+        $prefix = $config->get('Attr.IDPrefix');\r
+        if ($prefix !== '') {\r
+            $prefix .= $config->get('Attr.IDPrefixLocal');\r
+            // prevent re-appending the prefix\r
+            if (strpos($id, $prefix) !== 0) {\r
+                $id = $prefix . $id;\r
+            }\r
+        } elseif ($config->get('Attr.IDPrefixLocal') !== '') {\r
+            trigger_error(\r
+                '%Attr.IDPrefixLocal cannot be used unless ' .\r
+                '%Attr.IDPrefix is set',\r
+                E_USER_WARNING\r
+            );\r
+        }\r
+\r
+        if (!$this->selector) {\r
+            $id_accumulator =& $context->get('IDAccumulator');\r
+            if (isset($id_accumulator->ids[$id])) {\r
+                return false;\r
+            }\r
+        }\r
+\r
+        // we purposely avoid using regex, hopefully this is faster\r
+\r
+        if ($config->get('Attr.ID.HTML5') === true) {\r
+            if (preg_match('/[\t\n\x0b\x0c ]/', $id)) {\r
+                return false;\r
+            }\r
+        } else {\r
+            if (ctype_alpha($id)) {\r
+                // OK\r
+            } else {\r
+                if (!ctype_alpha(@$id[0])) {\r
+                    return false;\r
+                }\r
+                // primitive style of regexps, I suppose\r
+                $trim = trim(\r
+                    $id,\r
+                    'A..Za..z0..9:-._'\r
+                );\r
+                if ($trim !== '') {\r
+                    return false;\r
+                }\r
+            }\r
+        }\r
+\r
+        $regexp = $config->get('Attr.IDBlacklistRegexp');\r
+        if ($regexp && preg_match($regexp, $id)) {\r
+            return false;\r
+        }\r
+\r
+        if (!$this->selector) {\r
+            $id_accumulator->add($id);\r
+        }\r
+\r
+        // if no change was made to the ID, return the result\r
+        // else, return the new id if stripping whitespace made it\r
+        //     valid, or return false.\r
+        return $id;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates an integer representation of pixels according to the HTML spec.\r
+ */\r
+class HTMLPurifier_AttrDef_HTML_Pixels extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * @type int\r
+     */\r
+    protected $max;\r
+\r
+    /**\r
+     * @param int $max\r
+     */\r
+    public function __construct($max = null)\r
+    {\r
+        $this->max = $max;\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = trim($string);\r
+        if ($string === '0') {\r
+            return $string;\r
+        }\r
+        if ($string === '') {\r
+            return false;\r
+        }\r
+        $length = strlen($string);\r
+        if (substr($string, $length - 2) == 'px') {\r
+            $string = substr($string, 0, $length - 2);\r
+        }\r
+        if (!is_numeric($string)) {\r
+            return false;\r
+        }\r
+        $int = (int)$string;\r
+\r
+        if ($int < 0) {\r
+            return '0';\r
+        }\r
+\r
+        // upper-bound value, extremely high values can\r
+        // crash operating systems, see <http://ha.ckers.org/imagecrash.html>\r
+        // WARNING, above link WILL crash you if you're using Windows\r
+\r
+        if ($this->max !== null && $int > $this->max) {\r
+            return (string)$this->max;\r
+        }\r
+        return (string)$int;\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @return HTMLPurifier_AttrDef\r
+     */\r
+    public function make($string)\r
+    {\r
+        if ($string === '') {\r
+            $max = null;\r
+        } else {\r
+            $max = (int)$string;\r
+        }\r
+        $class = get_class($this);\r
+        return new $class($max);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates the HTML type length (not to be confused with CSS's length).\r
+ *\r
+ * This accepts integer pixels or percentages as lengths for certain\r
+ * HTML attributes.\r
+ */\r
+\r
+class HTMLPurifier_AttrDef_HTML_Length extends HTMLPurifier_AttrDef_HTML_Pixels\r
+{\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = trim($string);\r
+        if ($string === '') {\r
+            return false;\r
+        }\r
+\r
+        $parent_result = parent::validate($string, $config, $context);\r
+        if ($parent_result !== false) {\r
+            return $parent_result;\r
+        }\r
+\r
+        $length = strlen($string);\r
+        $last_char = $string[$length - 1];\r
+\r
+        if ($last_char !== '%') {\r
+            return false;\r
+        }\r
+\r
+        $points = substr($string, 0, $length - 1);\r
+\r
+        if (!is_numeric($points)) {\r
+            return false;\r
+        }\r
+\r
+        $points = (int)$points;\r
+\r
+        if ($points < 0) {\r
+            return '0%';\r
+        }\r
+        if ($points > 100) {\r
+            return '100%';\r
+        }\r
+        return ((string)$points) . '%';\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates a rel/rev link attribute against a directive of allowed values\r
+ * @note We cannot use Enum because link types allow multiple\r
+ *       values.\r
+ * @note Assumes link types are ASCII text\r
+ */\r
+class HTMLPurifier_AttrDef_HTML_LinkTypes extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Name config attribute to pull.\r
+     * @type string\r
+     */\r
+    protected $name;\r
+\r
+    /**\r
+     * @param string $name\r
+     */\r
+    public function __construct($name)\r
+    {\r
+        $configLookup = array(\r
+            'rel' => 'AllowedRel',\r
+            'rev' => 'AllowedRev'\r
+        );\r
+        if (!isset($configLookup[$name])) {\r
+            trigger_error(\r
+                'Unrecognized attribute name for link ' .\r
+                'relationship.',\r
+                E_USER_ERROR\r
+            );\r
+            return;\r
+        }\r
+        $this->name = $configLookup[$name];\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $allowed = $config->get('Attr.' . $this->name);\r
+        if (empty($allowed)) {\r
+            return false;\r
+        }\r
+\r
+        $string = $this->parseCDATA($string);\r
+        $parts = explode(' ', $string);\r
+\r
+        // lookup to prevent duplicates\r
+        $ret_lookup = array();\r
+        foreach ($parts as $part) {\r
+            $part = strtolower(trim($part));\r
+            if (!isset($allowed[$part])) {\r
+                continue;\r
+            }\r
+            $ret_lookup[$part] = true;\r
+        }\r
+\r
+        if (empty($ret_lookup)) {\r
+            return false;\r
+        }\r
+        $string = implode(' ', array_keys($ret_lookup));\r
+        return $string;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates a MultiLength as defined by the HTML spec.\r
+ *\r
+ * A multilength is either a integer (pixel count), a percentage, or\r
+ * a relative number.\r
+ */\r
+class HTMLPurifier_AttrDef_HTML_MultiLength extends HTMLPurifier_AttrDef_HTML_Length\r
+{\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $string = trim($string);\r
+        if ($string === '') {\r
+            return false;\r
+        }\r
+\r
+        $parent_result = parent::validate($string, $config, $context);\r
+        if ($parent_result !== false) {\r
+            return $parent_result;\r
+        }\r
+\r
+        $length = strlen($string);\r
+        $last_char = $string[$length - 1];\r
+\r
+        if ($last_char !== '*') {\r
+            return false;\r
+        }\r
+\r
+        $int = substr($string, 0, $length - 1);\r
+\r
+        if ($int == '') {\r
+            return '*';\r
+        }\r
+        if (!is_numeric($int)) {\r
+            return false;\r
+        }\r
+\r
+        $int = (int)$int;\r
+        if ($int < 0) {\r
+            return false;\r
+        }\r
+        if ($int == 0) {\r
+            return '0';\r
+        }\r
+        if ($int == 1) {\r
+            return '*';\r
+        }\r
+        return ((string)$int) . '*';\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+abstract class HTMLPurifier_AttrDef_URI_Email extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * Unpacks a mailbox into its display-name and address\r
+     * @param string $string\r
+     * @return mixed\r
+     */\r
+    public function unpack($string)\r
+    {\r
+        // needs to be implemented\r
+    }\r
+\r
+}\r
+\r
+// sub-implementations\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates a host according to the IPv4, IPv6 and DNS (future) specifications.\r
+ */\r
+class HTMLPurifier_AttrDef_URI_Host extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * IPv4 sub-validator.\r
+     * @type HTMLPurifier_AttrDef_URI_IPv4\r
+     */\r
+    protected $ipv4;\r
+\r
+    /**\r
+     * IPv6 sub-validator.\r
+     * @type HTMLPurifier_AttrDef_URI_IPv6\r
+     */\r
+    protected $ipv6;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->ipv4 = new HTMLPurifier_AttrDef_URI_IPv4();\r
+        $this->ipv6 = new HTMLPurifier_AttrDef_URI_IPv6();\r
+    }\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        $length = strlen($string);\r
+        // empty hostname is OK; it's usually semantically equivalent:\r
+        // the default host as defined by a URI scheme is used:\r
+        //\r
+        //      If the URI scheme defines a default for host, then that\r
+        //      default applies when the host subcomponent is undefined\r
+        //      or when the registered name is empty (zero length).\r
+        if ($string === '') {\r
+            return '';\r
+        }\r
+        if ($length > 1 && $string[0] === '[' && $string[$length - 1] === ']') {\r
+            //IPv6\r
+            $ip = substr($string, 1, $length - 2);\r
+            $valid = $this->ipv6->validate($ip, $config, $context);\r
+            if ($valid === false) {\r
+                return false;\r
+            }\r
+            return '[' . $valid . ']';\r
+        }\r
+\r
+        // need to do checks on unusual encodings too\r
+        $ipv4 = $this->ipv4->validate($string, $config, $context);\r
+        if ($ipv4 !== false) {\r
+            return $ipv4;\r
+        }\r
+\r
+        // A regular domain name.\r
+\r
+        // This doesn't match I18N domain names, but we don't have proper IRI support,\r
+        // so force users to insert Punycode.\r
+\r
+        // There is not a good sense in which underscores should be\r
+        // allowed, since it's technically not! (And if you go as\r
+        // far to allow everything as specified by the DNS spec...\r
+        // well, that's literally everything, modulo some space limits\r
+        // for the components and the overall name (which, by the way,\r
+        // we are NOT checking!).  So we (arbitrarily) decide this:\r
+        // let's allow underscores wherever we would have allowed\r
+        // hyphens, if they are enabled.  This is a pretty good match\r
+        // for browser behavior, for example, a large number of browsers\r
+        // cannot handle foo_.example.com, but foo_bar.example.com is\r
+        // fairly well supported.\r
+        $underscore = $config->get('Core.AllowHostnameUnderscore') ? '_' : '';\r
+\r
+        // Based off of RFC 1738, but amended so that\r
+        // as per RFC 3696, the top label need only not be all numeric.\r
+        // The productions describing this are:\r
+        $a   = '[a-z]';     // alpha\r
+        $an  = '[a-z0-9]';  // alphanum\r
+        $and = "[a-z0-9-$underscore]"; // alphanum | "-"\r
+        // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum\r
+        $domainlabel = "$an(?:$and*$an)?";\r
+        // AMENDED as per RFC 3696\r
+        // toplabel    = alphanum | alphanum *( alphanum | "-" ) alphanum\r
+        //      side condition: not all numeric\r
+        $toplabel = "$an(?:$and*$an)?";\r
+        // hostname    = *( domainlabel "." ) toplabel [ "." ]\r
+        if (preg_match("/^(?:$domainlabel\.)*($toplabel)\.?$/i", $string, $matches)) {\r
+            if (!ctype_digit($matches[1])) {\r
+                return $string;\r
+            }\r
+        }\r
+\r
+        // PHP 5.3 and later support this functionality natively\r
+        if (function_exists('idn_to_ascii')) {\r
+            if (defined('IDNA_NONTRANSITIONAL_TO_ASCII') && defined('INTL_IDNA_VARIANT_UTS46')) {\r
+                $string = idn_to_ascii($string, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);\r
+            } else {\r
+                $string = idn_to_ascii($string);\r
+            }\r
+\r
+        // If we have Net_IDNA2 support, we can support IRIs by\r
+        // punycoding them. (This is the most portable thing to do,\r
+        // since otherwise we have to assume browsers support\r
+        } elseif ($config->get('Core.EnableIDNA')) {\r
+            $idna = new Net_IDNA2(array('encoding' => 'utf8', 'overlong' => false, 'strict' => true));\r
+            // we need to encode each period separately\r
+            $parts = explode('.', $string);\r
+            try {\r
+                $new_parts = array();\r
+                foreach ($parts as $part) {\r
+                    $encodable = false;\r
+                    for ($i = 0, $c = strlen($part); $i < $c; $i++) {\r
+                        if (ord($part[$i]) > 0x7a) {\r
+                            $encodable = true;\r
+                            break;\r
+                        }\r
+                    }\r
+                    if (!$encodable) {\r
+                        $new_parts[] = $part;\r
+                    } else {\r
+                        $new_parts[] = $idna->encode($part);\r
+                    }\r
+                }\r
+                $string = implode('.', $new_parts);\r
+            } catch (Exception $e) {\r
+                // XXX error reporting\r
+            }\r
+        }\r
+        // Try again\r
+        if (preg_match("/^($domainlabel\.)*$toplabel\.?$/i", $string)) {\r
+            return $string;\r
+        }\r
+        return false;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates an IPv4 address\r
+ * @author Feyd @ forums.devnetwork.net (public domain)\r
+ */\r
+class HTMLPurifier_AttrDef_URI_IPv4 extends HTMLPurifier_AttrDef\r
+{\r
+\r
+    /**\r
+     * IPv4 regex, protected so that IPv6 can reuse it.\r
+     * @type string\r
+     */\r
+    protected $ip4;\r
+\r
+    /**\r
+     * @param string $aIP\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($aIP, $config, $context)\r
+    {\r
+        if (!$this->ip4) {\r
+            $this->_loadRegex();\r
+        }\r
+\r
+        if (preg_match('#^' . $this->ip4 . '$#s', $aIP)) {\r
+            return $aIP;\r
+        }\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * Lazy load function to prevent regex from being stuffed in\r
+     * cache.\r
+     */\r
+    protected function _loadRegex()\r
+    {\r
+        $oct = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])'; // 0-255\r
+        $this->ip4 = "(?:{$oct}\\.{$oct}\\.{$oct}\\.{$oct})";\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates an IPv6 address.\r
+ * @author Feyd @ forums.devnetwork.net (public domain)\r
+ * @note This function requires brackets to have been removed from address\r
+ *       in URI.\r
+ */\r
+class HTMLPurifier_AttrDef_URI_IPv6 extends HTMLPurifier_AttrDef_URI_IPv4\r
+{\r
+\r
+    /**\r
+     * @param string $aIP\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($aIP, $config, $context)\r
+    {\r
+        if (!$this->ip4) {\r
+            $this->_loadRegex();\r
+        }\r
+\r
+        $original = $aIP;\r
+\r
+        $hex = '[0-9a-fA-F]';\r
+        $blk = '(?:' . $hex . '{1,4})';\r
+        $pre = '(?:/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))'; // /0 - /128\r
+\r
+        //      prefix check\r
+        if (strpos($aIP, '/') !== false) {\r
+            if (preg_match('#' . $pre . '$#s', $aIP, $find)) {\r
+                $aIP = substr($aIP, 0, 0 - strlen($find[0]));\r
+                unset($find);\r
+            } else {\r
+                return false;\r
+            }\r
+        }\r
+\r
+        //      IPv4-compatiblity check\r
+        if (preg_match('#(?<=:' . ')' . $this->ip4 . '$#s', $aIP, $find)) {\r
+            $aIP = substr($aIP, 0, 0 - strlen($find[0]));\r
+            $ip = explode('.', $find[0]);\r
+            $ip = array_map('dechex', $ip);\r
+            $aIP .= $ip[0] . $ip[1] . ':' . $ip[2] . $ip[3];\r
+            unset($find, $ip);\r
+        }\r
+\r
+        //      compression check\r
+        $aIP = explode('::', $aIP);\r
+        $c = count($aIP);\r
+        if ($c > 2) {\r
+            return false;\r
+        } elseif ($c == 2) {\r
+            list($first, $second) = $aIP;\r
+            $first = explode(':', $first);\r
+            $second = explode(':', $second);\r
+\r
+            if (count($first) + count($second) > 8) {\r
+                return false;\r
+            }\r
+\r
+            while (count($first) < 8) {\r
+                array_push($first, '0');\r
+            }\r
+\r
+            array_splice($first, 8 - count($second), 8, $second);\r
+            $aIP = $first;\r
+            unset($first, $second);\r
+        } else {\r
+            $aIP = explode(':', $aIP[0]);\r
+        }\r
+        $c = count($aIP);\r
+\r
+        if ($c != 8) {\r
+            return false;\r
+        }\r
+\r
+        //      All the pieces should be 16-bit hex strings. Are they?\r
+        foreach ($aIP as $piece) {\r
+            if (!preg_match('#^[0-9a-fA-F]{4}$#s', sprintf('%04s', $piece))) {\r
+                return false;\r
+            }\r
+        }\r
+        return $original;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Primitive email validation class based on the regexp found at\r
+ * http://www.regular-expressions.info/email.html\r
+ */\r
+class HTMLPurifier_AttrDef_URI_Email_SimpleCheck extends HTMLPurifier_AttrDef_URI_Email\r
+{\r
+\r
+    /**\r
+     * @param string $string\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool|string\r
+     */\r
+    public function validate($string, $config, $context)\r
+    {\r
+        // no support for named mailboxes i.e. "Bob <bob@example.com>"\r
+        // that needs more percent encoding to be done\r
+        if ($string == '') {\r
+            return false;\r
+        }\r
+        $string = trim($string);\r
+        $result = preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $string);\r
+        return $result ? $string : false;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Pre-transform that changes proprietary background attribute to CSS.\r
+ */\r
+class HTMLPurifier_AttrTransform_Background extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr['background'])) {\r
+            return $attr;\r
+        }\r
+\r
+        $background = $this->confiscateAttr($attr, 'background');\r
+        // some validation should happen here\r
+\r
+        $this->prependCSS($attr, "background-image:url($background);");\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+// this MUST be placed in post, as it assumes that any value in dir is valid\r
+\r
+/**\r
+ * Post-trasnform that ensures that bdo tags have the dir attribute set.\r
+ */\r
+class HTMLPurifier_AttrTransform_BdoDir extends HTMLPurifier_AttrTransform\r
+{\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (isset($attr['dir'])) {\r
+            return $attr;\r
+        }\r
+        $attr['dir'] = $config->get('Attr.DefaultTextDir');\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Pre-transform that changes deprecated bgcolor attribute to CSS.\r
+ */\r
+class HTMLPurifier_AttrTransform_BgColor extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr['bgcolor'])) {\r
+            return $attr;\r
+        }\r
+\r
+        $bgcolor = $this->confiscateAttr($attr, 'bgcolor');\r
+        // some validation should happen here\r
+\r
+        $this->prependCSS($attr, "background-color:$bgcolor;");\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Pre-transform that changes converts a boolean attribute to fixed CSS\r
+ */\r
+class HTMLPurifier_AttrTransform_BoolToCSS extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * Name of boolean attribute that is trigger.\r
+     * @type string\r
+     */\r
+    protected $attr;\r
+\r
+    /**\r
+     * CSS declarations to add to style, needs trailing semicolon.\r
+     * @type string\r
+     */\r
+    protected $css;\r
+\r
+    /**\r
+     * @param string $attr attribute name to convert from\r
+     * @param string $css CSS declarations to add to style (needs semicolon)\r
+     */\r
+    public function __construct($attr, $css)\r
+    {\r
+        $this->attr = $attr;\r
+        $this->css = $css;\r
+    }\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr[$this->attr])) {\r
+            return $attr;\r
+        }\r
+        unset($attr[$this->attr]);\r
+        $this->prependCSS($attr, $this->css);\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Pre-transform that changes deprecated border attribute to CSS.\r
+ */\r
+class HTMLPurifier_AttrTransform_Border extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr['border'])) {\r
+            return $attr;\r
+        }\r
+        $border_width = $this->confiscateAttr($attr, 'border');\r
+        // some validation should happen here\r
+        $this->prependCSS($attr, "border:{$border_width}px solid;");\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Generic pre-transform that converts an attribute with a fixed number of\r
+ * values (enumerated) to CSS.\r
+ */\r
+class HTMLPurifier_AttrTransform_EnumToCSS extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * Name of attribute to transform from.\r
+     * @type string\r
+     */\r
+    protected $attr;\r
+\r
+    /**\r
+     * Lookup array of attribute values to CSS.\r
+     * @type array\r
+     */\r
+    protected $enumToCSS = array();\r
+\r
+    /**\r
+     * Case sensitivity of the matching.\r
+     * @type bool\r
+     * @warning Currently can only be guaranteed to work with ASCII\r
+     *          values.\r
+     */\r
+    protected $caseSensitive = false;\r
+\r
+    /**\r
+     * @param string $attr Attribute name to transform from\r
+     * @param array $enum_to_css Lookup array of attribute values to CSS\r
+     * @param bool $case_sensitive Case sensitivity indicator, default false\r
+     */\r
+    public function __construct($attr, $enum_to_css, $case_sensitive = false)\r
+    {\r
+        $this->attr = $attr;\r
+        $this->enumToCSS = $enum_to_css;\r
+        $this->caseSensitive = (bool)$case_sensitive;\r
+    }\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr[$this->attr])) {\r
+            return $attr;\r
+        }\r
+\r
+        $value = trim($attr[$this->attr]);\r
+        unset($attr[$this->attr]);\r
+\r
+        if (!$this->caseSensitive) {\r
+            $value = strtolower($value);\r
+        }\r
+\r
+        if (!isset($this->enumToCSS[$value])) {\r
+            return $attr;\r
+        }\r
+        $this->prependCSS($attr, $this->enumToCSS[$value]);\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+// must be called POST validation\r
+\r
+/**\r
+ * Transform that supplies default values for the src and alt attributes\r
+ * in img tags, as well as prevents the img tag from being removed\r
+ * because of a missing alt tag. This needs to be registered as both\r
+ * a pre and post attribute transform.\r
+ */\r
+class HTMLPurifier_AttrTransform_ImgRequired extends HTMLPurifier_AttrTransform\r
+{\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        $src = true;\r
+        if (!isset($attr['src'])) {\r
+            if ($config->get('Core.RemoveInvalidImg')) {\r
+                return $attr;\r
+            }\r
+            $attr['src'] = $config->get('Attr.DefaultInvalidImage');\r
+            $src = false;\r
+        }\r
+\r
+        if (!isset($attr['alt'])) {\r
+            if ($src) {\r
+                $alt = $config->get('Attr.DefaultImageAlt');\r
+                if ($alt === null) {\r
+                    $attr['alt'] = basename($attr['src']);\r
+                } else {\r
+                    $attr['alt'] = $alt;\r
+                }\r
+            } else {\r
+                $attr['alt'] = $config->get('Attr.DefaultInvalidImageAlt');\r
+            }\r
+        }\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Pre-transform that changes deprecated hspace and vspace attributes to CSS\r
+ */\r
+class HTMLPurifier_AttrTransform_ImgSpace extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    protected $attr;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $css = array(\r
+        'hspace' => array('left', 'right'),\r
+        'vspace' => array('top', 'bottom')\r
+    );\r
+\r
+    /**\r
+     * @param string $attr\r
+     */\r
+    public function __construct($attr)\r
+    {\r
+        $this->attr = $attr;\r
+        if (!isset($this->css[$attr])) {\r
+            trigger_error(htmlspecialchars($attr) . ' is not valid space attribute');\r
+        }\r
+    }\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr[$this->attr])) {\r
+            return $attr;\r
+        }\r
+\r
+        $width = $this->confiscateAttr($attr, $this->attr);\r
+        // some validation could happen here\r
+\r
+        if (!isset($this->css[$this->attr])) {\r
+            return $attr;\r
+        }\r
+\r
+        $style = '';\r
+        foreach ($this->css[$this->attr] as $suffix) {\r
+            $property = "margin-$suffix";\r
+            $style .= "$property:{$width}px;";\r
+        }\r
+        $this->prependCSS($attr, $style);\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Performs miscellaneous cross attribute validation and filtering for\r
+ * input elements. This is meant to be a post-transform.\r
+ */\r
+class HTMLPurifier_AttrTransform_Input extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @type HTMLPurifier_AttrDef_HTML_Pixels\r
+     */\r
+    protected $pixels;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->pixels = new HTMLPurifier_AttrDef_HTML_Pixels();\r
+    }\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr['type'])) {\r
+            $t = 'text';\r
+        } else {\r
+            $t = strtolower($attr['type']);\r
+        }\r
+        if (isset($attr['checked']) && $t !== 'radio' && $t !== 'checkbox') {\r
+            unset($attr['checked']);\r
+        }\r
+        if (isset($attr['maxlength']) && $t !== 'text' && $t !== 'password') {\r
+            unset($attr['maxlength']);\r
+        }\r
+        if (isset($attr['size']) && $t !== 'text' && $t !== 'password') {\r
+            $result = $this->pixels->validate($attr['size'], $config, $context);\r
+            if ($result === false) {\r
+                unset($attr['size']);\r
+            } else {\r
+                $attr['size'] = $result;\r
+            }\r
+        }\r
+        if (isset($attr['src']) && $t !== 'image') {\r
+            unset($attr['src']);\r
+        }\r
+        if (!isset($attr['value']) && ($t === 'radio' || $t === 'checkbox')) {\r
+            $attr['value'] = '';\r
+        }\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Post-transform that copies lang's value to xml:lang (and vice-versa)\r
+ * @note Theoretically speaking, this could be a pre-transform, but putting\r
+ *       post is more efficient.\r
+ */\r
+class HTMLPurifier_AttrTransform_Lang extends HTMLPurifier_AttrTransform\r
+{\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        $lang = isset($attr['lang']) ? $attr['lang'] : false;\r
+        $xml_lang = isset($attr['xml:lang']) ? $attr['xml:lang'] : false;\r
+\r
+        if ($lang !== false && $xml_lang === false) {\r
+            $attr['xml:lang'] = $lang;\r
+        } elseif ($xml_lang !== false) {\r
+            $attr['lang'] = $xml_lang;\r
+        }\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Class for handling width/height length attribute transformations to CSS\r
+ */\r
+class HTMLPurifier_AttrTransform_Length extends HTMLPurifier_AttrTransform\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    protected $name;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    protected $cssName;\r
+\r
+    public function __construct($name, $css_name = null)\r
+    {\r
+        $this->name = $name;\r
+        $this->cssName = $css_name ? $css_name : $name;\r
+    }\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr[$this->name])) {\r
+            return $attr;\r
+        }\r
+        $length = $this->confiscateAttr($attr, $this->name);\r
+        if (ctype_digit($length)) {\r
+            $length .= 'px';\r
+        }\r
+        $this->prependCSS($attr, $this->cssName . ":$length;");\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Pre-transform that changes deprecated name attribute to ID if necessary\r
+ */\r
+class HTMLPurifier_AttrTransform_Name extends HTMLPurifier_AttrTransform\r
+{\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        // Abort early if we're using relaxed definition of name\r
+        if ($config->get('HTML.Attr.Name.UseCDATA')) {\r
+            return $attr;\r
+        }\r
+        if (!isset($attr['name'])) {\r
+            return $attr;\r
+        }\r
+        $id = $this->confiscateAttr($attr, 'name');\r
+        if (isset($attr['id'])) {\r
+            return $attr;\r
+        }\r
+        $attr['id'] = $id;\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Post-transform that performs validation to the name attribute; if\r
+ * it is present with an equivalent id attribute, it is passed through;\r
+ * otherwise validation is performed.\r
+ */\r
+class HTMLPurifier_AttrTransform_NameSync extends HTMLPurifier_AttrTransform\r
+{\r
+\r
+    public function __construct()\r
+    {\r
+        $this->idDef = new HTMLPurifier_AttrDef_HTML_ID();\r
+    }\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr['name'])) {\r
+            return $attr;\r
+        }\r
+        $name = $attr['name'];\r
+        if (isset($attr['id']) && $attr['id'] === $name) {\r
+            return $attr;\r
+        }\r
+        $result = $this->idDef->validate($name, $config, $context);\r
+        if ($result === false) {\r
+            unset($attr['name']);\r
+        } else {\r
+            $attr['name'] = $result;\r
+        }\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+// must be called POST validation\r
+\r
+/**\r
+ * Adds rel="nofollow" to all outbound links.  This transform is\r
+ * only attached if Attr.Nofollow is TRUE.\r
+ */\r
+class HTMLPurifier_AttrTransform_Nofollow extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @type HTMLPurifier_URIParser\r
+     */\r
+    private $parser;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->parser = new HTMLPurifier_URIParser();\r
+    }\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr['href'])) {\r
+            return $attr;\r
+        }\r
+\r
+        // XXX Kind of inefficient\r
+        $url = $this->parser->parse($attr['href']);\r
+        $scheme = $url->getSchemeObj($config, $context);\r
+\r
+        if ($scheme->browsable && !$url->isLocal($config, $context)) {\r
+            if (isset($attr['rel'])) {\r
+                $rels = explode(' ', $attr['rel']);\r
+                if (!in_array('nofollow', $rels)) {\r
+                    $rels[] = 'nofollow';\r
+                }\r
+                $attr['rel'] = implode(' ', $rels);\r
+            } else {\r
+                $attr['rel'] = 'nofollow';\r
+            }\r
+        }\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_AttrTransform_SafeEmbed extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = "SafeEmbed";\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        $attr['allowscriptaccess'] = 'never';\r
+        $attr['allownetworking'] = 'internal';\r
+        $attr['type'] = 'application/x-shockwave-flash';\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Writes default type for all objects. Currently only supports flash.\r
+ */\r
+class HTMLPurifier_AttrTransform_SafeObject extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = "SafeObject";\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr['type'])) {\r
+            $attr['type'] = 'application/x-shockwave-flash';\r
+        }\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates name/value pairs in param tags to be used in safe objects. This\r
+ * will only allow name values it recognizes, and pre-fill certain attributes\r
+ * with required values.\r
+ *\r
+ * @note\r
+ *      This class only supports Flash. In the future, Quicktime support\r
+ *      may be added.\r
+ *\r
+ * @warning\r
+ *      This class expects an injector to add the necessary parameters tags.\r
+ */\r
+class HTMLPurifier_AttrTransform_SafeParam extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = "SafeParam";\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrDef_URI\r
+     */\r
+    private $uri;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->uri = new HTMLPurifier_AttrDef_URI(true); // embedded\r
+        $this->wmode = new HTMLPurifier_AttrDef_Enum(array('window', 'opaque', 'transparent'));\r
+    }\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        // If we add support for other objects, we'll need to alter the\r
+        // transforms.\r
+        switch ($attr['name']) {\r
+            // application/x-shockwave-flash\r
+            // Keep this synchronized with Injector/SafeObject.php\r
+            case 'allowScriptAccess':\r
+                $attr['value'] = 'never';\r
+                break;\r
+            case 'allowNetworking':\r
+                $attr['value'] = 'internal';\r
+                break;\r
+            case 'allowFullScreen':\r
+                if ($config->get('HTML.FlashAllowFullScreen')) {\r
+                    $attr['value'] = ($attr['value'] == 'true') ? 'true' : 'false';\r
+                } else {\r
+                    $attr['value'] = 'false';\r
+                }\r
+                break;\r
+            case 'wmode':\r
+                $attr['value'] = $this->wmode->validate($attr['value'], $config, $context);\r
+                break;\r
+            case 'movie':\r
+            case 'src':\r
+                $attr['name'] = "movie";\r
+                $attr['value'] = $this->uri->validate($attr['value'], $config, $context);\r
+                break;\r
+            case 'flashvars':\r
+                // we're going to allow arbitrary inputs to the SWF, on\r
+                // the reasoning that it could only hack the SWF, not us.\r
+                break;\r
+            // add other cases to support other param name/value pairs\r
+            default:\r
+                $attr['name'] = $attr['value'] = null;\r
+        }\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Implements required attribute stipulation for <script>\r
+ */\r
+class HTMLPurifier_AttrTransform_ScriptRequired extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr['type'])) {\r
+            $attr['type'] = 'text/javascript';\r
+        }\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+// must be called POST validation\r
+\r
+/**\r
+ * Adds target="blank" to all outbound links.  This transform is\r
+ * only attached if Attr.TargetBlank is TRUE.  This works regardless\r
+ * of whether or not Attr.AllowedFrameTargets\r
+ */\r
+class HTMLPurifier_AttrTransform_TargetBlank extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @type HTMLPurifier_URIParser\r
+     */\r
+    private $parser;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->parser = new HTMLPurifier_URIParser();\r
+    }\r
+\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (!isset($attr['href'])) {\r
+            return $attr;\r
+        }\r
+\r
+        // XXX Kind of inefficient\r
+        $url = $this->parser->parse($attr['href']);\r
+        $scheme = $url->getSchemeObj($config, $context);\r
+\r
+        if ($scheme->browsable && !$url->isBenign($config, $context)) {\r
+            $attr['target'] = '_blank';\r
+        }\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+// must be called POST validation\r
+\r
+/**\r
+ * Adds rel="noopener" to any links which target a different window\r
+ * than the current one.  This is used to prevent malicious websites\r
+ * from silently replacing the original window, which could be used\r
+ * to do phishing.\r
+ * This transform is controlled by %HTML.TargetNoopener.\r
+ */\r
+class HTMLPurifier_AttrTransform_TargetNoopener extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (isset($attr['rel'])) {\r
+            $rels = explode(' ', $attr['rel']);\r
+        } else {\r
+            $rels = array();\r
+        }\r
+        if (isset($attr['target']) && !in_array('noopener', $rels)) {\r
+            $rels[] = 'noopener';\r
+        }\r
+        if (!empty($rels) || isset($attr['rel'])) {\r
+            $attr['rel'] = implode(' ', $rels);\r
+        }\r
+\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+\r
+\r
+// must be called POST validation\r
+\r
+/**\r
+ * Adds rel="noreferrer" to any links which target a different window\r
+ * than the current one.  This is used to prevent malicious websites\r
+ * from silently replacing the original window, which could be used\r
+ * to do phishing.\r
+ * This transform is controlled by %HTML.TargetNoreferrer.\r
+ */\r
+class HTMLPurifier_AttrTransform_TargetNoreferrer extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        if (isset($attr['rel'])) {\r
+            $rels = explode(' ', $attr['rel']);\r
+        } else {\r
+            $rels = array();\r
+        }\r
+        if (isset($attr['target']) && !in_array('noreferrer', $rels)) {\r
+            $rels[] = 'noreferrer';\r
+        }\r
+        if (!empty($rels) || isset($attr['rel'])) {\r
+            $attr['rel'] = implode(' ', $rels);\r
+        }\r
+\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+\r
+\r
+/**\r
+ * Sets height/width defaults for <textarea>\r
+ */\r
+class HTMLPurifier_AttrTransform_Textarea extends HTMLPurifier_AttrTransform\r
+{\r
+    /**\r
+     * @param array $attr\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function transform($attr, $config, $context)\r
+    {\r
+        // Calculated from Firefox\r
+        if (!isset($attr['cols'])) {\r
+            $attr['cols'] = '22';\r
+        }\r
+        if (!isset($attr['rows'])) {\r
+            $attr['rows'] = '3';\r
+        }\r
+        return $attr;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Definition that uses different definitions depending on context.\r
+ *\r
+ * The del and ins tags are notable because they allow different types of\r
+ * elements depending on whether or not they're in a block or inline context.\r
+ * Chameleon allows this behavior to happen by using two different\r
+ * definitions depending on context.  While this somewhat generalized,\r
+ * it is specifically intended for those two tags.\r
+ */\r
+class HTMLPurifier_ChildDef_Chameleon extends HTMLPurifier_ChildDef\r
+{\r
+\r
+    /**\r
+     * Instance of the definition object to use when inline. Usually stricter.\r
+     * @type HTMLPurifier_ChildDef_Optional\r
+     */\r
+    public $inline;\r
+\r
+    /**\r
+     * Instance of the definition object to use when block.\r
+     * @type HTMLPurifier_ChildDef_Optional\r
+     */\r
+    public $block;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $type = 'chameleon';\r
+\r
+    /**\r
+     * @param array $inline List of elements to allow when inline.\r
+     * @param array $block List of elements to allow when block.\r
+     */\r
+    public function __construct($inline, $block)\r
+    {\r
+        $this->inline = new HTMLPurifier_ChildDef_Optional($inline);\r
+        $this->block = new HTMLPurifier_ChildDef_Optional($block);\r
+        $this->elements = $this->block->elements;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Node[] $children\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function validateChildren($children, $config, $context)\r
+    {\r
+        if ($context->get('IsInline') === false) {\r
+            return $this->block->validateChildren(\r
+                $children,\r
+                $config,\r
+                $context\r
+            );\r
+        } else {\r
+            return $this->inline->validateChildren(\r
+                $children,\r
+                $config,\r
+                $context\r
+            );\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Custom validation class, accepts DTD child definitions\r
+ *\r
+ * @warning Currently this class is an all or nothing proposition, that is,\r
+ *          it will only give a bool return value.\r
+ */\r
+class HTMLPurifier_ChildDef_Custom extends HTMLPurifier_ChildDef\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $type = 'custom';\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $allow_empty = false;\r
+\r
+    /**\r
+     * Allowed child pattern as defined by the DTD.\r
+     * @type string\r
+     */\r
+    public $dtd_regex;\r
+\r
+    /**\r
+     * PCRE regex derived from $dtd_regex.\r
+     * @type string\r
+     */\r
+    private $_pcre_regex;\r
+\r
+    /**\r
+     * @param $dtd_regex Allowed child pattern from the DTD\r
+     */\r
+    public function __construct($dtd_regex)\r
+    {\r
+        $this->dtd_regex = $dtd_regex;\r
+        $this->_compileRegex();\r
+    }\r
+\r
+    /**\r
+     * Compiles the PCRE regex from a DTD regex ($dtd_regex to $_pcre_regex)\r
+     */\r
+    protected function _compileRegex()\r
+    {\r
+        $raw = str_replace(' ', '', $this->dtd_regex);\r
+        if ($raw{0} != '(') {\r
+            $raw = "($raw)";\r
+        }\r
+        $el = '[#a-zA-Z0-9_.-]+';\r
+        $reg = $raw;\r
+\r
+        // COMPLICATED! AND MIGHT BE BUGGY! I HAVE NO CLUE WHAT I'M\r
+        // DOING! Seriously: if there's problems, please report them.\r
+\r
+        // collect all elements into the $elements array\r
+        preg_match_all("/$el/", $reg, $matches);\r
+        foreach ($matches[0] as $match) {\r
+            $this->elements[$match] = true;\r
+        }\r
+\r
+        // setup all elements as parentheticals with leading commas\r
+        $reg = preg_replace("/$el/", '(,\\0)', $reg);\r
+\r
+        // remove commas when they were not solicited\r
+        $reg = preg_replace("/([^,(|]\(+),/", '\\1', $reg);\r
+\r
+        // remove all non-paranthetical commas: they are handled by first regex\r
+        $reg = preg_replace("/,\(/", '(', $reg);\r
+\r
+        $this->_pcre_regex = $reg;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Node[] $children\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function validateChildren($children, $config, $context)\r
+    {\r
+        $list_of_children = '';\r
+        $nesting = 0; // depth into the nest\r
+        foreach ($children as $node) {\r
+            if (!empty($node->is_whitespace)) {\r
+                continue;\r
+            }\r
+            $list_of_children .= $node->name . ',';\r
+        }\r
+        // add leading comma to deal with stray comma declarations\r
+        $list_of_children = ',' . rtrim($list_of_children, ',');\r
+        $okay =\r
+            preg_match(\r
+                '/^,?' . $this->_pcre_regex . '$/',\r
+                $list_of_children\r
+            );\r
+        return (bool)$okay;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Definition that disallows all elements.\r
+ * @warning validateChildren() in this class is actually never called, because\r
+ *          empty elements are corrected in HTMLPurifier_Strategy_MakeWellFormed\r
+ *          before child definitions are parsed in earnest by\r
+ *          HTMLPurifier_Strategy_FixNesting.\r
+ */\r
+class HTMLPurifier_ChildDef_Empty extends HTMLPurifier_ChildDef\r
+{\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $allow_empty = true;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $type = 'empty';\r
+\r
+    public function __construct()\r
+    {\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Node[] $children\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function validateChildren($children, $config, $context)\r
+    {\r
+        return array();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Definition for list containers ul and ol.\r
+ *\r
+ * What does this do?  The big thing is to handle ol/ul at the top\r
+ * level of list nodes, which should be handled specially by /folding/\r
+ * them into the previous list node.  We generally shouldn't ever\r
+ * see other disallowed elements, because the autoclose behavior\r
+ * in MakeWellFormed handles it.\r
+ */\r
+class HTMLPurifier_ChildDef_List extends HTMLPurifier_ChildDef\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $type = 'list';\r
+    /**\r
+     * @type array\r
+     */\r
+    // lying a little bit, so that we can handle ul and ol ourselves\r
+    // XXX: This whole business with 'wrap' is all a bit unsatisfactory\r
+    public $elements = array('li' => true, 'ul' => true, 'ol' => true);\r
+\r
+    /**\r
+     * @param array $children\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function validateChildren($children, $config, $context)\r
+    {\r
+        // Flag for subclasses\r
+        $this->whitespace = false;\r
+\r
+        // if there are no tokens, delete parent node\r
+        if (empty($children)) {\r
+            return false;\r
+        }\r
+\r
+        // if li is not allowed, delete parent node\r
+        if (!isset($config->getHTMLDefinition()->info['li'])) {\r
+            trigger_error("Cannot allow ul/ol without allowing li", E_USER_WARNING);\r
+            return false;\r
+        }\r
+\r
+        // the new set of children\r
+        $result = array();\r
+\r
+        // a little sanity check to make sure it's not ALL whitespace\r
+        $all_whitespace = true;\r
+\r
+        $current_li = null;\r
+\r
+        foreach ($children as $node) {\r
+            if (!empty($node->is_whitespace)) {\r
+                $result[] = $node;\r
+                continue;\r
+            }\r
+            $all_whitespace = false; // phew, we're not talking about whitespace\r
+\r
+            if ($node->name === 'li') {\r
+                // good\r
+                $current_li = $node;\r
+                $result[] = $node;\r
+            } else {\r
+                // we want to tuck this into the previous li\r
+                // Invariant: we expect the node to be ol/ul\r
+                // ToDo: Make this more robust in the case of not ol/ul\r
+                // by distinguishing between existing li and li created\r
+                // to handle non-list elements; non-list elements should\r
+                // not be appended to an existing li; only li created\r
+                // for non-list. This distinction is not currently made.\r
+                if ($current_li === null) {\r
+                    $current_li = new HTMLPurifier_Node_Element('li');\r
+                    $result[] = $current_li;\r
+                }\r
+                $current_li->children[] = $node;\r
+                $current_li->empty = false; // XXX fascinating! Check for this error elsewhere ToDo\r
+            }\r
+        }\r
+        if (empty($result)) {\r
+            return false;\r
+        }\r
+        if ($all_whitespace) {\r
+            return false;\r
+        }\r
+        return $result;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Definition that allows a set of elements, but disallows empty children.\r
+ */\r
+class HTMLPurifier_ChildDef_Required extends HTMLPurifier_ChildDef\r
+{\r
+    /**\r
+     * Lookup table of allowed elements.\r
+     * @type array\r
+     */\r
+    public $elements = array();\r
+\r
+    /**\r
+     * Whether or not the last passed node was all whitespace.\r
+     * @type bool\r
+     */\r
+    protected $whitespace = false;\r
+\r
+    /**\r
+     * @param array|string $elements List of allowed element names (lowercase).\r
+     */\r
+    public function __construct($elements)\r
+    {\r
+        if (is_string($elements)) {\r
+            $elements = str_replace(' ', '', $elements);\r
+            $elements = explode('|', $elements);\r
+        }\r
+        $keys = array_keys($elements);\r
+        if ($keys == array_keys($keys)) {\r
+            $elements = array_flip($elements);\r
+            foreach ($elements as $i => $x) {\r
+                $elements[$i] = true;\r
+                if (empty($i)) {\r
+                    unset($elements[$i]);\r
+                } // remove blank\r
+            }\r
+        }\r
+        $this->elements = $elements;\r
+    }\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $allow_empty = false;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $type = 'required';\r
+\r
+    /**\r
+     * @param array $children\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function validateChildren($children, $config, $context)\r
+    {\r
+        // Flag for subclasses\r
+        $this->whitespace = false;\r
+\r
+        // if there are no tokens, delete parent node\r
+        if (empty($children)) {\r
+            return false;\r
+        }\r
+\r
+        // the new set of children\r
+        $result = array();\r
+\r
+        // whether or not parsed character data is allowed\r
+        // this controls whether or not we silently drop a tag\r
+        // or generate escaped HTML from it\r
+        $pcdata_allowed = isset($this->elements['#PCDATA']);\r
+\r
+        // a little sanity check to make sure it's not ALL whitespace\r
+        $all_whitespace = true;\r
+\r
+        $stack = array_reverse($children);\r
+        while (!empty($stack)) {\r
+            $node = array_pop($stack);\r
+            if (!empty($node->is_whitespace)) {\r
+                $result[] = $node;\r
+                continue;\r
+            }\r
+            $all_whitespace = false; // phew, we're not talking about whitespace\r
+\r
+            if (!isset($this->elements[$node->name])) {\r
+                // special case text\r
+                // XXX One of these ought to be redundant or something\r
+                if ($pcdata_allowed && $node instanceof HTMLPurifier_Node_Text) {\r
+                    $result[] = $node;\r
+                    continue;\r
+                }\r
+                // spill the child contents in\r
+                // ToDo: Make configurable\r
+                if ($node instanceof HTMLPurifier_Node_Element) {\r
+                    for ($i = count($node->children) - 1; $i >= 0; $i--) {\r
+                        $stack[] = $node->children[$i];\r
+                    }\r
+                    continue;\r
+                }\r
+                continue;\r
+            }\r
+            $result[] = $node;\r
+        }\r
+        if (empty($result)) {\r
+            return false;\r
+        }\r
+        if ($all_whitespace) {\r
+            $this->whitespace = true;\r
+            return false;\r
+        }\r
+        return $result;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Definition that allows a set of elements, and allows no children.\r
+ * @note This is a hack to reuse code from HTMLPurifier_ChildDef_Required,\r
+ *       really, one shouldn't inherit from the other.  Only altered behavior\r
+ *       is to overload a returned false with an array.  Thus, it will never\r
+ *       return false.\r
+ */\r
+class HTMLPurifier_ChildDef_Optional extends HTMLPurifier_ChildDef_Required\r
+{\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $allow_empty = true;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $type = 'optional';\r
+\r
+    /**\r
+     * @param array $children\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function validateChildren($children, $config, $context)\r
+    {\r
+        $result = parent::validateChildren($children, $config, $context);\r
+        // we assume that $children is not modified\r
+        if ($result === false) {\r
+            if (empty($children)) {\r
+                return true;\r
+            } elseif ($this->whitespace) {\r
+                return $children;\r
+            } else {\r
+                return array();\r
+            }\r
+        }\r
+        return $result;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Takes the contents of blockquote when in strict and reformats for validation.\r
+ */\r
+class HTMLPurifier_ChildDef_StrictBlockquote extends HTMLPurifier_ChildDef_Required\r
+{\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $real_elements;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $fake_elements;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $allow_empty = true;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $type = 'strictblockquote';\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    protected $init = false;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return array\r
+     * @note We don't want MakeWellFormed to auto-close inline elements since\r
+     *       they might be allowed.\r
+     */\r
+    public function getAllowedElements($config)\r
+    {\r
+        $this->init($config);\r
+        return $this->fake_elements;\r
+    }\r
+\r
+    /**\r
+     * @param array $children\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function validateChildren($children, $config, $context)\r
+    {\r
+        $this->init($config);\r
+\r
+        // trick the parent class into thinking it allows more\r
+        $this->elements = $this->fake_elements;\r
+        $result = parent::validateChildren($children, $config, $context);\r
+        $this->elements = $this->real_elements;\r
+\r
+        if ($result === false) {\r
+            return array();\r
+        }\r
+        if ($result === true) {\r
+            $result = $children;\r
+        }\r
+\r
+        $def = $config->getHTMLDefinition();\r
+        $block_wrap_name = $def->info_block_wrapper;\r
+        $block_wrap = false;\r
+        $ret = array();\r
+\r
+        foreach ($result as $node) {\r
+            if ($block_wrap === false) {\r
+                if (($node instanceof HTMLPurifier_Node_Text && !$node->is_whitespace) ||\r
+                    ($node instanceof HTMLPurifier_Node_Element && !isset($this->elements[$node->name]))) {\r
+                        $block_wrap = new HTMLPurifier_Node_Element($def->info_block_wrapper);\r
+                        $ret[] = $block_wrap;\r
+                }\r
+            } else {\r
+                if ($node instanceof HTMLPurifier_Node_Element && isset($this->elements[$node->name])) {\r
+                    $block_wrap = false;\r
+\r
+                }\r
+            }\r
+            if ($block_wrap) {\r
+                $block_wrap->children[] = $node;\r
+            } else {\r
+                $ret[] = $node;\r
+            }\r
+        }\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    private function init($config)\r
+    {\r
+        if (!$this->init) {\r
+            $def = $config->getHTMLDefinition();\r
+            // allow all inline elements\r
+            $this->real_elements = $this->elements;\r
+            $this->fake_elements = $def->info_content_sets['Flow'];\r
+            $this->fake_elements['#PCDATA'] = true;\r
+            $this->init = true;\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Definition for tables.  The general idea is to extract out all of the\r
+ * essential bits, and then reconstruct it later.\r
+ *\r
+ * This is a bit confusing, because the DTDs and the W3C\r
+ * validators seem to disagree on the appropriate definition. The\r
+ * DTD claims:\r
+ *\r
+ *      (CAPTION?, (COL*|COLGROUP*), THEAD?, TFOOT?, TBODY+)\r
+ *\r
+ * But actually, the HTML4 spec then has this to say:\r
+ *\r
+ *      The TBODY start tag is always required except when the table\r
+ *      contains only one table body and no table head or foot sections.\r
+ *      The TBODY end tag may always be safely omitted.\r
+ *\r
+ * So the DTD is kind of wrong.  The validator is, unfortunately, kind\r
+ * of on crack.\r
+ *\r
+ * The definition changed again in XHTML1.1; and in my opinion, this\r
+ * formulation makes the most sense.\r
+ *\r
+ *      caption?, ( col* | colgroup* ), (( thead?, tfoot?, tbody+ ) | ( tr+ ))\r
+ *\r
+ * Essentially, we have two modes: thead/tfoot/tbody mode, and tr mode.\r
+ * If we encounter a thead, tfoot or tbody, we are placed in the former\r
+ * mode, and we *must* wrap any stray tr segments with a tbody. But if\r
+ * we don't run into any of them, just have tr tags is OK.\r
+ */\r
+class HTMLPurifier_ChildDef_Table extends HTMLPurifier_ChildDef\r
+{\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $allow_empty = false;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $type = 'table';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $elements = array(\r
+        'tr' => true,\r
+        'tbody' => true,\r
+        'thead' => true,\r
+        'tfoot' => true,\r
+        'caption' => true,\r
+        'colgroup' => true,\r
+        'col' => true\r
+    );\r
+\r
+    public function __construct()\r
+    {\r
+    }\r
+\r
+    /**\r
+     * @param array $children\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array\r
+     */\r
+    public function validateChildren($children, $config, $context)\r
+    {\r
+        if (empty($children)) {\r
+            return false;\r
+        }\r
+\r
+        // only one of these elements is allowed in a table\r
+        $caption = false;\r
+        $thead = false;\r
+        $tfoot = false;\r
+\r
+        // whitespace\r
+        $initial_ws = array();\r
+        $after_caption_ws = array();\r
+        $after_thead_ws = array();\r
+        $after_tfoot_ws = array();\r
+\r
+        // as many of these as you want\r
+        $cols = array();\r
+        $content = array();\r
+\r
+        $tbody_mode = false; // if true, then we need to wrap any stray\r
+                             // <tr>s with a <tbody>.\r
+\r
+        $ws_accum =& $initial_ws;\r
+\r
+        foreach ($children as $node) {\r
+            if ($node instanceof HTMLPurifier_Node_Comment) {\r
+                $ws_accum[] = $node;\r
+                continue;\r
+            }\r
+            switch ($node->name) {\r
+            case 'tbody':\r
+                $tbody_mode = true;\r
+                // fall through\r
+            case 'tr':\r
+                $content[] = $node;\r
+                $ws_accum =& $content;\r
+                break;\r
+            case 'caption':\r
+                // there can only be one caption!\r
+                if ($caption !== false)  break;\r
+                $caption = $node;\r
+                $ws_accum =& $after_caption_ws;\r
+                break;\r
+            case 'thead':\r
+                $tbody_mode = true;\r
+                // XXX This breaks rendering properties with\r
+                // Firefox, which never floats a <thead> to\r
+                // the top. Ever. (Our scheme will float the\r
+                // first <thead> to the top.)  So maybe\r
+                // <thead>s that are not first should be\r
+                // turned into <tbody>? Very tricky, indeed.\r
+                if ($thead === false) {\r
+                    $thead = $node;\r
+                    $ws_accum =& $after_thead_ws;\r
+                } else {\r
+                    // Oops, there's a second one! What\r
+                    // should we do?  Current behavior is to\r
+                    // transmutate the first and last entries into\r
+                    // tbody tags, and then put into content.\r
+                    // Maybe a better idea is to *attach\r
+                    // it* to the existing thead or tfoot?\r
+                    // We don't do this, because Firefox\r
+                    // doesn't float an extra tfoot to the\r
+                    // bottom like it does for the first one.\r
+                    $node->name = 'tbody';\r
+                    $content[] = $node;\r
+                    $ws_accum =& $content;\r
+                }\r
+                break;\r
+            case 'tfoot':\r
+                // see above for some aveats\r
+                $tbody_mode = true;\r
+                if ($tfoot === false) {\r
+                    $tfoot = $node;\r
+                    $ws_accum =& $after_tfoot_ws;\r
+                } else {\r
+                    $node->name = 'tbody';\r
+                    $content[] = $node;\r
+                    $ws_accum =& $content;\r
+                }\r
+                break;\r
+            case 'colgroup':\r
+            case 'col':\r
+                $cols[] = $node;\r
+                $ws_accum =& $cols;\r
+                break;\r
+            case '#PCDATA':\r
+                // How is whitespace handled? We treat is as sticky to\r
+                // the *end* of the previous element. So all of the\r
+                // nonsense we have worked on is to keep things\r
+                // together.\r
+                if (!empty($node->is_whitespace)) {\r
+                    $ws_accum[] = $node;\r
+                }\r
+                break;\r
+            }\r
+        }\r
+\r
+        if (empty($content)) {\r
+            return false;\r
+        }\r
+\r
+        $ret = $initial_ws;\r
+        if ($caption !== false) {\r
+            $ret[] = $caption;\r
+            $ret = array_merge($ret, $after_caption_ws);\r
+        }\r
+        if ($cols !== false) {\r
+            $ret = array_merge($ret, $cols);\r
+        }\r
+        if ($thead !== false) {\r
+            $ret[] = $thead;\r
+            $ret = array_merge($ret, $after_thead_ws);\r
+        }\r
+        if ($tfoot !== false) {\r
+            $ret[] = $tfoot;\r
+            $ret = array_merge($ret, $after_tfoot_ws);\r
+        }\r
+\r
+        if ($tbody_mode) {\r
+            // we have to shuffle tr into tbody\r
+            $current_tr_tbody = null;\r
+\r
+            foreach($content as $node) {\r
+                switch ($node->name) {\r
+                case 'tbody':\r
+                    $current_tr_tbody = null;\r
+                    $ret[] = $node;\r
+                    break;\r
+                case 'tr':\r
+                    if ($current_tr_tbody === null) {\r
+                        $current_tr_tbody = new HTMLPurifier_Node_Element('tbody');\r
+                        $ret[] = $current_tr_tbody;\r
+                    }\r
+                    $current_tr_tbody->children[] = $node;\r
+                    break;\r
+                case '#PCDATA':\r
+                    //assert($node->is_whitespace);\r
+                    if ($current_tr_tbody === null) {\r
+                        $ret[] = $node;\r
+                    } else {\r
+                        $current_tr_tbody->children[] = $node;\r
+                    }\r
+                    break;\r
+                }\r
+            }\r
+        } else {\r
+            $ret = array_merge($ret, $content);\r
+        }\r
+\r
+        return $ret;\r
+\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_DefinitionCache_Decorator extends HTMLPurifier_DefinitionCache\r
+{\r
+\r
+    /**\r
+     * Cache object we are decorating\r
+     * @type HTMLPurifier_DefinitionCache\r
+     */\r
+    public $cache;\r
+\r
+    /**\r
+     * The name of the decorator\r
+     * @var string\r
+     */\r
+    public $name;\r
+\r
+    public function __construct()\r
+    {\r
+    }\r
+\r
+    /**\r
+     * Lazy decorator function\r
+     * @param HTMLPurifier_DefinitionCache $cache Reference to cache object to decorate\r
+     * @return HTMLPurifier_DefinitionCache_Decorator\r
+     */\r
+    public function decorate(&$cache)\r
+    {\r
+        $decorator = $this->copy();\r
+        // reference is necessary for mocks in PHP 4\r
+        $decorator->cache =& $cache;\r
+        $decorator->type = $cache->type;\r
+        return $decorator;\r
+    }\r
+\r
+    /**\r
+     * Cross-compatible clone substitute\r
+     * @return HTMLPurifier_DefinitionCache_Decorator\r
+     */\r
+    public function copy()\r
+    {\r
+        return new HTMLPurifier_DefinitionCache_Decorator();\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function add($def, $config)\r
+    {\r
+        return $this->cache->add($def, $config);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function set($def, $config)\r
+    {\r
+        return $this->cache->set($def, $config);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function replace($def, $config)\r
+    {\r
+        return $this->cache->replace($def, $config);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function get($config)\r
+    {\r
+        return $this->cache->get($config);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function remove($config)\r
+    {\r
+        return $this->cache->remove($config);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function flush($config)\r
+    {\r
+        return $this->cache->flush($config);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function cleanup($config)\r
+    {\r
+        return $this->cache->cleanup($config);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Null cache object to use when no caching is on.\r
+ */\r
+class HTMLPurifier_DefinitionCache_Null extends HTMLPurifier_DefinitionCache\r
+{\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function add($def, $config)\r
+    {\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function set($def, $config)\r
+    {\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function replace($def, $config)\r
+    {\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function remove($config)\r
+    {\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function get($config)\r
+    {\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function flush($config)\r
+    {\r
+        return false;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function cleanup($config)\r
+    {\r
+        return false;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_DefinitionCache_Serializer extends HTMLPurifier_DefinitionCache\r
+{\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return int|bool\r
+     */\r
+    public function add($def, $config)\r
+    {\r
+        if (!$this->checkDefType($def)) {\r
+            return;\r
+        }\r
+        $file = $this->generateFilePath($config);\r
+        if (file_exists($file)) {\r
+            return false;\r
+        }\r
+        if (!$this->_prepareDir($config)) {\r
+            return false;\r
+        }\r
+        return $this->_write($file, serialize($def), $config);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return int|bool\r
+     */\r
+    public function set($def, $config)\r
+    {\r
+        if (!$this->checkDefType($def)) {\r
+            return;\r
+        }\r
+        $file = $this->generateFilePath($config);\r
+        if (!$this->_prepareDir($config)) {\r
+            return false;\r
+        }\r
+        return $this->_write($file, serialize($def), $config);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return int|bool\r
+     */\r
+    public function replace($def, $config)\r
+    {\r
+        if (!$this->checkDefType($def)) {\r
+            return;\r
+        }\r
+        $file = $this->generateFilePath($config);\r
+        if (!file_exists($file)) {\r
+            return false;\r
+        }\r
+        if (!$this->_prepareDir($config)) {\r
+            return false;\r
+        }\r
+        return $this->_write($file, serialize($def), $config);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool|HTMLPurifier_Config\r
+     */\r
+    public function get($config)\r
+    {\r
+        $file = $this->generateFilePath($config);\r
+        if (!file_exists($file)) {\r
+            return false;\r
+        }\r
+        return unserialize(file_get_contents($file));\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function remove($config)\r
+    {\r
+        $file = $this->generateFilePath($config);\r
+        if (!file_exists($file)) {\r
+            return false;\r
+        }\r
+        return unlink($file);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function flush($config)\r
+    {\r
+        if (!$this->_prepareDir($config)) {\r
+            return false;\r
+        }\r
+        $dir = $this->generateDirectoryPath($config);\r
+        $dh = opendir($dir);\r
+        // Apparently, on some versions of PHP, readdir will return\r
+        // an empty string if you pass an invalid argument to readdir.\r
+        // So you need this test.  See #49.\r
+        if (false === $dh) {\r
+            return false;\r
+        }\r
+        while (false !== ($filename = readdir($dh))) {\r
+            if (empty($filename)) {\r
+                continue;\r
+            }\r
+            if ($filename[0] === '.') {\r
+                continue;\r
+            }\r
+            unlink($dir . '/' . $filename);\r
+        }\r
+        closedir($dh);\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function cleanup($config)\r
+    {\r
+        if (!$this->_prepareDir($config)) {\r
+            return false;\r
+        }\r
+        $dir = $this->generateDirectoryPath($config);\r
+        $dh = opendir($dir);\r
+        // See #49 (and above).\r
+        if (false === $dh) {\r
+            return false;\r
+        }\r
+        while (false !== ($filename = readdir($dh))) {\r
+            if (empty($filename)) {\r
+                continue;\r
+            }\r
+            if ($filename[0] === '.') {\r
+                continue;\r
+            }\r
+            $key = substr($filename, 0, strlen($filename) - 4);\r
+            if ($this->isOld($key, $config)) {\r
+                unlink($dir . '/' . $filename);\r
+            }\r
+        }\r
+        closedir($dh);\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Generates the file path to the serial file corresponding to\r
+     * the configuration and definition name\r
+     * @param HTMLPurifier_Config $config\r
+     * @return string\r
+     * @todo Make protected\r
+     */\r
+    public function generateFilePath($config)\r
+    {\r
+        $key = $this->generateKey($config);\r
+        return $this->generateDirectoryPath($config) . '/' . $key . '.ser';\r
+    }\r
+\r
+    /**\r
+     * Generates the path to the directory contain this cache's serial files\r
+     * @param HTMLPurifier_Config $config\r
+     * @return string\r
+     * @note No trailing slash\r
+     * @todo Make protected\r
+     */\r
+    public function generateDirectoryPath($config)\r
+    {\r
+        $base = $this->generateBaseDirectoryPath($config);\r
+        return $base . '/' . $this->type;\r
+    }\r
+\r
+    /**\r
+     * Generates path to base directory that contains all definition type\r
+     * serials\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed|string\r
+     * @todo Make protected\r
+     */\r
+    public function generateBaseDirectoryPath($config)\r
+    {\r
+        $base = $config->get('Cache.SerializerPath');\r
+        $base = is_null($base) ? HTMLPURIFIER_PREFIX . '/HTMLPurifier/DefinitionCache/Serializer' : $base;\r
+        return $base;\r
+    }\r
+\r
+    /**\r
+     * Convenience wrapper function for file_put_contents\r
+     * @param string $file File name to write to\r
+     * @param string $data Data to write into file\r
+     * @param HTMLPurifier_Config $config\r
+     * @return int|bool Number of bytes written if success, or false if failure.\r
+     */\r
+    private function _write($file, $data, $config)\r
+    {\r
+        $result = file_put_contents($file, $data);\r
+        if ($result !== false) {\r
+            // set permissions of the new file (no execute)\r
+            $chmod = $config->get('Cache.SerializerPermissions');\r
+            if ($chmod !== null) {\r
+                chmod($file, $chmod & 0666);\r
+            }\r
+        }\r
+        return $result;\r
+    }\r
+\r
+    /**\r
+     * Prepares the directory that this type stores the serials in\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool True if successful\r
+     */\r
+    private function _prepareDir($config)\r
+    {\r
+        $directory = $this->generateDirectoryPath($config);\r
+        $chmod = $config->get('Cache.SerializerPermissions');\r
+        if ($chmod === null) {\r
+            if (!@mkdir($directory) && !is_dir($directory)) {\r
+                trigger_error(\r
+                    'Could not create directory ' . $directory . '',\r
+                    E_USER_WARNING\r
+                );\r
+                return false;\r
+            }\r
+            return true;\r
+        }\r
+        if (!is_dir($directory)) {\r
+            $base = $this->generateBaseDirectoryPath($config);\r
+            if (!is_dir($base)) {\r
+                trigger_error(\r
+                    'Base directory ' . $base . ' does not exist,\r
+                    please create or change using %Cache.SerializerPath',\r
+                    E_USER_WARNING\r
+                );\r
+                return false;\r
+            } elseif (!$this->_testPermissions($base, $chmod)) {\r
+                return false;\r
+            }\r
+            if (!@mkdir($directory, $chmod) && !is_dir($directory)) {\r
+                trigger_error(\r
+                    'Could not create directory ' . $directory . '',\r
+                    E_USER_WARNING\r
+                );\r
+                return false;\r
+            }\r
+            if (!$this->_testPermissions($directory, $chmod)) {\r
+                return false;\r
+            }\r
+        } elseif (!$this->_testPermissions($directory, $chmod)) {\r
+            return false;\r
+        }\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Tests permissions on a directory and throws out friendly\r
+     * error messages and attempts to chmod it itself if possible\r
+     * @param string $dir Directory path\r
+     * @param int $chmod Permissions\r
+     * @return bool True if directory is writable\r
+     */\r
+    private function _testPermissions($dir, $chmod)\r
+    {\r
+        // early abort, if it is writable, everything is hunky-dory\r
+        if (is_writable($dir)) {\r
+            return true;\r
+        }\r
+        if (!is_dir($dir)) {\r
+            // generally, you'll want to handle this beforehand\r
+            // so a more specific error message can be given\r
+            trigger_error(\r
+                'Directory ' . $dir . ' does not exist',\r
+                E_USER_WARNING\r
+            );\r
+            return false;\r
+        }\r
+        if (function_exists('posix_getuid') && $chmod !== null) {\r
+            // POSIX system, we can give more specific advice\r
+            if (fileowner($dir) === posix_getuid()) {\r
+                // we can chmod it ourselves\r
+                $chmod = $chmod | 0700;\r
+                if (chmod($dir, $chmod)) {\r
+                    return true;\r
+                }\r
+            } elseif (filegroup($dir) === posix_getgid()) {\r
+                $chmod = $chmod | 0070;\r
+            } else {\r
+                // PHP's probably running as nobody, so we'll\r
+                // need to give global permissions\r
+                $chmod = $chmod | 0777;\r
+            }\r
+            trigger_error(\r
+                'Directory ' . $dir . ' not writable, ' .\r
+                'please chmod to ' . decoct($chmod),\r
+                E_USER_WARNING\r
+            );\r
+        } else {\r
+            // generic error message\r
+            trigger_error(\r
+                'Directory ' . $dir . ' not writable, ' .\r
+                'please alter file permissions',\r
+                E_USER_WARNING\r
+            );\r
+        }\r
+        return false;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Definition cache decorator class that cleans up the cache\r
+ * whenever there is a cache miss.\r
+ */\r
+class HTMLPurifier_DefinitionCache_Decorator_Cleanup extends HTMLPurifier_DefinitionCache_Decorator\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Cleanup';\r
+\r
+    /**\r
+     * @return HTMLPurifier_DefinitionCache_Decorator_Cleanup\r
+     */\r
+    public function copy()\r
+    {\r
+        return new HTMLPurifier_DefinitionCache_Decorator_Cleanup();\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function add($def, $config)\r
+    {\r
+        $status = parent::add($def, $config);\r
+        if (!$status) {\r
+            parent::cleanup($config);\r
+        }\r
+        return $status;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function set($def, $config)\r
+    {\r
+        $status = parent::set($def, $config);\r
+        if (!$status) {\r
+            parent::cleanup($config);\r
+        }\r
+        return $status;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function replace($def, $config)\r
+    {\r
+        $status = parent::replace($def, $config);\r
+        if (!$status) {\r
+            parent::cleanup($config);\r
+        }\r
+        return $status;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function get($config)\r
+    {\r
+        $ret = parent::get($config);\r
+        if (!$ret) {\r
+            parent::cleanup($config);\r
+        }\r
+        return $ret;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Definition cache decorator class that saves all cache retrievals\r
+ * to PHP's memory; good for unit tests or circumstances where\r
+ * there are lots of configuration objects floating around.\r
+ */\r
+class HTMLPurifier_DefinitionCache_Decorator_Memory extends HTMLPurifier_DefinitionCache_Decorator\r
+{\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $definitions;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Memory';\r
+\r
+    /**\r
+     * @return HTMLPurifier_DefinitionCache_Decorator_Memory\r
+     */\r
+    public function copy()\r
+    {\r
+        return new HTMLPurifier_DefinitionCache_Decorator_Memory();\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function add($def, $config)\r
+    {\r
+        $status = parent::add($def, $config);\r
+        if ($status) {\r
+            $this->definitions[$this->generateKey($config)] = $def;\r
+        }\r
+        return $status;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function set($def, $config)\r
+    {\r
+        $status = parent::set($def, $config);\r
+        if ($status) {\r
+            $this->definitions[$this->generateKey($config)] = $def;\r
+        }\r
+        return $status;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Definition $def\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function replace($def, $config)\r
+    {\r
+        $status = parent::replace($def, $config);\r
+        if ($status) {\r
+            $this->definitions[$this->generateKey($config)] = $def;\r
+        }\r
+        return $status;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return mixed\r
+     */\r
+    public function get($config)\r
+    {\r
+        $key = $this->generateKey($config);\r
+        if (isset($this->definitions[$key])) {\r
+            return $this->definitions[$key];\r
+        }\r
+        $this->definitions[$key] = parent::get($config);\r
+        return $this->definitions[$key];\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Bi-directional Text Module, defines elements that\r
+ * declare directionality of content. Text Extension Module.\r
+ */\r
+class HTMLPurifier_HTMLModule_Bdo extends HTMLPurifier_HTMLModule\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Bdo';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $attr_collections = array(\r
+        'I18N' => array('dir' => false)\r
+    );\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $bdo = $this->addElement(\r
+            'bdo',\r
+            'Inline',\r
+            'Inline',\r
+            array('Core', 'Lang'),\r
+            array(\r
+                'dir' => 'Enum#ltr,rtl', // required\r
+                // The Abstract Module specification has the attribute\r
+                // inclusions wrong for bdo: bdo allows Lang\r
+            )\r
+        );\r
+        $bdo->attr_transform_post[] = new HTMLPurifier_AttrTransform_BdoDir();\r
+\r
+        $this->attr_collections['I18N']['dir'] = 'Enum#ltr,rtl';\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_HTMLModule_CommonAttributes extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'CommonAttributes';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $attr_collections = array(\r
+        'Core' => array(\r
+            0 => array('Style'),\r
+            // 'xml:space' => false,\r
+            'class' => 'Class',\r
+            'id' => 'ID',\r
+            'title' => 'CDATA',\r
+        ),\r
+        'Lang' => array(),\r
+        'I18N' => array(\r
+            0 => array('Lang'), // proprietary, for xml:lang/lang\r
+        ),\r
+        'Common' => array(\r
+            0 => array('Core', 'I18N')\r
+        )\r
+    );\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Edit Module, defines editing-related elements. Text Extension\r
+ * Module.\r
+ */\r
+class HTMLPurifier_HTMLModule_Edit extends HTMLPurifier_HTMLModule\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Edit';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $contents = 'Chameleon: #PCDATA | Inline ! #PCDATA | Flow';\r
+        $attr = array(\r
+            'cite' => 'URI',\r
+            // 'datetime' => 'Datetime', // not implemented\r
+        );\r
+        $this->addElement('del', 'Inline', $contents, 'Common', $attr);\r
+        $this->addElement('ins', 'Inline', $contents, 'Common', $attr);\r
+    }\r
+\r
+    // HTML 4.01 specifies that ins/del must not contain block\r
+    // elements when used in an inline context, chameleon is\r
+    // a complicated workaround to acheive this effect\r
+\r
+    // Inline context ! Block context (exclamation mark is\r
+    // separator, see getChildDef for parsing)\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $defines_child_def = true;\r
+\r
+    /**\r
+     * @param HTMLPurifier_ElementDef $def\r
+     * @return HTMLPurifier_ChildDef_Chameleon\r
+     */\r
+    public function getChildDef($def)\r
+    {\r
+        if ($def->content_model_type != 'chameleon') {\r
+            return false;\r
+        }\r
+        $value = explode('!', $def->content_model);\r
+        return new HTMLPurifier_ChildDef_Chameleon($value[0], $value[1]);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Forms module, defines all form-related elements found in HTML 4.\r
+ */\r
+class HTMLPurifier_HTMLModule_Forms extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Forms';\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $safe = false;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $content_sets = array(\r
+        'Block' => 'Form',\r
+        'Inline' => 'Formctrl',\r
+    );\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $form = $this->addElement(\r
+            'form',\r
+            'Form',\r
+            'Required: Heading | List | Block | fieldset',\r
+            'Common',\r
+            array(\r
+                'accept' => 'ContentTypes',\r
+                'accept-charset' => 'Charsets',\r
+                'action*' => 'URI',\r
+                'method' => 'Enum#get,post',\r
+                // really ContentType, but these two are the only ones used today\r
+                'enctype' => 'Enum#application/x-www-form-urlencoded,multipart/form-data',\r
+            )\r
+        );\r
+        $form->excludes = array('form' => true);\r
+\r
+        $input = $this->addElement(\r
+            'input',\r
+            'Formctrl',\r
+            'Empty',\r
+            'Common',\r
+            array(\r
+                'accept' => 'ContentTypes',\r
+                'accesskey' => 'Character',\r
+                'alt' => 'Text',\r
+                'checked' => 'Bool#checked',\r
+                'disabled' => 'Bool#disabled',\r
+                'maxlength' => 'Number',\r
+                'name' => 'CDATA',\r
+                'readonly' => 'Bool#readonly',\r
+                'size' => 'Number',\r
+                'src' => 'URI#embedded',\r
+                'tabindex' => 'Number',\r
+                'type' => 'Enum#text,password,checkbox,button,radio,submit,reset,file,hidden,image',\r
+                'value' => 'CDATA',\r
+            )\r
+        );\r
+        $input->attr_transform_post[] = new HTMLPurifier_AttrTransform_Input();\r
+\r
+        $this->addElement(\r
+            'select',\r
+            'Formctrl',\r
+            'Required: optgroup | option',\r
+            'Common',\r
+            array(\r
+                'disabled' => 'Bool#disabled',\r
+                'multiple' => 'Bool#multiple',\r
+                'name' => 'CDATA',\r
+                'size' => 'Number',\r
+                'tabindex' => 'Number',\r
+            )\r
+        );\r
+\r
+        $this->addElement(\r
+            'option',\r
+            false,\r
+            'Optional: #PCDATA',\r
+            'Common',\r
+            array(\r
+                'disabled' => 'Bool#disabled',\r
+                'label' => 'Text',\r
+                'selected' => 'Bool#selected',\r
+                'value' => 'CDATA',\r
+            )\r
+        );\r
+        // It's illegal for there to be more than one selected, but not\r
+        // be multiple. Also, no selected means undefined behavior. This might\r
+        // be difficult to implement; perhaps an injector, or a context variable.\r
+\r
+        $textarea = $this->addElement(\r
+            'textarea',\r
+            'Formctrl',\r
+            'Optional: #PCDATA',\r
+            'Common',\r
+            array(\r
+                'accesskey' => 'Character',\r
+                'cols*' => 'Number',\r
+                'disabled' => 'Bool#disabled',\r
+                'name' => 'CDATA',\r
+                'readonly' => 'Bool#readonly',\r
+                'rows*' => 'Number',\r
+                'tabindex' => 'Number',\r
+            )\r
+        );\r
+        $textarea->attr_transform_pre[] = new HTMLPurifier_AttrTransform_Textarea();\r
+\r
+        $button = $this->addElement(\r
+            'button',\r
+            'Formctrl',\r
+            'Optional: #PCDATA | Heading | List | Block | Inline',\r
+            'Common',\r
+            array(\r
+                'accesskey' => 'Character',\r
+                'disabled' => 'Bool#disabled',\r
+                'name' => 'CDATA',\r
+                'tabindex' => 'Number',\r
+                'type' => 'Enum#button,submit,reset',\r
+                'value' => 'CDATA',\r
+            )\r
+        );\r
+\r
+        // For exclusions, ideally we'd specify content sets, not literal elements\r
+        $button->excludes = $this->makeLookup(\r
+            'form',\r
+            'fieldset', // Form\r
+            'input',\r
+            'select',\r
+            'textarea',\r
+            'label',\r
+            'button', // Formctrl\r
+            'a', // as per HTML 4.01 spec, this is omitted by modularization\r
+            'isindex',\r
+            'iframe' // legacy items\r
+        );\r
+\r
+        // Extra exclusion: img usemap="" is not permitted within this element.\r
+        // We'll omit this for now, since we don't have any good way of\r
+        // indicating it yet.\r
+\r
+        // This is HIGHLY user-unfriendly; we need a custom child-def for this\r
+        $this->addElement('fieldset', 'Form', 'Custom: (#WS?,legend,(Flow|#PCDATA)*)', 'Common');\r
+\r
+        $label = $this->addElement(\r
+            'label',\r
+            'Formctrl',\r
+            'Optional: #PCDATA | Inline',\r
+            'Common',\r
+            array(\r
+                'accesskey' => 'Character',\r
+                // 'for' => 'IDREF', // IDREF not implemented, cannot allow\r
+            )\r
+        );\r
+        $label->excludes = array('label' => true);\r
+\r
+        $this->addElement(\r
+            'legend',\r
+            false,\r
+            'Optional: #PCDATA | Inline',\r
+            'Common',\r
+            array(\r
+                'accesskey' => 'Character',\r
+            )\r
+        );\r
+\r
+        $this->addElement(\r
+            'optgroup',\r
+            false,\r
+            'Required: option',\r
+            'Common',\r
+            array(\r
+                'disabled' => 'Bool#disabled',\r
+                'label*' => 'Text',\r
+            )\r
+        );\r
+        // Don't forget an injector for <isindex>. This one's a little complex\r
+        // because it maps to multiple elements.\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Hypertext Module, defines hypertext links. Core Module.\r
+ */\r
+class HTMLPurifier_HTMLModule_Hypertext extends HTMLPurifier_HTMLModule\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Hypertext';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $a = $this->addElement(\r
+            'a',\r
+            'Inline',\r
+            'Inline',\r
+            'Common',\r
+            array(\r
+                // 'accesskey' => 'Character',\r
+                // 'charset' => 'Charset',\r
+                'href' => 'URI',\r
+                // 'hreflang' => 'LanguageCode',\r
+                'rel' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rel'),\r
+                'rev' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rev'),\r
+                // 'tabindex' => 'Number',\r
+                // 'type' => 'ContentType',\r
+            )\r
+        );\r
+        $a->formatting = true;\r
+        $a->excludes = array('a' => true);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Iframe Module provides inline frames.\r
+ *\r
+ * @note This module is not considered safe unless an Iframe\r
+ * whitelisting mechanism is specified.  Currently, the only\r
+ * such mechanism is %URL.SafeIframeRegexp\r
+ */\r
+class HTMLPurifier_HTMLModule_Iframe extends HTMLPurifier_HTMLModule\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Iframe';\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $safe = false;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        if ($config->get('HTML.SafeIframe')) {\r
+            $this->safe = true;\r
+        }\r
+        $this->addElement(\r
+            'iframe',\r
+            'Inline',\r
+            'Flow',\r
+            'Common',\r
+            array(\r
+                'src' => 'URI#embedded',\r
+                'width' => 'Length',\r
+                'height' => 'Length',\r
+                'name' => 'ID',\r
+                'scrolling' => 'Enum#yes,no,auto',\r
+                'frameborder' => 'Enum#0,1',\r
+                'longdesc' => 'URI',\r
+                'marginheight' => 'Pixels',\r
+                'marginwidth' => 'Pixels',\r
+            )\r
+        );\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Image Module provides basic image embedding.\r
+ * @note There is specialized code for removing empty images in\r
+ *       HTMLPurifier_Strategy_RemoveForeignElements\r
+ */\r
+class HTMLPurifier_HTMLModule_Image extends HTMLPurifier_HTMLModule\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Image';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $max = $config->get('HTML.MaxImgLength');\r
+        $img = $this->addElement(\r
+            'img',\r
+            'Inline',\r
+            'Empty',\r
+            'Common',\r
+            array(\r
+                'alt*' => 'Text',\r
+                // According to the spec, it's Length, but percents can\r
+                // be abused, so we allow only Pixels.\r
+                'height' => 'Pixels#' . $max,\r
+                'width' => 'Pixels#' . $max,\r
+                'longdesc' => 'URI',\r
+                'src*' => new HTMLPurifier_AttrDef_URI(true), // embedded\r
+            )\r
+        );\r
+        if ($max === null || $config->get('HTML.Trusted')) {\r
+            $img->attr['height'] =\r
+            $img->attr['width'] = 'Length';\r
+        }\r
+\r
+        // kind of strange, but splitting things up would be inefficient\r
+        $img->attr_transform_pre[] =\r
+        $img->attr_transform_post[] =\r
+            new HTMLPurifier_AttrTransform_ImgRequired();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Legacy module defines elements that were previously\r
+ * deprecated.\r
+ *\r
+ * @note Not all legacy elements have been implemented yet, which\r
+ *       is a bit of a reverse problem as compared to browsers! In\r
+ *       addition, this legacy module may implement a bit more than\r
+ *       mandated by XHTML 1.1.\r
+ *\r
+ * This module can be used in combination with TransformToStrict in order\r
+ * to transform as many deprecated elements as possible, but retain\r
+ * questionably deprecated elements that do not have good alternatives\r
+ * as well as transform elements that don't have an implementation.\r
+ * See docs/ref-strictness.txt for more details.\r
+ */\r
+\r
+class HTMLPurifier_HTMLModule_Legacy extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Legacy';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $this->addElement(\r
+            'basefont',\r
+            'Inline',\r
+            'Empty',\r
+            null,\r
+            array(\r
+                'color' => 'Color',\r
+                'face' => 'Text', // extremely broad, we should\r
+                'size' => 'Text', // tighten it\r
+                'id' => 'ID'\r
+            )\r
+        );\r
+        $this->addElement('center', 'Block', 'Flow', 'Common');\r
+        $this->addElement(\r
+            'dir',\r
+            'Block',\r
+            'Required: li',\r
+            'Common',\r
+            array(\r
+                'compact' => 'Bool#compact'\r
+            )\r
+        );\r
+        $this->addElement(\r
+            'font',\r
+            'Inline',\r
+            'Inline',\r
+            array('Core', 'I18N'),\r
+            array(\r
+                'color' => 'Color',\r
+                'face' => 'Text', // extremely broad, we should\r
+                'size' => 'Text', // tighten it\r
+            )\r
+        );\r
+        $this->addElement(\r
+            'menu',\r
+            'Block',\r
+            'Required: li',\r
+            'Common',\r
+            array(\r
+                'compact' => 'Bool#compact'\r
+            )\r
+        );\r
+\r
+        $s = $this->addElement('s', 'Inline', 'Inline', 'Common');\r
+        $s->formatting = true;\r
+\r
+        $strike = $this->addElement('strike', 'Inline', 'Inline', 'Common');\r
+        $strike->formatting = true;\r
+\r
+        $u = $this->addElement('u', 'Inline', 'Inline', 'Common');\r
+        $u->formatting = true;\r
+\r
+        // setup modifications to old elements\r
+\r
+        $align = 'Enum#left,right,center,justify';\r
+\r
+        $address = $this->addBlankElement('address');\r
+        $address->content_model = 'Inline | #PCDATA | p';\r
+        $address->content_model_type = 'optional';\r
+        $address->child = false;\r
+\r
+        $blockquote = $this->addBlankElement('blockquote');\r
+        $blockquote->content_model = 'Flow | #PCDATA';\r
+        $blockquote->content_model_type = 'optional';\r
+        $blockquote->child = false;\r
+\r
+        $br = $this->addBlankElement('br');\r
+        $br->attr['clear'] = 'Enum#left,all,right,none';\r
+\r
+        $caption = $this->addBlankElement('caption');\r
+        $caption->attr['align'] = 'Enum#top,bottom,left,right';\r
+\r
+        $div = $this->addBlankElement('div');\r
+        $div->attr['align'] = $align;\r
+\r
+        $dl = $this->addBlankElement('dl');\r
+        $dl->attr['compact'] = 'Bool#compact';\r
+\r
+        for ($i = 1; $i <= 6; $i++) {\r
+            $h = $this->addBlankElement("h$i");\r
+            $h->attr['align'] = $align;\r
+        }\r
+\r
+        $hr = $this->addBlankElement('hr');\r
+        $hr->attr['align'] = $align;\r
+        $hr->attr['noshade'] = 'Bool#noshade';\r
+        $hr->attr['size'] = 'Pixels';\r
+        $hr->attr['width'] = 'Length';\r
+\r
+        $img = $this->addBlankElement('img');\r
+        $img->attr['align'] = 'IAlign';\r
+        $img->attr['border'] = 'Pixels';\r
+        $img->attr['hspace'] = 'Pixels';\r
+        $img->attr['vspace'] = 'Pixels';\r
+\r
+        // figure out this integer business\r
+\r
+        $li = $this->addBlankElement('li');\r
+        $li->attr['value'] = new HTMLPurifier_AttrDef_Integer();\r
+        $li->attr['type'] = 'Enum#s:1,i,I,a,A,disc,square,circle';\r
+\r
+        $ol = $this->addBlankElement('ol');\r
+        $ol->attr['compact'] = 'Bool#compact';\r
+        $ol->attr['start'] = new HTMLPurifier_AttrDef_Integer();\r
+        $ol->attr['type'] = 'Enum#s:1,i,I,a,A';\r
+\r
+        $p = $this->addBlankElement('p');\r
+        $p->attr['align'] = $align;\r
+\r
+        $pre = $this->addBlankElement('pre');\r
+        $pre->attr['width'] = 'Number';\r
+\r
+        // script omitted\r
+\r
+        $table = $this->addBlankElement('table');\r
+        $table->attr['align'] = 'Enum#left,center,right';\r
+        $table->attr['bgcolor'] = 'Color';\r
+\r
+        $tr = $this->addBlankElement('tr');\r
+        $tr->attr['bgcolor'] = 'Color';\r
+\r
+        $th = $this->addBlankElement('th');\r
+        $th->attr['bgcolor'] = 'Color';\r
+        $th->attr['height'] = 'Length';\r
+        $th->attr['nowrap'] = 'Bool#nowrap';\r
+        $th->attr['width'] = 'Length';\r
+\r
+        $td = $this->addBlankElement('td');\r
+        $td->attr['bgcolor'] = 'Color';\r
+        $td->attr['height'] = 'Length';\r
+        $td->attr['nowrap'] = 'Bool#nowrap';\r
+        $td->attr['width'] = 'Length';\r
+\r
+        $ul = $this->addBlankElement('ul');\r
+        $ul->attr['compact'] = 'Bool#compact';\r
+        $ul->attr['type'] = 'Enum#square,disc,circle';\r
+\r
+        // "safe" modifications to "unsafe" elements\r
+        // WARNING: If you want to add support for an unsafe, legacy\r
+        // attribute, make a new TrustedLegacy module with the trusted\r
+        // bit set appropriately\r
+\r
+        $form = $this->addBlankElement('form');\r
+        $form->content_model = 'Flow | #PCDATA';\r
+        $form->content_model_type = 'optional';\r
+        $form->attr['target'] = 'FrameTarget';\r
+\r
+        $input = $this->addBlankElement('input');\r
+        $input->attr['align'] = 'IAlign';\r
+\r
+        $legend = $this->addBlankElement('legend');\r
+        $legend->attr['align'] = 'LAlign';\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 List Module, defines list-oriented elements. Core Module.\r
+ */\r
+class HTMLPurifier_HTMLModule_List extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'List';\r
+\r
+    // According to the abstract schema, the List content set is a fully formed\r
+    // one or more expr, but it invariably occurs in an optional declaration\r
+    // so we're not going to do that subtlety. It might cause trouble\r
+    // if a user defines "List" and expects that multiple lists are\r
+    // allowed to be specified, but then again, that's not very intuitive.\r
+    // Furthermore, the actual XML Schema may disagree. Regardless,\r
+    // we don't have support for such nested expressions without using\r
+    // the incredibly inefficient and draconic Custom ChildDef.\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $content_sets = array('Flow' => 'List');\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $ol = $this->addElement('ol', 'List', new HTMLPurifier_ChildDef_List(), 'Common');\r
+        $ul = $this->addElement('ul', 'List', new HTMLPurifier_ChildDef_List(), 'Common');\r
+        // XXX The wrap attribute is handled by MakeWellFormed.  This is all\r
+        // quite unsatisfactory, because we generated this\r
+        // *specifically* for lists, and now a big chunk of the handling\r
+        // is done properly by the List ChildDef.  So actually, we just\r
+        // want enough information to make autoclosing work properly,\r
+        // and then hand off the tricky stuff to the ChildDef.\r
+        $ol->wrap = 'li';\r
+        $ul->wrap = 'li';\r
+        $this->addElement('dl', 'List', 'Required: dt | dd', 'Common');\r
+\r
+        $this->addElement('li', false, 'Flow', 'Common');\r
+\r
+        $this->addElement('dd', false, 'Flow', 'Common');\r
+        $this->addElement('dt', false, 'Inline', 'Common');\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_HTMLModule_Name extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Name';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $elements = array('a', 'applet', 'form', 'frame', 'iframe', 'img', 'map');\r
+        foreach ($elements as $name) {\r
+            $element = $this->addBlankElement($name);\r
+            $element->attr['name'] = 'CDATA';\r
+            if (!$config->get('HTML.Attr.Name.UseCDATA')) {\r
+                $element->attr_transform_post[] = new HTMLPurifier_AttrTransform_NameSync();\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Module adds the nofollow attribute transformation to a tags.  It\r
+ * is enabled by HTML.Nofollow\r
+ */\r
+class HTMLPurifier_HTMLModule_Nofollow extends HTMLPurifier_HTMLModule\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Nofollow';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $a = $this->addBlankElement('a');\r
+        $a->attr_transform_post[] = new HTMLPurifier_AttrTransform_Nofollow();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_HTMLModule_NonXMLCommonAttributes extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'NonXMLCommonAttributes';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $attr_collections = array(\r
+        'Lang' => array(\r
+            'lang' => 'LanguageCode',\r
+        )\r
+    );\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Object Module, defines elements for generic object inclusion\r
+ * @warning Users will commonly use <embed> to cater to legacy browsers: this\r
+ *      module does not allow this sort of behavior\r
+ */\r
+class HTMLPurifier_HTMLModule_Object extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Object';\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $safe = false;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $this->addElement(\r
+            'object',\r
+            'Inline',\r
+            'Optional: #PCDATA | Flow | param',\r
+            'Common',\r
+            array(\r
+                'archive' => 'URI',\r
+                'classid' => 'URI',\r
+                'codebase' => 'URI',\r
+                'codetype' => 'Text',\r
+                'data' => 'URI',\r
+                'declare' => 'Bool#declare',\r
+                'height' => 'Length',\r
+                'name' => 'CDATA',\r
+                'standby' => 'Text',\r
+                'tabindex' => 'Number',\r
+                'type' => 'ContentType',\r
+                'width' => 'Length'\r
+            )\r
+        );\r
+\r
+        $this->addElement(\r
+            'param',\r
+            false,\r
+            'Empty',\r
+            null,\r
+            array(\r
+                'id' => 'ID',\r
+                'name*' => 'Text',\r
+                'type' => 'Text',\r
+                'value' => 'Text',\r
+                'valuetype' => 'Enum#data,ref,object'\r
+            )\r
+        );\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Presentation Module, defines simple presentation-related\r
+ * markup. Text Extension Module.\r
+ * @note The official XML Schema and DTD specs further divide this into\r
+ *       two modules:\r
+ *          - Block Presentation (hr)\r
+ *          - Inline Presentation (b, big, i, small, sub, sup, tt)\r
+ *       We have chosen not to heed this distinction, as content_sets\r
+ *       provides satisfactory disambiguation.\r
+ */\r
+class HTMLPurifier_HTMLModule_Presentation extends HTMLPurifier_HTMLModule\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Presentation';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $this->addElement('hr', 'Block', 'Empty', 'Common');\r
+        $this->addElement('sub', 'Inline', 'Inline', 'Common');\r
+        $this->addElement('sup', 'Inline', 'Inline', 'Common');\r
+        $b = $this->addElement('b', 'Inline', 'Inline', 'Common');\r
+        $b->formatting = true;\r
+        $big = $this->addElement('big', 'Inline', 'Inline', 'Common');\r
+        $big->formatting = true;\r
+        $i = $this->addElement('i', 'Inline', 'Inline', 'Common');\r
+        $i->formatting = true;\r
+        $small = $this->addElement('small', 'Inline', 'Inline', 'Common');\r
+        $small->formatting = true;\r
+        $tt = $this->addElement('tt', 'Inline', 'Inline', 'Common');\r
+        $tt->formatting = true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Module defines proprietary tags and attributes in HTML.\r
+ * @warning If this module is enabled, standards-compliance is off!\r
+ */\r
+class HTMLPurifier_HTMLModule_Proprietary extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Proprietary';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $this->addElement(\r
+            'marquee',\r
+            'Inline',\r
+            'Flow',\r
+            'Common',\r
+            array(\r
+                'direction' => 'Enum#left,right,up,down',\r
+                'behavior' => 'Enum#alternate',\r
+                'width' => 'Length',\r
+                'height' => 'Length',\r
+                'scrolldelay' => 'Number',\r
+                'scrollamount' => 'Number',\r
+                'loop' => 'Number',\r
+                'bgcolor' => 'Color',\r
+                'hspace' => 'Pixels',\r
+                'vspace' => 'Pixels',\r
+            )\r
+        );\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Ruby Annotation Module, defines elements that indicate\r
+ * short runs of text alongside base text for annotation or pronounciation.\r
+ */\r
+class HTMLPurifier_HTMLModule_Ruby extends HTMLPurifier_HTMLModule\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Ruby';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $this->addElement(\r
+            'ruby',\r
+            'Inline',\r
+            'Custom: ((rb, (rt | (rp, rt, rp))) | (rbc, rtc, rtc?))',\r
+            'Common'\r
+        );\r
+        $this->addElement('rbc', false, 'Required: rb', 'Common');\r
+        $this->addElement('rtc', false, 'Required: rt', 'Common');\r
+        $rb = $this->addElement('rb', false, 'Inline', 'Common');\r
+        $rb->excludes = array('ruby' => true);\r
+        $rt = $this->addElement('rt', false, 'Inline', 'Common', array('rbspan' => 'Number'));\r
+        $rt->excludes = array('ruby' => true);\r
+        $this->addElement('rp', false, 'Optional: #PCDATA', 'Common');\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * A "safe" embed module. See SafeObject. This is a proprietary element.\r
+ */\r
+class HTMLPurifier_HTMLModule_SafeEmbed extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'SafeEmbed';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $max = $config->get('HTML.MaxImgLength');\r
+        $embed = $this->addElement(\r
+            'embed',\r
+            'Inline',\r
+            'Empty',\r
+            'Common',\r
+            array(\r
+                'src*' => 'URI#embedded',\r
+                'type' => 'Enum#application/x-shockwave-flash',\r
+                'width' => 'Pixels#' . $max,\r
+                'height' => 'Pixels#' . $max,\r
+                'allowscriptaccess' => 'Enum#never',\r
+                'allownetworking' => 'Enum#internal',\r
+                'flashvars' => 'Text',\r
+                'wmode' => 'Enum#window,transparent,opaque',\r
+                'name' => 'ID',\r
+            )\r
+        );\r
+        $embed->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeEmbed();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * A "safe" object module. In theory, objects permitted by this module will\r
+ * be safe, and untrusted users can be allowed to embed arbitrary flash objects\r
+ * (maybe other types too, but only Flash is supported as of right now).\r
+ * Highly experimental.\r
+ */\r
+class HTMLPurifier_HTMLModule_SafeObject extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'SafeObject';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        // These definitions are not intrinsically safe: the attribute transforms\r
+        // are a vital part of ensuring safety.\r
+\r
+        $max = $config->get('HTML.MaxImgLength');\r
+        $object = $this->addElement(\r
+            'object',\r
+            'Inline',\r
+            'Optional: param | Flow | #PCDATA',\r
+            'Common',\r
+            array(\r
+                // While technically not required by the spec, we're forcing\r
+                // it to this value.\r
+                'type' => 'Enum#application/x-shockwave-flash',\r
+                'width' => 'Pixels#' . $max,\r
+                'height' => 'Pixels#' . $max,\r
+                'data' => 'URI#embedded',\r
+                'codebase' => new HTMLPurifier_AttrDef_Enum(\r
+                    array(\r
+                        'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'\r
+                    )\r
+                ),\r
+            )\r
+        );\r
+        $object->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeObject();\r
+\r
+        $param = $this->addElement(\r
+            'param',\r
+            false,\r
+            'Empty',\r
+            false,\r
+            array(\r
+                'id' => 'ID',\r
+                'name*' => 'Text',\r
+                'value' => 'Text'\r
+            )\r
+        );\r
+        $param->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeParam();\r
+        $this->info_injector[] = 'SafeObject';\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * A "safe" script module. No inline JS is allowed, and pointed to JS\r
+ * files must match whitelist.\r
+ */\r
+class HTMLPurifier_HTMLModule_SafeScripting extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'SafeScripting';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        // These definitions are not intrinsically safe: the attribute transforms\r
+        // are a vital part of ensuring safety.\r
+\r
+        $allowed = $config->get('HTML.SafeScripting');\r
+        $script = $this->addElement(\r
+            'script',\r
+            'Inline',\r
+            'Optional:', // Not `Empty` to not allow to autoclose the <script /> tag @see https://www.w3.org/TR/html4/interact/scripts.html\r
+            null,\r
+            array(\r
+                // While technically not required by the spec, we're forcing\r
+                // it to this value.\r
+                'type' => 'Enum#text/javascript',\r
+                'src*' => new HTMLPurifier_AttrDef_Enum(array_keys($allowed), /*case sensitive*/ true)\r
+            )\r
+        );\r
+        $script->attr_transform_pre[] =\r
+        $script->attr_transform_post[] = new HTMLPurifier_AttrTransform_ScriptRequired();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/*\r
+\r
+WARNING: THIS MODULE IS EXTREMELY DANGEROUS AS IT ENABLES INLINE SCRIPTING\r
+INSIDE HTML PURIFIER DOCUMENTS. USE ONLY WITH TRUSTED USER INPUT!!!\r
+\r
+*/\r
+\r
+/**\r
+ * XHTML 1.1 Scripting module, defines elements that are used to contain\r
+ * information pertaining to executable scripts or the lack of support\r
+ * for executable scripts.\r
+ * @note This module does not contain inline scripting elements\r
+ */\r
+class HTMLPurifier_HTMLModule_Scripting extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Scripting';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $elements = array('script', 'noscript');\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $content_sets = array('Block' => 'script | noscript', 'Inline' => 'script | noscript');\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $safe = false;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        // TODO: create custom child-definition for noscript that\r
+        // auto-wraps stray #PCDATA in a similar manner to\r
+        // blockquote's custom definition (we would use it but\r
+        // blockquote's contents are optional while noscript's contents\r
+        // are required)\r
+\r
+        // TODO: convert this to new syntax, main problem is getting\r
+        // both content sets working\r
+\r
+        // In theory, this could be safe, but I don't see any reason to\r
+        // allow it.\r
+        $this->info['noscript'] = new HTMLPurifier_ElementDef();\r
+        $this->info['noscript']->attr = array(0 => array('Common'));\r
+        $this->info['noscript']->content_model = 'Heading | List | Block';\r
+        $this->info['noscript']->content_model_type = 'required';\r
+\r
+        $this->info['script'] = new HTMLPurifier_ElementDef();\r
+        $this->info['script']->attr = array(\r
+            'defer' => new HTMLPurifier_AttrDef_Enum(array('defer')),\r
+            'src' => new HTMLPurifier_AttrDef_URI(true),\r
+            'type' => new HTMLPurifier_AttrDef_Enum(array('text/javascript'))\r
+        );\r
+        $this->info['script']->content_model = '#PCDATA';\r
+        $this->info['script']->content_model_type = 'optional';\r
+        $this->info['script']->attr_transform_pre[] =\r
+        $this->info['script']->attr_transform_post[] =\r
+            new HTMLPurifier_AttrTransform_ScriptRequired();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Edit Module, defines editing-related elements. Text Extension\r
+ * Module.\r
+ */\r
+class HTMLPurifier_HTMLModule_StyleAttribute extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'StyleAttribute';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $attr_collections = array(\r
+        // The inclusion routine differs from the Abstract Modules but\r
+        // is in line with the DTD and XML Schemas.\r
+        'Style' => array('style' => false), // see constructor\r
+        'Core' => array(0 => array('Style'))\r
+    );\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $this->attr_collections['Style']['style'] = new HTMLPurifier_AttrDef_CSS();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Tables Module, fully defines accessible table elements.\r
+ */\r
+class HTMLPurifier_HTMLModule_Tables extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Tables';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $this->addElement('caption', false, 'Inline', 'Common');\r
+\r
+        $this->addElement(\r
+            'table',\r
+            'Block',\r
+            new HTMLPurifier_ChildDef_Table(),\r
+            'Common',\r
+            array(\r
+                'border' => 'Pixels',\r
+                'cellpadding' => 'Length',\r
+                'cellspacing' => 'Length',\r
+                'frame' => 'Enum#void,above,below,hsides,lhs,rhs,vsides,box,border',\r
+                'rules' => 'Enum#none,groups,rows,cols,all',\r
+                'summary' => 'Text',\r
+                'width' => 'Length'\r
+            )\r
+        );\r
+\r
+        // common attributes\r
+        $cell_align = array(\r
+            'align' => 'Enum#left,center,right,justify,char',\r
+            'charoff' => 'Length',\r
+            'valign' => 'Enum#top,middle,bottom,baseline',\r
+        );\r
+\r
+        $cell_t = array_merge(\r
+            array(\r
+                'abbr' => 'Text',\r
+                'colspan' => 'Number',\r
+                'rowspan' => 'Number',\r
+                // Apparently, as of HTML5 this attribute only applies\r
+                // to 'th' elements.\r
+                'scope' => 'Enum#row,col,rowgroup,colgroup',\r
+            ),\r
+            $cell_align\r
+        );\r
+        $this->addElement('td', false, 'Flow', 'Common', $cell_t);\r
+        $this->addElement('th', false, 'Flow', 'Common', $cell_t);\r
+\r
+        $this->addElement('tr', false, 'Required: td | th', 'Common', $cell_align);\r
+\r
+        $cell_col = array_merge(\r
+            array(\r
+                'span' => 'Number',\r
+                'width' => 'MultiLength',\r
+            ),\r
+            $cell_align\r
+        );\r
+        $this->addElement('col', false, 'Empty', 'Common', $cell_col);\r
+        $this->addElement('colgroup', false, 'Optional: col', 'Common', $cell_col);\r
+\r
+        $this->addElement('tbody', false, 'Required: tr', 'Common', $cell_align);\r
+        $this->addElement('thead', false, 'Required: tr', 'Common', $cell_align);\r
+        $this->addElement('tfoot', false, 'Required: tr', 'Common', $cell_align);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Target Module, defines target attribute in link elements.\r
+ */\r
+class HTMLPurifier_HTMLModule_Target extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Target';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $elements = array('a');\r
+        foreach ($elements as $name) {\r
+            $e = $this->addBlankElement($name);\r
+            $e->attr = array(\r
+                'target' => new HTMLPurifier_AttrDef_HTML_FrameTarget()\r
+            );\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Module adds the target=blank attribute transformation to a tags.  It\r
+ * is enabled by HTML.TargetBlank\r
+ */\r
+class HTMLPurifier_HTMLModule_TargetBlank extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'TargetBlank';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        $a = $this->addBlankElement('a');\r
+        $a->attr_transform_post[] = new HTMLPurifier_AttrTransform_TargetBlank();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Module adds the target-based noopener attribute transformation to a tags.  It\r
+ * is enabled by HTML.TargetNoopener\r
+ */\r
+class HTMLPurifier_HTMLModule_TargetNoopener extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'TargetNoopener';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config) {\r
+        $a = $this->addBlankElement('a');\r
+        $a->attr_transform_post[] = new HTMLPurifier_AttrTransform_TargetNoopener();\r
+    }\r
+}\r
+
+\r
+\r
+/**\r
+ * Module adds the target-based noreferrer attribute transformation to a tags.  It\r
+ * is enabled by HTML.TargetNoreferrer\r
+ */\r
+class HTMLPurifier_HTMLModule_TargetNoreferrer extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'TargetNoreferrer';\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config) {\r
+        $a = $this->addBlankElement('a');\r
+        $a->attr_transform_post[] = new HTMLPurifier_AttrTransform_TargetNoreferrer();\r
+    }\r
+}\r
+
+\r
+\r
+/**\r
+ * XHTML 1.1 Text Module, defines basic text containers. Core Module.\r
+ * @note In the normative XML Schema specification, this module\r
+ *       is further abstracted into the following modules:\r
+ *          - Block Phrasal (address, blockquote, pre, h1, h2, h3, h4, h5, h6)\r
+ *          - Block Structural (div, p)\r
+ *          - Inline Phrasal (abbr, acronym, cite, code, dfn, em, kbd, q, samp, strong, var)\r
+ *          - Inline Structural (br, span)\r
+ *       This module, functionally, does not distinguish between these\r
+ *       sub-modules, but the code is internally structured to reflect\r
+ *       these distinctions.\r
+ */\r
+class HTMLPurifier_HTMLModule_Text extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Text';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $content_sets = array(\r
+        'Flow' => 'Heading | Block | Inline'\r
+    );\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function setup($config)\r
+    {\r
+        // Inline Phrasal -------------------------------------------------\r
+        $this->addElement('abbr', 'Inline', 'Inline', 'Common');\r
+        $this->addElement('acronym', 'Inline', 'Inline', 'Common');\r
+        $this->addElement('cite', 'Inline', 'Inline', 'Common');\r
+        $this->addElement('dfn', 'Inline', 'Inline', 'Common');\r
+        $this->addElement('kbd', 'Inline', 'Inline', 'Common');\r
+        $this->addElement('q', 'Inline', 'Inline', 'Common', array('cite' => 'URI'));\r
+        $this->addElement('samp', 'Inline', 'Inline', 'Common');\r
+        $this->addElement('var', 'Inline', 'Inline', 'Common');\r
+\r
+        $em = $this->addElement('em', 'Inline', 'Inline', 'Common');\r
+        $em->formatting = true;\r
+\r
+        $strong = $this->addElement('strong', 'Inline', 'Inline', 'Common');\r
+        $strong->formatting = true;\r
+\r
+        $code = $this->addElement('code', 'Inline', 'Inline', 'Common');\r
+        $code->formatting = true;\r
+\r
+        // Inline Structural ----------------------------------------------\r
+        $this->addElement('span', 'Inline', 'Inline', 'Common');\r
+        $this->addElement('br', 'Inline', 'Empty', 'Core');\r
+\r
+        // Block Phrasal --------------------------------------------------\r
+        $this->addElement('address', 'Block', 'Inline', 'Common');\r
+        $this->addElement('blockquote', 'Block', 'Optional: Heading | Block | List', 'Common', array('cite' => 'URI'));\r
+        $pre = $this->addElement('pre', 'Block', 'Inline', 'Common');\r
+        $pre->excludes = $this->makeLookup(\r
+            'img',\r
+            'big',\r
+            'small',\r
+            'object',\r
+            'applet',\r
+            'font',\r
+            'basefont'\r
+        );\r
+        $this->addElement('h1', 'Heading', 'Inline', 'Common');\r
+        $this->addElement('h2', 'Heading', 'Inline', 'Common');\r
+        $this->addElement('h3', 'Heading', 'Inline', 'Common');\r
+        $this->addElement('h4', 'Heading', 'Inline', 'Common');\r
+        $this->addElement('h5', 'Heading', 'Inline', 'Common');\r
+        $this->addElement('h6', 'Heading', 'Inline', 'Common');\r
+\r
+        // Block Structural -----------------------------------------------\r
+        $p = $this->addElement('p', 'Block', 'Inline', 'Common');\r
+        $p->autoclose = array_flip(\r
+            array("address", "blockquote", "center", "dir", "div", "dl", "fieldset", "ol", "p", "ul")\r
+        );\r
+\r
+        $this->addElement('div', 'Block', 'Flow', 'Common');\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Abstract class for a set of proprietary modules that clean up (tidy)\r
+ * poorly written HTML.\r
+ * @todo Figure out how to protect some of these methods/properties\r
+ */\r
+class HTMLPurifier_HTMLModule_Tidy extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * List of supported levels.\r
+     * Index zero is a special case "no fixes" level.\r
+     * @type array\r
+     */\r
+    public $levels = array(0 => 'none', 'light', 'medium', 'heavy');\r
+\r
+    /**\r
+     * Default level to place all fixes in.\r
+     * Disabled by default.\r
+     * @type string\r
+     */\r
+    public $defaultLevel = null;\r
+\r
+    /**\r
+     * Lists of fixes used by getFixesForLevel().\r
+     * Format is:\r
+     *      HTMLModule_Tidy->fixesForLevel[$level] = array('fix-1', 'fix-2');\r
+     * @type array\r
+     */\r
+    public $fixesForLevel = array(\r
+        'light' => array(),\r
+        'medium' => array(),\r
+        'heavy' => array()\r
+    );\r
+\r
+    /**\r
+     * Lazy load constructs the module by determining the necessary\r
+     * fixes to create and then delegating to the populate() function.\r
+     * @param HTMLPurifier_Config $config\r
+     * @todo Wildcard matching and error reporting when an added or\r
+     *       subtracted fix has no effect.\r
+     */\r
+    public function setup($config)\r
+    {\r
+        // create fixes, initialize fixesForLevel\r
+        $fixes = $this->makeFixes();\r
+        $this->makeFixesForLevel($fixes);\r
+\r
+        // figure out which fixes to use\r
+        $level = $config->get('HTML.TidyLevel');\r
+        $fixes_lookup = $this->getFixesForLevel($level);\r
+\r
+        // get custom fix declarations: these need namespace processing\r
+        $add_fixes = $config->get('HTML.TidyAdd');\r
+        $remove_fixes = $config->get('HTML.TidyRemove');\r
+\r
+        foreach ($fixes as $name => $fix) {\r
+            // needs to be refactored a little to implement globbing\r
+            if (isset($remove_fixes[$name]) ||\r
+                (!isset($add_fixes[$name]) && !isset($fixes_lookup[$name]))) {\r
+                unset($fixes[$name]);\r
+            }\r
+        }\r
+\r
+        // populate this module with necessary fixes\r
+        $this->populate($fixes);\r
+    }\r
+\r
+    /**\r
+     * Retrieves all fixes per a level, returning fixes for that specific\r
+     * level as well as all levels below it.\r
+     * @param string $level level identifier, see $levels for valid values\r
+     * @return array Lookup up table of fixes\r
+     */\r
+    public function getFixesForLevel($level)\r
+    {\r
+        if ($level == $this->levels[0]) {\r
+            return array();\r
+        }\r
+        $activated_levels = array();\r
+        for ($i = 1, $c = count($this->levels); $i < $c; $i++) {\r
+            $activated_levels[] = $this->levels[$i];\r
+            if ($this->levels[$i] == $level) {\r
+                break;\r
+            }\r
+        }\r
+        if ($i == $c) {\r
+            trigger_error(\r
+                'Tidy level ' . htmlspecialchars($level) . ' not recognized',\r
+                E_USER_WARNING\r
+            );\r
+            return array();\r
+        }\r
+        $ret = array();\r
+        foreach ($activated_levels as $level) {\r
+            foreach ($this->fixesForLevel[$level] as $fix) {\r
+                $ret[$fix] = true;\r
+            }\r
+        }\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Dynamically populates the $fixesForLevel member variable using\r
+     * the fixes array. It may be custom overloaded, used in conjunction\r
+     * with $defaultLevel, or not used at all.\r
+     * @param array $fixes\r
+     */\r
+    public function makeFixesForLevel($fixes)\r
+    {\r
+        if (!isset($this->defaultLevel)) {\r
+            return;\r
+        }\r
+        if (!isset($this->fixesForLevel[$this->defaultLevel])) {\r
+            trigger_error(\r
+                'Default level ' . $this->defaultLevel . ' does not exist',\r
+                E_USER_ERROR\r
+            );\r
+            return;\r
+        }\r
+        $this->fixesForLevel[$this->defaultLevel] = array_keys($fixes);\r
+    }\r
+\r
+    /**\r
+     * Populates the module with transforms and other special-case code\r
+     * based on a list of fixes passed to it\r
+     * @param array $fixes Lookup table of fixes to activate\r
+     */\r
+    public function populate($fixes)\r
+    {\r
+        foreach ($fixes as $name => $fix) {\r
+            // determine what the fix is for\r
+            list($type, $params) = $this->getFixType($name);\r
+            switch ($type) {\r
+                case 'attr_transform_pre':\r
+                case 'attr_transform_post':\r
+                    $attr = $params['attr'];\r
+                    if (isset($params['element'])) {\r
+                        $element = $params['element'];\r
+                        if (empty($this->info[$element])) {\r
+                            $e = $this->addBlankElement($element);\r
+                        } else {\r
+                            $e = $this->info[$element];\r
+                        }\r
+                    } else {\r
+                        $type = "info_$type";\r
+                        $e = $this;\r
+                    }\r
+                    // PHP does some weird parsing when I do\r
+                    // $e->$type[$attr], so I have to assign a ref.\r
+                    $f =& $e->$type;\r
+                    $f[$attr] = $fix;\r
+                    break;\r
+                case 'tag_transform':\r
+                    $this->info_tag_transform[$params['element']] = $fix;\r
+                    break;\r
+                case 'child':\r
+                case 'content_model_type':\r
+                    $element = $params['element'];\r
+                    if (empty($this->info[$element])) {\r
+                        $e = $this->addBlankElement($element);\r
+                    } else {\r
+                        $e = $this->info[$element];\r
+                    }\r
+                    $e->$type = $fix;\r
+                    break;\r
+                default:\r
+                    trigger_error("Fix type $type not supported", E_USER_ERROR);\r
+                    break;\r
+            }\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Parses a fix name and determines what kind of fix it is, as well\r
+     * as other information defined by the fix\r
+     * @param $name String name of fix\r
+     * @return array(string $fix_type, array $fix_parameters)\r
+     * @note $fix_parameters is type dependant, see populate() for usage\r
+     *       of these parameters\r
+     */\r
+    public function getFixType($name)\r
+    {\r
+        // parse it\r
+        $property = $attr = null;\r
+        if (strpos($name, '#') !== false) {\r
+            list($name, $property) = explode('#', $name);\r
+        }\r
+        if (strpos($name, '@') !== false) {\r
+            list($name, $attr) = explode('@', $name);\r
+        }\r
+\r
+        // figure out the parameters\r
+        $params = array();\r
+        if ($name !== '') {\r
+            $params['element'] = $name;\r
+        }\r
+        if (!is_null($attr)) {\r
+            $params['attr'] = $attr;\r
+        }\r
+\r
+        // special case: attribute transform\r
+        if (!is_null($attr)) {\r
+            if (is_null($property)) {\r
+                $property = 'pre';\r
+            }\r
+            $type = 'attr_transform_' . $property;\r
+            return array($type, $params);\r
+        }\r
+\r
+        // special case: tag transform\r
+        if (is_null($property)) {\r
+            return array('tag_transform', $params);\r
+        }\r
+\r
+        return array($property, $params);\r
+\r
+    }\r
+\r
+    /**\r
+     * Defines all fixes the module will perform in a compact\r
+     * associative array of fix name to fix implementation.\r
+     * @return array\r
+     */\r
+    public function makeFixes()\r
+    {\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_HTMLModule_XMLCommonAttributes extends HTMLPurifier_HTMLModule\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'XMLCommonAttributes';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $attr_collections = array(\r
+        'Lang' => array(\r
+            'xml:lang' => 'LanguageCode',\r
+        )\r
+    );\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Name is deprecated, but allowed in strict doctypes, so onl\r
+ */\r
+class HTMLPurifier_HTMLModule_Tidy_Name extends HTMLPurifier_HTMLModule_Tidy\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Tidy_Name';\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $defaultLevel = 'heavy';\r
+\r
+    /**\r
+     * @return array\r
+     */\r
+    public function makeFixes()\r
+    {\r
+        $r = array();\r
+        // @name for img, a -----------------------------------------------\r
+        // Technically, it's allowed even on strict, so we allow authors to use\r
+        // it. However, it's deprecated in future versions of XHTML.\r
+        $r['img@name'] =\r
+        $r['a@name'] = new HTMLPurifier_AttrTransform_Name();\r
+        return $r;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_HTMLModule_Tidy_Proprietary extends HTMLPurifier_HTMLModule_Tidy\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Tidy_Proprietary';\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $defaultLevel = 'light';\r
+\r
+    /**\r
+     * @return array\r
+     */\r
+    public function makeFixes()\r
+    {\r
+        $r = array();\r
+        $r['table@background'] = new HTMLPurifier_AttrTransform_Background();\r
+        $r['td@background']    = new HTMLPurifier_AttrTransform_Background();\r
+        $r['th@background']    = new HTMLPurifier_AttrTransform_Background();\r
+        $r['tr@background']    = new HTMLPurifier_AttrTransform_Background();\r
+        $r['thead@background'] = new HTMLPurifier_AttrTransform_Background();\r
+        $r['tfoot@background'] = new HTMLPurifier_AttrTransform_Background();\r
+        $r['tbody@background'] = new HTMLPurifier_AttrTransform_Background();\r
+        $r['table@height']     = new HTMLPurifier_AttrTransform_Length('height');\r
+        return $r;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4 extends HTMLPurifier_HTMLModule_Tidy\r
+{\r
+\r
+    /**\r
+     * @return array\r
+     */\r
+    public function makeFixes()\r
+    {\r
+        $r = array();\r
+\r
+        // == deprecated tag transforms ===================================\r
+\r
+        $r['font'] = new HTMLPurifier_TagTransform_Font();\r
+        $r['menu'] = new HTMLPurifier_TagTransform_Simple('ul');\r
+        $r['dir'] = new HTMLPurifier_TagTransform_Simple('ul');\r
+        $r['center'] = new HTMLPurifier_TagTransform_Simple('div', 'text-align:center;');\r
+        $r['u'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:underline;');\r
+        $r['s'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;');\r
+        $r['strike'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;');\r
+\r
+        // == deprecated attribute transforms =============================\r
+\r
+        $r['caption@align'] =\r
+            new HTMLPurifier_AttrTransform_EnumToCSS(\r
+                'align',\r
+                array(\r
+                    // we're following IE's behavior, not Firefox's, due\r
+                    // to the fact that no one supports caption-side:right,\r
+                    // W3C included (with CSS 2.1). This is a slightly\r
+                    // unreasonable attribute!\r
+                    'left' => 'text-align:left;',\r
+                    'right' => 'text-align:right;',\r
+                    'top' => 'caption-side:top;',\r
+                    'bottom' => 'caption-side:bottom;' // not supported by IE\r
+                )\r
+            );\r
+\r
+        // @align for img -------------------------------------------------\r
+        $r['img@align'] =\r
+            new HTMLPurifier_AttrTransform_EnumToCSS(\r
+                'align',\r
+                array(\r
+                    'left' => 'float:left;',\r
+                    'right' => 'float:right;',\r
+                    'top' => 'vertical-align:top;',\r
+                    'middle' => 'vertical-align:middle;',\r
+                    'bottom' => 'vertical-align:baseline;',\r
+                )\r
+            );\r
+\r
+        // @align for table -----------------------------------------------\r
+        $r['table@align'] =\r
+            new HTMLPurifier_AttrTransform_EnumToCSS(\r
+                'align',\r
+                array(\r
+                    'left' => 'float:left;',\r
+                    'center' => 'margin-left:auto;margin-right:auto;',\r
+                    'right' => 'float:right;'\r
+                )\r
+            );\r
+\r
+        // @align for hr -----------------------------------------------\r
+        $r['hr@align'] =\r
+            new HTMLPurifier_AttrTransform_EnumToCSS(\r
+                'align',\r
+                array(\r
+                    // we use both text-align and margin because these work\r
+                    // for different browsers (IE and Firefox, respectively)\r
+                    // and the melange makes for a pretty cross-compatible\r
+                    // solution\r
+                    'left' => 'margin-left:0;margin-right:auto;text-align:left;',\r
+                    'center' => 'margin-left:auto;margin-right:auto;text-align:center;',\r
+                    'right' => 'margin-left:auto;margin-right:0;text-align:right;'\r
+                )\r
+            );\r
+\r
+        // @align for h1, h2, h3, h4, h5, h6, p, div ----------------------\r
+        // {{{\r
+        $align_lookup = array();\r
+        $align_values = array('left', 'right', 'center', 'justify');\r
+        foreach ($align_values as $v) {\r
+            $align_lookup[$v] = "text-align:$v;";\r
+        }\r
+        // }}}\r
+        $r['h1@align'] =\r
+        $r['h2@align'] =\r
+        $r['h3@align'] =\r
+        $r['h4@align'] =\r
+        $r['h5@align'] =\r
+        $r['h6@align'] =\r
+        $r['p@align'] =\r
+        $r['div@align'] =\r
+            new HTMLPurifier_AttrTransform_EnumToCSS('align', $align_lookup);\r
+\r
+        // @bgcolor for table, tr, td, th ---------------------------------\r
+        $r['table@bgcolor'] =\r
+        $r['td@bgcolor'] =\r
+        $r['th@bgcolor'] =\r
+            new HTMLPurifier_AttrTransform_BgColor();\r
+\r
+        // @border for img ------------------------------------------------\r
+        $r['img@border'] = new HTMLPurifier_AttrTransform_Border();\r
+\r
+        // @clear for br --------------------------------------------------\r
+        $r['br@clear'] =\r
+            new HTMLPurifier_AttrTransform_EnumToCSS(\r
+                'clear',\r
+                array(\r
+                    'left' => 'clear:left;',\r
+                    'right' => 'clear:right;',\r
+                    'all' => 'clear:both;',\r
+                    'none' => 'clear:none;',\r
+                )\r
+            );\r
+\r
+        // @height for td, th ---------------------------------------------\r
+        $r['td@height'] =\r
+        $r['th@height'] =\r
+            new HTMLPurifier_AttrTransform_Length('height');\r
+\r
+        // @hspace for img ------------------------------------------------\r
+        $r['img@hspace'] = new HTMLPurifier_AttrTransform_ImgSpace('hspace');\r
+\r
+        // @noshade for hr ------------------------------------------------\r
+        // this transformation is not precise but often good enough.\r
+        // different browsers use different styles to designate noshade\r
+        $r['hr@noshade'] =\r
+            new HTMLPurifier_AttrTransform_BoolToCSS(\r
+                'noshade',\r
+                'color:#808080;background-color:#808080;border:0;'\r
+            );\r
+\r
+        // @nowrap for td, th ---------------------------------------------\r
+        $r['td@nowrap'] =\r
+        $r['th@nowrap'] =\r
+            new HTMLPurifier_AttrTransform_BoolToCSS(\r
+                'nowrap',\r
+                'white-space:nowrap;'\r
+            );\r
+\r
+        // @size for hr  --------------------------------------------------\r
+        $r['hr@size'] = new HTMLPurifier_AttrTransform_Length('size', 'height');\r
+\r
+        // @type for li, ol, ul -------------------------------------------\r
+        // {{{\r
+        $ul_types = array(\r
+            'disc' => 'list-style-type:disc;',\r
+            'square' => 'list-style-type:square;',\r
+            'circle' => 'list-style-type:circle;'\r
+        );\r
+        $ol_types = array(\r
+            '1' => 'list-style-type:decimal;',\r
+            'i' => 'list-style-type:lower-roman;',\r
+            'I' => 'list-style-type:upper-roman;',\r
+            'a' => 'list-style-type:lower-alpha;',\r
+            'A' => 'list-style-type:upper-alpha;'\r
+        );\r
+        $li_types = $ul_types + $ol_types;\r
+        // }}}\r
+\r
+        $r['ul@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ul_types);\r
+        $r['ol@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ol_types, true);\r
+        $r['li@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $li_types, true);\r
+\r
+        // @vspace for img ------------------------------------------------\r
+        $r['img@vspace'] = new HTMLPurifier_AttrTransform_ImgSpace('vspace');\r
+\r
+        // @width for hr, td, th ------------------------------------------\r
+        $r['td@width'] =\r
+        $r['th@width'] =\r
+        $r['hr@width'] = new HTMLPurifier_AttrTransform_Length('width');\r
+\r
+        return $r;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_HTMLModule_Tidy_Strict extends HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Tidy_Strict';\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $defaultLevel = 'light';\r
+\r
+    /**\r
+     * @return array\r
+     */\r
+    public function makeFixes()\r
+    {\r
+        $r = parent::makeFixes();\r
+        $r['blockquote#content_model_type'] = 'strictblockquote';\r
+        return $r;\r
+    }\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $defines_child_def = true;\r
+\r
+    /**\r
+     * @param HTMLPurifier_ElementDef $def\r
+     * @return HTMLPurifier_ChildDef_StrictBlockquote\r
+     */\r
+    public function getChildDef($def)\r
+    {\r
+        if ($def->content_model_type != 'strictblockquote') {\r
+            return parent::getChildDef($def);\r
+        }\r
+        return new HTMLPurifier_ChildDef_StrictBlockquote($def->content_model);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_HTMLModule_Tidy_Transitional extends HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Tidy_Transitional';\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $defaultLevel = 'heavy';\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_HTMLModule_Tidy_XHTML extends HTMLPurifier_HTMLModule_Tidy\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Tidy_XHTML';\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $defaultLevel = 'medium';\r
+\r
+    /**\r
+     * @return array\r
+     */\r
+    public function makeFixes()\r
+    {\r
+        $r = array();\r
+        $r['@lang'] = new HTMLPurifier_AttrTransform_Lang();\r
+        return $r;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Injector that auto paragraphs text in the root node based on\r
+ * double-spacing.\r
+ * @todo Ensure all states are unit tested, including variations as well.\r
+ * @todo Make a graph of the flow control for this Injector.\r
+ */\r
+class HTMLPurifier_Injector_AutoParagraph extends HTMLPurifier_Injector\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'AutoParagraph';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $needed = array('p');\r
+\r
+    /**\r
+     * @return HTMLPurifier_Token_Start\r
+     */\r
+    private function _pStart()\r
+    {\r
+        $par = new HTMLPurifier_Token_Start('p');\r
+        $par->armor['MakeWellFormed_TagClosedError'] = true;\r
+        return $par;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token_Text $token\r
+     */\r
+    public function handleText(&$token)\r
+    {\r
+        $text = $token->data;\r
+        // Does the current parent allow <p> tags?\r
+        if ($this->allowsElement('p')) {\r
+            if (empty($this->currentNesting) || strpos($text, "\n\n") !== false) {\r
+                // Note that we have differing behavior when dealing with text\r
+                // in the anonymous root node, or a node inside the document.\r
+                // If the text as a double-newline, the treatment is the same;\r
+                // if it doesn't, see the next if-block if you're in the document.\r
+\r
+                $i = $nesting = null;\r
+                if (!$this->forwardUntilEndToken($i, $current, $nesting) && $token->is_whitespace) {\r
+                    // State 1.1: ...    ^ (whitespace, then document end)\r
+                    //               ----\r
+                    // This is a degenerate case\r
+                } else {\r
+                    if (!$token->is_whitespace || $this->_isInline($current)) {\r
+                        // State 1.2: PAR1\r
+                        //            ----\r
+\r
+                        // State 1.3: PAR1\n\nPAR2\r
+                        //            ------------\r
+\r
+                        // State 1.4: <div>PAR1\n\nPAR2 (see State 2)\r
+                        //                 ------------\r
+                        $token = array($this->_pStart());\r
+                        $this->_splitText($text, $token);\r
+                    } else {\r
+                        // State 1.5: \n<hr />\r
+                        //            --\r
+                    }\r
+                }\r
+            } else {\r
+                // State 2:   <div>PAR1... (similar to 1.4)\r
+                //                 ----\r
+\r
+                // We're in an element that allows paragraph tags, but we're not\r
+                // sure if we're going to need them.\r
+                if ($this->_pLookAhead()) {\r
+                    // State 2.1: <div>PAR1<b>PAR1\n\nPAR2\r
+                    //                 ----\r
+                    // Note: This will always be the first child, since any\r
+                    // previous inline element would have triggered this very\r
+                    // same routine, and found the double newline. One possible\r
+                    // exception would be a comment.\r
+                    $token = array($this->_pStart(), $token);\r
+                } else {\r
+                    // State 2.2.1: <div>PAR1<div>\r
+                    //                   ----\r
+\r
+                    // State 2.2.2: <div>PAR1<b>PAR1</b></div>\r
+                    //                   ----\r
+                }\r
+            }\r
+            // Is the current parent a <p> tag?\r
+        } elseif (!empty($this->currentNesting) &&\r
+            $this->currentNesting[count($this->currentNesting) - 1]->name == 'p') {\r
+            // State 3.1: ...<p>PAR1\r
+            //                  ----\r
+\r
+            // State 3.2: ...<p>PAR1\n\nPAR2\r
+            //                  ------------\r
+            $token = array();\r
+            $this->_splitText($text, $token);\r
+            // Abort!\r
+        } else {\r
+            // State 4.1: ...<b>PAR1\r
+            //                  ----\r
+\r
+            // State 4.2: ...<b>PAR1\n\nPAR2\r
+            //                  ------------\r
+        }\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token $token\r
+     */\r
+    public function handleElement(&$token)\r
+    {\r
+        // We don't have to check if we're already in a <p> tag for block\r
+        // tokens, because the tag would have been autoclosed by MakeWellFormed.\r
+        if ($this->allowsElement('p')) {\r
+            if (!empty($this->currentNesting)) {\r
+                if ($this->_isInline($token)) {\r
+                    // State 1: <div>...<b>\r
+                    //                  ---\r
+                    // Check if this token is adjacent to the parent token\r
+                    // (seek backwards until token isn't whitespace)\r
+                    $i = null;\r
+                    $this->backward($i, $prev);\r
+\r
+                    if (!$prev instanceof HTMLPurifier_Token_Start) {\r
+                        // Token wasn't adjacent\r
+                        if ($prev instanceof HTMLPurifier_Token_Text &&\r
+                            substr($prev->data, -2) === "\n\n"\r
+                        ) {\r
+                            // State 1.1.4: <div><p>PAR1</p>\n\n<b>\r
+                            //                                  ---\r
+                            // Quite frankly, this should be handled by splitText\r
+                            $token = array($this->_pStart(), $token);\r
+                        } else {\r
+                            // State 1.1.1: <div><p>PAR1</p><b>\r
+                            //                              ---\r
+                            // State 1.1.2: <div><br /><b>\r
+                            //                         ---\r
+                            // State 1.1.3: <div>PAR<b>\r
+                            //                      ---\r
+                        }\r
+                    } else {\r
+                        // State 1.2.1: <div><b>\r
+                        //                   ---\r
+                        // Lookahead to see if <p> is needed.\r
+                        if ($this->_pLookAhead()) {\r
+                            // State 1.3.1: <div><b>PAR1\n\nPAR2\r
+                            //                   ---\r
+                            $token = array($this->_pStart(), $token);\r
+                        } else {\r
+                            // State 1.3.2: <div><b>PAR1</b></div>\r
+                            //                   ---\r
+\r
+                            // State 1.3.3: <div><b>PAR1</b><div></div>\n\n</div>\r
+                            //                   ---\r
+                        }\r
+                    }\r
+                } else {\r
+                    // State 2.3: ...<div>\r
+                    //               -----\r
+                }\r
+            } else {\r
+                if ($this->_isInline($token)) {\r
+                    // State 3.1: <b>\r
+                    //            ---\r
+                    // This is where the {p} tag is inserted, not reflected in\r
+                    // inputTokens yet, however.\r
+                    $token = array($this->_pStart(), $token);\r
+                } else {\r
+                    // State 3.2: <div>\r
+                    //            -----\r
+                }\r
+\r
+                $i = null;\r
+                if ($this->backward($i, $prev)) {\r
+                    if (!$prev instanceof HTMLPurifier_Token_Text) {\r
+                        // State 3.1.1: ...</p>{p}<b>\r
+                        //                        ---\r
+                        // State 3.2.1: ...</p><div>\r
+                        //                     -----\r
+                        if (!is_array($token)) {\r
+                            $token = array($token);\r
+                        }\r
+                        array_unshift($token, new HTMLPurifier_Token_Text("\n\n"));\r
+                    } else {\r
+                        // State 3.1.2: ...</p>\n\n{p}<b>\r
+                        //                            ---\r
+                        // State 3.2.2: ...</p>\n\n<div>\r
+                        //                         -----\r
+                        // Note: PAR<ELEM> cannot occur because PAR would have been\r
+                        // wrapped in <p> tags.\r
+                    }\r
+                }\r
+            }\r
+        } else {\r
+            // State 2.2: <ul><li>\r
+            //                ----\r
+            // State 2.4: <p><b>\r
+            //               ---\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Splits up a text in paragraph tokens and appends them\r
+     * to the result stream that will replace the original\r
+     * @param string $data String text data that will be processed\r
+     *    into paragraphs\r
+     * @param HTMLPurifier_Token[] $result Reference to array of tokens that the\r
+     *    tags will be appended onto\r
+     */\r
+    private function _splitText($data, &$result)\r
+    {\r
+        $raw_paragraphs = explode("\n\n", $data);\r
+        $paragraphs = array(); // without empty paragraphs\r
+        $needs_start = false;\r
+        $needs_end = false;\r
+\r
+        $c = count($raw_paragraphs);\r
+        if ($c == 1) {\r
+            // There were no double-newlines, abort quickly. In theory this\r
+            // should never happen.\r
+            $result[] = new HTMLPurifier_Token_Text($data);\r
+            return;\r
+        }\r
+        for ($i = 0; $i < $c; $i++) {\r
+            $par = $raw_paragraphs[$i];\r
+            if (trim($par) !== '') {\r
+                $paragraphs[] = $par;\r
+            } else {\r
+                if ($i == 0) {\r
+                    // Double newline at the front\r
+                    if (empty($result)) {\r
+                        // The empty result indicates that the AutoParagraph\r
+                        // injector did not add any start paragraph tokens.\r
+                        // This means that we have been in a paragraph for\r
+                        // a while, and the newline means we should start a new one.\r
+                        $result[] = new HTMLPurifier_Token_End('p');\r
+                        $result[] = new HTMLPurifier_Token_Text("\n\n");\r
+                        // However, the start token should only be added if\r
+                        // there is more processing to be done (i.e. there are\r
+                        // real paragraphs in here). If there are none, the\r
+                        // next start paragraph tag will be handled by the\r
+                        // next call to the injector\r
+                        $needs_start = true;\r
+                    } else {\r
+                        // We just started a new paragraph!\r
+                        // Reinstate a double-newline for presentation's sake, since\r
+                        // it was in the source code.\r
+                        array_unshift($result, new HTMLPurifier_Token_Text("\n\n"));\r
+                    }\r
+                } elseif ($i + 1 == $c) {\r
+                    // Double newline at the end\r
+                    // There should be a trailing </p> when we're finally done.\r
+                    $needs_end = true;\r
+                }\r
+            }\r
+        }\r
+\r
+        // Check if this was just a giant blob of whitespace. Move this earlier,\r
+        // perhaps?\r
+        if (empty($paragraphs)) {\r
+            return;\r
+        }\r
+\r
+        // Add the start tag indicated by \n\n at the beginning of $data\r
+        if ($needs_start) {\r
+            $result[] = $this->_pStart();\r
+        }\r
+\r
+        // Append the paragraphs onto the result\r
+        foreach ($paragraphs as $par) {\r
+            $result[] = new HTMLPurifier_Token_Text($par);\r
+            $result[] = new HTMLPurifier_Token_End('p');\r
+            $result[] = new HTMLPurifier_Token_Text("\n\n");\r
+            $result[] = $this->_pStart();\r
+        }\r
+\r
+        // Remove trailing start token; Injector will handle this later if\r
+        // it was indeed needed. This prevents from needing to do a lookahead,\r
+        // at the cost of a lookbehind later.\r
+        array_pop($result);\r
+\r
+        // If there is no need for an end tag, remove all of it and let\r
+        // MakeWellFormed close it later.\r
+        if (!$needs_end) {\r
+            array_pop($result); // removes \n\n\r
+            array_pop($result); // removes </p>\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Returns true if passed token is inline (and, ergo, allowed in\r
+     * paragraph tags)\r
+     * @param HTMLPurifier_Token $token\r
+     * @return bool\r
+     */\r
+    private function _isInline($token)\r
+    {\r
+        return isset($this->htmlDefinition->info['p']->child->elements[$token->name]);\r
+    }\r
+\r
+    /**\r
+     * Looks ahead in the token list and determines whether or not we need\r
+     * to insert a <p> tag.\r
+     * @return bool\r
+     */\r
+    private function _pLookAhead()\r
+    {\r
+        if ($this->currentToken instanceof HTMLPurifier_Token_Start) {\r
+            $nesting = 1;\r
+        } else {\r
+            $nesting = 0;\r
+        }\r
+        $ok = false;\r
+        $i = null;\r
+        while ($this->forwardUntilEndToken($i, $current, $nesting)) {\r
+            $result = $this->_checkNeedsP($current);\r
+            if ($result !== null) {\r
+                $ok = $result;\r
+                break;\r
+            }\r
+        }\r
+        return $ok;\r
+    }\r
+\r
+    /**\r
+     * Determines if a particular token requires an earlier inline token\r
+     * to get a paragraph. This should be used with _forwardUntilEndToken\r
+     * @param HTMLPurifier_Token $current\r
+     * @return bool\r
+     */\r
+    private function _checkNeedsP($current)\r
+    {\r
+        if ($current instanceof HTMLPurifier_Token_Start) {\r
+            if (!$this->_isInline($current)) {\r
+                // <div>PAR1<div>\r
+                //      ----\r
+                // Terminate early, since we hit a block element\r
+                return false;\r
+            }\r
+        } elseif ($current instanceof HTMLPurifier_Token_Text) {\r
+            if (strpos($current->data, "\n\n") !== false) {\r
+                // <div>PAR1<b>PAR1\n\nPAR2\r
+                //      ----\r
+                return true;\r
+            } else {\r
+                // <div>PAR1<b>PAR1...\r
+                //      ----\r
+            }\r
+        }\r
+        return null;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Injector that displays the URL of an anchor instead of linking to it, in addition to showing the text of the link.\r
+ */\r
+class HTMLPurifier_Injector_DisplayLinkURI extends HTMLPurifier_Injector\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'DisplayLinkURI';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $needed = array('a');\r
+\r
+    /**\r
+     * @param $token\r
+     */\r
+    public function handleElement(&$token)\r
+    {\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token $token\r
+     */\r
+    public function handleEnd(&$token)\r
+    {\r
+        if (isset($token->start->attr['href'])) {\r
+            $url = $token->start->attr['href'];\r
+            unset($token->start->attr['href']);\r
+            $token = array($token, new HTMLPurifier_Token_Text(" ($url)"));\r
+        } else {\r
+            // nothing to display\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Injector that converts http, https and ftp text URLs to actual links.\r
+ */\r
+class HTMLPurifier_Injector_Linkify extends HTMLPurifier_Injector\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Linkify';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $needed = array('a' => array('href'));\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token $token\r
+     */\r
+    public function handleText(&$token)\r
+    {\r
+        if (!$this->allowsElement('a')) {\r
+            return;\r
+        }\r
+\r
+        if (strpos($token->data, '://') === false) {\r
+            // our really quick heuristic failed, abort\r
+            // this may not work so well if we want to match things like\r
+            // "google.com", but then again, most people don't\r
+            return;\r
+        }\r
+\r
+        // there is/are URL(s). Let's split the string.\r
+        // We use this regex:\r
+        // https://gist.github.com/gruber/249502\r
+        // but with @cscott's backtracking fix and also\r
+        // the Unicode characters un-Unicodified.\r
+        $bits = preg_split(\r
+            '/\\b((?:[a-z][\\w\\-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]|\\((?:[^\\s()<>]|(?:\\([^\\s()<>]+\\)))*\\))+(?:\\((?:[^\\s()<>]|(?:\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'".,<>?\x{00ab}\x{00bb}\x{201c}\x{201d}\x{2018}\x{2019}]))/iu',\r
+            $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);\r
+\r
+\r
+        $token = array();\r
+\r
+        // $i = index\r
+        // $c = count\r
+        // $l = is link\r
+        for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {\r
+            if (!$l) {\r
+                if ($bits[$i] === '') {\r
+                    continue;\r
+                }\r
+                $token[] = new HTMLPurifier_Token_Text($bits[$i]);\r
+            } else {\r
+                $token[] = new HTMLPurifier_Token_Start('a', array('href' => $bits[$i]));\r
+                $token[] = new HTMLPurifier_Token_Text($bits[$i]);\r
+                $token[] = new HTMLPurifier_Token_End('a');\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Injector that converts configuration directive syntax %Namespace.Directive\r
+ * to links\r
+ */\r
+class HTMLPurifier_Injector_PurifierLinkify extends HTMLPurifier_Injector\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'PurifierLinkify';\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $docURL;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $needed = array('a' => array('href'));\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     */\r
+    public function prepare($config, $context)\r
+    {\r
+        $this->docURL = $config->get('AutoFormat.PurifierLinkify.DocURL');\r
+        return parent::prepare($config, $context);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token $token\r
+     */\r
+    public function handleText(&$token)\r
+    {\r
+        if (!$this->allowsElement('a')) {\r
+            return;\r
+        }\r
+        if (strpos($token->data, '%') === false) {\r
+            return;\r
+        }\r
+\r
+        $bits = preg_split('#%([a-z0-9]+\.[a-z0-9]+)#Si', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);\r
+        $token = array();\r
+\r
+        // $i = index\r
+        // $c = count\r
+        // $l = is link\r
+        for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {\r
+            if (!$l) {\r
+                if ($bits[$i] === '') {\r
+                    continue;\r
+                }\r
+                $token[] = new HTMLPurifier_Token_Text($bits[$i]);\r
+            } else {\r
+                $token[] = new HTMLPurifier_Token_Start(\r
+                    'a',\r
+                    array('href' => str_replace('%s', $bits[$i], $this->docURL))\r
+                );\r
+                $token[] = new HTMLPurifier_Token_Text('%' . $bits[$i]);\r
+                $token[] = new HTMLPurifier_Token_End('a');\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_Injector_RemoveEmpty extends HTMLPurifier_Injector\r
+{\r
+    /**\r
+     * @type HTMLPurifier_Context\r
+     */\r
+    private $context;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Config\r
+     */\r
+    private $config;\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrValidator\r
+     */\r
+    private $attrValidator;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    private $removeNbsp;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    private $removeNbspExceptions;\r
+\r
+    /**\r
+     * Cached contents of %AutoFormat.RemoveEmpty.Predicate\r
+     * @type array\r
+     */\r
+    private $exclude;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return void\r
+     */\r
+    public function prepare($config, $context)\r
+    {\r
+        parent::prepare($config, $context);\r
+        $this->config = $config;\r
+        $this->context = $context;\r
+        $this->removeNbsp = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp');\r
+        $this->removeNbspExceptions = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions');\r
+        $this->exclude = $config->get('AutoFormat.RemoveEmpty.Predicate');\r
+        foreach ($this->exclude as $key => $attrs) {\r
+            if (!is_array($attrs)) {\r
+                // HACK, see HTMLPurifier/Printer/ConfigForm.php\r
+                $this->exclude[$key] = explode(';', $attrs);\r
+            }\r
+        }\r
+        $this->attrValidator = new HTMLPurifier_AttrValidator();\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token $token\r
+     */\r
+    public function handleElement(&$token)\r
+    {\r
+        if (!$token instanceof HTMLPurifier_Token_Start) {\r
+            return;\r
+        }\r
+        $next = false;\r
+        $deleted = 1; // the current tag\r
+        for ($i = count($this->inputZipper->back) - 1; $i >= 0; $i--, $deleted++) {\r
+            $next = $this->inputZipper->back[$i];\r
+            if ($next instanceof HTMLPurifier_Token_Text) {\r
+                if ($next->is_whitespace) {\r
+                    continue;\r
+                }\r
+                if ($this->removeNbsp && !isset($this->removeNbspExceptions[$token->name])) {\r
+                    $plain = str_replace("\xC2\xA0", "", $next->data);\r
+                    $isWsOrNbsp = $plain === '' || ctype_space($plain);\r
+                    if ($isWsOrNbsp) {\r
+                        continue;\r
+                    }\r
+                }\r
+            }\r
+            break;\r
+        }\r
+        if (!$next || ($next instanceof HTMLPurifier_Token_End && $next->name == $token->name)) {\r
+            $this->attrValidator->validateToken($token, $this->config, $this->context);\r
+            $token->armor['ValidateAttributes'] = true;\r
+            if (isset($this->exclude[$token->name])) {\r
+                $r = true;\r
+                foreach ($this->exclude[$token->name] as $elem) {\r
+                    if (!isset($token->attr[$elem])) $r = false;\r
+                }\r
+                if ($r) return;\r
+            }\r
+            if (isset($token->attr['id']) || isset($token->attr['name'])) {\r
+                return;\r
+            }\r
+            $token = $deleted + 1;\r
+            for ($b = 0, $c = count($this->inputZipper->front); $b < $c; $b++) {\r
+                $prev = $this->inputZipper->front[$b];\r
+                if ($prev instanceof HTMLPurifier_Token_Text && $prev->is_whitespace) {\r
+                    continue;\r
+                }\r
+                break;\r
+            }\r
+            // This is safe because we removed the token that triggered this.\r
+            $this->rewindOffset($b+$deleted);\r
+            return;\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Injector that removes spans with no attributes\r
+ */\r
+class HTMLPurifier_Injector_RemoveSpansWithoutAttributes extends HTMLPurifier_Injector\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'RemoveSpansWithoutAttributes';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $needed = array('span');\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrValidator\r
+     */\r
+    private $attrValidator;\r
+\r
+    /**\r
+     * Used by AttrValidator.\r
+     * @type HTMLPurifier_Config\r
+     */\r
+    private $config;\r
+\r
+    /**\r
+     * @type HTMLPurifier_Context\r
+     */\r
+    private $context;\r
+\r
+    public function prepare($config, $context)\r
+    {\r
+        $this->attrValidator = new HTMLPurifier_AttrValidator();\r
+        $this->config = $config;\r
+        $this->context = $context;\r
+        return parent::prepare($config, $context);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token $token\r
+     */\r
+    public function handleElement(&$token)\r
+    {\r
+        if ($token->name !== 'span' || !$token instanceof HTMLPurifier_Token_Start) {\r
+            return;\r
+        }\r
+\r
+        // We need to validate the attributes now since this doesn't normally\r
+        // happen until after MakeWellFormed. If all the attributes are removed\r
+        // the span needs to be removed too.\r
+        $this->attrValidator->validateToken($token, $this->config, $this->context);\r
+        $token->armor['ValidateAttributes'] = true;\r
+\r
+        if (!empty($token->attr)) {\r
+            return;\r
+        }\r
+\r
+        $nesting = 0;\r
+        while ($this->forwardUntilEndToken($i, $current, $nesting)) {\r
+        }\r
+\r
+        if ($current instanceof HTMLPurifier_Token_End && $current->name === 'span') {\r
+            // Mark closing span tag for deletion\r
+            $current->markForDeletion = true;\r
+            // Delete open span tag\r
+            $token = false;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token $token\r
+     */\r
+    public function handleEnd(&$token)\r
+    {\r
+        if ($token->markForDeletion) {\r
+            $token = false;\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Adds important param elements to inside of object in order to make\r
+ * things safe.\r
+ */\r
+class HTMLPurifier_Injector_SafeObject extends HTMLPurifier_Injector\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'SafeObject';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $needed = array('object', 'param');\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $objectStack = array();\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $paramStack = array();\r
+\r
+    /**\r
+     * Keep this synchronized with AttrTransform/SafeParam.php.\r
+     * @type array\r
+     */\r
+    protected $addParam = array(\r
+        'allowScriptAccess' => 'never',\r
+        'allowNetworking' => 'internal',\r
+    );\r
+\r
+    /**\r
+     * These are all lower-case keys.\r
+     * @type array\r
+     */\r
+    protected $allowedParam = array(\r
+        'wmode' => true,\r
+        'movie' => true,\r
+        'flashvars' => true,\r
+        'src' => true,\r
+        'allowfullscreen' => true, // if omitted, assume to be 'false'\r
+    );\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return void\r
+     */\r
+    public function prepare($config, $context)\r
+    {\r
+        parent::prepare($config, $context);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token $token\r
+     */\r
+    public function handleElement(&$token)\r
+    {\r
+        if ($token->name == 'object') {\r
+            $this->objectStack[] = $token;\r
+            $this->paramStack[] = array();\r
+            $new = array($token);\r
+            foreach ($this->addParam as $name => $value) {\r
+                $new[] = new HTMLPurifier_Token_Empty('param', array('name' => $name, 'value' => $value));\r
+            }\r
+            $token = $new;\r
+        } elseif ($token->name == 'param') {\r
+            $nest = count($this->currentNesting) - 1;\r
+            if ($nest >= 0 && $this->currentNesting[$nest]->name === 'object') {\r
+                $i = count($this->objectStack) - 1;\r
+                if (!isset($token->attr['name'])) {\r
+                    $token = false;\r
+                    return;\r
+                }\r
+                $n = $token->attr['name'];\r
+                // We need this fix because YouTube doesn't supply a data\r
+                // attribute, which we need if a type is specified. This is\r
+                // *very* Flash specific.\r
+                if (!isset($this->objectStack[$i]->attr['data']) &&\r
+                    ($token->attr['name'] == 'movie' || $token->attr['name'] == 'src')\r
+                ) {\r
+                    $this->objectStack[$i]->attr['data'] = $token->attr['value'];\r
+                }\r
+                // Check if the parameter is the correct value but has not\r
+                // already been added\r
+                if (!isset($this->paramStack[$i][$n]) &&\r
+                    isset($this->addParam[$n]) &&\r
+                    $token->attr['name'] === $this->addParam[$n]) {\r
+                    // keep token, and add to param stack\r
+                    $this->paramStack[$i][$n] = true;\r
+                } elseif (isset($this->allowedParam[strtolower($n)])) {\r
+                    // keep token, don't do anything to it\r
+                    // (could possibly check for duplicates here)\r
+                    // Note: In principle, parameters should be case sensitive.\r
+                    // But it seems they are not really; so accept any case.\r
+                } else {\r
+                    $token = false;\r
+                }\r
+            } else {\r
+                // not directly inside an object, DENY!\r
+                $token = false;\r
+            }\r
+        }\r
+    }\r
+\r
+    public function handleEnd(&$token)\r
+    {\r
+        // This is the WRONG way of handling the object and param stacks;\r
+        // we should be inserting them directly on the relevant object tokens\r
+        // so that the global stack handling handles it.\r
+        if ($token->name == 'object') {\r
+            array_pop($this->objectStack);\r
+            array_pop($this->paramStack);\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Parser that uses PHP 5's DOM extension (part of the core).\r
+ *\r
+ * In PHP 5, the DOM XML extension was revamped into DOM and added to the core.\r
+ * It gives us a forgiving HTML parser, which we use to transform the HTML\r
+ * into a DOM, and then into the tokens.  It is blazingly fast (for large\r
+ * documents, it performs twenty times faster than\r
+ * HTMLPurifier_Lexer_DirectLex,and is the default choice for PHP 5.\r
+ *\r
+ * @note Any empty elements will have empty tokens associated with them, even if\r
+ * this is prohibited by the spec. This is cannot be fixed until the spec\r
+ * comes into play.\r
+ *\r
+ * @note PHP's DOM extension does not actually parse any entities, we use\r
+ *       our own function to do that.\r
+ *\r
+ * @warning DOM tends to drop whitespace, which may wreak havoc on indenting.\r
+ *          If this is a huge problem, due to the fact that HTML is hand\r
+ *          edited and you are unable to get a parser cache that caches the\r
+ *          the output of HTML Purifier while keeping the original HTML lying\r
+ *          around, you may want to run Tidy on the resulting output or use\r
+ *          HTMLPurifier_DirectLex\r
+ */\r
+\r
+class HTMLPurifier_Lexer_DOMLex extends HTMLPurifier_Lexer\r
+{\r
+\r
+    /**\r
+     * @type HTMLPurifier_TokenFactory\r
+     */\r
+    private $factory;\r
+\r
+    public function __construct()\r
+    {\r
+        // setup the factory\r
+        parent::__construct();\r
+        $this->factory = new HTMLPurifier_TokenFactory();\r
+    }\r
+\r
+    /**\r
+     * @param string $html\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return HTMLPurifier_Token[]\r
+     */\r
+    public function tokenizeHTML($html, $config, $context)\r
+    {\r
+        $html = $this->normalize($html, $config, $context);\r
+\r
+        // attempt to armor stray angled brackets that cannot possibly\r
+        // form tags and thus are probably being used as emoticons\r
+        if ($config->get('Core.AggressivelyFixLt')) {\r
+            $char = '[^a-z!\/]';\r
+            $comment = "/<!--(.*?)(-->|\z)/is";\r
+            $html = preg_replace_callback($comment, array($this, 'callbackArmorCommentEntities'), $html);\r
+            do {\r
+                $old = $html;\r
+                $html = preg_replace("/<($char)/i", '&lt;\\1', $html);\r
+            } while ($html !== $old);\r
+            $html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments\r
+        }\r
+\r
+        // preprocess html, essential for UTF-8\r
+        $html = $this->wrapHTML($html, $config, $context);\r
+\r
+        $doc = new DOMDocument();\r
+        $doc->encoding = 'UTF-8'; // theoretically, the above has this covered\r
+\r
+        $options = 0;\r
+        if ($config->get('Core.AllowParseManyTags') && defined('LIBXML_PARSEHUGE')) {\r
+            $options |= LIBXML_PARSEHUGE;\r
+        }\r
+\r
+        set_error_handler(array($this, 'muteErrorHandler'));\r
+        $doc->loadHTML($html, $options);\r
+        restore_error_handler();\r
+\r
+        $body = $doc->getElementsByTagName('html')->item(0)-> // <html>\r
+                      getElementsByTagName('body')->item(0);  // <body>\r
+\r
+        $div = $body->getElementsByTagName('div')->item(0); // <div>\r
+        $tokens = array();\r
+        $this->tokenizeDOM($div, $tokens, $config);\r
+        // If the div has a sibling, that means we tripped across\r
+        // a premature </div> tag.  So remove the div we parsed,\r
+        // and then tokenize the rest of body.  We can't tokenize\r
+        // the sibling directly as we'll lose the tags in that case.\r
+        if ($div->nextSibling) {\r
+            $body->removeChild($div);\r
+            $this->tokenizeDOM($body, $tokens, $config);\r
+        }\r
+        return $tokens;\r
+    }\r
+\r
+    /**\r
+     * Iterative function that tokenizes a node, putting it into an accumulator.\r
+     * To iterate is human, to recurse divine - L. Peter Deutsch\r
+     * @param DOMNode $node DOMNode to be tokenized.\r
+     * @param HTMLPurifier_Token[] $tokens   Array-list of already tokenized tokens.\r
+     * @return HTMLPurifier_Token of node appended to previously passed tokens.\r
+     */\r
+    protected function tokenizeDOM($node, &$tokens, $config)\r
+    {\r
+        $level = 0;\r
+        $nodes = array($level => new HTMLPurifier_Queue(array($node)));\r
+        $closingNodes = array();\r
+        do {\r
+            while (!$nodes[$level]->isEmpty()) {\r
+                $node = $nodes[$level]->shift(); // FIFO\r
+                $collect = $level > 0 ? true : false;\r
+                $needEndingTag = $this->createStartNode($node, $tokens, $collect, $config);\r
+                if ($needEndingTag) {\r
+                    $closingNodes[$level][] = $node;\r
+                }\r
+                if ($node->childNodes && $node->childNodes->length) {\r
+                    $level++;\r
+                    $nodes[$level] = new HTMLPurifier_Queue();\r
+                    foreach ($node->childNodes as $childNode) {\r
+                        $nodes[$level]->push($childNode);\r
+                    }\r
+                }\r
+            }\r
+            $level--;\r
+            if ($level && isset($closingNodes[$level])) {\r
+                while ($node = array_pop($closingNodes[$level])) {\r
+                    $this->createEndNode($node, $tokens);\r
+                }\r
+            }\r
+        } while ($level > 0);\r
+    }\r
+\r
+    /**\r
+     * Portably retrieve the tag name of a node; deals with older versions\r
+     * of libxml like 2.7.6\r
+     * @param DOMNode $node\r
+     */\r
+    protected function getTagName($node)\r
+    {\r
+        if (isset($node->tagName)) {\r
+            return $node->tagName;\r
+        } else if (isset($node->nodeName)) {\r
+            return $node->nodeName;\r
+        } else if (isset($node->localName)) {\r
+            return $node->localName;\r
+        }\r
+        return null;\r
+    }\r
+\r
+    /**\r
+     * Portably retrieve the data of a node; deals with older versions\r
+     * of libxml like 2.7.6\r
+     * @param DOMNode $node\r
+     */\r
+    protected function getData($node)\r
+    {\r
+        if (isset($node->data)) {\r
+            return $node->data;\r
+        } else if (isset($node->nodeValue)) {\r
+            return $node->nodeValue;\r
+        } else if (isset($node->textContent)) {\r
+            return $node->textContent;\r
+        }\r
+        return null;\r
+    }\r
+\r
+\r
+    /**\r
+     * @param DOMNode $node DOMNode to be tokenized.\r
+     * @param HTMLPurifier_Token[] $tokens   Array-list of already tokenized tokens.\r
+     * @param bool $collect  Says whether or start and close are collected, set to\r
+     *                    false at first recursion because it's the implicit DIV\r
+     *                    tag you're dealing with.\r
+     * @return bool if the token needs an endtoken\r
+     * @todo data and tagName properties don't seem to exist in DOMNode?\r
+     */\r
+    protected function createStartNode($node, &$tokens, $collect, $config)\r
+    {\r
+        // intercept non element nodes. WE MUST catch all of them,\r
+        // but we're not getting the character reference nodes because\r
+        // those should have been preprocessed\r
+        if ($node->nodeType === XML_TEXT_NODE) {\r
+            $data = $this->getData($node); // Handle variable data property\r
+            if ($data !== null) {\r
+              $tokens[] = $this->factory->createText($data);\r
+            }\r
+            return false;\r
+        } elseif ($node->nodeType === XML_CDATA_SECTION_NODE) {\r
+            // undo libxml's special treatment of <script> and <style> tags\r
+            $last = end($tokens);\r
+            $data = $node->data;\r
+            // (note $node->tagname is already normalized)\r
+            if ($last instanceof HTMLPurifier_Token_Start && ($last->name == 'script' || $last->name == 'style')) {\r
+                $new_data = trim($data);\r
+                if (substr($new_data, 0, 4) === '<!--') {\r
+                    $data = substr($new_data, 4);\r
+                    if (substr($data, -3) === '-->') {\r
+                        $data = substr($data, 0, -3);\r
+                    } else {\r
+                        // Highly suspicious! Not sure what to do...\r
+                    }\r
+                }\r
+            }\r
+            $tokens[] = $this->factory->createText($this->parseText($data, $config));\r
+            return false;\r
+        } elseif ($node->nodeType === XML_COMMENT_NODE) {\r
+            // this is code is only invoked for comments in script/style in versions\r
+            // of libxml pre-2.6.28 (regular comments, of course, are still\r
+            // handled regularly)\r
+            $tokens[] = $this->factory->createComment($node->data);\r
+            return false;\r
+        } elseif ($node->nodeType !== XML_ELEMENT_NODE) {\r
+            // not-well tested: there may be other nodes we have to grab\r
+            return false;\r
+        }\r
+        $attr = $node->hasAttributes() ? $this->transformAttrToAssoc($node->attributes) : array();\r
+        $tag_name = $this->getTagName($node); // Handle variable tagName property\r
+        if (empty($tag_name)) {\r
+            return (bool) $node->childNodes->length;\r
+        }\r
+        // We still have to make sure that the element actually IS empty\r
+        if (!$node->childNodes->length) {\r
+            if ($collect) {\r
+                $tokens[] = $this->factory->createEmpty($tag_name, $attr);\r
+            }\r
+            return false;\r
+        } else {\r
+            if ($collect) {\r
+                $tokens[] = $this->factory->createStart($tag_name, $attr);\r
+            }\r
+            return true;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * @param DOMNode $node\r
+     * @param HTMLPurifier_Token[] $tokens\r
+     */\r
+    protected function createEndNode($node, &$tokens)\r
+    {\r
+        $tag_name = $this->getTagName($node); // Handle variable tagName property\r
+        $tokens[] = $this->factory->createEnd($tag_name);\r
+    }\r
+\r
+    /**\r
+     * Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.\r
+     *\r
+     * @param DOMNamedNodeMap $node_map DOMNamedNodeMap of DOMAttr objects.\r
+     * @return array Associative array of attributes.\r
+     */\r
+    protected function transformAttrToAssoc($node_map)\r
+    {\r
+        // NamedNodeMap is documented very well, so we're using undocumented\r
+        // features, namely, the fact that it implements Iterator and\r
+        // has a ->length attribute\r
+        if ($node_map->length === 0) {\r
+            return array();\r
+        }\r
+        $array = array();\r
+        foreach ($node_map as $attr) {\r
+            $array[$attr->name] = $attr->value;\r
+        }\r
+        return $array;\r
+    }\r
+\r
+    /**\r
+     * An error handler that mutes all errors\r
+     * @param int $errno\r
+     * @param string $errstr\r
+     */\r
+    public function muteErrorHandler($errno, $errstr)\r
+    {\r
+    }\r
+\r
+    /**\r
+     * Callback function for undoing escaping of stray angled brackets\r
+     * in comments\r
+     * @param array $matches\r
+     * @return string\r
+     */\r
+    public function callbackUndoCommentSubst($matches)\r
+    {\r
+        return '<!--' . strtr($matches[1], array('&amp;' => '&', '&lt;' => '<')) . $matches[2];\r
+    }\r
+\r
+    /**\r
+     * Callback function that entity-izes ampersands in comments so that\r
+     * callbackUndoCommentSubst doesn't clobber them\r
+     * @param array $matches\r
+     * @return string\r
+     */\r
+    public function callbackArmorCommentEntities($matches)\r
+    {\r
+        return '<!--' . str_replace('&', '&amp;', $matches[1]) . $matches[2];\r
+    }\r
+\r
+    /**\r
+     * Wraps an HTML fragment in the necessary HTML\r
+     * @param string $html\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     */\r
+    protected function wrapHTML($html, $config, $context, $use_div = true)\r
+    {\r
+        $def = $config->getDefinition('HTML');\r
+        $ret = '';\r
+\r
+        if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {\r
+            $ret .= '<!DOCTYPE html ';\r
+            if (!empty($def->doctype->dtdPublic)) {\r
+                $ret .= 'PUBLIC "' . $def->doctype->dtdPublic . '" ';\r
+            }\r
+            if (!empty($def->doctype->dtdSystem)) {\r
+                $ret .= '"' . $def->doctype->dtdSystem . '" ';\r
+            }\r
+            $ret .= '>';\r
+        }\r
+\r
+        $ret .= '<html><head>';\r
+        $ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';\r
+        // No protection if $html contains a stray </div>!\r
+        $ret .= '</head><body>';\r
+        if ($use_div) $ret .= '<div>';\r
+        $ret .= $html;\r
+        if ($use_div) $ret .= '</div>';\r
+        $ret .= '</body></html>';\r
+        return $ret;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Our in-house implementation of a parser.\r
+ *\r
+ * A pure PHP parser, DirectLex has absolutely no dependencies, making\r
+ * it a reasonably good default for PHP4.  Written with efficiency in mind,\r
+ * it can be four times faster than HTMLPurifier_Lexer_PEARSax3, although it\r
+ * pales in comparison to HTMLPurifier_Lexer_DOMLex.\r
+ *\r
+ * @todo Reread XML spec and document differences.\r
+ */\r
+class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer\r
+{\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $tracksLineNumbers = true;\r
+\r
+    /**\r
+     * Whitespace characters for str(c)spn.\r
+     * @type string\r
+     */\r
+    protected $_whitespace = "\x20\x09\x0D\x0A";\r
+\r
+    /**\r
+     * Callback function for script CDATA fudge\r
+     * @param array $matches, in form of array(opening tag, contents, closing tag)\r
+     * @return string\r
+     */\r
+    protected function scriptCallback($matches)\r
+    {\r
+        return $matches[1] . htmlspecialchars($matches[2], ENT_COMPAT, 'UTF-8') . $matches[3];\r
+    }\r
+\r
+    /**\r
+     * @param String $html\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array|HTMLPurifier_Token[]\r
+     */\r
+    public function tokenizeHTML($html, $config, $context)\r
+    {\r
+        // special normalization for script tags without any armor\r
+        // our "armor" heurstic is a < sign any number of whitespaces after\r
+        // the first script tag\r
+        if ($config->get('HTML.Trusted')) {\r
+            $html = preg_replace_callback(\r
+                '#(<script[^>]*>)(\s*[^<].+?)(</script>)#si',\r
+                array($this, 'scriptCallback'),\r
+                $html\r
+            );\r
+        }\r
+\r
+        $html = $this->normalize($html, $config, $context);\r
+\r
+        $cursor = 0; // our location in the text\r
+        $inside_tag = false; // whether or not we're parsing the inside of a tag\r
+        $array = array(); // result array\r
+\r
+        // This is also treated to mean maintain *column* numbers too\r
+        $maintain_line_numbers = $config->get('Core.MaintainLineNumbers');\r
+\r
+        if ($maintain_line_numbers === null) {\r
+            // automatically determine line numbering by checking\r
+            // if error collection is on\r
+            $maintain_line_numbers = $config->get('Core.CollectErrors');\r
+        }\r
+\r
+        if ($maintain_line_numbers) {\r
+            $current_line = 1;\r
+            $current_col = 0;\r
+            $length = strlen($html);\r
+        } else {\r
+            $current_line = false;\r
+            $current_col = false;\r
+            $length = false;\r
+        }\r
+        $context->register('CurrentLine', $current_line);\r
+        $context->register('CurrentCol', $current_col);\r
+        $nl = "\n";\r
+        // how often to manually recalculate. This will ALWAYS be right,\r
+        // but it's pretty wasteful. Set to 0 to turn off\r
+        $synchronize_interval = $config->get('Core.DirectLexLineNumberSyncInterval');\r
+\r
+        $e = false;\r
+        if ($config->get('Core.CollectErrors')) {\r
+            $e =& $context->get('ErrorCollector');\r
+        }\r
+\r
+        // for testing synchronization\r
+        $loops = 0;\r
+\r
+        while (++$loops) {\r
+            // $cursor is either at the start of a token, or inside of\r
+            // a tag (i.e. there was a < immediately before it), as indicated\r
+            // by $inside_tag\r
+\r
+            if ($maintain_line_numbers) {\r
+                // $rcursor, however, is always at the start of a token.\r
+                $rcursor = $cursor - (int)$inside_tag;\r
+\r
+                // Column number is cheap, so we calculate it every round.\r
+                // We're interested at the *end* of the newline string, so\r
+                // we need to add strlen($nl) == 1 to $nl_pos before subtracting it\r
+                // from our "rcursor" position.\r
+                $nl_pos = strrpos($html, $nl, $rcursor - $length);\r
+                $current_col = $rcursor - (is_bool($nl_pos) ? 0 : $nl_pos + 1);\r
+\r
+                // recalculate lines\r
+                if ($synchronize_interval && // synchronization is on\r
+                    $cursor > 0 && // cursor is further than zero\r
+                    $loops % $synchronize_interval === 0) { // time to synchronize!\r
+                    $current_line = 1 + $this->substrCount($html, $nl, 0, $cursor);\r
+                }\r
+            }\r
+\r
+            $position_next_lt = strpos($html, '<', $cursor);\r
+            $position_next_gt = strpos($html, '>', $cursor);\r
+\r
+            // triggers on "<b>asdf</b>" but not "asdf <b></b>"\r
+            // special case to set up context\r
+            if ($position_next_lt === $cursor) {\r
+                $inside_tag = true;\r
+                $cursor++;\r
+            }\r
+\r
+            if (!$inside_tag && $position_next_lt !== false) {\r
+                // We are not inside tag and there still is another tag to parse\r
+                $token = new\r
+                HTMLPurifier_Token_Text(\r
+                    $this->parseText(\r
+                        substr(\r
+                            $html,\r
+                            $cursor,\r
+                            $position_next_lt - $cursor\r
+                        ), $config\r
+                    )\r
+                );\r
+                if ($maintain_line_numbers) {\r
+                    $token->rawPosition($current_line, $current_col);\r
+                    $current_line += $this->substrCount($html, $nl, $cursor, $position_next_lt - $cursor);\r
+                }\r
+                $array[] = $token;\r
+                $cursor = $position_next_lt + 1;\r
+                $inside_tag = true;\r
+                continue;\r
+            } elseif (!$inside_tag) {\r
+                // We are not inside tag but there are no more tags\r
+                // If we're already at the end, break\r
+                if ($cursor === strlen($html)) {\r
+                    break;\r
+                }\r
+                // Create Text of rest of string\r
+                $token = new\r
+                HTMLPurifier_Token_Text(\r
+                    $this->parseText(\r
+                        substr(\r
+                            $html,\r
+                            $cursor\r
+                        ), $config\r
+                    )\r
+                );\r
+                if ($maintain_line_numbers) {\r
+                    $token->rawPosition($current_line, $current_col);\r
+                }\r
+                $array[] = $token;\r
+                break;\r
+            } elseif ($inside_tag && $position_next_gt !== false) {\r
+                // We are in tag and it is well formed\r
+                // Grab the internals of the tag\r
+                $strlen_segment = $position_next_gt - $cursor;\r
+\r
+                if ($strlen_segment < 1) {\r
+                    // there's nothing to process!\r
+                    $token = new HTMLPurifier_Token_Text('<');\r
+                    $cursor++;\r
+                    continue;\r
+                }\r
+\r
+                $segment = substr($html, $cursor, $strlen_segment);\r
+\r
+                if ($segment === false) {\r
+                    // somehow, we attempted to access beyond the end of\r
+                    // the string, defense-in-depth, reported by Nate Abele\r
+                    break;\r
+                }\r
+\r
+                // Check if it's a comment\r
+                if (substr($segment, 0, 3) === '!--') {\r
+                    // re-determine segment length, looking for -->\r
+                    $position_comment_end = strpos($html, '-->', $cursor);\r
+                    if ($position_comment_end === false) {\r
+                        // uh oh, we have a comment that extends to\r
+                        // infinity. Can't be helped: set comment\r
+                        // end position to end of string\r
+                        if ($e) {\r
+                            $e->send(E_WARNING, 'Lexer: Unclosed comment');\r
+                        }\r
+                        $position_comment_end = strlen($html);\r
+                        $end = true;\r
+                    } else {\r
+                        $end = false;\r
+                    }\r
+                    $strlen_segment = $position_comment_end - $cursor;\r
+                    $segment = substr($html, $cursor, $strlen_segment);\r
+                    $token = new\r
+                    HTMLPurifier_Token_Comment(\r
+                        substr(\r
+                            $segment,\r
+                            3,\r
+                            $strlen_segment - 3\r
+                        )\r
+                    );\r
+                    if ($maintain_line_numbers) {\r
+                        $token->rawPosition($current_line, $current_col);\r
+                        $current_line += $this->substrCount($html, $nl, $cursor, $strlen_segment);\r
+                    }\r
+                    $array[] = $token;\r
+                    $cursor = $end ? $position_comment_end : $position_comment_end + 3;\r
+                    $inside_tag = false;\r
+                    continue;\r
+                }\r
+\r
+                // Check if it's an end tag\r
+                $is_end_tag = (strpos($segment, '/') === 0);\r
+                if ($is_end_tag) {\r
+                    $type = substr($segment, 1);\r
+                    $token = new HTMLPurifier_Token_End($type);\r
+                    if ($maintain_line_numbers) {\r
+                        $token->rawPosition($current_line, $current_col);\r
+                        $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);\r
+                    }\r
+                    $array[] = $token;\r
+                    $inside_tag = false;\r
+                    $cursor = $position_next_gt + 1;\r
+                    continue;\r
+                }\r
+\r
+                // Check leading character is alnum, if not, we may\r
+                // have accidently grabbed an emoticon. Translate into\r
+                // text and go our merry way\r
+                if (!ctype_alpha($segment[0])) {\r
+                    // XML:  $segment[0] !== '_' && $segment[0] !== ':'\r
+                    if ($e) {\r
+                        $e->send(E_NOTICE, 'Lexer: Unescaped lt');\r
+                    }\r
+                    $token = new HTMLPurifier_Token_Text('<');\r
+                    if ($maintain_line_numbers) {\r
+                        $token->rawPosition($current_line, $current_col);\r
+                        $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);\r
+                    }\r
+                    $array[] = $token;\r
+                    $inside_tag = false;\r
+                    continue;\r
+                }\r
+\r
+                // Check if it is explicitly self closing, if so, remove\r
+                // trailing slash. Remember, we could have a tag like <br>, so\r
+                // any later token processing scripts must convert improperly\r
+                // classified EmptyTags from StartTags.\r
+                $is_self_closing = (strrpos($segment, '/') === $strlen_segment - 1);\r
+                if ($is_self_closing) {\r
+                    $strlen_segment--;\r
+                    $segment = substr($segment, 0, $strlen_segment);\r
+                }\r
+\r
+                // Check if there are any attributes\r
+                $position_first_space = strcspn($segment, $this->_whitespace);\r
+\r
+                if ($position_first_space >= $strlen_segment) {\r
+                    if ($is_self_closing) {\r
+                        $token = new HTMLPurifier_Token_Empty($segment);\r
+                    } else {\r
+                        $token = new HTMLPurifier_Token_Start($segment);\r
+                    }\r
+                    if ($maintain_line_numbers) {\r
+                        $token->rawPosition($current_line, $current_col);\r
+                        $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);\r
+                    }\r
+                    $array[] = $token;\r
+                    $inside_tag = false;\r
+                    $cursor = $position_next_gt + 1;\r
+                    continue;\r
+                }\r
+\r
+                // Grab out all the data\r
+                $type = substr($segment, 0, $position_first_space);\r
+                $attribute_string =\r
+                    trim(\r
+                        substr(\r
+                            $segment,\r
+                            $position_first_space\r
+                        )\r
+                    );\r
+                if ($attribute_string) {\r
+                    $attr = $this->parseAttributeString(\r
+                        $attribute_string,\r
+                        $config,\r
+                        $context\r
+                    );\r
+                } else {\r
+                    $attr = array();\r
+                }\r
+\r
+                if ($is_self_closing) {\r
+                    $token = new HTMLPurifier_Token_Empty($type, $attr);\r
+                } else {\r
+                    $token = new HTMLPurifier_Token_Start($type, $attr);\r
+                }\r
+                if ($maintain_line_numbers) {\r
+                    $token->rawPosition($current_line, $current_col);\r
+                    $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);\r
+                }\r
+                $array[] = $token;\r
+                $cursor = $position_next_gt + 1;\r
+                $inside_tag = false;\r
+                continue;\r
+            } else {\r
+                // inside tag, but there's no ending > sign\r
+                if ($e) {\r
+                    $e->send(E_WARNING, 'Lexer: Missing gt');\r
+                }\r
+                $token = new\r
+                HTMLPurifier_Token_Text(\r
+                    '<' .\r
+                    $this->parseText(\r
+                        substr($html, $cursor), $config\r
+                    )\r
+                );\r
+                if ($maintain_line_numbers) {\r
+                    $token->rawPosition($current_line, $current_col);\r
+                }\r
+                // no cursor scroll? Hmm...\r
+                $array[] = $token;\r
+                break;\r
+            }\r
+            break;\r
+        }\r
+\r
+        $context->destroy('CurrentLine');\r
+        $context->destroy('CurrentCol');\r
+        return $array;\r
+    }\r
+\r
+    /**\r
+     * PHP 5.0.x compatible substr_count that implements offset and length\r
+     * @param string $haystack\r
+     * @param string $needle\r
+     * @param int $offset\r
+     * @param int $length\r
+     * @return int\r
+     */\r
+    protected function substrCount($haystack, $needle, $offset, $length)\r
+    {\r
+        static $oldVersion;\r
+        if ($oldVersion === null) {\r
+            $oldVersion = version_compare(PHP_VERSION, '5.1', '<');\r
+        }\r
+        if ($oldVersion) {\r
+            $haystack = substr($haystack, $offset, $length);\r
+            return substr_count($haystack, $needle);\r
+        } else {\r
+            return substr_count($haystack, $needle, $offset, $length);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Takes the inside of an HTML tag and makes an assoc array of attributes.\r
+     *\r
+     * @param string $string Inside of tag excluding name.\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array Assoc array of attributes.\r
+     */\r
+    public function parseAttributeString($string, $config, $context)\r
+    {\r
+        $string = (string)$string; // quick typecast\r
+\r
+        if ($string == '') {\r
+            return array();\r
+        } // no attributes\r
+\r
+        $e = false;\r
+        if ($config->get('Core.CollectErrors')) {\r
+            $e =& $context->get('ErrorCollector');\r
+        }\r
+\r
+        // let's see if we can abort as quickly as possible\r
+        // one equal sign, no spaces => one attribute\r
+        $num_equal = substr_count($string, '=');\r
+        $has_space = strpos($string, ' ');\r
+        if ($num_equal === 0 && !$has_space) {\r
+            // bool attribute\r
+            return array($string => $string);\r
+        } elseif ($num_equal === 1 && !$has_space) {\r
+            // only one attribute\r
+            list($key, $quoted_value) = explode('=', $string);\r
+            $quoted_value = trim($quoted_value);\r
+            if (!$key) {\r
+                if ($e) {\r
+                    $e->send(E_ERROR, 'Lexer: Missing attribute key');\r
+                }\r
+                return array();\r
+            }\r
+            if (!$quoted_value) {\r
+                return array($key => '');\r
+            }\r
+            $first_char = @$quoted_value[0];\r
+            $last_char = @$quoted_value[strlen($quoted_value) - 1];\r
+\r
+            $same_quote = ($first_char == $last_char);\r
+            $open_quote = ($first_char == '"' || $first_char == "'");\r
+\r
+            if ($same_quote && $open_quote) {\r
+                // well behaved\r
+                $value = substr($quoted_value, 1, strlen($quoted_value) - 2);\r
+            } else {\r
+                // not well behaved\r
+                if ($open_quote) {\r
+                    if ($e) {\r
+                        $e->send(E_ERROR, 'Lexer: Missing end quote');\r
+                    }\r
+                    $value = substr($quoted_value, 1);\r
+                } else {\r
+                    $value = $quoted_value;\r
+                }\r
+            }\r
+            if ($value === false) {\r
+                $value = '';\r
+            }\r
+            return array($key => $this->parseAttr($value, $config));\r
+        }\r
+\r
+        // setup loop environment\r
+        $array = array(); // return assoc array of attributes\r
+        $cursor = 0; // current position in string (moves forward)\r
+        $size = strlen($string); // size of the string (stays the same)\r
+\r
+        // if we have unquoted attributes, the parser expects a terminating\r
+        // space, so let's guarantee that there's always a terminating space.\r
+        $string .= ' ';\r
+\r
+        $old_cursor = -1;\r
+        while ($cursor < $size) {\r
+            if ($old_cursor >= $cursor) {\r
+                throw new Exception("Infinite loop detected");\r
+            }\r
+            $old_cursor = $cursor;\r
+\r
+            $cursor += ($value = strspn($string, $this->_whitespace, $cursor));\r
+            // grab the key\r
+\r
+            $key_begin = $cursor; //we're currently at the start of the key\r
+\r
+            // scroll past all characters that are the key (not whitespace or =)\r
+            $cursor += strcspn($string, $this->_whitespace . '=', $cursor);\r
+\r
+            $key_end = $cursor; // now at the end of the key\r
+\r
+            $key = substr($string, $key_begin, $key_end - $key_begin);\r
+\r
+            if (!$key) {\r
+                if ($e) {\r
+                    $e->send(E_ERROR, 'Lexer: Missing attribute key');\r
+                }\r
+                $cursor += 1 + strcspn($string, $this->_whitespace, $cursor + 1); // prevent infinite loop\r
+                continue; // empty key\r
+            }\r
+\r
+            // scroll past all whitespace\r
+            $cursor += strspn($string, $this->_whitespace, $cursor);\r
+\r
+            if ($cursor >= $size) {\r
+                $array[$key] = $key;\r
+                break;\r
+            }\r
+\r
+            // if the next character is an equal sign, we've got a regular\r
+            // pair, otherwise, it's a bool attribute\r
+            $first_char = @$string[$cursor];\r
+\r
+            if ($first_char == '=') {\r
+                // key="value"\r
+\r
+                $cursor++;\r
+                $cursor += strspn($string, $this->_whitespace, $cursor);\r
+\r
+                if ($cursor === false) {\r
+                    $array[$key] = '';\r
+                    break;\r
+                }\r
+\r
+                // we might be in front of a quote right now\r
+\r
+                $char = @$string[$cursor];\r
+\r
+                if ($char == '"' || $char == "'") {\r
+                    // it's quoted, end bound is $char\r
+                    $cursor++;\r
+                    $value_begin = $cursor;\r
+                    $cursor = strpos($string, $char, $cursor);\r
+                    $value_end = $cursor;\r
+                } else {\r
+                    // it's not quoted, end bound is whitespace\r
+                    $value_begin = $cursor;\r
+                    $cursor += strcspn($string, $this->_whitespace, $cursor);\r
+                    $value_end = $cursor;\r
+                }\r
+\r
+                // we reached a premature end\r
+                if ($cursor === false) {\r
+                    $cursor = $size;\r
+                    $value_end = $cursor;\r
+                }\r
+\r
+                $value = substr($string, $value_begin, $value_end - $value_begin);\r
+                if ($value === false) {\r
+                    $value = '';\r
+                }\r
+                $array[$key] = $this->parseAttr($value, $config);\r
+                $cursor++;\r
+            } else {\r
+                // boolattr\r
+                if ($key !== '') {\r
+                    $array[$key] = $key;\r
+                } else {\r
+                    // purely theoretical\r
+                    if ($e) {\r
+                        $e->send(E_ERROR, 'Lexer: Missing attribute key');\r
+                    }\r
+                }\r
+            }\r
+        }\r
+        return $array;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Concrete comment node class.\r
+ */\r
+class HTMLPurifier_Node_Comment extends HTMLPurifier_Node\r
+{\r
+    /**\r
+     * Character data within comment.\r
+     * @type string\r
+     */\r
+    public $data;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $is_whitespace = true;\r
+\r
+    /**\r
+     * Transparent constructor.\r
+     *\r
+     * @param string $data String comment data.\r
+     * @param int $line\r
+     * @param int $col\r
+     */\r
+    public function __construct($data, $line = null, $col = null)\r
+    {\r
+        $this->data = $data;\r
+        $this->line = $line;\r
+        $this->col = $col;\r
+    }\r
+\r
+    public function toTokenPair() {\r
+        return array(new HTMLPurifier_Token_Comment($this->data, $this->line, $this->col), null);\r
+    }\r
+}\r
+
+\r
+\r
+/**\r
+ * Concrete element node class.\r
+ */\r
+class HTMLPurifier_Node_Element extends HTMLPurifier_Node\r
+{\r
+    /**\r
+     * The lower-case name of the tag, like 'a', 'b' or 'blockquote'.\r
+     *\r
+     * @note Strictly speaking, XML tags are case sensitive, so we shouldn't\r
+     * be lower-casing them, but these tokens cater to HTML tags, which are\r
+     * insensitive.\r
+     * @type string\r
+     */\r
+    public $name;\r
+\r
+    /**\r
+     * Associative array of the node's attributes.\r
+     * @type array\r
+     */\r
+    public $attr = array();\r
+\r
+    /**\r
+     * List of child elements.\r
+     * @type array\r
+     */\r
+    public $children = array();\r
+\r
+    /**\r
+     * Does this use the <a></a> form or the </a> form, i.e.\r
+     * is it a pair of start/end tokens or an empty token.\r
+     * @bool\r
+     */\r
+    public $empty = false;\r
+\r
+    public $endCol = null, $endLine = null, $endArmor = array();\r
+\r
+    public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array()) {\r
+        $this->name = $name;\r
+        $this->attr = $attr;\r
+        $this->line = $line;\r
+        $this->col = $col;\r
+        $this->armor = $armor;\r
+    }\r
+\r
+    public function toTokenPair() {\r
+        // XXX inefficiency here, normalization is not necessary\r
+        if ($this->empty) {\r
+            return array(new HTMLPurifier_Token_Empty($this->name, $this->attr, $this->line, $this->col, $this->armor), null);\r
+        } else {\r
+            $start = new HTMLPurifier_Token_Start($this->name, $this->attr, $this->line, $this->col, $this->armor);\r
+            $end = new HTMLPurifier_Token_End($this->name, array(), $this->endLine, $this->endCol, $this->endArmor);\r
+            //$end->start = $start;\r
+            return array($start, $end);\r
+        }\r
+    }\r
+}\r
+\r
+
+\r
+\r
+/**\r
+ * Concrete text token class.\r
+ *\r
+ * Text tokens comprise of regular parsed character data (PCDATA) and raw\r
+ * character data (from the CDATA sections). Internally, their\r
+ * data is parsed with all entities expanded. Surprisingly, the text token\r
+ * does have a "tag name" called #PCDATA, which is how the DTD represents it\r
+ * in permissible child nodes.\r
+ */\r
+class HTMLPurifier_Node_Text extends HTMLPurifier_Node\r
+{\r
+\r
+    /**\r
+     * PCDATA tag name compatible with DTD, see\r
+     * HTMLPurifier_ChildDef_Custom for details.\r
+     * @type string\r
+     */\r
+    public $name = '#PCDATA';\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $data;\r
+    /**< Parsed character data of text. */\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $is_whitespace;\r
+\r
+    /**< Bool indicating if node is whitespace. */\r
+\r
+    /**\r
+     * Constructor, accepts data and determines if it is whitespace.\r
+     * @param string $data String parsed character data.\r
+     * @param int $line\r
+     * @param int $col\r
+     */\r
+    public function __construct($data, $is_whitespace, $line = null, $col = null)\r
+    {\r
+        $this->data = $data;\r
+        $this->is_whitespace = $is_whitespace;\r
+        $this->line = $line;\r
+        $this->col = $col;\r
+    }\r
+\r
+    public function toTokenPair() {\r
+        return array(new HTMLPurifier_Token_Text($this->data, $this->line, $this->col), null);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Composite strategy that runs multiple strategies on tokens.\r
+ */\r
+abstract class HTMLPurifier_Strategy_Composite extends HTMLPurifier_Strategy\r
+{\r
+\r
+    /**\r
+     * List of strategies to run tokens through.\r
+     * @type HTMLPurifier_Strategy[]\r
+     */\r
+    protected $strategies = array();\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token[] $tokens\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return HTMLPurifier_Token[]\r
+     */\r
+    public function execute($tokens, $config, $context)\r
+    {\r
+        foreach ($this->strategies as $strategy) {\r
+            $tokens = $strategy->execute($tokens, $config, $context);\r
+        }\r
+        return $tokens;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Core strategy composed of the big four strategies.\r
+ */\r
+class HTMLPurifier_Strategy_Core extends HTMLPurifier_Strategy_Composite\r
+{\r
+    public function __construct()\r
+    {\r
+        $this->strategies[] = new HTMLPurifier_Strategy_RemoveForeignElements();\r
+        $this->strategies[] = new HTMLPurifier_Strategy_MakeWellFormed();\r
+        $this->strategies[] = new HTMLPurifier_Strategy_FixNesting();\r
+        $this->strategies[] = new HTMLPurifier_Strategy_ValidateAttributes();\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Takes a well formed list of tokens and fixes their nesting.\r
+ *\r
+ * HTML elements dictate which elements are allowed to be their children,\r
+ * for example, you can't have a p tag in a span tag.  Other elements have\r
+ * much more rigorous definitions: tables, for instance, require a specific\r
+ * order for their elements.  There are also constraints not expressible by\r
+ * document type definitions, such as the chameleon nature of ins/del\r
+ * tags and global child exclusions.\r
+ *\r
+ * The first major objective of this strategy is to iterate through all\r
+ * the nodes and determine whether or not their children conform to the\r
+ * element's definition.  If they do not, the child definition may\r
+ * optionally supply an amended list of elements that is valid or\r
+ * require that the entire node be deleted (and the previous node\r
+ * rescanned).\r
+ *\r
+ * The second objective is to ensure that explicitly excluded elements of\r
+ * an element do not appear in its children.  Code that accomplishes this\r
+ * task is pervasive through the strategy, though the two are distinct tasks\r
+ * and could, theoretically, be seperated (although it's not recommended).\r
+ *\r
+ * @note Whether or not unrecognized children are silently dropped or\r
+ *       translated into text depends on the child definitions.\r
+ *\r
+ * @todo Enable nodes to be bubbled out of the structure.  This is\r
+ *       easier with our new algorithm.\r
+ */\r
+\r
+class HTMLPurifier_Strategy_FixNesting extends HTMLPurifier_Strategy\r
+{\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token[] $tokens\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array|HTMLPurifier_Token[]\r
+     */\r
+    public function execute($tokens, $config, $context)\r
+    {\r
+\r
+        //####################################################################//\r
+        // Pre-processing\r
+\r
+        // O(n) pass to convert to a tree, so that we can efficiently\r
+        // refer to substrings\r
+        $top_node = HTMLPurifier_Arborize::arborize($tokens, $config, $context);\r
+\r
+        // get a copy of the HTML definition\r
+        $definition = $config->getHTMLDefinition();\r
+\r
+        $excludes_enabled = !$config->get('Core.DisableExcludes');\r
+\r
+        // setup the context variable 'IsInline', for chameleon processing\r
+        // is 'false' when we are not inline, 'true' when it must always\r
+        // be inline, and an integer when it is inline for a certain\r
+        // branch of the document tree\r
+        $is_inline = $definition->info_parent_def->descendants_are_inline;\r
+        $context->register('IsInline', $is_inline);\r
+\r
+        // setup error collector\r
+        $e =& $context->get('ErrorCollector', true);\r
+\r
+        //####################################################################//\r
+        // Loop initialization\r
+\r
+        // stack that contains all elements that are excluded\r
+        // it is organized by parent elements, similar to $stack,\r
+        // but it is only populated when an element with exclusions is\r
+        // processed, i.e. there won't be empty exclusions.\r
+        $exclude_stack = array($definition->info_parent_def->excludes);\r
+\r
+        // variable that contains the start token while we are processing\r
+        // nodes. This enables error reporting to do its job\r
+        $node = $top_node;\r
+        // dummy token\r
+        list($token, $d) = $node->toTokenPair();\r
+        $context->register('CurrentNode', $node);\r
+        $context->register('CurrentToken', $token);\r
+\r
+        //####################################################################//\r
+        // Loop\r
+\r
+        // We need to implement a post-order traversal iteratively, to\r
+        // avoid running into stack space limits.  This is pretty tricky\r
+        // to reason about, so we just manually stack-ify the recursive\r
+        // variant:\r
+        //\r
+        //  function f($node) {\r
+        //      foreach ($node->children as $child) {\r
+        //          f($child);\r
+        //      }\r
+        //      validate($node);\r
+        //  }\r
+        //\r
+        // Thus, we will represent a stack frame as array($node,\r
+        // $is_inline, stack of children)\r
+        // e.g. array_reverse($node->children) - already processed\r
+        // children.\r
+\r
+        $parent_def = $definition->info_parent_def;\r
+        $stack = array(\r
+            array($top_node,\r
+                  $parent_def->descendants_are_inline,\r
+                  $parent_def->excludes, // exclusions\r
+                  0)\r
+            );\r
+\r
+        while (!empty($stack)) {\r
+            list($node, $is_inline, $excludes, $ix) = array_pop($stack);\r
+            // recursive call\r
+            $go = false;\r
+            $def = empty($stack) ? $definition->info_parent_def : $definition->info[$node->name];\r
+            while (isset($node->children[$ix])) {\r
+                $child = $node->children[$ix++];\r
+                if ($child instanceof HTMLPurifier_Node_Element) {\r
+                    $go = true;\r
+                    $stack[] = array($node, $is_inline, $excludes, $ix);\r
+                    $stack[] = array($child,\r
+                        // ToDo: I don't think it matters if it's def or\r
+                        // child_def, but double check this...\r
+                        $is_inline || $def->descendants_are_inline,\r
+                        empty($def->excludes) ? $excludes\r
+                                              : array_merge($excludes, $def->excludes),\r
+                        0);\r
+                    break;\r
+                }\r
+            };\r
+            if ($go) continue;\r
+            list($token, $d) = $node->toTokenPair();\r
+            // base case\r
+            if ($excludes_enabled && isset($excludes[$node->name])) {\r
+                $node->dead = true;\r
+                if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded');\r
+            } else {\r
+                // XXX I suppose it would be slightly more efficient to\r
+                // avoid the allocation here and have children\r
+                // strategies handle it\r
+                $children = array();\r
+                foreach ($node->children as $child) {\r
+                    if (!$child->dead) $children[] = $child;\r
+                }\r
+                $result = $def->child->validateChildren($children, $config, $context);\r
+                if ($result === true) {\r
+                    // nop\r
+                    $node->children = $children;\r
+                } elseif ($result === false) {\r
+                    $node->dead = true;\r
+                    if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node removed');\r
+                } else {\r
+                    $node->children = $result;\r
+                    if ($e) {\r
+                        // XXX This will miss mutations of internal nodes. Perhaps defer to the child validators\r
+                        if (empty($result) && !empty($children)) {\r
+                            $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed');\r
+                        } else if ($result != $children) {\r
+                            $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized');\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        //####################################################################//\r
+        // Post-processing\r
+\r
+        // remove context variables\r
+        $context->destroy('IsInline');\r
+        $context->destroy('CurrentNode');\r
+        $context->destroy('CurrentToken');\r
+\r
+        //####################################################################//\r
+        // Return\r
+\r
+        return HTMLPurifier_Arborize::flatten($node, $config, $context);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Takes tokens makes them well-formed (balance end tags, etc.)\r
+ *\r
+ * Specification of the armor attributes this strategy uses:\r
+ *\r
+ *      - MakeWellFormed_TagClosedError: This armor field is used to\r
+ *        suppress tag closed errors for certain tokens [TagClosedSuppress],\r
+ *        in particular, if a tag was generated automatically by HTML\r
+ *        Purifier, we may rely on our infrastructure to close it for us\r
+ *        and shouldn't report an error to the user [TagClosedAuto].\r
+ */\r
+class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy\r
+{\r
+\r
+    /**\r
+     * Array stream of tokens being processed.\r
+     * @type HTMLPurifier_Token[]\r
+     */\r
+    protected $tokens;\r
+\r
+    /**\r
+     * Current token.\r
+     * @type HTMLPurifier_Token\r
+     */\r
+    protected $token;\r
+\r
+    /**\r
+     * Zipper managing the true state.\r
+     * @type HTMLPurifier_Zipper\r
+     */\r
+    protected $zipper;\r
+\r
+    /**\r
+     * Current nesting of elements.\r
+     * @type array\r
+     */\r
+    protected $stack;\r
+\r
+    /**\r
+     * Injectors active in this stream processing.\r
+     * @type HTMLPurifier_Injector[]\r
+     */\r
+    protected $injectors;\r
+\r
+    /**\r
+     * Current instance of HTMLPurifier_Config.\r
+     * @type HTMLPurifier_Config\r
+     */\r
+    protected $config;\r
+\r
+    /**\r
+     * Current instance of HTMLPurifier_Context.\r
+     * @type HTMLPurifier_Context\r
+     */\r
+    protected $context;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token[] $tokens\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return HTMLPurifier_Token[]\r
+     * @throws HTMLPurifier_Exception\r
+     */\r
+    public function execute($tokens, $config, $context)\r
+    {\r
+        $definition = $config->getHTMLDefinition();\r
+\r
+        // local variables\r
+        $generator = new HTMLPurifier_Generator($config, $context);\r
+        $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');\r
+        // used for autoclose early abortion\r
+        $global_parent_allowed_elements = $definition->info_parent_def->child->getAllowedElements($config);\r
+        $e = $context->get('ErrorCollector', true);\r
+        $i = false; // injector index\r
+        list($zipper, $token) = HTMLPurifier_Zipper::fromArray($tokens);\r
+        if ($token === NULL) {\r
+            return array();\r
+        }\r
+        $reprocess = false; // whether or not to reprocess the same token\r
+        $stack = array();\r
+\r
+        // member variables\r
+        $this->stack =& $stack;\r
+        $this->tokens =& $tokens;\r
+        $this->token =& $token;\r
+        $this->zipper =& $zipper;\r
+        $this->config = $config;\r
+        $this->context = $context;\r
+\r
+        // context variables\r
+        $context->register('CurrentNesting', $stack);\r
+        $context->register('InputZipper', $zipper);\r
+        $context->register('CurrentToken', $token);\r
+\r
+        // -- begin INJECTOR --\r
+\r
+        $this->injectors = array();\r
+\r
+        $injectors = $config->getBatch('AutoFormat');\r
+        $def_injectors = $definition->info_injector;\r
+        $custom_injectors = $injectors['Custom'];\r
+        unset($injectors['Custom']); // special case\r
+        foreach ($injectors as $injector => $b) {\r
+            // XXX: Fix with a legitimate lookup table of enabled filters\r
+            if (strpos($injector, '.') !== false) {\r
+                continue;\r
+            }\r
+            $injector = "HTMLPurifier_Injector_$injector";\r
+            if (!$b) {\r
+                continue;\r
+            }\r
+            $this->injectors[] = new $injector;\r
+        }\r
+        foreach ($def_injectors as $injector) {\r
+            // assumed to be objects\r
+            $this->injectors[] = $injector;\r
+        }\r
+        foreach ($custom_injectors as $injector) {\r
+            if (!$injector) {\r
+                continue;\r
+            }\r
+            if (is_string($injector)) {\r
+                $injector = "HTMLPurifier_Injector_$injector";\r
+                $injector = new $injector;\r
+            }\r
+            $this->injectors[] = $injector;\r
+        }\r
+\r
+        // give the injectors references to the definition and context\r
+        // variables for performance reasons\r
+        foreach ($this->injectors as $ix => $injector) {\r
+            $error = $injector->prepare($config, $context);\r
+            if (!$error) {\r
+                continue;\r
+            }\r
+            array_splice($this->injectors, $ix, 1); // rm the injector\r
+            trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING);\r
+        }\r
+\r
+        // -- end INJECTOR --\r
+\r
+        // a note on reprocessing:\r
+        //      In order to reduce code duplication, whenever some code needs\r
+        //      to make HTML changes in order to make things "correct", the\r
+        //      new HTML gets sent through the purifier, regardless of its\r
+        //      status. This means that if we add a start token, because it\r
+        //      was totally necessary, we don't have to update nesting; we just\r
+        //      punt ($reprocess = true; continue;) and it does that for us.\r
+\r
+        // isset is in loop because $tokens size changes during loop exec\r
+        for (;;\r
+             // only increment if we don't need to reprocess\r
+             $reprocess ? $reprocess = false : $token = $zipper->next($token)) {\r
+\r
+            // check for a rewind\r
+            if (is_int($i)) {\r
+                // possibility: disable rewinding if the current token has a\r
+                // rewind set on it already. This would offer protection from\r
+                // infinite loop, but might hinder some advanced rewinding.\r
+                $rewind_offset = $this->injectors[$i]->getRewindOffset();\r
+                if (is_int($rewind_offset)) {\r
+                    for ($j = 0; $j < $rewind_offset; $j++) {\r
+                        if (empty($zipper->front)) break;\r
+                        $token = $zipper->prev($token);\r
+                        // indicate that other injectors should not process this token,\r
+                        // but we need to reprocess it.  See Note [Injector skips]\r
+                        unset($token->skip[$i]);\r
+                        $token->rewind = $i;\r
+                        if ($token instanceof HTMLPurifier_Token_Start) {\r
+                            array_pop($this->stack);\r
+                        } elseif ($token instanceof HTMLPurifier_Token_End) {\r
+                            $this->stack[] = $token->start;\r
+                        }\r
+                    }\r
+                }\r
+                $i = false;\r
+            }\r
+\r
+            // handle case of document end\r
+            if ($token === NULL) {\r
+                // kill processing if stack is empty\r
+                if (empty($this->stack)) {\r
+                    break;\r
+                }\r
+\r
+                // peek\r
+                $top_nesting = array_pop($this->stack);\r
+                $this->stack[] = $top_nesting;\r
+\r
+                // send error [TagClosedSuppress]\r
+                if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) {\r
+                    $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting);\r
+                }\r
+\r
+                // append, don't splice, since this is the end\r
+                $token = new HTMLPurifier_Token_End($top_nesting->name);\r
+\r
+                // punt!\r
+                $reprocess = true;\r
+                continue;\r
+            }\r
+\r
+            //echo '<br>'; printZipper($zipper, $token);//printTokens($this->stack);\r
+            //flush();\r
+\r
+            // quick-check: if it's not a tag, no need to process\r
+            if (empty($token->is_tag)) {\r
+                if ($token instanceof HTMLPurifier_Token_Text) {\r
+                    foreach ($this->injectors as $i => $injector) {\r
+                        if (isset($token->skip[$i])) {\r
+                            // See Note [Injector skips]\r
+                            continue;\r
+                        }\r
+                        if ($token->rewind !== null && $token->rewind !== $i) {\r
+                            continue;\r
+                        }\r
+                        // XXX fuckup\r
+                        $r = $token;\r
+                        $injector->handleText($r);\r
+                        $token = $this->processToken($r, $i);\r
+                        $reprocess = true;\r
+                        break;\r
+                    }\r
+                }\r
+                // another possibility is a comment\r
+                continue;\r
+            }\r
+\r
+            if (isset($definition->info[$token->name])) {\r
+                $type = $definition->info[$token->name]->child->type;\r
+            } else {\r
+                $type = false; // Type is unknown, treat accordingly\r
+            }\r
+\r
+            // quick tag checks: anything that's *not* an end tag\r
+            $ok = false;\r
+            if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) {\r
+                // claims to be a start tag but is empty\r
+                $token = new HTMLPurifier_Token_Empty(\r
+                    $token->name,\r
+                    $token->attr,\r
+                    $token->line,\r
+                    $token->col,\r
+                    $token->armor\r
+                );\r
+                $ok = true;\r
+            } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) {\r
+                // claims to be empty but really is a start tag\r
+                // NB: this assignment is required\r
+                $old_token = $token;\r
+                $token = new HTMLPurifier_Token_End($token->name);\r
+                $token = $this->insertBefore(\r
+                    new HTMLPurifier_Token_Start($old_token->name, $old_token->attr, $old_token->line, $old_token->col, $old_token->armor)\r
+                );\r
+                // punt (since we had to modify the input stream in a non-trivial way)\r
+                $reprocess = true;\r
+                continue;\r
+            } elseif ($token instanceof HTMLPurifier_Token_Empty) {\r
+                // real empty token\r
+                $ok = true;\r
+            } elseif ($token instanceof HTMLPurifier_Token_Start) {\r
+                // start tag\r
+\r
+                // ...unless they also have to close their parent\r
+                if (!empty($this->stack)) {\r
+\r
+                    // Performance note: you might think that it's rather\r
+                    // inefficient, recalculating the autoclose information\r
+                    // for every tag that a token closes (since when we\r
+                    // do an autoclose, we push a new token into the\r
+                    // stream and then /process/ that, before\r
+                    // re-processing this token.)  But this is\r
+                    // necessary, because an injector can make an\r
+                    // arbitrary transformations to the autoclosing\r
+                    // tokens we introduce, so things may have changed\r
+                    // in the meantime.  Also, doing the inefficient thing is\r
+                    // "easy" to reason about (for certain perverse definitions\r
+                    // of "easy")\r
+\r
+                    $parent = array_pop($this->stack);\r
+                    $this->stack[] = $parent;\r
+\r
+                    $parent_def = null;\r
+                    $parent_elements = null;\r
+                    $autoclose = false;\r
+                    if (isset($definition->info[$parent->name])) {\r
+                        $parent_def = $definition->info[$parent->name];\r
+                        $parent_elements = $parent_def->child->getAllowedElements($config);\r
+                        $autoclose = !isset($parent_elements[$token->name]);\r
+                    }\r
+\r
+                    if ($autoclose && $definition->info[$token->name]->wrap) {\r
+                        // Check if an element can be wrapped by another\r
+                        // element to make it valid in a context (for\r
+                        // example, <ul><ul> needs a <li> in between)\r
+                        $wrapname = $definition->info[$token->name]->wrap;\r
+                        $wrapdef = $definition->info[$wrapname];\r
+                        $elements = $wrapdef->child->getAllowedElements($config);\r
+                        if (isset($elements[$token->name]) && isset($parent_elements[$wrapname])) {\r
+                            $newtoken = new HTMLPurifier_Token_Start($wrapname);\r
+                            $token = $this->insertBefore($newtoken);\r
+                            $reprocess = true;\r
+                            continue;\r
+                        }\r
+                    }\r
+\r
+                    $carryover = false;\r
+                    if ($autoclose && $parent_def->formatting) {\r
+                        $carryover = true;\r
+                    }\r
+\r
+                    if ($autoclose) {\r
+                        // check if this autoclose is doomed to fail\r
+                        // (this rechecks $parent, which his harmless)\r
+                        $autoclose_ok = isset($global_parent_allowed_elements[$token->name]);\r
+                        if (!$autoclose_ok) {\r
+                            foreach ($this->stack as $ancestor) {\r
+                                $elements = $definition->info[$ancestor->name]->child->getAllowedElements($config);\r
+                                if (isset($elements[$token->name])) {\r
+                                    $autoclose_ok = true;\r
+                                    break;\r
+                                }\r
+                                if ($definition->info[$token->name]->wrap) {\r
+                                    $wrapname = $definition->info[$token->name]->wrap;\r
+                                    $wrapdef = $definition->info[$wrapname];\r
+                                    $wrap_elements = $wrapdef->child->getAllowedElements($config);\r
+                                    if (isset($wrap_elements[$token->name]) && isset($elements[$wrapname])) {\r
+                                        $autoclose_ok = true;\r
+                                        break;\r
+                                    }\r
+                                }\r
+                            }\r
+                        }\r
+                        if ($autoclose_ok) {\r
+                            // errors need to be updated\r
+                            $new_token = new HTMLPurifier_Token_End($parent->name);\r
+                            $new_token->start = $parent;\r
+                            // [TagClosedSuppress]\r
+                            if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) {\r
+                                if (!$carryover) {\r
+                                    $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);\r
+                                } else {\r
+                                    $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent);\r
+                                }\r
+                            }\r
+                            if ($carryover) {\r
+                                $element = clone $parent;\r
+                                // [TagClosedAuto]\r
+                                $element->armor['MakeWellFormed_TagClosedError'] = true;\r
+                                $element->carryover = true;\r
+                                $token = $this->processToken(array($new_token, $token, $element));\r
+                            } else {\r
+                                $token = $this->insertBefore($new_token);\r
+                            }\r
+                        } else {\r
+                            $token = $this->remove();\r
+                        }\r
+                        $reprocess = true;\r
+                        continue;\r
+                    }\r
+\r
+                }\r
+                $ok = true;\r
+            }\r
+\r
+            if ($ok) {\r
+                foreach ($this->injectors as $i => $injector) {\r
+                    if (isset($token->skip[$i])) {\r
+                        // See Note [Injector skips]\r
+                        continue;\r
+                    }\r
+                    if ($token->rewind !== null && $token->rewind !== $i) {\r
+                        continue;\r
+                    }\r
+                    $r = $token;\r
+                    $injector->handleElement($r);\r
+                    $token = $this->processToken($r, $i);\r
+                    $reprocess = true;\r
+                    break;\r
+                }\r
+                if (!$reprocess) {\r
+                    // ah, nothing interesting happened; do normal processing\r
+                    if ($token instanceof HTMLPurifier_Token_Start) {\r
+                        $this->stack[] = $token;\r
+                    } elseif ($token instanceof HTMLPurifier_Token_End) {\r
+                        throw new HTMLPurifier_Exception(\r
+                            'Improper handling of end tag in start code; possible error in MakeWellFormed'\r
+                        );\r
+                    }\r
+                }\r
+                continue;\r
+            }\r
+\r
+            // sanity check: we should be dealing with a closing tag\r
+            if (!$token instanceof HTMLPurifier_Token_End) {\r
+                throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier');\r
+            }\r
+\r
+            // make sure that we have something open\r
+            if (empty($this->stack)) {\r
+                if ($escape_invalid_tags) {\r
+                    if ($e) {\r
+                        $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text');\r
+                    }\r
+                    $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token));\r
+                } else {\r
+                    if ($e) {\r
+                        $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed');\r
+                    }\r
+                    $token = $this->remove();\r
+                }\r
+                $reprocess = true;\r
+                continue;\r
+            }\r
+\r
+            // first, check for the simplest case: everything closes neatly.\r
+            // Eventually, everything passes through here; if there are problems\r
+            // we modify the input stream accordingly and then punt, so that\r
+            // the tokens get processed again.\r
+            $current_parent = array_pop($this->stack);\r
+            if ($current_parent->name == $token->name) {\r
+                $token->start = $current_parent;\r
+                foreach ($this->injectors as $i => $injector) {\r
+                    if (isset($token->skip[$i])) {\r
+                        // See Note [Injector skips]\r
+                        continue;\r
+                    }\r
+                    if ($token->rewind !== null && $token->rewind !== $i) {\r
+                        continue;\r
+                    }\r
+                    $r = $token;\r
+                    $injector->handleEnd($r);\r
+                    $token = $this->processToken($r, $i);\r
+                    $this->stack[] = $current_parent;\r
+                    $reprocess = true;\r
+                    break;\r
+                }\r
+                continue;\r
+            }\r
+\r
+            // okay, so we're trying to close the wrong tag\r
+\r
+            // undo the pop previous pop\r
+            $this->stack[] = $current_parent;\r
+\r
+            // scroll back the entire nest, trying to find our tag.\r
+            // (feature could be to specify how far you'd like to go)\r
+            $size = count($this->stack);\r
+            // -2 because -1 is the last element, but we already checked that\r
+            $skipped_tags = false;\r
+            for ($j = $size - 2; $j >= 0; $j--) {\r
+                if ($this->stack[$j]->name == $token->name) {\r
+                    $skipped_tags = array_slice($this->stack, $j);\r
+                    break;\r
+                }\r
+            }\r
+\r
+            // we didn't find the tag, so remove\r
+            if ($skipped_tags === false) {\r
+                if ($escape_invalid_tags) {\r
+                    if ($e) {\r
+                        $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text');\r
+                    }\r
+                    $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token));\r
+                } else {\r
+                    if ($e) {\r
+                        $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed');\r
+                    }\r
+                    $token = $this->remove();\r
+                }\r
+                $reprocess = true;\r
+                continue;\r
+            }\r
+\r
+            // do errors, in REVERSE $j order: a,b,c with </a></b></c>\r
+            $c = count($skipped_tags);\r
+            if ($e) {\r
+                for ($j = $c - 1; $j > 0; $j--) {\r
+                    // notice we exclude $j == 0, i.e. the current ending tag, from\r
+                    // the errors... [TagClosedSuppress]\r
+                    if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) {\r
+                        $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]);\r
+                    }\r
+                }\r
+            }\r
+\r
+            // insert tags, in FORWARD $j order: c,b,a with </a></b></c>\r
+            $replace = array($token);\r
+            for ($j = 1; $j < $c; $j++) {\r
+                // ...as well as from the insertions\r
+                $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name);\r
+                $new_token->start = $skipped_tags[$j];\r
+                array_unshift($replace, $new_token);\r
+                if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) {\r
+                    // [TagClosedAuto]\r
+                    $element = clone $skipped_tags[$j];\r
+                    $element->carryover = true;\r
+                    $element->armor['MakeWellFormed_TagClosedError'] = true;\r
+                    $replace[] = $element;\r
+                }\r
+            }\r
+            $token = $this->processToken($replace);\r
+            $reprocess = true;\r
+            continue;\r
+        }\r
+\r
+        $context->destroy('CurrentToken');\r
+        $context->destroy('CurrentNesting');\r
+        $context->destroy('InputZipper');\r
+\r
+        unset($this->injectors, $this->stack, $this->tokens);\r
+        return $zipper->toArray($token);\r
+    }\r
+\r
+    /**\r
+     * Processes arbitrary token values for complicated substitution patterns.\r
+     * In general:\r
+     *\r
+     * If $token is an array, it is a list of tokens to substitute for the\r
+     * current token. These tokens then get individually processed. If there\r
+     * is a leading integer in the list, that integer determines how many\r
+     * tokens from the stream should be removed.\r
+     *\r
+     * If $token is a regular token, it is swapped with the current token.\r
+     *\r
+     * If $token is false, the current token is deleted.\r
+     *\r
+     * If $token is an integer, that number of tokens (with the first token\r
+     * being the current one) will be deleted.\r
+     *\r
+     * @param HTMLPurifier_Token|array|int|bool $token Token substitution value\r
+     * @param HTMLPurifier_Injector|int $injector Injector that performed the substitution; default is if\r
+     *        this is not an injector related operation.\r
+     * @throws HTMLPurifier_Exception\r
+     */\r
+    protected function processToken($token, $injector = -1)\r
+    {\r
+        // Zend OpCache miscompiles $token = array($token), so\r
+        // avoid this pattern.  See: https://github.com/ezyang/htmlpurifier/issues/108\r
+\r
+        // normalize forms of token\r
+        if (is_object($token)) {\r
+            $tmp = $token;\r
+            $token = array(1, $tmp);\r
+        }\r
+        if (is_int($token)) {\r
+            $tmp = $token;\r
+            $token = array($tmp);\r
+        }\r
+        if ($token === false) {\r
+            $token = array(1);\r
+        }\r
+        if (!is_array($token)) {\r
+            throw new HTMLPurifier_Exception('Invalid token type from injector');\r
+        }\r
+        if (!is_int($token[0])) {\r
+            array_unshift($token, 1);\r
+        }\r
+        if ($token[0] === 0) {\r
+            throw new HTMLPurifier_Exception('Deleting zero tokens is not valid');\r
+        }\r
+\r
+        // $token is now an array with the following form:\r
+        // array(number nodes to delete, new node 1, new node 2, ...)\r
+\r
+        $delete = array_shift($token);\r
+        list($old, $r) = $this->zipper->splice($this->token, $delete, $token);\r
+\r
+        if ($injector > -1) {\r
+            // See Note [Injector skips]\r
+            // Determine appropriate skips.  Here's what the code does:\r
+            //  *If* we deleted one or more tokens, copy the skips\r
+            //  of those tokens into the skips of the new tokens (in $token).\r
+            //  Also, mark the newly inserted tokens as having come from\r
+            //  $injector.\r
+            $oldskip = isset($old[0]) ? $old[0]->skip : array();\r
+            foreach ($token as $object) {\r
+                $object->skip = $oldskip;\r
+                $object->skip[$injector] = true;\r
+            }\r
+        }\r
+\r
+        return $r;\r
+\r
+    }\r
+\r
+    /**\r
+     * Inserts a token before the current token. Cursor now points to\r
+     * this token.  You must reprocess after this.\r
+     * @param HTMLPurifier_Token $token\r
+     */\r
+    private function insertBefore($token)\r
+    {\r
+        // NB not $this->zipper->insertBefore(), due to positioning\r
+        // differences\r
+        $splice = $this->zipper->splice($this->token, 0, array($token));\r
+\r
+        return $splice[1];\r
+    }\r
+\r
+    /**\r
+     * Removes current token. Cursor now points to new token occupying previously\r
+     * occupied space.  You must reprocess after this.\r
+     */\r
+    private function remove()\r
+    {\r
+        return $this->zipper->delete();\r
+    }\r
+}\r
+\r
+// Note [Injector skips]\r
+// ~~~~~~~~~~~~~~~~~~~~~\r
+// When I originally designed this class, the idea behind the 'skip'\r
+// property of HTMLPurifier_Token was to help avoid infinite loops\r
+// in injector processing.  For example, suppose you wrote an injector\r
+// that bolded swear words.  Naively, you might write it so that\r
+// whenever you saw ****, you replaced it with <strong>****</strong>.\r
+//\r
+// When this happens, we will reprocess all of the tokens with the\r
+// other injectors.  Now there is an opportunity for infinite loop:\r
+// if we rerun the swear-word injector on these tokens, we might\r
+// see **** and then reprocess again to get\r
+// <strong><strong>****</strong></strong> ad infinitum.\r
+//\r
+// Thus, the idea of a skip is that once we process a token with\r
+// an injector, we mark all of those tokens as having "come from"\r
+// the injector, and we never run the injector again on these\r
+// tokens.\r
+//\r
+// There were two more complications, however:\r
+//\r
+//  - With HTMLPurifier_Injector_RemoveEmpty, we noticed that if\r
+//    you had <b><i></i></b>, after you removed the <i></i>, you\r
+//    really would like this injector to go back and reprocess\r
+//    the <b> tag, discovering that it is now empty and can be\r
+//    removed.  So we reintroduced the possibility of infinite looping\r
+//    by adding a "rewind" function, which let you go back to an\r
+//    earlier point in the token stream and reprocess it with injectors.\r
+//    Needless to say, we need to UN-skip the token so it gets\r
+//    reprocessed.\r
+//\r
+//  - Suppose that you successfuly process a token, replace it with\r
+//    one with your skip mark, but now another injector wants to\r
+//    process the skipped token with another token.  Should you continue\r
+//    to skip that new token, or reprocess it?  If you reprocess,\r
+//    you can end up with an infinite loop where one injector converts\r
+//    <a> to <b>, and then another injector converts it back.  So\r
+//    we inherit the skips, but for some reason, I thought that we\r
+//    should inherit the skip from the first token of the token\r
+//    that we deleted.  Why?  Well, it seems to work OK.\r
+//\r
+// If I were to redesign this functionality, I would absolutely not\r
+// go about doing it this way: the semantics are just not very well\r
+// defined, and in any case you probably wanted to operate on trees,\r
+// not token streams.\r
+\r
+
+
+\r
+\r
+/**\r
+ * Removes all unrecognized tags from the list of tokens.\r
+ *\r
+ * This strategy iterates through all the tokens and removes unrecognized\r
+ * tokens. If a token is not recognized but a TagTransform is defined for\r
+ * that element, the element will be transformed accordingly.\r
+ */\r
+\r
+class HTMLPurifier_Strategy_RemoveForeignElements extends HTMLPurifier_Strategy\r
+{\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token[] $tokens\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return array|HTMLPurifier_Token[]\r
+     */\r
+    public function execute($tokens, $config, $context)\r
+    {\r
+        $definition = $config->getHTMLDefinition();\r
+        $generator = new HTMLPurifier_Generator($config, $context);\r
+        $result = array();\r
+\r
+        $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');\r
+        $remove_invalid_img = $config->get('Core.RemoveInvalidImg');\r
+\r
+        // currently only used to determine if comments should be kept\r
+        $trusted = $config->get('HTML.Trusted');\r
+        $comment_lookup = $config->get('HTML.AllowedComments');\r
+        $comment_regexp = $config->get('HTML.AllowedCommentsRegexp');\r
+        $check_comments = $comment_lookup !== array() || $comment_regexp !== null;\r
+\r
+        $remove_script_contents = $config->get('Core.RemoveScriptContents');\r
+        $hidden_elements = $config->get('Core.HiddenElements');\r
+\r
+        // remove script contents compatibility\r
+        if ($remove_script_contents === true) {\r
+            $hidden_elements['script'] = true;\r
+        } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) {\r
+            unset($hidden_elements['script']);\r
+        }\r
+\r
+        $attr_validator = new HTMLPurifier_AttrValidator();\r
+\r
+        // removes tokens until it reaches a closing tag with its value\r
+        $remove_until = false;\r
+\r
+        // converts comments into text tokens when this is equal to a tag name\r
+        $textify_comments = false;\r
+\r
+        $token = false;\r
+        $context->register('CurrentToken', $token);\r
+\r
+        $e = false;\r
+        if ($config->get('Core.CollectErrors')) {\r
+            $e =& $context->get('ErrorCollector');\r
+        }\r
+\r
+        foreach ($tokens as $token) {\r
+            if ($remove_until) {\r
+                if (empty($token->is_tag) || $token->name !== $remove_until) {\r
+                    continue;\r
+                }\r
+            }\r
+            if (!empty($token->is_tag)) {\r
+                // DEFINITION CALL\r
+\r
+                // before any processing, try to transform the element\r
+                if (isset($definition->info_tag_transform[$token->name])) {\r
+                    $original_name = $token->name;\r
+                    // there is a transformation for this tag\r
+                    // DEFINITION CALL\r
+                    $token = $definition->\r
+                        info_tag_transform[$token->name]->transform($token, $config, $context);\r
+                    if ($e) {\r
+                        $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name);\r
+                    }\r
+                }\r
+\r
+                if (isset($definition->info[$token->name])) {\r
+                    // mostly everything's good, but\r
+                    // we need to make sure required attributes are in order\r
+                    if (($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) &&\r
+                        $definition->info[$token->name]->required_attr &&\r
+                        ($token->name != 'img' || $remove_invalid_img) // ensure config option still works\r
+                    ) {\r
+                        $attr_validator->validateToken($token, $config, $context);\r
+                        $ok = true;\r
+                        foreach ($definition->info[$token->name]->required_attr as $name) {\r
+                            if (!isset($token->attr[$name])) {\r
+                                $ok = false;\r
+                                break;\r
+                            }\r
+                        }\r
+                        if (!$ok) {\r
+                            if ($e) {\r
+                                $e->send(\r
+                                    E_ERROR,\r
+                                    'Strategy_RemoveForeignElements: Missing required attribute',\r
+                                    $name\r
+                                );\r
+                            }\r
+                            continue;\r
+                        }\r
+                        $token->armor['ValidateAttributes'] = true;\r
+                    }\r
+\r
+                    if (isset($hidden_elements[$token->name]) && $token instanceof HTMLPurifier_Token_Start) {\r
+                        $textify_comments = $token->name;\r
+                    } elseif ($token->name === $textify_comments && $token instanceof HTMLPurifier_Token_End) {\r
+                        $textify_comments = false;\r
+                    }\r
+\r
+                } elseif ($escape_invalid_tags) {\r
+                    // invalid tag, generate HTML representation and insert in\r
+                    if ($e) {\r
+                        $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text');\r
+                    }\r
+                    $token = new HTMLPurifier_Token_Text(\r
+                        $generator->generateFromToken($token)\r
+                    );\r
+                } else {\r
+                    // check if we need to destroy all of the tag's children\r
+                    // CAN BE GENERICIZED\r
+                    if (isset($hidden_elements[$token->name])) {\r
+                        if ($token instanceof HTMLPurifier_Token_Start) {\r
+                            $remove_until = $token->name;\r
+                        } elseif ($token instanceof HTMLPurifier_Token_Empty) {\r
+                            // do nothing: we're still looking\r
+                        } else {\r
+                            $remove_until = false;\r
+                        }\r
+                        if ($e) {\r
+                            $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed');\r
+                        }\r
+                    } else {\r
+                        if ($e) {\r
+                            $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign element removed');\r
+                        }\r
+                    }\r
+                    continue;\r
+                }\r
+            } elseif ($token instanceof HTMLPurifier_Token_Comment) {\r
+                // textify comments in script tags when they are allowed\r
+                if ($textify_comments !== false) {\r
+                    $data = $token->data;\r
+                    $token = new HTMLPurifier_Token_Text($data);\r
+                } elseif ($trusted || $check_comments) {\r
+                    // always cleanup comments\r
+                    $trailing_hyphen = false;\r
+                    if ($e) {\r
+                        // perform check whether or not there's a trailing hyphen\r
+                        if (substr($token->data, -1) == '-') {\r
+                            $trailing_hyphen = true;\r
+                        }\r
+                    }\r
+                    $token->data = rtrim($token->data, '-');\r
+                    $found_double_hyphen = false;\r
+                    while (strpos($token->data, '--') !== false) {\r
+                        $found_double_hyphen = true;\r
+                        $token->data = str_replace('--', '-', $token->data);\r
+                    }\r
+                    if ($trusted || !empty($comment_lookup[trim($token->data)]) ||\r
+                        ($comment_regexp !== null && preg_match($comment_regexp, trim($token->data)))) {\r
+                        // OK good\r
+                        if ($e) {\r
+                            if ($trailing_hyphen) {\r
+                                $e->send(\r
+                                    E_NOTICE,\r
+                                    'Strategy_RemoveForeignElements: Trailing hyphen in comment removed'\r
+                                );\r
+                            }\r
+                            if ($found_double_hyphen) {\r
+                                $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Hyphens in comment collapsed');\r
+                            }\r
+                        }\r
+                    } else {\r
+                        if ($e) {\r
+                            $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed');\r
+                        }\r
+                        continue;\r
+                    }\r
+                } else {\r
+                    // strip comments\r
+                    if ($e) {\r
+                        $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed');\r
+                    }\r
+                    continue;\r
+                }\r
+            } elseif ($token instanceof HTMLPurifier_Token_Text) {\r
+            } else {\r
+                continue;\r
+            }\r
+            $result[] = $token;\r
+        }\r
+        if ($remove_until && $e) {\r
+            // we removed tokens until the end, throw error\r
+            $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Token removed to end', $remove_until);\r
+        }\r
+        $context->destroy('CurrentToken');\r
+        return $result;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validate all attributes in the tokens.\r
+ */\r
+\r
+class HTMLPurifier_Strategy_ValidateAttributes extends HTMLPurifier_Strategy\r
+{\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token[] $tokens\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return HTMLPurifier_Token[]\r
+     */\r
+    public function execute($tokens, $config, $context)\r
+    {\r
+        // setup validator\r
+        $validator = new HTMLPurifier_AttrValidator();\r
+\r
+        $token = false;\r
+        $context->register('CurrentToken', $token);\r
+\r
+        foreach ($tokens as $key => $token) {\r
+\r
+            // only process tokens that have attributes,\r
+            //   namely start and empty tags\r
+            if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) {\r
+                continue;\r
+            }\r
+\r
+            // skip tokens that are armored\r
+            if (!empty($token->armor['ValidateAttributes'])) {\r
+                continue;\r
+            }\r
+\r
+            // note that we have no facilities here for removing tokens\r
+            $validator->validateToken($token, $config, $context);\r
+        }\r
+        $context->destroy('CurrentToken');\r
+        return $tokens;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Transforms FONT tags to the proper form (SPAN with CSS styling)\r
+ *\r
+ * This transformation takes the three proprietary attributes of FONT and\r
+ * transforms them into their corresponding CSS attributes.  These are color,\r
+ * face, and size.\r
+ *\r
+ * @note Size is an interesting case because it doesn't map cleanly to CSS.\r
+ *       Thanks to\r
+ *       http://style.cleverchimp.com/font_size_intervals/altintervals.html\r
+ *       for reasonable mappings.\r
+ * @warning This doesn't work completely correctly; specifically, this\r
+ *          TagTransform operates before well-formedness is enforced, so\r
+ *          the "active formatting elements" algorithm doesn't get applied.\r
+ */\r
+class HTMLPurifier_TagTransform_Font extends HTMLPurifier_TagTransform\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $transform_to = 'span';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $_size_lookup = array(\r
+        '0' => 'xx-small',\r
+        '1' => 'xx-small',\r
+        '2' => 'small',\r
+        '3' => 'medium',\r
+        '4' => 'large',\r
+        '5' => 'x-large',\r
+        '6' => 'xx-large',\r
+        '7' => '300%',\r
+        '-1' => 'smaller',\r
+        '-2' => '60%',\r
+        '+1' => 'larger',\r
+        '+2' => '150%',\r
+        '+3' => '200%',\r
+        '+4' => '300%'\r
+    );\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token_Tag $tag\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return HTMLPurifier_Token_End|string\r
+     */\r
+    public function transform($tag, $config, $context)\r
+    {\r
+        if ($tag instanceof HTMLPurifier_Token_End) {\r
+            $new_tag = clone $tag;\r
+            $new_tag->name = $this->transform_to;\r
+            return $new_tag;\r
+        }\r
+\r
+        $attr = $tag->attr;\r
+        $prepend_style = '';\r
+\r
+        // handle color transform\r
+        if (isset($attr['color'])) {\r
+            $prepend_style .= 'color:' . $attr['color'] . ';';\r
+            unset($attr['color']);\r
+        }\r
+\r
+        // handle face transform\r
+        if (isset($attr['face'])) {\r
+            $prepend_style .= 'font-family:' . $attr['face'] . ';';\r
+            unset($attr['face']);\r
+        }\r
+\r
+        // handle size transform\r
+        if (isset($attr['size'])) {\r
+            // normalize large numbers\r
+            if ($attr['size'] !== '') {\r
+                if ($attr['size']{0} == '+' || $attr['size']{0} == '-') {\r
+                    $size = (int)$attr['size'];\r
+                    if ($size < -2) {\r
+                        $attr['size'] = '-2';\r
+                    }\r
+                    if ($size > 4) {\r
+                        $attr['size'] = '+4';\r
+                    }\r
+                } else {\r
+                    $size = (int)$attr['size'];\r
+                    if ($size > 7) {\r
+                        $attr['size'] = '7';\r
+                    }\r
+                }\r
+            }\r
+            if (isset($this->_size_lookup[$attr['size']])) {\r
+                $prepend_style .= 'font-size:' .\r
+                    $this->_size_lookup[$attr['size']] . ';';\r
+            }\r
+            unset($attr['size']);\r
+        }\r
+\r
+        if ($prepend_style) {\r
+            $attr['style'] = isset($attr['style']) ?\r
+                $prepend_style . $attr['style'] :\r
+                $prepend_style;\r
+        }\r
+\r
+        $new_tag = clone $tag;\r
+        $new_tag->name = $this->transform_to;\r
+        $new_tag->attr = $attr;\r
+\r
+        return $new_tag;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Simple transformation, just change tag name to something else,\r
+ * and possibly add some styling. This will cover most of the deprecated\r
+ * tag cases.\r
+ */\r
+class HTMLPurifier_TagTransform_Simple extends HTMLPurifier_TagTransform\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    protected $style;\r
+\r
+    /**\r
+     * @param string $transform_to Tag name to transform to.\r
+     * @param string $style CSS style to add to the tag\r
+     */\r
+    public function __construct($transform_to, $style = null)\r
+    {\r
+        $this->transform_to = $transform_to;\r
+        $this->style = $style;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_Token_Tag $tag\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     */\r
+    public function transform($tag, $config, $context)\r
+    {\r
+        $new_tag = clone $tag;\r
+        $new_tag->name = $this->transform_to;\r
+        if (!is_null($this->style) &&\r
+            ($new_tag instanceof HTMLPurifier_Token_Start || $new_tag instanceof HTMLPurifier_Token_Empty)\r
+        ) {\r
+            $this->prependCSS($new_tag->attr, $this->style);\r
+        }\r
+        return $new_tag;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Concrete comment token class. Generally will be ignored.\r
+ */\r
+class HTMLPurifier_Token_Comment extends HTMLPurifier_Token\r
+{\r
+    /**\r
+     * Character data within comment.\r
+     * @type string\r
+     */\r
+    public $data;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $is_whitespace = true;\r
+\r
+    /**\r
+     * Transparent constructor.\r
+     *\r
+     * @param string $data String comment data.\r
+     * @param int $line\r
+     * @param int $col\r
+     */\r
+    public function __construct($data, $line = null, $col = null)\r
+    {\r
+        $this->data = $data;\r
+        $this->line = $line;\r
+        $this->col = $col;\r
+    }\r
+\r
+    public function toNode() {\r
+        return new HTMLPurifier_Node_Comment($this->data, $this->line, $this->col);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Abstract class of a tag token (start, end or empty), and its behavior.\r
+ */\r
+abstract class HTMLPurifier_Token_Tag extends HTMLPurifier_Token\r
+{\r
+    /**\r
+     * Static bool marker that indicates the class is a tag.\r
+     *\r
+     * This allows us to check objects with <tt>!empty($obj->is_tag)</tt>\r
+     * without having to use a function call <tt>is_a()</tt>.\r
+     * @type bool\r
+     */\r
+    public $is_tag = true;\r
+\r
+    /**\r
+     * The lower-case name of the tag, like 'a', 'b' or 'blockquote'.\r
+     *\r
+     * @note Strictly speaking, XML tags are case sensitive, so we shouldn't\r
+     * be lower-casing them, but these tokens cater to HTML tags, which are\r
+     * insensitive.\r
+     * @type string\r
+     */\r
+    public $name;\r
+\r
+    /**\r
+     * Associative array of the tag's attributes.\r
+     * @type array\r
+     */\r
+    public $attr = array();\r
+\r
+    /**\r
+     * Non-overloaded constructor, which lower-cases passed tag name.\r
+     *\r
+     * @param string $name String name.\r
+     * @param array $attr Associative array of attributes.\r
+     * @param int $line\r
+     * @param int $col\r
+     * @param array $armor\r
+     */\r
+    public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array())\r
+    {\r
+        $this->name = ctype_lower($name) ? $name : strtolower($name);\r
+        foreach ($attr as $key => $value) {\r
+            // normalization only necessary when key is not lowercase\r
+            if (!ctype_lower($key)) {\r
+                $new_key = strtolower($key);\r
+                if (!isset($attr[$new_key])) {\r
+                    $attr[$new_key] = $attr[$key];\r
+                }\r
+                if ($new_key !== $key) {\r
+                    unset($attr[$key]);\r
+                }\r
+            }\r
+        }\r
+        $this->attr = $attr;\r
+        $this->line = $line;\r
+        $this->col = $col;\r
+        $this->armor = $armor;\r
+    }\r
+\r
+    public function toNode() {\r
+        return new HTMLPurifier_Node_Element($this->name, $this->attr, $this->line, $this->col, $this->armor);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Concrete empty token class.\r
+ */\r
+class HTMLPurifier_Token_Empty extends HTMLPurifier_Token_Tag\r
+{\r
+    public function toNode() {\r
+        $n = parent::toNode();\r
+        $n->empty = true;\r
+        return $n;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Concrete end token class.\r
+ *\r
+ * @warning This class accepts attributes even though end tags cannot. This\r
+ * is for optimization reasons, as under normal circumstances, the Lexers\r
+ * do not pass attributes.\r
+ */\r
+class HTMLPurifier_Token_End extends HTMLPurifier_Token_Tag\r
+{\r
+    /**\r
+     * Token that started this node.\r
+     * Added by MakeWellFormed. Please do not edit this!\r
+     * @type HTMLPurifier_Token\r
+     */\r
+    public $start;\r
+\r
+    public function toNode() {\r
+        throw new Exception("HTMLPurifier_Token_End->toNode not supported!");\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Concrete start token class.\r
+ */\r
+class HTMLPurifier_Token_Start extends HTMLPurifier_Token_Tag\r
+{\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Concrete text token class.\r
+ *\r
+ * Text tokens comprise of regular parsed character data (PCDATA) and raw\r
+ * character data (from the CDATA sections). Internally, their\r
+ * data is parsed with all entities expanded. Surprisingly, the text token\r
+ * does have a "tag name" called #PCDATA, which is how the DTD represents it\r
+ * in permissible child nodes.\r
+ */\r
+class HTMLPurifier_Token_Text extends HTMLPurifier_Token\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = '#PCDATA';\r
+    /**< PCDATA tag name compatible with DTD. */\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $data;\r
+    /**< Parsed character data of text. */\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $is_whitespace;\r
+\r
+    /**< Bool indicating if node is whitespace. */\r
+\r
+    /**\r
+     * Constructor, accepts data and determines if it is whitespace.\r
+     * @param string $data String parsed character data.\r
+     * @param int $line\r
+     * @param int $col\r
+     */\r
+    public function __construct($data, $line = null, $col = null)\r
+    {\r
+        $this->data = $data;\r
+        $this->is_whitespace = ctype_space($data);\r
+        $this->line = $line;\r
+        $this->col = $col;\r
+    }\r
+\r
+    public function toNode() {\r
+        return new HTMLPurifier_Node_Text($this->data, $this->is_whitespace, $this->line, $this->col);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_URIFilter_DisableExternal extends HTMLPurifier_URIFilter\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'DisableExternal';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $ourHostParts = false;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return void\r
+     */\r
+    public function prepare($config)\r
+    {\r
+        $our_host = $config->getDefinition('URI')->host;\r
+        if ($our_host !== null) {\r
+            $this->ourHostParts = array_reverse(explode('.', $our_host));\r
+        }\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri Reference\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function filter(&$uri, $config, $context)\r
+    {\r
+        if (is_null($uri->host)) {\r
+            return true;\r
+        }\r
+        if ($this->ourHostParts === false) {\r
+            return false;\r
+        }\r
+        $host_parts = array_reverse(explode('.', $uri->host));\r
+        foreach ($this->ourHostParts as $i => $x) {\r
+            if (!isset($host_parts[$i])) {\r
+                return false;\r
+            }\r
+            if ($host_parts[$i] != $this->ourHostParts[$i]) {\r
+                return false;\r
+            }\r
+        }\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_URIFilter_DisableExternalResources extends HTMLPurifier_URIFilter_DisableExternal\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'DisableExternalResources';\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function filter(&$uri, $config, $context)\r
+    {\r
+        if (!$context->get('EmbeddedURI', true)) {\r
+            return true;\r
+        }\r
+        return parent::filter($uri, $config, $context);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_URIFilter_DisableResources extends HTMLPurifier_URIFilter\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'DisableResources';\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function filter(&$uri, $config, $context)\r
+    {\r
+        return !$context->get('EmbeddedURI', true);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+// It's not clear to me whether or not Punycode means that hostnames\r
+// do not have canonical forms anymore. As far as I can tell, it's\r
+// not a problem (punycoding should be identity when no Unicode\r
+// points are involved), but I'm not 100% sure\r
+class HTMLPurifier_URIFilter_HostBlacklist extends HTMLPurifier_URIFilter\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'HostBlacklist';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $blacklist = array();\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function prepare($config)\r
+    {\r
+        $this->blacklist = $config->get('URI.HostBlacklist');\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function filter(&$uri, $config, $context)\r
+    {\r
+        foreach ($this->blacklist as $blacklisted_host_fragment) {\r
+            if (strpos($uri->host, $blacklisted_host_fragment) !== false) {\r
+                return false;\r
+            }\r
+        }\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+// does not support network paths\r
+\r
+class HTMLPurifier_URIFilter_MakeAbsolute extends HTMLPurifier_URIFilter\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'MakeAbsolute';\r
+\r
+    /**\r
+     * @type\r
+     */\r
+    protected $base;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $basePathStack = array();\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function prepare($config)\r
+    {\r
+        $def = $config->getDefinition('URI');\r
+        $this->base = $def->base;\r
+        if (is_null($this->base)) {\r
+            trigger_error(\r
+                'URI.MakeAbsolute is being ignored due to lack of ' .\r
+                'value for URI.Base configuration',\r
+                E_USER_WARNING\r
+            );\r
+            return false;\r
+        }\r
+        $this->base->fragment = null; // fragment is invalid for base URI\r
+        $stack = explode('/', $this->base->path);\r
+        array_pop($stack); // discard last segment\r
+        $stack = $this->_collapseStack($stack); // do pre-parsing\r
+        $this->basePathStack = $stack;\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function filter(&$uri, $config, $context)\r
+    {\r
+        if (is_null($this->base)) {\r
+            return true;\r
+        } // abort early\r
+        if ($uri->path === '' && is_null($uri->scheme) &&\r
+            is_null($uri->host) && is_null($uri->query) && is_null($uri->fragment)) {\r
+            // reference to current document\r
+            $uri = clone $this->base;\r
+            return true;\r
+        }\r
+        if (!is_null($uri->scheme)) {\r
+            // absolute URI already: don't change\r
+            if (!is_null($uri->host)) {\r
+                return true;\r
+            }\r
+            $scheme_obj = $uri->getSchemeObj($config, $context);\r
+            if (!$scheme_obj) {\r
+                // scheme not recognized\r
+                return false;\r
+            }\r
+            if (!$scheme_obj->hierarchical) {\r
+                // non-hierarchal URI with explicit scheme, don't change\r
+                return true;\r
+            }\r
+            // special case: had a scheme but always is hierarchical and had no authority\r
+        }\r
+        if (!is_null($uri->host)) {\r
+            // network path, don't bother\r
+            return true;\r
+        }\r
+        if ($uri->path === '') {\r
+            $uri->path = $this->base->path;\r
+        } elseif ($uri->path[0] !== '/') {\r
+            // relative path, needs more complicated processing\r
+            $stack = explode('/', $uri->path);\r
+            $new_stack = array_merge($this->basePathStack, $stack);\r
+            if ($new_stack[0] !== '' && !is_null($this->base->host)) {\r
+                array_unshift($new_stack, '');\r
+            }\r
+            $new_stack = $this->_collapseStack($new_stack);\r
+            $uri->path = implode('/', $new_stack);\r
+        } else {\r
+            // absolute path, but still we should collapse\r
+            $uri->path = implode('/', $this->_collapseStack(explode('/', $uri->path)));\r
+        }\r
+        // re-combine\r
+        $uri->scheme = $this->base->scheme;\r
+        if (is_null($uri->userinfo)) {\r
+            $uri->userinfo = $this->base->userinfo;\r
+        }\r
+        if (is_null($uri->host)) {\r
+            $uri->host = $this->base->host;\r
+        }\r
+        if (is_null($uri->port)) {\r
+            $uri->port = $this->base->port;\r
+        }\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Resolve dots and double-dots in a path stack\r
+     * @param array $stack\r
+     * @return array\r
+     */\r
+    private function _collapseStack($stack)\r
+    {\r
+        $result = array();\r
+        $is_folder = false;\r
+        for ($i = 0; isset($stack[$i]); $i++) {\r
+            $is_folder = false;\r
+            // absorb an internally duplicated slash\r
+            if ($stack[$i] == '' && $i && isset($stack[$i + 1])) {\r
+                continue;\r
+            }\r
+            if ($stack[$i] == '..') {\r
+                if (!empty($result)) {\r
+                    $segment = array_pop($result);\r
+                    if ($segment === '' && empty($result)) {\r
+                        // error case: attempted to back out too far:\r
+                        // restore the leading slash\r
+                        $result[] = '';\r
+                    } elseif ($segment === '..') {\r
+                        $result[] = '..'; // cannot remove .. with ..\r
+                    }\r
+                } else {\r
+                    // relative path, preserve the double-dots\r
+                    $result[] = '..';\r
+                }\r
+                $is_folder = true;\r
+                continue;\r
+            }\r
+            if ($stack[$i] == '.') {\r
+                // silently absorb\r
+                $is_folder = true;\r
+                continue;\r
+            }\r
+            $result[] = $stack[$i];\r
+        }\r
+        if ($is_folder) {\r
+            $result[] = '';\r
+        }\r
+        return $result;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+class HTMLPurifier_URIFilter_Munge extends HTMLPurifier_URIFilter\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'Munge';\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $post = true;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    private $target;\r
+\r
+    /**\r
+     * @type HTMLPurifier_URIParser\r
+     */\r
+    private $parser;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    private $doEmbed;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    private $secretKey;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $replace = array();\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function prepare($config)\r
+    {\r
+        $this->target = $config->get('URI.' . $this->name);\r
+        $this->parser = new HTMLPurifier_URIParser();\r
+        $this->doEmbed = $config->get('URI.MungeResources');\r
+        $this->secretKey = $config->get('URI.MungeSecretKey');\r
+        if ($this->secretKey && !function_exists('hash_hmac')) {\r
+            throw new Exception("Cannot use %URI.MungeSecretKey without hash_hmac support.");\r
+        }\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function filter(&$uri, $config, $context)\r
+    {\r
+        if ($context->get('EmbeddedURI', true) && !$this->doEmbed) {\r
+            return true;\r
+        }\r
+\r
+        $scheme_obj = $uri->getSchemeObj($config, $context);\r
+        if (!$scheme_obj) {\r
+            return true;\r
+        } // ignore unknown schemes, maybe another postfilter did it\r
+        if (!$scheme_obj->browsable) {\r
+            return true;\r
+        } // ignore non-browseable schemes, since we can't munge those in a reasonable way\r
+        if ($uri->isBenign($config, $context)) {\r
+            return true;\r
+        } // don't redirect if a benign URL\r
+\r
+        $this->makeReplace($uri, $config, $context);\r
+        $this->replace = array_map('rawurlencode', $this->replace);\r
+\r
+        $new_uri = strtr($this->target, $this->replace);\r
+        $new_uri = $this->parser->parse($new_uri);\r
+        // don't redirect if the target host is the same as the\r
+        // starting host\r
+        if ($uri->host === $new_uri->host) {\r
+            return true;\r
+        }\r
+        $uri = $new_uri; // overwrite\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     */\r
+    protected function makeReplace($uri, $config, $context)\r
+    {\r
+        $string = $uri->toString();\r
+        // always available\r
+        $this->replace['%s'] = $string;\r
+        $this->replace['%r'] = $context->get('EmbeddedURI', true);\r
+        $token = $context->get('CurrentToken', true);\r
+        $this->replace['%n'] = $token ? $token->name : null;\r
+        $this->replace['%m'] = $context->get('CurrentAttr', true);\r
+        $this->replace['%p'] = $context->get('CurrentCSSProperty', true);\r
+        // not always available\r
+        if ($this->secretKey) {\r
+            $this->replace['%t'] = hash_hmac("sha256", $string, $this->secretKey);\r
+        }\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Implements safety checks for safe iframes.\r
+ *\r
+ * @warning This filter is *critical* for ensuring that %HTML.SafeIframe\r
+ * works safely.\r
+ */\r
+class HTMLPurifier_URIFilter_SafeIframe extends HTMLPurifier_URIFilter\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'SafeIframe';\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $always_load = true;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    protected $regexp = null;\r
+\r
+    // XXX: The not so good bit about how this is all set up now is we\r
+    // can't check HTML.SafeIframe in the 'prepare' step: we have to\r
+    // defer till the actual filtering.\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return bool\r
+     */\r
+    public function prepare($config)\r
+    {\r
+        $this->regexp = $config->get('URI.SafeIframeRegexp');\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function filter(&$uri, $config, $context)\r
+    {\r
+        // check if filter not applicable\r
+        if (!$config->get('HTML.SafeIframe')) {\r
+            return true;\r
+        }\r
+        // check if the filter should actually trigger\r
+        if (!$context->get('EmbeddedURI', true)) {\r
+            return true;\r
+        }\r
+        $token = $context->get('CurrentToken', true);\r
+        if (!($token && $token->name == 'iframe')) {\r
+            return true;\r
+        }\r
+        // check if we actually have some whitelists enabled\r
+        if ($this->regexp === null) {\r
+            return false;\r
+        }\r
+        // actually check the whitelists\r
+        return preg_match($this->regexp, $uri->toString());\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Implements data: URI for base64 encoded images supported by GD.\r
+ */\r
+class HTMLPurifier_URIScheme_data extends HTMLPurifier_URIScheme\r
+{\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $browsable = true;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    public $allowed_types = array(\r
+        // you better write validation code for other types if you\r
+        // decide to allow them\r
+        'image/jpeg' => true,\r
+        'image/gif' => true,\r
+        'image/png' => true,\r
+    );\r
+    // this is actually irrelevant since we only write out the path\r
+    // component\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $may_omit_host = true;\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function doValidate(&$uri, $config, $context)\r
+    {\r
+        $result = explode(',', $uri->path, 2);\r
+        $is_base64 = false;\r
+        $charset = null;\r
+        $content_type = null;\r
+        if (count($result) == 2) {\r
+            list($metadata, $data) = $result;\r
+            // do some legwork on the metadata\r
+            $metas = explode(';', $metadata);\r
+            while (!empty($metas)) {\r
+                $cur = array_shift($metas);\r
+                if ($cur == 'base64') {\r
+                    $is_base64 = true;\r
+                    break;\r
+                }\r
+                if (substr($cur, 0, 8) == 'charset=') {\r
+                    // doesn't match if there are arbitrary spaces, but\r
+                    // whatever dude\r
+                    if ($charset !== null) {\r
+                        continue;\r
+                    } // garbage\r
+                    $charset = substr($cur, 8); // not used\r
+                } else {\r
+                    if ($content_type !== null) {\r
+                        continue;\r
+                    } // garbage\r
+                    $content_type = $cur;\r
+                }\r
+            }\r
+        } else {\r
+            $data = $result[0];\r
+        }\r
+        if ($content_type !== null && empty($this->allowed_types[$content_type])) {\r
+            return false;\r
+        }\r
+        if ($charset !== null) {\r
+            // error; we don't allow plaintext stuff\r
+            $charset = null;\r
+        }\r
+        $data = rawurldecode($data);\r
+        if ($is_base64) {\r
+            $raw_data = base64_decode($data);\r
+        } else {\r
+            $raw_data = $data;\r
+        }\r
+        if ( strlen($raw_data) < 12 ) {\r
+            // error; exif_imagetype throws exception with small files,\r
+            // and this likely indicates a corrupt URI/failed parse anyway\r
+            return false;\r
+        }\r
+        // XXX probably want to refactor this into a general mechanism\r
+        // for filtering arbitrary content types\r
+        if (function_exists('sys_get_temp_dir')) {\r
+            $file = tempnam(sys_get_temp_dir(), "");\r
+        } else {\r
+            $file = tempnam("/tmp", "");\r
+        }\r
+        file_put_contents($file, $raw_data);\r
+        if (function_exists('exif_imagetype')) {\r
+            $image_code = exif_imagetype($file);\r
+            unlink($file);\r
+        } elseif (function_exists('getimagesize')) {\r
+            set_error_handler(array($this, 'muteErrorHandler'));\r
+            $info = getimagesize($file);\r
+            restore_error_handler();\r
+            unlink($file);\r
+            if ($info == false) {\r
+                return false;\r
+            }\r
+            $image_code = $info[2];\r
+        } else {\r
+            trigger_error("could not find exif_imagetype or getimagesize functions", E_USER_ERROR);\r
+        }\r
+        $real_content_type = image_type_to_mime_type($image_code);\r
+        if ($real_content_type != $content_type) {\r
+            // we're nice guys; if the content type is something else we\r
+            // support, change it over\r
+            if (empty($this->allowed_types[$real_content_type])) {\r
+                return false;\r
+            }\r
+            $content_type = $real_content_type;\r
+        }\r
+        // ok, it's kosher, rewrite what we need\r
+        $uri->userinfo = null;\r
+        $uri->host = null;\r
+        $uri->port = null;\r
+        $uri->fragment = null;\r
+        $uri->query = null;\r
+        $uri->path = "$content_type;base64," . base64_encode($raw_data);\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * @param int $errno\r
+     * @param string $errstr\r
+     */\r
+    public function muteErrorHandler($errno, $errstr)\r
+    {\r
+    }\r
+}\r
+
+\r
+\r
+/**\r
+ * Validates file as defined by RFC 1630 and RFC 1738.\r
+ */\r
+class HTMLPurifier_URIScheme_file extends HTMLPurifier_URIScheme\r
+{\r
+    /**\r
+     * Generally file:// URLs are not accessible from most\r
+     * machines, so placing them as an img src is incorrect.\r
+     * @type bool\r
+     */\r
+    public $browsable = false;\r
+\r
+    /**\r
+     * Basically the *only* URI scheme for which this is true, since\r
+     * accessing files on the local machine is very common.  In fact,\r
+     * browsers on some operating systems don't understand the\r
+     * authority, though I hear it is used on Windows to refer to\r
+     * network shares.\r
+     * @type bool\r
+     */\r
+    public $may_omit_host = true;\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function doValidate(&$uri, $config, $context)\r
+    {\r
+        // Authentication method is not supported\r
+        $uri->userinfo = null;\r
+        // file:// makes no provisions for accessing the resource\r
+        $uri->port = null;\r
+        // While it seems to work on Firefox, the querystring has\r
+        // no possible effect and is thus stripped.\r
+        $uri->query = null;\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates ftp (File Transfer Protocol) URIs as defined by generic RFC 1738.\r
+ */\r
+class HTMLPurifier_URIScheme_ftp extends HTMLPurifier_URIScheme\r
+{\r
+    /**\r
+     * @type int\r
+     */\r
+    public $default_port = 21;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $browsable = true; // usually\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $hierarchical = true;\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function doValidate(&$uri, $config, $context)\r
+    {\r
+        $uri->query = null;\r
+\r
+        // typecode check\r
+        $semicolon_pos = strrpos($uri->path, ';'); // reverse\r
+        if ($semicolon_pos !== false) {\r
+            $type = substr($uri->path, $semicolon_pos + 1); // no semicolon\r
+            $uri->path = substr($uri->path, 0, $semicolon_pos);\r
+            $type_ret = '';\r
+            if (strpos($type, '=') !== false) {\r
+                // figure out whether or not the declaration is correct\r
+                list($key, $typecode) = explode('=', $type, 2);\r
+                if ($key !== 'type') {\r
+                    // invalid key, tack it back on encoded\r
+                    $uri->path .= '%3B' . $type;\r
+                } elseif ($typecode === 'a' || $typecode === 'i' || $typecode === 'd') {\r
+                    $type_ret = ";type=$typecode";\r
+                }\r
+            } else {\r
+                $uri->path .= '%3B' . $type;\r
+            }\r
+            $uri->path = str_replace(';', '%3B', $uri->path);\r
+            $uri->path .= $type_ret;\r
+        }\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates http (HyperText Transfer Protocol) as defined by RFC 2616\r
+ */\r
+class HTMLPurifier_URIScheme_http extends HTMLPurifier_URIScheme\r
+{\r
+    /**\r
+     * @type int\r
+     */\r
+    public $default_port = 80;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $browsable = true;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $hierarchical = true;\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function doValidate(&$uri, $config, $context)\r
+    {\r
+        $uri->userinfo = null;\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates https (Secure HTTP) according to http scheme.\r
+ */\r
+class HTMLPurifier_URIScheme_https extends HTMLPurifier_URIScheme_http\r
+{\r
+    /**\r
+     * @type int\r
+     */\r
+    public $default_port = 443;\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $secure = true;\r
+}\r
+\r
+
+
+\r
+\r
+// VERY RELAXED! Shouldn't cause problems, not even Firefox checks if the\r
+// email is valid, but be careful!\r
+\r
+/**\r
+ * Validates mailto (for E-mail) according to RFC 2368\r
+ * @todo Validate the email address\r
+ * @todo Filter allowed query parameters\r
+ */\r
+\r
+class HTMLPurifier_URIScheme_mailto extends HTMLPurifier_URIScheme\r
+{\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $browsable = false;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $may_omit_host = true;\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function doValidate(&$uri, $config, $context)\r
+    {\r
+        $uri->userinfo = null;\r
+        $uri->host     = null;\r
+        $uri->port     = null;\r
+        // we need to validate path against RFC 2368's addr-spec\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates news (Usenet) as defined by generic RFC 1738\r
+ */\r
+class HTMLPurifier_URIScheme_news extends HTMLPurifier_URIScheme\r
+{\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $browsable = false;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $may_omit_host = true;\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function doValidate(&$uri, $config, $context)\r
+    {\r
+        $uri->userinfo = null;\r
+        $uri->host = null;\r
+        $uri->port = null;\r
+        $uri->query = null;\r
+        // typecode check needed on path\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates nntp (Network News Transfer Protocol) as defined by generic RFC 1738\r
+ */\r
+class HTMLPurifier_URIScheme_nntp extends HTMLPurifier_URIScheme\r
+{\r
+    /**\r
+     * @type int\r
+     */\r
+    public $default_port = 119;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $browsable = false;\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function doValidate(&$uri, $config, $context)\r
+    {\r
+        $uri->userinfo = null;\r
+        $uri->query = null;\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Validates tel (for phone numbers).\r
+ *\r
+ * The relevant specifications for this protocol are RFC 3966 and RFC 5341,\r
+ * but this class takes a much simpler approach: we normalize phone\r
+ * numbers so that they only include (possibly) a leading plus,\r
+ * and then any number of digits and x'es.\r
+ */\r
+\r
+class HTMLPurifier_URIScheme_tel extends HTMLPurifier_URIScheme\r
+{\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $browsable = false;\r
+\r
+    /**\r
+     * @type bool\r
+     */\r
+    public $may_omit_host = true;\r
+\r
+    /**\r
+     * @param HTMLPurifier_URI $uri\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return bool\r
+     */\r
+    public function doValidate(&$uri, $config, $context)\r
+    {\r
+        $uri->userinfo = null;\r
+        $uri->host     = null;\r
+        $uri->port     = null;\r
+\r
+        // Delete all non-numeric characters, non-x characters\r
+        // from phone number, EXCEPT for a leading plus sign.\r
+        $uri->path = preg_replace('/(?!^\+)[^\dx]/', '',\r
+                     // Normalize e(x)tension to lower-case\r
+                     str_replace('X', 'x', $uri->path));\r
+\r
+        return true;\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * Performs safe variable parsing based on types which can be used by\r
+ * users. This may not be able to represent all possible data inputs,\r
+ * however.\r
+ */\r
+class HTMLPurifier_VarParser_Flexible extends HTMLPurifier_VarParser\r
+{\r
+    /**\r
+     * @param mixed $var\r
+     * @param int $type\r
+     * @param bool $allow_null\r
+     * @return array|bool|float|int|mixed|null|string\r
+     * @throws HTMLPurifier_VarParserException\r
+     */\r
+    protected function parseImplementation($var, $type, $allow_null)\r
+    {\r
+        if ($allow_null && $var === null) {\r
+            return null;\r
+        }\r
+        switch ($type) {\r
+            // Note: if code "breaks" from the switch, it triggers a generic\r
+            // exception to be thrown. Specific errors can be specifically\r
+            // done here.\r
+            case self::C_MIXED:\r
+            case self::ISTRING:\r
+            case self::C_STRING:\r
+            case self::TEXT:\r
+            case self::ITEXT:\r
+                return $var;\r
+            case self::C_INT:\r
+                if (is_string($var) && ctype_digit($var)) {\r
+                    $var = (int)$var;\r
+                }\r
+                return $var;\r
+            case self::C_FLOAT:\r
+                if ((is_string($var) && is_numeric($var)) || is_int($var)) {\r
+                    $var = (float)$var;\r
+                }\r
+                return $var;\r
+            case self::C_BOOL:\r
+                if (is_int($var) && ($var === 0 || $var === 1)) {\r
+                    $var = (bool)$var;\r
+                } elseif (is_string($var)) {\r
+                    if ($var == 'on' || $var == 'true' || $var == '1') {\r
+                        $var = true;\r
+                    } elseif ($var == 'off' || $var == 'false' || $var == '0') {\r
+                        $var = false;\r
+                    } else {\r
+                        throw new HTMLPurifier_VarParserException("Unrecognized value '$var' for $type");\r
+                    }\r
+                }\r
+                return $var;\r
+            case self::ALIST:\r
+            case self::HASH:\r
+            case self::LOOKUP:\r
+                if (is_string($var)) {\r
+                    // special case: technically, this is an array with\r
+                    // a single empty string item, but having an empty\r
+                    // array is more intuitive\r
+                    if ($var == '') {\r
+                        return array();\r
+                    }\r
+                    if (strpos($var, "\n") === false && strpos($var, "\r") === false) {\r
+                        // simplistic string to array method that only works\r
+                        // for simple lists of tag names or alphanumeric characters\r
+                        $var = explode(',', $var);\r
+                    } else {\r
+                        $var = preg_split('/(,|[\n\r]+)/', $var);\r
+                    }\r
+                    // remove spaces\r
+                    foreach ($var as $i => $j) {\r
+                        $var[$i] = trim($j);\r
+                    }\r
+                    if ($type === self::HASH) {\r
+                        // key:value,key2:value2\r
+                        $nvar = array();\r
+                        foreach ($var as $keypair) {\r
+                            $c = explode(':', $keypair, 2);\r
+                            if (!isset($c[1])) {\r
+                                continue;\r
+                            }\r
+                            $nvar[trim($c[0])] = trim($c[1]);\r
+                        }\r
+                        $var = $nvar;\r
+                    }\r
+                }\r
+                if (!is_array($var)) {\r
+                    break;\r
+                }\r
+                $keys = array_keys($var);\r
+                if ($keys === array_keys($keys)) {\r
+                    if ($type == self::ALIST) {\r
+                        return $var;\r
+                    } elseif ($type == self::LOOKUP) {\r
+                        $new = array();\r
+                        foreach ($var as $key) {\r
+                            $new[$key] = true;\r
+                        }\r
+                        return $new;\r
+                    } else {\r
+                        break;\r
+                    }\r
+                }\r
+                if ($type === self::ALIST) {\r
+                    trigger_error("Array list did not have consecutive integer indexes", E_USER_WARNING);\r
+                    return array_values($var);\r
+                }\r
+                if ($type === self::LOOKUP) {\r
+                    foreach ($var as $key => $value) {\r
+                        if ($value !== true) {\r
+                            trigger_error(\r
+                                "Lookup array has non-true value at key '$key'; " .\r
+                                "maybe your input array was not indexed numerically",\r
+                                E_USER_WARNING\r
+                            );\r
+                        }\r
+                        $var[$key] = true;\r
+                    }\r
+                }\r
+                return $var;\r
+            default:\r
+                $this->errorInconsistent(__CLASS__, $type);\r
+        }\r
+        $this->errorGeneric($var, $type);\r
+    }\r
+}\r
+\r
+
+
+\r
+\r
+/**\r
+ * This variable parser uses PHP's internal code engine. Because it does\r
+ * this, it can represent all inputs; however, it is dangerous and cannot\r
+ * be used by users.\r
+ */\r
+class HTMLPurifier_VarParser_Native extends HTMLPurifier_VarParser\r
+{\r
+\r
+    /**\r
+     * @param mixed $var\r
+     * @param int $type\r
+     * @param bool $allow_null\r
+     * @return null|string\r
+     */\r
+    protected function parseImplementation($var, $type, $allow_null)\r
+    {\r
+        return $this->evalExpression($var);\r
+    }\r
+\r
+    /**\r
+     * @param string $expr\r
+     * @return mixed\r
+     * @throws HTMLPurifier_VarParserException\r
+     */\r
+    protected function evalExpression($expr)\r
+    {\r
+        $var = null;\r
+        $result = eval("\$var = $expr;");\r
+        if ($result === false) {\r
+            throw new HTMLPurifier_VarParserException("Fatal error in evaluated code");\r
+        }\r
+        return $var;\r
+    }\r
+}\r
+\r
+
+
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php b/code/backend/standalone/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php
new file mode 100644 (file)
index 0000000..1174575
--- /dev/null
@@ -0,0 +1,48 @@
+<?php\r
+\r
+/**\r
+ * Converts HTMLPurifier_ConfigSchema_Interchange to our runtime\r
+ * representation used to perform checks on user configuration.\r
+ */\r
+class HTMLPurifier_ConfigSchema_Builder_ConfigSchema\r
+{\r
+\r
+    /**\r
+     * @param HTMLPurifier_ConfigSchema_Interchange $interchange\r
+     * @return HTMLPurifier_ConfigSchema\r
+     */\r
+    public function build($interchange)\r
+    {\r
+        $schema = new HTMLPurifier_ConfigSchema();\r
+        foreach ($interchange->directives as $d) {\r
+            $schema->add(\r
+                $d->id->key,\r
+                $d->default,\r
+                $d->type,\r
+                $d->typeAllowsNull\r
+            );\r
+            if ($d->allowed !== null) {\r
+                $schema->addAllowedValues(\r
+                    $d->id->key,\r
+                    $d->allowed\r
+                );\r
+            }\r
+            foreach ($d->aliases as $alias) {\r
+                $schema->addAlias(\r
+                    $alias->key,\r
+                    $d->id->key\r
+                );\r
+            }\r
+            if ($d->valueAliases !== null) {\r
+                $schema->addValueAliases(\r
+                    $d->id->key,\r
+                    $d->valueAliases\r
+                );\r
+            }\r
+        }\r
+        $schema->postProcess();\r
+        return $schema;\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/Builder/Xml.php b/code/backend/standalone/HTMLPurifier/ConfigSchema/Builder/Xml.php
new file mode 100644 (file)
index 0000000..0d00bf1
--- /dev/null
@@ -0,0 +1,144 @@
+<?php\r
+\r
+/**\r
+ * Converts HTMLPurifier_ConfigSchema_Interchange to an XML format,\r
+ * which can be further processed to generate documentation.\r
+ */\r
+class HTMLPurifier_ConfigSchema_Builder_Xml extends XMLWriter\r
+{\r
+\r
+    /**\r
+     * @type HTMLPurifier_ConfigSchema_Interchange\r
+     */\r
+    protected $interchange;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    private $namespace;\r
+\r
+    /**\r
+     * @param string $html\r
+     */\r
+    protected function writeHTMLDiv($html)\r
+    {\r
+        $this->startElement('div');\r
+\r
+        $purifier = HTMLPurifier::getInstance();\r
+        $html = $purifier->purify($html);\r
+        $this->writeAttribute('xmlns', 'http://www.w3.org/1999/xhtml');\r
+        $this->writeRaw($html);\r
+\r
+        $this->endElement(); // div\r
+    }\r
+\r
+    /**\r
+     * @param mixed $var\r
+     * @return string\r
+     */\r
+    protected function export($var)\r
+    {\r
+        if ($var === array()) {\r
+            return 'array()';\r
+        }\r
+        return var_export($var, true);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_ConfigSchema_Interchange $interchange\r
+     */\r
+    public function build($interchange)\r
+    {\r
+        // global access, only use as last resort\r
+        $this->interchange = $interchange;\r
+\r
+        $this->setIndent(true);\r
+        $this->startDocument('1.0', 'UTF-8');\r
+        $this->startElement('configdoc');\r
+        $this->writeElement('title', $interchange->name);\r
+\r
+        foreach ($interchange->directives as $directive) {\r
+            $this->buildDirective($directive);\r
+        }\r
+\r
+        if ($this->namespace) {\r
+            $this->endElement();\r
+        } // namespace\r
+\r
+        $this->endElement(); // configdoc\r
+        $this->flush();\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_ConfigSchema_Interchange_Directive $directive\r
+     */\r
+    public function buildDirective($directive)\r
+    {\r
+        // Kludge, although I suppose having a notion of a "root namespace"\r
+        // certainly makes things look nicer when documentation is built.\r
+        // Depends on things being sorted.\r
+        if (!$this->namespace || $this->namespace !== $directive->id->getRootNamespace()) {\r
+            if ($this->namespace) {\r
+                $this->endElement();\r
+            } // namespace\r
+            $this->namespace = $directive->id->getRootNamespace();\r
+            $this->startElement('namespace');\r
+            $this->writeAttribute('id', $this->namespace);\r
+            $this->writeElement('name', $this->namespace);\r
+        }\r
+\r
+        $this->startElement('directive');\r
+        $this->writeAttribute('id', $directive->id->toString());\r
+\r
+        $this->writeElement('name', $directive->id->getDirective());\r
+\r
+        $this->startElement('aliases');\r
+        foreach ($directive->aliases as $alias) {\r
+            $this->writeElement('alias', $alias->toString());\r
+        }\r
+        $this->endElement(); // aliases\r
+\r
+        $this->startElement('constraints');\r
+        if ($directive->version) {\r
+            $this->writeElement('version', $directive->version);\r
+        }\r
+        $this->startElement('type');\r
+        if ($directive->typeAllowsNull) {\r
+            $this->writeAttribute('allow-null', 'yes');\r
+        }\r
+        $this->text($directive->type);\r
+        $this->endElement(); // type\r
+        if ($directive->allowed) {\r
+            $this->startElement('allowed');\r
+            foreach ($directive->allowed as $value => $x) {\r
+                $this->writeElement('value', $value);\r
+            }\r
+            $this->endElement(); // allowed\r
+        }\r
+        $this->writeElement('default', $this->export($directive->default));\r
+        $this->writeAttribute('xml:space', 'preserve');\r
+        if ($directive->external) {\r
+            $this->startElement('external');\r
+            foreach ($directive->external as $project) {\r
+                $this->writeElement('project', $project);\r
+            }\r
+            $this->endElement();\r
+        }\r
+        $this->endElement(); // constraints\r
+\r
+        if ($directive->deprecatedVersion) {\r
+            $this->startElement('deprecated');\r
+            $this->writeElement('version', $directive->deprecatedVersion);\r
+            $this->writeElement('use', $directive->deprecatedUse->toString());\r
+            $this->endElement(); // deprecated\r
+        }\r
+\r
+        $this->startElement('description');\r
+        $this->writeHTMLDiv($directive->description);\r
+        $this->endElement(); // description\r
+\r
+        $this->endElement(); // directive\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/Exception.php b/code/backend/standalone/HTMLPurifier/ConfigSchema/Exception.php
new file mode 100644 (file)
index 0000000..1abdcfc
--- /dev/null
@@ -0,0 +1,11 @@
+<?php\r
+\r
+/**\r
+ * Exceptions related to configuration schema\r
+ */\r
+class HTMLPurifier_ConfigSchema_Exception extends HTMLPurifier_Exception\r
+{\r
+\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/Interchange.php b/code/backend/standalone/HTMLPurifier/ConfigSchema/Interchange.php
new file mode 100644 (file)
index 0000000..c094fa0
--- /dev/null
@@ -0,0 +1,47 @@
+<?php\r
+\r
+/**\r
+ * Generic schema interchange format that can be converted to a runtime\r
+ * representation (HTMLPurifier_ConfigSchema) or HTML documentation. Members\r
+ * are completely validated.\r
+ */\r
+class HTMLPurifier_ConfigSchema_Interchange\r
+{\r
+\r
+    /**\r
+     * Name of the application this schema is describing.\r
+     * @type string\r
+     */\r
+    public $name;\r
+\r
+    /**\r
+     * Array of Directive ID => array(directive info)\r
+     * @type HTMLPurifier_ConfigSchema_Interchange_Directive[]\r
+     */\r
+    public $directives = array();\r
+\r
+    /**\r
+     * Adds a directive array to $directives\r
+     * @param HTMLPurifier_ConfigSchema_Interchange_Directive $directive\r
+     * @throws HTMLPurifier_ConfigSchema_Exception\r
+     */\r
+    public function addDirective($directive)\r
+    {\r
+        if (isset($this->directives[$i = $directive->id->toString()])) {\r
+            throw new HTMLPurifier_ConfigSchema_Exception("Cannot redefine directive '$i'");\r
+        }\r
+        $this->directives[$i] = $directive;\r
+    }\r
+\r
+    /**\r
+     * Convenience function to perform standard validation. Throws exception\r
+     * on failed validation.\r
+     */\r
+    public function validate()\r
+    {\r
+        $validator = new HTMLPurifier_ConfigSchema_Validator();\r
+        return $validator->validate($this);\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/Interchange/Directive.php b/code/backend/standalone/HTMLPurifier/ConfigSchema/Interchange/Directive.php
new file mode 100644 (file)
index 0000000..4c39c5c
--- /dev/null
@@ -0,0 +1,89 @@
+<?php\r
+\r
+/**\r
+ * Interchange component class describing configuration directives.\r
+ */\r
+class HTMLPurifier_ConfigSchema_Interchange_Directive\r
+{\r
+\r
+    /**\r
+     * ID of directive.\r
+     * @type HTMLPurifier_ConfigSchema_Interchange_Id\r
+     */\r
+    public $id;\r
+\r
+    /**\r
+     * Type, e.g. 'integer' or 'istring'.\r
+     * @type string\r
+     */\r
+    public $type;\r
+\r
+    /**\r
+     * Default value, e.g. 3 or 'DefaultVal'.\r
+     * @type mixed\r
+     */\r
+    public $default;\r
+\r
+    /**\r
+     * HTML description.\r
+     * @type string\r
+     */\r
+    public $description;\r
+\r
+    /**\r
+     * Whether or not null is allowed as a value.\r
+     * @type bool\r
+     */\r
+    public $typeAllowsNull = false;\r
+\r
+    /**\r
+     * Lookup table of allowed scalar values.\r
+     * e.g. array('allowed' => true).\r
+     * Null if all values are allowed.\r
+     * @type array\r
+     */\r
+    public $allowed;\r
+\r
+    /**\r
+     * List of aliases for the directive.\r
+     * e.g. array(new HTMLPurifier_ConfigSchema_Interchange_Id('Ns', 'Dir'))).\r
+     * @type HTMLPurifier_ConfigSchema_Interchange_Id[]\r
+     */\r
+    public $aliases = array();\r
+\r
+    /**\r
+     * Hash of value aliases, e.g. array('alt' => 'real'). Null if value\r
+     * aliasing is disabled (necessary for non-scalar types).\r
+     * @type array\r
+     */\r
+    public $valueAliases;\r
+\r
+    /**\r
+     * Version of HTML Purifier the directive was introduced, e.g. '1.3.1'.\r
+     * Null if the directive has always existed.\r
+     * @type string\r
+     */\r
+    public $version;\r
+\r
+    /**\r
+     * ID of directive that supercedes this old directive.\r
+     * Null if not deprecated.\r
+     * @type HTMLPurifier_ConfigSchema_Interchange_Id\r
+     */\r
+    public $deprecatedUse;\r
+\r
+    /**\r
+     * Version of HTML Purifier this directive was deprecated. Null if not\r
+     * deprecated.\r
+     * @type string\r
+     */\r
+    public $deprecatedVersion;\r
+\r
+    /**\r
+     * List of external projects this directive depends on, e.g. array('CSSTidy').\r
+     * @type array\r
+     */\r
+    public $external = array();\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/Interchange/Id.php b/code/backend/standalone/HTMLPurifier/ConfigSchema/Interchange/Id.php
new file mode 100644 (file)
index 0000000..3ee8171
--- /dev/null
@@ -0,0 +1,58 @@
+<?php\r
+\r
+/**\r
+ * Represents a directive ID in the interchange format.\r
+ */\r
+class HTMLPurifier_ConfigSchema_Interchange_Id\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $key;\r
+\r
+    /**\r
+     * @param string $key\r
+     */\r
+    public function __construct($key)\r
+    {\r
+        $this->key = $key;\r
+    }\r
+\r
+    /**\r
+     * @return string\r
+     * @warning This is NOT magic, to ensure that people don't abuse SPL and\r
+     *          cause problems for PHP 5.0 support.\r
+     */\r
+    public function toString()\r
+    {\r
+        return $this->key;\r
+    }\r
+\r
+    /**\r
+     * @return string\r
+     */\r
+    public function getRootNamespace()\r
+    {\r
+        return substr($this->key, 0, strpos($this->key, "."));\r
+    }\r
+\r
+    /**\r
+     * @return string\r
+     */\r
+    public function getDirective()\r
+    {\r
+        return substr($this->key, strpos($this->key, ".") + 1);\r
+    }\r
+\r
+    /**\r
+     * @param string $id\r
+     * @return HTMLPurifier_ConfigSchema_Interchange_Id\r
+     */\r
+    public static function make($id)\r
+    {\r
+        return new HTMLPurifier_ConfigSchema_Interchange_Id($id);\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/InterchangeBuilder.php b/code/backend/standalone/HTMLPurifier/ConfigSchema/InterchangeBuilder.php
new file mode 100644 (file)
index 0000000..fe9b326
--- /dev/null
@@ -0,0 +1,226 @@
+<?php\r
+\r
+class HTMLPurifier_ConfigSchema_InterchangeBuilder\r
+{\r
+\r
+    /**\r
+     * Used for processing DEFAULT, nothing else.\r
+     * @type HTMLPurifier_VarParser\r
+     */\r
+    protected $varParser;\r
+\r
+    /**\r
+     * @param HTMLPurifier_VarParser $varParser\r
+     */\r
+    public function __construct($varParser = null)\r
+    {\r
+        $this->varParser = $varParser ? $varParser : new HTMLPurifier_VarParser_Native();\r
+    }\r
+\r
+    /**\r
+     * @param string $dir\r
+     * @return HTMLPurifier_ConfigSchema_Interchange\r
+     */\r
+    public static function buildFromDirectory($dir = null)\r
+    {\r
+        $builder = new HTMLPurifier_ConfigSchema_InterchangeBuilder();\r
+        $interchange = new HTMLPurifier_ConfigSchema_Interchange();\r
+        return $builder->buildDir($interchange, $dir);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_ConfigSchema_Interchange $interchange\r
+     * @param string $dir\r
+     * @return HTMLPurifier_ConfigSchema_Interchange\r
+     */\r
+    public function buildDir($interchange, $dir = null)\r
+    {\r
+        if (!$dir) {\r
+            $dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema';\r
+        }\r
+        if (file_exists($dir . '/info.ini')) {\r
+            $info = parse_ini_file($dir . '/info.ini');\r
+            $interchange->name = $info['name'];\r
+        }\r
+\r
+        $files = array();\r
+        $dh = opendir($dir);\r
+        while (false !== ($file = readdir($dh))) {\r
+            if (!$file || $file[0] == '.' || strrchr($file, '.') !== '.txt') {\r
+                continue;\r
+            }\r
+            $files[] = $file;\r
+        }\r
+        closedir($dh);\r
+\r
+        sort($files);\r
+        foreach ($files as $file) {\r
+            $this->buildFile($interchange, $dir . '/' . $file);\r
+        }\r
+        return $interchange;\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_ConfigSchema_Interchange $interchange\r
+     * @param string $file\r
+     */\r
+    public function buildFile($interchange, $file)\r
+    {\r
+        $parser = new HTMLPurifier_StringHashParser();\r
+        $this->build(\r
+            $interchange,\r
+            new HTMLPurifier_StringHash($parser->parseFile($file))\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Builds an interchange object based on a hash.\r
+     * @param HTMLPurifier_ConfigSchema_Interchange $interchange HTMLPurifier_ConfigSchema_Interchange object to build\r
+     * @param HTMLPurifier_StringHash $hash source data\r
+     * @throws HTMLPurifier_ConfigSchema_Exception\r
+     */\r
+    public function build($interchange, $hash)\r
+    {\r
+        if (!$hash instanceof HTMLPurifier_StringHash) {\r
+            $hash = new HTMLPurifier_StringHash($hash);\r
+        }\r
+        if (!isset($hash['ID'])) {\r
+            throw new HTMLPurifier_ConfigSchema_Exception('Hash does not have any ID');\r
+        }\r
+        if (strpos($hash['ID'], '.') === false) {\r
+            if (count($hash) == 2 && isset($hash['DESCRIPTION'])) {\r
+                $hash->offsetGet('DESCRIPTION'); // prevent complaining\r
+            } else {\r
+                throw new HTMLPurifier_ConfigSchema_Exception('All directives must have a namespace');\r
+            }\r
+        } else {\r
+            $this->buildDirective($interchange, $hash);\r
+        }\r
+        $this->_findUnused($hash);\r
+    }\r
+\r
+    /**\r
+     * @param HTMLPurifier_ConfigSchema_Interchange $interchange\r
+     * @param HTMLPurifier_StringHash $hash\r
+     * @throws HTMLPurifier_ConfigSchema_Exception\r
+     */\r
+    public function buildDirective($interchange, $hash)\r
+    {\r
+        $directive = new HTMLPurifier_ConfigSchema_Interchange_Directive();\r
+\r
+        // These are required elements:\r
+        $directive->id = $this->id($hash->offsetGet('ID'));\r
+        $id = $directive->id->toString(); // convenience\r
+\r
+        if (isset($hash['TYPE'])) {\r
+            $type = explode('/', $hash->offsetGet('TYPE'));\r
+            if (isset($type[1])) {\r
+                $directive->typeAllowsNull = true;\r
+            }\r
+            $directive->type = $type[0];\r
+        } else {\r
+            throw new HTMLPurifier_ConfigSchema_Exception("TYPE in directive hash '$id' not defined");\r
+        }\r
+\r
+        if (isset($hash['DEFAULT'])) {\r
+            try {\r
+                $directive->default = $this->varParser->parse(\r
+                    $hash->offsetGet('DEFAULT'),\r
+                    $directive->type,\r
+                    $directive->typeAllowsNull\r
+                );\r
+            } catch (HTMLPurifier_VarParserException $e) {\r
+                throw new HTMLPurifier_ConfigSchema_Exception($e->getMessage() . " in DEFAULT in directive hash '$id'");\r
+            }\r
+        }\r
+\r
+        if (isset($hash['DESCRIPTION'])) {\r
+            $directive->description = $hash->offsetGet('DESCRIPTION');\r
+        }\r
+\r
+        if (isset($hash['ALLOWED'])) {\r
+            $directive->allowed = $this->lookup($this->evalArray($hash->offsetGet('ALLOWED')));\r
+        }\r
+\r
+        if (isset($hash['VALUE-ALIASES'])) {\r
+            $directive->valueAliases = $this->evalArray($hash->offsetGet('VALUE-ALIASES'));\r
+        }\r
+\r
+        if (isset($hash['ALIASES'])) {\r
+            $raw_aliases = trim($hash->offsetGet('ALIASES'));\r
+            $aliases = preg_split('/\s*,\s*/', $raw_aliases);\r
+            foreach ($aliases as $alias) {\r
+                $directive->aliases[] = $this->id($alias);\r
+            }\r
+        }\r
+\r
+        if (isset($hash['VERSION'])) {\r
+            $directive->version = $hash->offsetGet('VERSION');\r
+        }\r
+\r
+        if (isset($hash['DEPRECATED-USE'])) {\r
+            $directive->deprecatedUse = $this->id($hash->offsetGet('DEPRECATED-USE'));\r
+        }\r
+\r
+        if (isset($hash['DEPRECATED-VERSION'])) {\r
+            $directive->deprecatedVersion = $hash->offsetGet('DEPRECATED-VERSION');\r
+        }\r
+\r
+        if (isset($hash['EXTERNAL'])) {\r
+            $directive->external = preg_split('/\s*,\s*/', trim($hash->offsetGet('EXTERNAL')));\r
+        }\r
+\r
+        $interchange->addDirective($directive);\r
+    }\r
+\r
+    /**\r
+     * Evaluates an array PHP code string without array() wrapper\r
+     * @param string $contents\r
+     */\r
+    protected function evalArray($contents)\r
+    {\r
+        return eval('return array(' . $contents . ');');\r
+    }\r
+\r
+    /**\r
+     * Converts an array list into a lookup array.\r
+     * @param array $array\r
+     * @return array\r
+     */\r
+    protected function lookup($array)\r
+    {\r
+        $ret = array();\r
+        foreach ($array as $val) {\r
+            $ret[$val] = true;\r
+        }\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Convenience function that creates an HTMLPurifier_ConfigSchema_Interchange_Id\r
+     * object based on a string Id.\r
+     * @param string $id\r
+     * @return HTMLPurifier_ConfigSchema_Interchange_Id\r
+     */\r
+    protected function id($id)\r
+    {\r
+        return HTMLPurifier_ConfigSchema_Interchange_Id::make($id);\r
+    }\r
+\r
+    /**\r
+     * Triggers errors for any unused keys passed in the hash; such keys\r
+     * may indicate typos, missing values, etc.\r
+     * @param HTMLPurifier_StringHash $hash Hash to check.\r
+     */\r
+    protected function _findUnused($hash)\r
+    {\r
+        $accessed = $hash->getAccessed();\r
+        foreach ($hash as $k => $v) {\r
+            if (!isset($accessed[$k])) {\r
+                trigger_error("String hash key '$k' not used by builder", E_USER_NOTICE);\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/Validator.php b/code/backend/standalone/HTMLPurifier/ConfigSchema/Validator.php
new file mode 100644 (file)
index 0000000..9f14444
--- /dev/null
@@ -0,0 +1,248 @@
+<?php\r
+\r
+/**\r
+ * Performs validations on HTMLPurifier_ConfigSchema_Interchange\r
+ *\r
+ * @note If you see '// handled by InterchangeBuilder', that means a\r
+ *       design decision in that class would prevent this validation from\r
+ *       ever being necessary. We have them anyway, however, for\r
+ *       redundancy.\r
+ */\r
+class HTMLPurifier_ConfigSchema_Validator\r
+{\r
+\r
+    /**\r
+     * @type HTMLPurifier_ConfigSchema_Interchange\r
+     */\r
+    protected $interchange;\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    protected $aliases;\r
+\r
+    /**\r
+     * Context-stack to provide easy to read error messages.\r
+     * @type array\r
+     */\r
+    protected $context = array();\r
+\r
+    /**\r
+     * to test default's type.\r
+     * @type HTMLPurifier_VarParser\r
+     */\r
+    protected $parser;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->parser = new HTMLPurifier_VarParser();\r
+    }\r
+\r
+    /**\r
+     * Validates a fully-formed interchange object.\r
+     * @param HTMLPurifier_ConfigSchema_Interchange $interchange\r
+     * @return bool\r
+     */\r
+    public function validate($interchange)\r
+    {\r
+        $this->interchange = $interchange;\r
+        $this->aliases = array();\r
+        // PHP is a bit lax with integer <=> string conversions in\r
+        // arrays, so we don't use the identical !== comparison\r
+        foreach ($interchange->directives as $i => $directive) {\r
+            $id = $directive->id->toString();\r
+            if ($i != $id) {\r
+                $this->error(false, "Integrity violation: key '$i' does not match internal id '$id'");\r
+            }\r
+            $this->validateDirective($directive);\r
+        }\r
+        return true;\r
+    }\r
+\r
+    /**\r
+     * Validates a HTMLPurifier_ConfigSchema_Interchange_Id object.\r
+     * @param HTMLPurifier_ConfigSchema_Interchange_Id $id\r
+     */\r
+    public function validateId($id)\r
+    {\r
+        $id_string = $id->toString();\r
+        $this->context[] = "id '$id_string'";\r
+        if (!$id instanceof HTMLPurifier_ConfigSchema_Interchange_Id) {\r
+            // handled by InterchangeBuilder\r
+            $this->error(false, 'is not an instance of HTMLPurifier_ConfigSchema_Interchange_Id');\r
+        }\r
+        // keys are now unconstrained (we might want to narrow down to A-Za-z0-9.)\r
+        // we probably should check that it has at least one namespace\r
+        $this->with($id, 'key')\r
+            ->assertNotEmpty()\r
+            ->assertIsString(); // implicit assertIsString handled by InterchangeBuilder\r
+        array_pop($this->context);\r
+    }\r
+\r
+    /**\r
+     * Validates a HTMLPurifier_ConfigSchema_Interchange_Directive object.\r
+     * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d\r
+     */\r
+    public function validateDirective($d)\r
+    {\r
+        $id = $d->id->toString();\r
+        $this->context[] = "directive '$id'";\r
+        $this->validateId($d->id);\r
+\r
+        $this->with($d, 'description')\r
+            ->assertNotEmpty();\r
+\r
+        // BEGIN - handled by InterchangeBuilder\r
+        $this->with($d, 'type')\r
+            ->assertNotEmpty();\r
+        $this->with($d, 'typeAllowsNull')\r
+            ->assertIsBool();\r
+        try {\r
+            // This also tests validity of $d->type\r
+            $this->parser->parse($d->default, $d->type, $d->typeAllowsNull);\r
+        } catch (HTMLPurifier_VarParserException $e) {\r
+            $this->error('default', 'had error: ' . $e->getMessage());\r
+        }\r
+        // END - handled by InterchangeBuilder\r
+\r
+        if (!is_null($d->allowed) || !empty($d->valueAliases)) {\r
+            // allowed and valueAliases require that we be dealing with\r
+            // strings, so check for that early.\r
+            $d_int = HTMLPurifier_VarParser::$types[$d->type];\r
+            if (!isset(HTMLPurifier_VarParser::$stringTypes[$d_int])) {\r
+                $this->error('type', 'must be a string type when used with allowed or value aliases');\r
+            }\r
+        }\r
+\r
+        $this->validateDirectiveAllowed($d);\r
+        $this->validateDirectiveValueAliases($d);\r
+        $this->validateDirectiveAliases($d);\r
+\r
+        array_pop($this->context);\r
+    }\r
+\r
+    /**\r
+     * Extra validation if $allowed member variable of\r
+     * HTMLPurifier_ConfigSchema_Interchange_Directive is defined.\r
+     * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d\r
+     */\r
+    public function validateDirectiveAllowed($d)\r
+    {\r
+        if (is_null($d->allowed)) {\r
+            return;\r
+        }\r
+        $this->with($d, 'allowed')\r
+            ->assertNotEmpty()\r
+            ->assertIsLookup(); // handled by InterchangeBuilder\r
+        if (is_string($d->default) && !isset($d->allowed[$d->default])) {\r
+            $this->error('default', 'must be an allowed value');\r
+        }\r
+        $this->context[] = 'allowed';\r
+        foreach ($d->allowed as $val => $x) {\r
+            if (!is_string($val)) {\r
+                $this->error("value $val", 'must be a string');\r
+            }\r
+        }\r
+        array_pop($this->context);\r
+    }\r
+\r
+    /**\r
+     * Extra validation if $valueAliases member variable of\r
+     * HTMLPurifier_ConfigSchema_Interchange_Directive is defined.\r
+     * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d\r
+     */\r
+    public function validateDirectiveValueAliases($d)\r
+    {\r
+        if (is_null($d->valueAliases)) {\r
+            return;\r
+        }\r
+        $this->with($d, 'valueAliases')\r
+            ->assertIsArray(); // handled by InterchangeBuilder\r
+        $this->context[] = 'valueAliases';\r
+        foreach ($d->valueAliases as $alias => $real) {\r
+            if (!is_string($alias)) {\r
+                $this->error("alias $alias", 'must be a string');\r
+            }\r
+            if (!is_string($real)) {\r
+                $this->error("alias target $real from alias '$alias'", 'must be a string');\r
+            }\r
+            if ($alias === $real) {\r
+                $this->error("alias '$alias'", "must not be an alias to itself");\r
+            }\r
+        }\r
+        if (!is_null($d->allowed)) {\r
+            foreach ($d->valueAliases as $alias => $real) {\r
+                if (isset($d->allowed[$alias])) {\r
+                    $this->error("alias '$alias'", 'must not be an allowed value');\r
+                } elseif (!isset($d->allowed[$real])) {\r
+                    $this->error("alias '$alias'", 'must be an alias to an allowed value');\r
+                }\r
+            }\r
+        }\r
+        array_pop($this->context);\r
+    }\r
+\r
+    /**\r
+     * Extra validation if $aliases member variable of\r
+     * HTMLPurifier_ConfigSchema_Interchange_Directive is defined.\r
+     * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d\r
+     */\r
+    public function validateDirectiveAliases($d)\r
+    {\r
+        $this->with($d, 'aliases')\r
+            ->assertIsArray(); // handled by InterchangeBuilder\r
+        $this->context[] = 'aliases';\r
+        foreach ($d->aliases as $alias) {\r
+            $this->validateId($alias);\r
+            $s = $alias->toString();\r
+            if (isset($this->interchange->directives[$s])) {\r
+                $this->error("alias '$s'", 'collides with another directive');\r
+            }\r
+            if (isset($this->aliases[$s])) {\r
+                $other_directive = $this->aliases[$s];\r
+                $this->error("alias '$s'", "collides with alias for directive '$other_directive'");\r
+            }\r
+            $this->aliases[$s] = $d->id->toString();\r
+        }\r
+        array_pop($this->context);\r
+    }\r
+\r
+    // protected helper functions\r
+\r
+    /**\r
+     * Convenience function for generating HTMLPurifier_ConfigSchema_ValidatorAtom\r
+     * for validating simple member variables of objects.\r
+     * @param $obj\r
+     * @param $member\r
+     * @return HTMLPurifier_ConfigSchema_ValidatorAtom\r
+     */\r
+    protected function with($obj, $member)\r
+    {\r
+        return new HTMLPurifier_ConfigSchema_ValidatorAtom($this->getFormattedContext(), $obj, $member);\r
+    }\r
+\r
+    /**\r
+     * Emits an error, providing helpful context.\r
+     * @throws HTMLPurifier_ConfigSchema_Exception\r
+     */\r
+    protected function error($target, $msg)\r
+    {\r
+        if ($target !== false) {\r
+            $prefix = ucfirst($target) . ' in ' . $this->getFormattedContext();\r
+        } else {\r
+            $prefix = ucfirst($this->getFormattedContext());\r
+        }\r
+        throw new HTMLPurifier_ConfigSchema_Exception(trim($prefix . ' ' . $msg));\r
+    }\r
+\r
+    /**\r
+     * Returns a formatted context string.\r
+     * @return string\r
+     */\r
+    protected function getFormattedContext()\r
+    {\r
+        return implode(' in ', array_reverse($this->context));\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/ValidatorAtom.php b/code/backend/standalone/HTMLPurifier/ConfigSchema/ValidatorAtom.php
new file mode 100644 (file)
index 0000000..a2e0b4a
--- /dev/null
@@ -0,0 +1,130 @@
+<?php\r
+\r
+/**\r
+ * Fluent interface for validating the contents of member variables.\r
+ * This should be immutable. See HTMLPurifier_ConfigSchema_Validator for\r
+ * use-cases. We name this an 'atom' because it's ONLY for validations that\r
+ * are independent and usually scalar.\r
+ */\r
+class HTMLPurifier_ConfigSchema_ValidatorAtom\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    protected $context;\r
+\r
+    /**\r
+     * @type object\r
+     */\r
+    protected $obj;\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    protected $member;\r
+\r
+    /**\r
+     * @type mixed\r
+     */\r
+    protected $contents;\r
+\r
+    public function __construct($context, $obj, $member)\r
+    {\r
+        $this->context = $context;\r
+        $this->obj = $obj;\r
+        $this->member = $member;\r
+        $this->contents =& $obj->$member;\r
+    }\r
+\r
+    /**\r
+     * @return HTMLPurifier_ConfigSchema_ValidatorAtom\r
+     */\r
+    public function assertIsString()\r
+    {\r
+        if (!is_string($this->contents)) {\r
+            $this->error('must be a string');\r
+        }\r
+        return $this;\r
+    }\r
+\r
+    /**\r
+     * @return HTMLPurifier_ConfigSchema_ValidatorAtom\r
+     */\r
+    public function assertIsBool()\r
+    {\r
+        if (!is_bool($this->contents)) {\r
+            $this->error('must be a boolean');\r
+        }\r
+        return $this;\r
+    }\r
+\r
+    /**\r
+     * @return HTMLPurifier_ConfigSchema_ValidatorAtom\r
+     */\r
+    public function assertIsArray()\r
+    {\r
+        if (!is_array($this->contents)) {\r
+            $this->error('must be an array');\r
+        }\r
+        return $this;\r
+    }\r
+\r
+    /**\r
+     * @return HTMLPurifier_ConfigSchema_ValidatorAtom\r
+     */\r
+    public function assertNotNull()\r
+    {\r
+        if ($this->contents === null) {\r
+            $this->error('must not be null');\r
+        }\r
+        return $this;\r
+    }\r
+\r
+    /**\r
+     * @return HTMLPurifier_ConfigSchema_ValidatorAtom\r
+     */\r
+    public function assertAlnum()\r
+    {\r
+        $this->assertIsString();\r
+        if (!ctype_alnum($this->contents)) {\r
+            $this->error('must be alphanumeric');\r
+        }\r
+        return $this;\r
+    }\r
+\r
+    /**\r
+     * @return HTMLPurifier_ConfigSchema_ValidatorAtom\r
+     */\r
+    public function assertNotEmpty()\r
+    {\r
+        if (empty($this->contents)) {\r
+            $this->error('must not be empty');\r
+        }\r
+        return $this;\r
+    }\r
+\r
+    /**\r
+     * @return HTMLPurifier_ConfigSchema_ValidatorAtom\r
+     */\r
+    public function assertIsLookup()\r
+    {\r
+        $this->assertIsArray();\r
+        foreach ($this->contents as $v) {\r
+            if ($v !== true) {\r
+                $this->error('must be a lookup array');\r
+            }\r
+        }\r
+        return $this;\r
+    }\r
+\r
+    /**\r
+     * @param string $msg\r
+     * @throws HTMLPurifier_ConfigSchema_Exception\r
+     */\r
+    protected function error($msg)\r
+    {\r
+        throw new HTMLPurifier_ConfigSchema_Exception(ucfirst($this->member) . ' in ' . $this->context . ' ' . $msg);\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema.ser b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema.ser
new file mode 100644 (file)
index 0000000..47bd259
--- /dev/null
@@ -0,0 +1 @@
+O:25:"HTMLPurifier_ConfigSchema":3:{s:8:"defaults";a:126:{s:19:"Attr.AllowedClasses";N;s:24:"Attr.AllowedFrameTargets";a:0:{}s:15:"Attr.AllowedRel";a:0:{}s:15:"Attr.AllowedRev";a:0:{}s:18:"Attr.ClassUseCDATA";N;s:20:"Attr.DefaultImageAlt";N;s:24:"Attr.DefaultInvalidImage";s:0:"";s:27:"Attr.DefaultInvalidImageAlt";s:13:"Invalid image";s:19:"Attr.DefaultTextDir";s:3:"ltr";s:13:"Attr.EnableID";b:0;s:21:"Attr.ForbiddenClasses";a:0:{}s:13:"Attr.ID.HTML5";N;s:16:"Attr.IDBlacklist";a:0:{}s:22:"Attr.IDBlacklistRegexp";N;s:13:"Attr.IDPrefix";s:0:"";s:18:"Attr.IDPrefixLocal";s:0:"";s:24:"AutoFormat.AutoParagraph";b:0;s:17:"AutoFormat.Custom";a:0:{}s:25:"AutoFormat.DisplayLinkURI";b:0;s:18:"AutoFormat.Linkify";b:0;s:33:"AutoFormat.PurifierLinkify.DocURL";s:3:"#%s";s:26:"AutoFormat.PurifierLinkify";b:0;s:32:"AutoFormat.RemoveEmpty.Predicate";a:4:{s:8:"colgroup";a:0:{}s:2:"th";a:0:{}s:2:"td";a:0:{}s:6:"iframe";a:1:{i:0;s:3:"src";}}s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";a:2:{s:2:"td";b:1;s:2:"th";b:1;}s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";b:0;s:22:"AutoFormat.RemoveEmpty";b:0;s:39:"AutoFormat.RemoveSpansWithoutAttributes";b:0;s:19:"CSS.AllowDuplicates";b:0;s:18:"CSS.AllowImportant";b:0;s:15:"CSS.AllowTricky";b:0;s:16:"CSS.AllowedFonts";N;s:21:"CSS.AllowedProperties";N;s:17:"CSS.DefinitionRev";i:1;s:23:"CSS.ForbiddenProperties";a:0:{}s:16:"CSS.MaxImgLength";s:6:"1200px";s:15:"CSS.Proprietary";b:0;s:11:"CSS.Trusted";b:0;s:20:"Cache.DefinitionImpl";s:10:"Serializer";s:20:"Cache.SerializerPath";N;s:27:"Cache.SerializerPermissions";i:493;s:22:"Core.AggressivelyFixLt";b:1;s:29:"Core.AggressivelyRemoveScript";b:1;s:28:"Core.AllowHostnameUnderscore";b:0;s:23:"Core.AllowParseManyTags";b:0;s:18:"Core.CollectErrors";b:0;s:18:"Core.ColorKeywords";a:148:{s:9:"aliceblue";s:7:"#F0F8FF";s:12:"antiquewhite";s:7:"#FAEBD7";s:4:"aqua";s:7:"#00FFFF";s:10:"aquamarine";s:7:"#7FFFD4";s:5:"azure";s:7:"#F0FFFF";s:5:"beige";s:7:"#F5F5DC";s:6:"bisque";s:7:"#FFE4C4";s:5:"black";s:7:"#000000";s:14:"blanchedalmond";s:7:"#FFEBCD";s:4:"blue";s:7:"#0000FF";s:10:"blueviolet";s:7:"#8A2BE2";s:5:"brown";s:7:"#A52A2A";s:9:"burlywood";s:7:"#DEB887";s:9:"cadetblue";s:7:"#5F9EA0";s:10:"chartreuse";s:7:"#7FFF00";s:9:"chocolate";s:7:"#D2691E";s:5:"coral";s:7:"#FF7F50";s:14:"cornflowerblue";s:7:"#6495ED";s:8:"cornsilk";s:7:"#FFF8DC";s:7:"crimson";s:7:"#DC143C";s:4:"cyan";s:7:"#00FFFF";s:8:"darkblue";s:7:"#00008B";s:8:"darkcyan";s:7:"#008B8B";s:13:"darkgoldenrod";s:7:"#B8860B";s:8:"darkgray";s:7:"#A9A9A9";s:8:"darkgrey";s:7:"#A9A9A9";s:9:"darkgreen";s:7:"#006400";s:9:"darkkhaki";s:7:"#BDB76B";s:11:"darkmagenta";s:7:"#8B008B";s:14:"darkolivegreen";s:7:"#556B2F";s:10:"darkorange";s:7:"#FF8C00";s:10:"darkorchid";s:7:"#9932CC";s:7:"darkred";s:7:"#8B0000";s:10:"darksalmon";s:7:"#E9967A";s:12:"darkseagreen";s:7:"#8FBC8F";s:13:"darkslateblue";s:7:"#483D8B";s:13:"darkslategray";s:7:"#2F4F4F";s:13:"darkslategrey";s:7:"#2F4F4F";s:13:"darkturquoise";s:7:"#00CED1";s:10:"darkviolet";s:7:"#9400D3";s:8:"deeppink";s:7:"#FF1493";s:11:"deepskyblue";s:7:"#00BFFF";s:7:"dimgray";s:7:"#696969";s:7:"dimgrey";s:7:"#696969";s:10:"dodgerblue";s:7:"#1E90FF";s:9:"firebrick";s:7:"#B22222";s:11:"floralwhite";s:7:"#FFFAF0";s:11:"forestgreen";s:7:"#228B22";s:7:"fuchsia";s:7:"#FF00FF";s:9:"gainsboro";s:7:"#DCDCDC";s:10:"ghostwhite";s:7:"#F8F8FF";s:4:"gold";s:7:"#FFD700";s:9:"goldenrod";s:7:"#DAA520";s:4:"gray";s:7:"#808080";s:4:"grey";s:7:"#808080";s:5:"green";s:7:"#008000";s:11:"greenyellow";s:7:"#ADFF2F";s:8:"honeydew";s:7:"#F0FFF0";s:7:"hotpink";s:7:"#FF69B4";s:9:"indianred";s:7:"#CD5C5C";s:6:"indigo";s:7:"#4B0082";s:5:"ivory";s:7:"#FFFFF0";s:5:"khaki";s:7:"#F0E68C";s:8:"lavender";s:7:"#E6E6FA";s:13:"lavenderblush";s:7:"#FFF0F5";s:9:"lawngreen";s:7:"#7CFC00";s:12:"lemonchiffon";s:7:"#FFFACD";s:9:"lightblue";s:7:"#ADD8E6";s:10:"lightcoral";s:7:"#F08080";s:9:"lightcyan";s:7:"#E0FFFF";s:20:"lightgoldenrodyellow";s:7:"#FAFAD2";s:9:"lightgray";s:7:"#D3D3D3";s:9:"lightgrey";s:7:"#D3D3D3";s:10:"lightgreen";s:7:"#90EE90";s:9:"lightpink";s:7:"#FFB6C1";s:11:"lightsalmon";s:7:"#FFA07A";s:13:"lightseagreen";s:7:"#20B2AA";s:12:"lightskyblue";s:7:"#87CEFA";s:14:"lightslategray";s:7:"#778899";s:14:"lightslategrey";s:7:"#778899";s:14:"lightsteelblue";s:7:"#B0C4DE";s:11:"lightyellow";s:7:"#FFFFE0";s:4:"lime";s:7:"#00FF00";s:9:"limegreen";s:7:"#32CD32";s:5:"linen";s:7:"#FAF0E6";s:7:"magenta";s:7:"#FF00FF";s:6:"maroon";s:7:"#800000";s:16:"mediumaquamarine";s:7:"#66CDAA";s:10:"mediumblue";s:7:"#0000CD";s:12:"mediumorchid";s:7:"#BA55D3";s:12:"mediumpurple";s:7:"#9370DB";s:14:"mediumseagreen";s:7:"#3CB371";s:15:"mediumslateblue";s:7:"#7B68EE";s:17:"mediumspringgreen";s:7:"#00FA9A";s:15:"mediumturquoise";s:7:"#48D1CC";s:15:"mediumvioletred";s:7:"#C71585";s:12:"midnightblue";s:7:"#191970";s:9:"mintcream";s:7:"#F5FFFA";s:9:"mistyrose";s:7:"#FFE4E1";s:8:"moccasin";s:7:"#FFE4B5";s:11:"navajowhite";s:7:"#FFDEAD";s:4:"navy";s:7:"#000080";s:7:"oldlace";s:7:"#FDF5E6";s:5:"olive";s:7:"#808000";s:9:"olivedrab";s:7:"#6B8E23";s:6:"orange";s:7:"#FFA500";s:9:"orangered";s:7:"#FF4500";s:6:"orchid";s:7:"#DA70D6";s:13:"palegoldenrod";s:7:"#EEE8AA";s:9:"palegreen";s:7:"#98FB98";s:13:"paleturquoise";s:7:"#AFEEEE";s:13:"palevioletred";s:7:"#DB7093";s:10:"papayawhip";s:7:"#FFEFD5";s:9:"peachpuff";s:7:"#FFDAB9";s:4:"peru";s:7:"#CD853F";s:4:"pink";s:7:"#FFC0CB";s:4:"plum";s:7:"#DDA0DD";s:10:"powderblue";s:7:"#B0E0E6";s:6:"purple";s:7:"#800080";s:13:"rebeccapurple";s:7:"#663399";s:3:"red";s:7:"#FF0000";s:9:"rosybrown";s:7:"#BC8F8F";s:9:"royalblue";s:7:"#4169E1";s:11:"saddlebrown";s:7:"#8B4513";s:6:"salmon";s:7:"#FA8072";s:10:"sandybrown";s:7:"#F4A460";s:8:"seagreen";s:7:"#2E8B57";s:8:"seashell";s:7:"#FFF5EE";s:6:"sienna";s:7:"#A0522D";s:6:"silver";s:7:"#C0C0C0";s:7:"skyblue";s:7:"#87CEEB";s:9:"slateblue";s:7:"#6A5ACD";s:9:"slategray";s:7:"#708090";s:9:"slategrey";s:7:"#708090";s:4:"snow";s:7:"#FFFAFA";s:11:"springgreen";s:7:"#00FF7F";s:9:"steelblue";s:7:"#4682B4";s:3:"tan";s:7:"#D2B48C";s:4:"teal";s:7:"#008080";s:7:"thistle";s:7:"#D8BFD8";s:6:"tomato";s:7:"#FF6347";s:9:"turquoise";s:7:"#40E0D0";s:6:"violet";s:7:"#EE82EE";s:5:"wheat";s:7:"#F5DEB3";s:5:"white";s:7:"#FFFFFF";s:10:"whitesmoke";s:7:"#F5F5F5";s:6:"yellow";s:7:"#FFFF00";s:11:"yellowgreen";s:7:"#9ACD32";}s:30:"Core.ConvertDocumentToFragment";b:1;s:36:"Core.DirectLexLineNumberSyncInterval";i:0;s:20:"Core.DisableExcludes";b:0;s:15:"Core.EnableIDNA";b:0;s:13:"Core.Encoding";s:5:"utf-8";s:26:"Core.EscapeInvalidChildren";b:0;s:22:"Core.EscapeInvalidTags";b:0;s:29:"Core.EscapeNonASCIICharacters";b:0;s:19:"Core.HiddenElements";a:2:{s:6:"script";b:1;s:5:"style";b:1;}s:13:"Core.Language";s:2:"en";s:24:"Core.LegacyEntityDecoder";b:0;s:14:"Core.LexerImpl";N;s:24:"Core.MaintainLineNumbers";N;s:22:"Core.NormalizeNewlines";b:1;s:21:"Core.RemoveInvalidImg";b:1;s:33:"Core.RemoveProcessingInstructions";b:0;s:25:"Core.RemoveScriptContents";N;s:13:"Filter.Custom";a:0:{}s:34:"Filter.ExtractStyleBlocks.Escaping";b:1;s:31:"Filter.ExtractStyleBlocks.Scope";N;s:34:"Filter.ExtractStyleBlocks.TidyImpl";N;s:25:"Filter.ExtractStyleBlocks";b:0;s:14:"Filter.YouTube";b:0;s:12:"HTML.Allowed";N;s:22:"HTML.AllowedAttributes";N;s:20:"HTML.AllowedComments";a:0:{}s:26:"HTML.AllowedCommentsRegexp";N;s:20:"HTML.AllowedElements";N;s:19:"HTML.AllowedModules";N;s:23:"HTML.Attr.Name.UseCDATA";b:0;s:17:"HTML.BlockWrapper";s:1:"p";s:16:"HTML.CoreModules";a:7:{s:9:"Structure";b:1;s:4:"Text";b:1;s:9:"Hypertext";b:1;s:4:"List";b:1;s:22:"NonXMLCommonAttributes";b:1;s:19:"XMLCommonAttributes";b:1;s:16:"CommonAttributes";b:1;}s:18:"HTML.CustomDoctype";N;s:17:"HTML.DefinitionID";N;s:18:"HTML.DefinitionRev";i:1;s:12:"HTML.Doctype";N;s:25:"HTML.FlashAllowFullScreen";b:0;s:24:"HTML.ForbiddenAttributes";a:0:{}s:22:"HTML.ForbiddenElements";a:0:{}s:17:"HTML.MaxImgLength";i:1200;s:13:"HTML.Nofollow";b:0;s:11:"HTML.Parent";s:3:"div";s:16:"HTML.Proprietary";b:0;s:14:"HTML.SafeEmbed";b:0;s:15:"HTML.SafeIframe";b:0;s:15:"HTML.SafeObject";b:0;s:18:"HTML.SafeScripting";a:0:{}s:11:"HTML.Strict";b:0;s:16:"HTML.TargetBlank";b:0;s:19:"HTML.TargetNoopener";b:1;s:21:"HTML.TargetNoreferrer";b:1;s:12:"HTML.TidyAdd";a:0:{}s:14:"HTML.TidyLevel";s:6:"medium";s:15:"HTML.TidyRemove";a:0:{}s:12:"HTML.Trusted";b:0;s:10:"HTML.XHTML";b:1;s:28:"Output.CommentScriptContents";b:1;s:19:"Output.FixInnerHTML";b:1;s:18:"Output.FlashCompat";b:0;s:14:"Output.Newline";N;s:15:"Output.SortAttr";b:0;s:17:"Output.TidyFormat";b:0;s:17:"Test.ForceNoIconv";b:0;s:18:"URI.AllowedSchemes";a:7:{s:4:"http";b:1;s:5:"https";b:1;s:6:"mailto";b:1;s:3:"ftp";b:1;s:4:"nntp";b:1;s:4:"news";b:1;s:3:"tel";b:1;}s:8:"URI.Base";N;s:17:"URI.DefaultScheme";s:4:"http";s:16:"URI.DefinitionID";N;s:17:"URI.DefinitionRev";i:1;s:11:"URI.Disable";b:0;s:19:"URI.DisableExternal";b:0;s:28:"URI.DisableExternalResources";b:0;s:20:"URI.DisableResources";b:0;s:8:"URI.Host";N;s:17:"URI.HostBlacklist";a:0:{}s:16:"URI.MakeAbsolute";b:0;s:9:"URI.Munge";N;s:18:"URI.MungeResources";b:0;s:18:"URI.MungeSecretKey";N;s:26:"URI.OverrideAllowedSchemes";b:1;s:20:"URI.SafeIframeRegexp";N;}s:12:"defaultPlist";O:25:"HTMLPurifier_PropertyList":3:{s:7:"\0*\0data";a:126:{s:19:"Attr.AllowedClasses";N;s:24:"Attr.AllowedFrameTargets";a:0:{}s:15:"Attr.AllowedRel";a:0:{}s:15:"Attr.AllowedRev";a:0:{}s:18:"Attr.ClassUseCDATA";N;s:20:"Attr.DefaultImageAlt";N;s:24:"Attr.DefaultInvalidImage";s:0:"";s:27:"Attr.DefaultInvalidImageAlt";s:13:"Invalid image";s:19:"Attr.DefaultTextDir";s:3:"ltr";s:13:"Attr.EnableID";b:0;s:21:"Attr.ForbiddenClasses";a:0:{}s:13:"Attr.ID.HTML5";N;s:16:"Attr.IDBlacklist";a:0:{}s:22:"Attr.IDBlacklistRegexp";N;s:13:"Attr.IDPrefix";s:0:"";s:18:"Attr.IDPrefixLocal";s:0:"";s:24:"AutoFormat.AutoParagraph";b:0;s:17:"AutoFormat.Custom";a:0:{}s:25:"AutoFormat.DisplayLinkURI";b:0;s:18:"AutoFormat.Linkify";b:0;s:33:"AutoFormat.PurifierLinkify.DocURL";s:3:"#%s";s:26:"AutoFormat.PurifierLinkify";b:0;s:32:"AutoFormat.RemoveEmpty.Predicate";a:4:{s:8:"colgroup";a:0:{}s:2:"th";a:0:{}s:2:"td";a:0:{}s:6:"iframe";a:1:{i:0;s:3:"src";}}s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";a:2:{s:2:"td";b:1;s:2:"th";b:1;}s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";b:0;s:22:"AutoFormat.RemoveEmpty";b:0;s:39:"AutoFormat.RemoveSpansWithoutAttributes";b:0;s:19:"CSS.AllowDuplicates";b:0;s:18:"CSS.AllowImportant";b:0;s:15:"CSS.AllowTricky";b:0;s:16:"CSS.AllowedFonts";N;s:21:"CSS.AllowedProperties";N;s:17:"CSS.DefinitionRev";i:1;s:23:"CSS.ForbiddenProperties";a:0:{}s:16:"CSS.MaxImgLength";s:6:"1200px";s:15:"CSS.Proprietary";b:0;s:11:"CSS.Trusted";b:0;s:20:"Cache.DefinitionImpl";s:10:"Serializer";s:20:"Cache.SerializerPath";N;s:27:"Cache.SerializerPermissions";i:493;s:22:"Core.AggressivelyFixLt";b:1;s:29:"Core.AggressivelyRemoveScript";b:1;s:28:"Core.AllowHostnameUnderscore";b:0;s:23:"Core.AllowParseManyTags";b:0;s:18:"Core.CollectErrors";b:0;s:18:"Core.ColorKeywords";a:148:{s:9:"aliceblue";s:7:"#F0F8FF";s:12:"antiquewhite";s:7:"#FAEBD7";s:4:"aqua";s:7:"#00FFFF";s:10:"aquamarine";s:7:"#7FFFD4";s:5:"azure";s:7:"#F0FFFF";s:5:"beige";s:7:"#F5F5DC";s:6:"bisque";s:7:"#FFE4C4";s:5:"black";s:7:"#000000";s:14:"blanchedalmond";s:7:"#FFEBCD";s:4:"blue";s:7:"#0000FF";s:10:"blueviolet";s:7:"#8A2BE2";s:5:"brown";s:7:"#A52A2A";s:9:"burlywood";s:7:"#DEB887";s:9:"cadetblue";s:7:"#5F9EA0";s:10:"chartreuse";s:7:"#7FFF00";s:9:"chocolate";s:7:"#D2691E";s:5:"coral";s:7:"#FF7F50";s:14:"cornflowerblue";s:7:"#6495ED";s:8:"cornsilk";s:7:"#FFF8DC";s:7:"crimson";s:7:"#DC143C";s:4:"cyan";s:7:"#00FFFF";s:8:"darkblue";s:7:"#00008B";s:8:"darkcyan";s:7:"#008B8B";s:13:"darkgoldenrod";s:7:"#B8860B";s:8:"darkgray";s:7:"#A9A9A9";s:8:"darkgrey";s:7:"#A9A9A9";s:9:"darkgreen";s:7:"#006400";s:9:"darkkhaki";s:7:"#BDB76B";s:11:"darkmagenta";s:7:"#8B008B";s:14:"darkolivegreen";s:7:"#556B2F";s:10:"darkorange";s:7:"#FF8C00";s:10:"darkorchid";s:7:"#9932CC";s:7:"darkred";s:7:"#8B0000";s:10:"darksalmon";s:7:"#E9967A";s:12:"darkseagreen";s:7:"#8FBC8F";s:13:"darkslateblue";s:7:"#483D8B";s:13:"darkslategray";s:7:"#2F4F4F";s:13:"darkslategrey";s:7:"#2F4F4F";s:13:"darkturquoise";s:7:"#00CED1";s:10:"darkviolet";s:7:"#9400D3";s:8:"deeppink";s:7:"#FF1493";s:11:"deepskyblue";s:7:"#00BFFF";s:7:"dimgray";s:7:"#696969";s:7:"dimgrey";s:7:"#696969";s:10:"dodgerblue";s:7:"#1E90FF";s:9:"firebrick";s:7:"#B22222";s:11:"floralwhite";s:7:"#FFFAF0";s:11:"forestgreen";s:7:"#228B22";s:7:"fuchsia";s:7:"#FF00FF";s:9:"gainsboro";s:7:"#DCDCDC";s:10:"ghostwhite";s:7:"#F8F8FF";s:4:"gold";s:7:"#FFD700";s:9:"goldenrod";s:7:"#DAA520";s:4:"gray";s:7:"#808080";s:4:"grey";s:7:"#808080";s:5:"green";s:7:"#008000";s:11:"greenyellow";s:7:"#ADFF2F";s:8:"honeydew";s:7:"#F0FFF0";s:7:"hotpink";s:7:"#FF69B4";s:9:"indianred";s:7:"#CD5C5C";s:6:"indigo";s:7:"#4B0082";s:5:"ivory";s:7:"#FFFFF0";s:5:"khaki";s:7:"#F0E68C";s:8:"lavender";s:7:"#E6E6FA";s:13:"lavenderblush";s:7:"#FFF0F5";s:9:"lawngreen";s:7:"#7CFC00";s:12:"lemonchiffon";s:7:"#FFFACD";s:9:"lightblue";s:7:"#ADD8E6";s:10:"lightcoral";s:7:"#F08080";s:9:"lightcyan";s:7:"#E0FFFF";s:20:"lightgoldenrodyellow";s:7:"#FAFAD2";s:9:"lightgray";s:7:"#D3D3D3";s:9:"lightgrey";s:7:"#D3D3D3";s:10:"lightgreen";s:7:"#90EE90";s:9:"lightpink";s:7:"#FFB6C1";s:11:"lightsalmon";s:7:"#FFA07A";s:13:"lightseagreen";s:7:"#20B2AA";s:12:"lightskyblue";s:7:"#87CEFA";s:14:"lightslategray";s:7:"#778899";s:14:"lightslategrey";s:7:"#778899";s:14:"lightsteelblue";s:7:"#B0C4DE";s:11:"lightyellow";s:7:"#FFFFE0";s:4:"lime";s:7:"#00FF00";s:9:"limegreen";s:7:"#32CD32";s:5:"linen";s:7:"#FAF0E6";s:7:"magenta";s:7:"#FF00FF";s:6:"maroon";s:7:"#800000";s:16:"mediumaquamarine";s:7:"#66CDAA";s:10:"mediumblue";s:7:"#0000CD";s:12:"mediumorchid";s:7:"#BA55D3";s:12:"mediumpurple";s:7:"#9370DB";s:14:"mediumseagreen";s:7:"#3CB371";s:15:"mediumslateblue";s:7:"#7B68EE";s:17:"mediumspringgreen";s:7:"#00FA9A";s:15:"mediumturquoise";s:7:"#48D1CC";s:15:"mediumvioletred";s:7:"#C71585";s:12:"midnightblue";s:7:"#191970";s:9:"mintcream";s:7:"#F5FFFA";s:9:"mistyrose";s:7:"#FFE4E1";s:8:"moccasin";s:7:"#FFE4B5";s:11:"navajowhite";s:7:"#FFDEAD";s:4:"navy";s:7:"#000080";s:7:"oldlace";s:7:"#FDF5E6";s:5:"olive";s:7:"#808000";s:9:"olivedrab";s:7:"#6B8E23";s:6:"orange";s:7:"#FFA500";s:9:"orangered";s:7:"#FF4500";s:6:"orchid";s:7:"#DA70D6";s:13:"palegoldenrod";s:7:"#EEE8AA";s:9:"palegreen";s:7:"#98FB98";s:13:"paleturquoise";s:7:"#AFEEEE";s:13:"palevioletred";s:7:"#DB7093";s:10:"papayawhip";s:7:"#FFEFD5";s:9:"peachpuff";s:7:"#FFDAB9";s:4:"peru";s:7:"#CD853F";s:4:"pink";s:7:"#FFC0CB";s:4:"plum";s:7:"#DDA0DD";s:10:"powderblue";s:7:"#B0E0E6";s:6:"purple";s:7:"#800080";s:13:"rebeccapurple";s:7:"#663399";s:3:"red";s:7:"#FF0000";s:9:"rosybrown";s:7:"#BC8F8F";s:9:"royalblue";s:7:"#4169E1";s:11:"saddlebrown";s:7:"#8B4513";s:6:"salmon";s:7:"#FA8072";s:10:"sandybrown";s:7:"#F4A460";s:8:"seagreen";s:7:"#2E8B57";s:8:"seashell";s:7:"#FFF5EE";s:6:"sienna";s:7:"#A0522D";s:6:"silver";s:7:"#C0C0C0";s:7:"skyblue";s:7:"#87CEEB";s:9:"slateblue";s:7:"#6A5ACD";s:9:"slategray";s:7:"#708090";s:9:"slategrey";s:7:"#708090";s:4:"snow";s:7:"#FFFAFA";s:11:"springgreen";s:7:"#00FF7F";s:9:"steelblue";s:7:"#4682B4";s:3:"tan";s:7:"#D2B48C";s:4:"teal";s:7:"#008080";s:7:"thistle";s:7:"#D8BFD8";s:6:"tomato";s:7:"#FF6347";s:9:"turquoise";s:7:"#40E0D0";s:6:"violet";s:7:"#EE82EE";s:5:"wheat";s:7:"#F5DEB3";s:5:"white";s:7:"#FFFFFF";s:10:"whitesmoke";s:7:"#F5F5F5";s:6:"yellow";s:7:"#FFFF00";s:11:"yellowgreen";s:7:"#9ACD32";}s:30:"Core.ConvertDocumentToFragment";b:1;s:36:"Core.DirectLexLineNumberSyncInterval";i:0;s:20:"Core.DisableExcludes";b:0;s:15:"Core.EnableIDNA";b:0;s:13:"Core.Encoding";s:5:"utf-8";s:26:"Core.EscapeInvalidChildren";b:0;s:22:"Core.EscapeInvalidTags";b:0;s:29:"Core.EscapeNonASCIICharacters";b:0;s:19:"Core.HiddenElements";a:2:{s:6:"script";b:1;s:5:"style";b:1;}s:13:"Core.Language";s:2:"en";s:24:"Core.LegacyEntityDecoder";b:0;s:14:"Core.LexerImpl";N;s:24:"Core.MaintainLineNumbers";N;s:22:"Core.NormalizeNewlines";b:1;s:21:"Core.RemoveInvalidImg";b:1;s:33:"Core.RemoveProcessingInstructions";b:0;s:25:"Core.RemoveScriptContents";N;s:13:"Filter.Custom";a:0:{}s:34:"Filter.ExtractStyleBlocks.Escaping";b:1;s:31:"Filter.ExtractStyleBlocks.Scope";N;s:34:"Filter.ExtractStyleBlocks.TidyImpl";N;s:25:"Filter.ExtractStyleBlocks";b:0;s:14:"Filter.YouTube";b:0;s:12:"HTML.Allowed";N;s:22:"HTML.AllowedAttributes";N;s:20:"HTML.AllowedComments";a:0:{}s:26:"HTML.AllowedCommentsRegexp";N;s:20:"HTML.AllowedElements";N;s:19:"HTML.AllowedModules";N;s:23:"HTML.Attr.Name.UseCDATA";b:0;s:17:"HTML.BlockWrapper";s:1:"p";s:16:"HTML.CoreModules";a:7:{s:9:"Structure";b:1;s:4:"Text";b:1;s:9:"Hypertext";b:1;s:4:"List";b:1;s:22:"NonXMLCommonAttributes";b:1;s:19:"XMLCommonAttributes";b:1;s:16:"CommonAttributes";b:1;}s:18:"HTML.CustomDoctype";N;s:17:"HTML.DefinitionID";N;s:18:"HTML.DefinitionRev";i:1;s:12:"HTML.Doctype";N;s:25:"HTML.FlashAllowFullScreen";b:0;s:24:"HTML.ForbiddenAttributes";a:0:{}s:22:"HTML.ForbiddenElements";a:0:{}s:17:"HTML.MaxImgLength";i:1200;s:13:"HTML.Nofollow";b:0;s:11:"HTML.Parent";s:3:"div";s:16:"HTML.Proprietary";b:0;s:14:"HTML.SafeEmbed";b:0;s:15:"HTML.SafeIframe";b:0;s:15:"HTML.SafeObject";b:0;s:18:"HTML.SafeScripting";a:0:{}s:11:"HTML.Strict";b:0;s:16:"HTML.TargetBlank";b:0;s:19:"HTML.TargetNoopener";b:1;s:21:"HTML.TargetNoreferrer";b:1;s:12:"HTML.TidyAdd";a:0:{}s:14:"HTML.TidyLevel";s:6:"medium";s:15:"HTML.TidyRemove";a:0:{}s:12:"HTML.Trusted";b:0;s:10:"HTML.XHTML";b:1;s:28:"Output.CommentScriptContents";b:1;s:19:"Output.FixInnerHTML";b:1;s:18:"Output.FlashCompat";b:0;s:14:"Output.Newline";N;s:15:"Output.SortAttr";b:0;s:17:"Output.TidyFormat";b:0;s:17:"Test.ForceNoIconv";b:0;s:18:"URI.AllowedSchemes";a:7:{s:4:"http";b:1;s:5:"https";b:1;s:6:"mailto";b:1;s:3:"ftp";b:1;s:4:"nntp";b:1;s:4:"news";b:1;s:3:"tel";b:1;}s:8:"URI.Base";N;s:17:"URI.DefaultScheme";s:4:"http";s:16:"URI.DefinitionID";N;s:17:"URI.DefinitionRev";i:1;s:11:"URI.Disable";b:0;s:19:"URI.DisableExternal";b:0;s:28:"URI.DisableExternalResources";b:0;s:20:"URI.DisableResources";b:0;s:8:"URI.Host";N;s:17:"URI.HostBlacklist";a:0:{}s:16:"URI.MakeAbsolute";b:0;s:9:"URI.Munge";N;s:18:"URI.MungeResources";b:0;s:18:"URI.MungeSecretKey";N;s:26:"URI.OverrideAllowedSchemes";b:1;s:20:"URI.SafeIframeRegexp";N;}s:9:"\0*\0parent";N;s:8:"\0*\0cache";N;}s:4:"info";a:139:{s:19:"Attr.AllowedClasses";i:-8;s:24:"Attr.AllowedFrameTargets";i:8;s:15:"Attr.AllowedRel";i:8;s:15:"Attr.AllowedRev";i:8;s:18:"Attr.ClassUseCDATA";i:-7;s:20:"Attr.DefaultImageAlt";i:-1;s:24:"Attr.DefaultInvalidImage";i:1;s:27:"Attr.DefaultInvalidImageAlt";i:1;s:19:"Attr.DefaultTextDir";O:8:"stdClass":2:{s:4:"type";i:1;s:7:"allowed";a:2:{s:3:"ltr";b:1;s:3:"rtl";b:1;}}s:13:"Attr.EnableID";i:7;s:17:"HTML.EnableAttrID";O:8:"stdClass":2:{s:3:"key";s:13:"Attr.EnableID";s:7:"isAlias";b:1;}s:21:"Attr.ForbiddenClasses";i:8;s:13:"Attr.ID.HTML5";i:-7;s:16:"Attr.IDBlacklist";i:9;s:22:"Attr.IDBlacklistRegexp";i:-1;s:13:"Attr.IDPrefix";i:1;s:18:"Attr.IDPrefixLocal";i:1;s:24:"AutoFormat.AutoParagraph";i:7;s:17:"AutoFormat.Custom";i:9;s:25:"AutoFormat.DisplayLinkURI";i:7;s:18:"AutoFormat.Linkify";i:7;s:33:"AutoFormat.PurifierLinkify.DocURL";i:1;s:37:"AutoFormatParam.PurifierLinkifyDocURL";O:8:"stdClass":2:{s:3:"key";s:33:"AutoFormat.PurifierLinkify.DocURL";s:7:"isAlias";b:1;}s:26:"AutoFormat.PurifierLinkify";i:7;s:32:"AutoFormat.RemoveEmpty.Predicate";i:10;s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";i:8;s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";i:7;s:22:"AutoFormat.RemoveEmpty";i:7;s:39:"AutoFormat.RemoveSpansWithoutAttributes";i:7;s:19:"CSS.AllowDuplicates";i:7;s:18:"CSS.AllowImportant";i:7;s:15:"CSS.AllowTricky";i:7;s:16:"CSS.AllowedFonts";i:-8;s:21:"CSS.AllowedProperties";i:-8;s:17:"CSS.DefinitionRev";i:5;s:23:"CSS.ForbiddenProperties";i:8;s:16:"CSS.MaxImgLength";i:-1;s:15:"CSS.Proprietary";i:7;s:11:"CSS.Trusted";i:7;s:20:"Cache.DefinitionImpl";i:-1;s:20:"Core.DefinitionCache";O:8:"stdClass":2:{s:3:"key";s:20:"Cache.DefinitionImpl";s:7:"isAlias";b:1;}s:20:"Cache.SerializerPath";i:-1;s:27:"Cache.SerializerPermissions";i:-5;s:22:"Core.AggressivelyFixLt";i:7;s:29:"Core.AggressivelyRemoveScript";i:7;s:28:"Core.AllowHostnameUnderscore";i:7;s:23:"Core.AllowParseManyTags";i:7;s:18:"Core.CollectErrors";i:7;s:18:"Core.ColorKeywords";i:10;s:30:"Core.ConvertDocumentToFragment";i:7;s:24:"Core.AcceptFullDocuments";O:8:"stdClass":2:{s:3:"key";s:30:"Core.ConvertDocumentToFragment";s:7:"isAlias";b:1;}s:36:"Core.DirectLexLineNumberSyncInterval";i:5;s:20:"Core.DisableExcludes";i:7;s:15:"Core.EnableIDNA";i:7;s:13:"Core.Encoding";i:2;s:26:"Core.EscapeInvalidChildren";i:7;s:22:"Core.EscapeInvalidTags";i:7;s:29:"Core.EscapeNonASCIICharacters";i:7;s:19:"Core.HiddenElements";i:8;s:13:"Core.Language";i:1;s:24:"Core.LegacyEntityDecoder";i:7;s:14:"Core.LexerImpl";i:-11;s:24:"Core.MaintainLineNumbers";i:-7;s:22:"Core.NormalizeNewlines";i:7;s:21:"Core.RemoveInvalidImg";i:7;s:33:"Core.RemoveProcessingInstructions";i:7;s:25:"Core.RemoveScriptContents";i:-7;s:13:"Filter.Custom";i:9;s:34:"Filter.ExtractStyleBlocks.Escaping";i:7;s:33:"Filter.ExtractStyleBlocksEscaping";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.Escaping";s:7:"isAlias";b:1;}s:38:"FilterParam.ExtractStyleBlocksEscaping";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.Escaping";s:7:"isAlias";b:1;}s:31:"Filter.ExtractStyleBlocks.Scope";i:-1;s:30:"Filter.ExtractStyleBlocksScope";O:8:"stdClass":2:{s:3:"key";s:31:"Filter.ExtractStyleBlocks.Scope";s:7:"isAlias";b:1;}s:35:"FilterParam.ExtractStyleBlocksScope";O:8:"stdClass":2:{s:3:"key";s:31:"Filter.ExtractStyleBlocks.Scope";s:7:"isAlias";b:1;}s:34:"Filter.ExtractStyleBlocks.TidyImpl";i:-11;s:38:"FilterParam.ExtractStyleBlocksTidyImpl";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.TidyImpl";s:7:"isAlias";b:1;}s:25:"Filter.ExtractStyleBlocks";i:7;s:14:"Filter.YouTube";i:7;s:12:"HTML.Allowed";i:-4;s:22:"HTML.AllowedAttributes";i:-8;s:20:"HTML.AllowedComments";i:8;s:26:"HTML.AllowedCommentsRegexp";i:-1;s:20:"HTML.AllowedElements";i:-8;s:19:"HTML.AllowedModules";i:-8;s:23:"HTML.Attr.Name.UseCDATA";i:7;s:17:"HTML.BlockWrapper";i:1;s:16:"HTML.CoreModules";i:8;s:18:"HTML.CustomDoctype";i:-1;s:17:"HTML.DefinitionID";i:-1;s:18:"HTML.DefinitionRev";i:5;s:12:"HTML.Doctype";O:8:"stdClass":3:{s:4:"type";i:1;s:10:"allow_null";b:1;s:7:"allowed";a:5:{s:22:"HTML 4.01 Transitional";b:1;s:16:"HTML 4.01 Strict";b:1;s:22:"XHTML 1.0 Transitional";b:1;s:16:"XHTML 1.0 Strict";b:1;s:9:"XHTML 1.1";b:1;}}s:25:"HTML.FlashAllowFullScreen";i:7;s:24:"HTML.ForbiddenAttributes";i:8;s:22:"HTML.ForbiddenElements";i:8;s:17:"HTML.MaxImgLength";i:-5;s:13:"HTML.Nofollow";i:7;s:11:"HTML.Parent";i:1;s:16:"HTML.Proprietary";i:7;s:14:"HTML.SafeEmbed";i:7;s:15:"HTML.SafeIframe";i:7;s:15:"HTML.SafeObject";i:7;s:18:"HTML.SafeScripting";i:8;s:11:"HTML.Strict";i:7;s:16:"HTML.TargetBlank";i:7;s:19:"HTML.TargetNoopener";i:7;s:21:"HTML.TargetNoreferrer";i:7;s:12:"HTML.TidyAdd";i:8;s:14:"HTML.TidyLevel";O:8:"stdClass":2:{s:4:"type";i:1;s:7:"allowed";a:4:{s:4:"none";b:1;s:5:"light";b:1;s:6:"medium";b:1;s:5:"heavy";b:1;}}s:15:"HTML.TidyRemove";i:8;s:12:"HTML.Trusted";i:7;s:10:"HTML.XHTML";i:7;s:10:"Core.XHTML";O:8:"stdClass":2:{s:3:"key";s:10:"HTML.XHTML";s:7:"isAlias";b:1;}s:28:"Output.CommentScriptContents";i:7;s:26:"Core.CommentScriptContents";O:8:"stdClass":2:{s:3:"key";s:28:"Output.CommentScriptContents";s:7:"isAlias";b:1;}s:19:"Output.FixInnerHTML";i:7;s:18:"Output.FlashCompat";i:7;s:14:"Output.Newline";i:-1;s:15:"Output.SortAttr";i:7;s:17:"Output.TidyFormat";i:7;s:15:"Core.TidyFormat";O:8:"stdClass":2:{s:3:"key";s:17:"Output.TidyFormat";s:7:"isAlias";b:1;}s:17:"Test.ForceNoIconv";i:7;s:18:"URI.AllowedSchemes";i:8;s:8:"URI.Base";i:-1;s:17:"URI.DefaultScheme";i:-1;s:16:"URI.DefinitionID";i:-1;s:17:"URI.DefinitionRev";i:5;s:11:"URI.Disable";i:7;s:15:"Attr.DisableURI";O:8:"stdClass":2:{s:3:"key";s:11:"URI.Disable";s:7:"isAlias";b:1;}s:19:"URI.DisableExternal";i:7;s:28:"URI.DisableExternalResources";i:7;s:20:"URI.DisableResources";i:7;s:8:"URI.Host";i:-1;s:17:"URI.HostBlacklist";i:9;s:16:"URI.MakeAbsolute";i:7;s:9:"URI.Munge";i:-1;s:18:"URI.MungeResources";i:7;s:18:"URI.MungeSecretKey";i:-1;s:26:"URI.OverrideAllowedSchemes";i:7;s:20:"URI.SafeIframeRegexp";i:-1;}}
\ No newline at end of file
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt
new file mode 100644 (file)
index 0000000..4a42382
--- /dev/null
@@ -0,0 +1,8 @@
+Attr.AllowedClasses\r
+TYPE: lookup/null\r
+VERSION: 4.0.0\r
+DEFAULT: null\r
+--DESCRIPTION--\r
+List of allowed class values in the class attribute. By default, this is null,\r
+which means all classes are allowed.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt
new file mode 100644 (file)
index 0000000..b033eb5
--- /dev/null
@@ -0,0 +1,12 @@
+Attr.AllowedFrameTargets\r
+TYPE: lookup\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+Lookup table of all allowed link frame targets.  Some commonly used link\r
+targets include _blank, _self, _parent and _top. Values should be\r
+lowercase, as validation will be done in a case-sensitive manner despite\r
+W3C's recommendation. XHTML 1.0 Strict does not permit the target attribute\r
+so this directive will have no effect in that doctype. XHTML 1.1 does not\r
+enable the Target module by default, you will have to manually enable it\r
+(see the module documentation for more details.)\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt
new file mode 100644 (file)
index 0000000..ed72a9d
--- /dev/null
@@ -0,0 +1,9 @@
+Attr.AllowedRel\r
+TYPE: lookup\r
+VERSION: 1.6.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+List of allowed forward document relationships in the rel attribute. Common\r
+values may be nofollow or print. By default, this is empty, meaning that no\r
+document relationships are allowed.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt
new file mode 100644 (file)
index 0000000..1ae672d
--- /dev/null
@@ -0,0 +1,9 @@
+Attr.AllowedRev\r
+TYPE: lookup\r
+VERSION: 1.6.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+List of allowed reverse document relationships in the rev attribute. This\r
+attribute is a bit of an edge-case; if you don't know what it is for, stay\r
+away.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt
new file mode 100644 (file)
index 0000000..119a9d2
--- /dev/null
@@ -0,0 +1,19 @@
+Attr.ClassUseCDATA\r
+TYPE: bool/null\r
+DEFAULT: null\r
+VERSION: 4.0.0\r
+--DESCRIPTION--\r
+If null, class will auto-detect the doctype and, if matching XHTML 1.1 or\r
+XHTML 2.0, will use the restrictive NMTOKENS specification of class. Otherwise,\r
+it will use a relaxed CDATA definition.  If true, the relaxed CDATA definition\r
+is forced; if false, the NMTOKENS definition is forced.  To get behavior\r
+of HTML Purifier prior to 4.0.0, set this directive to false.\r
+\r
+Some rational behind the auto-detection:\r
+in previous versions of HTML Purifier, it was assumed that the form of\r
+class was NMTOKENS, as specified by the XHTML Modularization (representing\r
+XHTML 1.1 and XHTML 2.0).  The DTDs for HTML 4.01 and XHTML 1.0, however\r
+specify class as CDATA.  HTML 5 effectively defines it as CDATA, but\r
+with the additional constraint that each name should be unique (this is not\r
+explicitly outlined in previous specifications).\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt
new file mode 100644 (file)
index 0000000..80b1431
--- /dev/null
@@ -0,0 +1,11 @@
+Attr.DefaultImageAlt\r
+TYPE: string/null\r
+DEFAULT: null\r
+VERSION: 3.2.0\r
+--DESCRIPTION--\r
+This is the content of the alt tag of an image if the user had not\r
+previously specified an alt attribute.  This applies to all images without\r
+a valid alt attribute, as opposed to %Attr.DefaultInvalidImageAlt, which\r
+only applies to invalid images, and overrides in the case of an invalid image.\r
+Default behavior with null is to use the basename of the src tag for the alt.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt
new file mode 100644 (file)
index 0000000..c51000d
--- /dev/null
@@ -0,0 +1,9 @@
+Attr.DefaultInvalidImage\r
+TYPE: string\r
+DEFAULT: ''\r
+--DESCRIPTION--\r
+This is the default image an img tag will be pointed to if it does not have\r
+a valid src attribute.  In future versions, we may allow the image tag to\r
+be removed completely, but due to design issues, this is not possible right\r
+now.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt
new file mode 100644 (file)
index 0000000..c1ec4b0
--- /dev/null
@@ -0,0 +1,8 @@
+Attr.DefaultInvalidImageAlt\r
+TYPE: string\r
+DEFAULT: 'Invalid image'\r
+--DESCRIPTION--\r
+This is the content of the alt tag of an invalid image if the user had not\r
+previously specified an alt attribute.  It has no effect when the image is\r
+valid but there was no alt attribute present.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt
new file mode 100644 (file)
index 0000000..f57dcc4
--- /dev/null
@@ -0,0 +1,10 @@
+Attr.DefaultTextDir\r
+TYPE: string\r
+DEFAULT: 'ltr'\r
+--DESCRIPTION--\r
+Defines the default text direction (ltr or rtl) of the document being\r
+parsed.  This generally is the same as the value of the dir attribute in\r
+HTML, or ltr if that is not specified.\r
+--ALLOWED--\r
+'ltr', 'rtl'\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt
new file mode 100644 (file)
index 0000000..9b93a55
--- /dev/null
@@ -0,0 +1,16 @@
+Attr.EnableID\r
+TYPE: bool\r
+DEFAULT: false\r
+VERSION: 1.2.0\r
+--DESCRIPTION--\r
+Allows the ID attribute in HTML.  This is disabled by default due to the\r
+fact that without proper configuration user input can easily break the\r
+validation of a webpage by specifying an ID that is already on the\r
+surrounding HTML.  If you don't mind throwing caution to the wind, enable\r
+this directive, but I strongly recommend you also consider blacklisting IDs\r
+you use (%Attr.IDBlacklist) or prefixing all user supplied IDs\r
+(%Attr.IDPrefix).  When set to true HTML Purifier reverts to the behavior of\r
+pre-1.2.0 versions.\r
+--ALIASES--\r
+HTML.EnableAttrID\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt
new file mode 100644 (file)
index 0000000..fed8954
--- /dev/null
@@ -0,0 +1,8 @@
+Attr.ForbiddenClasses\r
+TYPE: lookup\r
+VERSION: 4.0.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+List of forbidden class values in the class attribute. By default, this is\r
+empty, which means that no classes are forbidden. See also %Attr.AllowedClasses.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt
new file mode 100644 (file)
index 0000000..c48e62f
--- /dev/null
@@ -0,0 +1,10 @@
+Attr.ID.HTML5\r
+TYPE: bool/null\r
+DEFAULT: null\r
+VERSION: 4.8.0\r
+--DESCRIPTION--\r
+In HTML5, restrictions on the format of the id attribute have been significantly\r
+relaxed, such that any string is valid so long as it contains no spaces and\r
+is at least one character.  In lieu of a general HTML5 compatibility flag,\r
+set this configuration directive to true to use the relaxed rules.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt
new file mode 100644 (file)
index 0000000..52168bb
--- /dev/null
@@ -0,0 +1,5 @@
+Attr.IDBlacklist\r
+TYPE: list\r
+DEFAULT: array()\r
+DESCRIPTION: Array of IDs not allowed in the document.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt
new file mode 100644 (file)
index 0000000..7b85043
--- /dev/null
@@ -0,0 +1,9 @@
+Attr.IDBlacklistRegexp\r
+TYPE: string/null\r
+VERSION: 1.6.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+PCRE regular expression to be matched against all IDs. If the expression is\r
+matches, the ID is rejected. Use this with care: may cause significant\r
+degradation. ID matching is done after all other validation.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt
new file mode 100644 (file)
index 0000000..5781382
--- /dev/null
@@ -0,0 +1,12 @@
+Attr.IDPrefix\r
+TYPE: string\r
+VERSION: 1.2.0\r
+DEFAULT: ''\r
+--DESCRIPTION--\r
+String to prefix to IDs.  If you have no idea what IDs your pages may use,\r
+you may opt to simply add a prefix to all user-submitted ID attributes so\r
+that they are still usable, but will not conflict with core page IDs.\r
+Example: setting the directive to 'user_' will result in a user submitted\r
+'foo' to become 'user_foo'  Be sure to set %HTML.EnableAttrID to true\r
+before using this.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt
new file mode 100644 (file)
index 0000000..f91fcd6
--- /dev/null
@@ -0,0 +1,14 @@
+Attr.IDPrefixLocal\r
+TYPE: string\r
+VERSION: 1.2.0\r
+DEFAULT: ''\r
+--DESCRIPTION--\r
+Temporary prefix for IDs used in conjunction with %Attr.IDPrefix.  If you\r
+need to allow multiple sets of user content on web page, you may need to\r
+have a seperate prefix that changes with each iteration.  This way,\r
+seperately submitted user content displayed on the same page doesn't\r
+clobber each other. Ideal values are unique identifiers for the content it\r
+represents (i.e. the id of the row in the database). Be sure to add a\r
+seperator (like an underscore) at the end.  Warning: this directive will\r
+not work unless %Attr.IDPrefix is set to a non-empty value!\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt
new file mode 100644 (file)
index 0000000..2d7f94e
--- /dev/null
@@ -0,0 +1,31 @@
+AutoFormat.AutoParagraph\r
+TYPE: bool\r
+VERSION: 2.0.1\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  This directive turns on auto-paragraphing, where double newlines are\r
+  converted in to paragraphs whenever possible. Auto-paragraphing:\r
+</p>\r
+<ul>\r
+  <li>Always applies to inline elements or text in the root node,</li>\r
+  <li>Applies to inline elements or text with double newlines in nodes\r
+      that allow paragraph tags,</li>\r
+  <li>Applies to double newlines in paragraph tags</li>\r
+</ul>\r
+<p>\r
+  <code>p</code> tags must be allowed for this directive to take effect.\r
+  We do not use <code>br</code> tags for paragraphing, as that is\r
+  semantically incorrect.\r
+</p>\r
+<p>\r
+  To prevent auto-paragraphing as a content-producer, refrain from using\r
+  double-newlines except to specify a new paragraph or in contexts where\r
+  it has special meaning (whitespace usually has no meaning except in\r
+  tags like <code>pre</code>, so this should not be difficult.) To prevent\r
+  the paragraphing of inline text adjacent to block elements, wrap them\r
+  in <code>div</code> tags (the behavior is slightly different outside of\r
+  the root node.)\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt
new file mode 100644 (file)
index 0000000..2eb1974
--- /dev/null
@@ -0,0 +1,12 @@
+AutoFormat.Custom\r
+TYPE: list\r
+VERSION: 2.0.1\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  This directive can be used to add custom auto-format injectors.\r
+  Specify an array of injector names (class name minus the prefix)\r
+  or concrete implementations. Injector class must exist.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt
new file mode 100644 (file)
index 0000000..c955de7
--- /dev/null
@@ -0,0 +1,11 @@
+AutoFormat.DisplayLinkURI\r
+TYPE: bool\r
+VERSION: 3.2.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+  This directive turns on the in-text display of URIs in &lt;a&gt; tags, and disables\r
+  those links. For example, <a href="http://example.com">example</a> becomes\r
+  example (<a>http://example.com</a>).\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt
new file mode 100644 (file)
index 0000000..328b2b2
--- /dev/null
@@ -0,0 +1,12 @@
+AutoFormat.Linkify\r
+TYPE: bool\r
+VERSION: 2.0.1\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  This directive turns on linkification, auto-linking http, ftp and\r
+  https URLs. <code>a</code> tags with the <code>href</code> attribute\r
+  must be allowed.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt
new file mode 100644 (file)
index 0000000..d0532b6
--- /dev/null
@@ -0,0 +1,12 @@
+AutoFormat.PurifierLinkify.DocURL\r
+TYPE: string\r
+VERSION: 2.0.1\r
+DEFAULT: '#%s'\r
+ALIASES: AutoFormatParam.PurifierLinkifyDocURL\r
+--DESCRIPTION--\r
+<p>\r
+  Location of configuration documentation to link to, let %s substitute\r
+  into the configuration's namespace and directive names sans the percent\r
+  sign.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt
new file mode 100644 (file)
index 0000000..f3ab259
--- /dev/null
@@ -0,0 +1,12 @@
+AutoFormat.PurifierLinkify\r
+TYPE: bool\r
+VERSION: 2.0.1\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  Internal auto-formatter that converts configuration directives in\r
+  syntax <a>%Namespace.Directive</a> to links. <code>a</code> tags\r
+  with the <code>href</code> attribute must be allowed.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt
new file mode 100644 (file)
index 0000000..376f771
--- /dev/null
@@ -0,0 +1,14 @@
+AutoFormat.RemoveEmpty.Predicate\r
+TYPE: hash\r
+VERSION: 4.7.0\r
+DEFAULT: array('colgroup' => array(), 'th' => array(), 'td' => array(), 'iframe' => array('src'))\r
+--DESCRIPTION--\r
+<p>\r
+  Given that an element has no contents, it will be removed by default, unless\r
+  this predicate dictates otherwise.  The predicate can either be an associative\r
+  map from tag name to list of attributes that must be present for the element\r
+  to be considered preserved: thus, the default always preserves <code>colgroup</code>,\r
+  <code>th</code> and <code>td</code>, and also <code>iframe</code> if it\r
+  has a <code>src</code>.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt
new file mode 100644 (file)
index 0000000..219d04a
--- /dev/null
@@ -0,0 +1,11 @@
+AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions\r
+TYPE: lookup\r
+VERSION: 4.0.0\r
+DEFAULT: array('td' => true, 'th' => true)\r
+--DESCRIPTION--\r
+<p>\r
+  When %AutoFormat.RemoveEmpty and %AutoFormat.RemoveEmpty.RemoveNbsp\r
+  are enabled, this directive defines what HTML elements should not be\r
+  removede if they have only a non-breaking space in them.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt
new file mode 100644 (file)
index 0000000..e557ad2
--- /dev/null
@@ -0,0 +1,15 @@
+AutoFormat.RemoveEmpty.RemoveNbsp\r
+TYPE: bool\r
+VERSION: 4.0.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+  When enabled, HTML Purifier will treat any elements that contain only\r
+  non-breaking spaces as well as regular whitespace as empty, and remove\r
+  them when %AutoFormat.RemoveEmpty is enabled.\r
+</p>\r
+<p>\r
+  See %AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions for a list of elements\r
+  that don't have this behavior applied to them.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt
new file mode 100644 (file)
index 0000000..6b5a7a5
--- /dev/null
@@ -0,0 +1,46 @@
+AutoFormat.RemoveEmpty\r
+TYPE: bool\r
+VERSION: 3.2.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+  When enabled, HTML Purifier will attempt to remove empty elements that\r
+  contribute no semantic information to the document. The following types\r
+  of nodes will be removed:\r
+</p>\r
+<ul><li>\r
+    Tags with no attributes and no content, and that are not empty\r
+    elements (remove <code>&lt;a&gt;&lt;/a&gt;</code> but not\r
+    <code>&lt;br /&gt;</code>), and\r
+  </li>\r
+  <li>\r
+    Tags with no content, except for:<ul>\r
+      <li>The <code>colgroup</code> element, or</li>\r
+      <li>\r
+        Elements with the <code>id</code> or <code>name</code> attribute,\r
+        when those attributes are permitted on those elements.\r
+      </li>\r
+    </ul></li>\r
+</ul>\r
+<p>\r
+  Please be very careful when using this functionality; while it may not\r
+  seem that empty elements contain useful information, they can alter the\r
+  layout of a document given appropriate styling. This directive is most\r
+  useful when you are processing machine-generated HTML, please avoid using\r
+  it on regular user HTML.\r
+</p>\r
+<p>\r
+  Elements that contain only whitespace will be treated as empty. Non-breaking\r
+  spaces, however, do not count as whitespace. See\r
+  %AutoFormat.RemoveEmpty.RemoveNbsp for alternate behavior.\r
+</p>\r
+<p>\r
+  This algorithm is not perfect; you may still notice some empty tags,\r
+  particularly if a node had elements, but those elements were later removed\r
+  because they were not permitted in that context, or tags that, after\r
+  being auto-closed by another tag, where empty. This is for safety reasons\r
+  to prevent clever code from breaking validation. The general rule of thumb:\r
+  if a tag looked empty on the way in, it will get removed; if HTML Purifier\r
+  made it empty, it will stay.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt
new file mode 100644 (file)
index 0000000..a448770
--- /dev/null
@@ -0,0 +1,11 @@
+AutoFormat.RemoveSpansWithoutAttributes\r
+TYPE: bool\r
+VERSION: 4.0.1\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+  This directive causes <code>span</code> tags without any attributes\r
+  to be removed. It will also remove spans that had all attributes\r
+  removed during processing.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt
new file mode 100644 (file)
index 0000000..acfeab3
--- /dev/null
@@ -0,0 +1,11 @@
+CSS.AllowDuplicates\r
+TYPE: bool\r
+DEFAULT: false\r
+VERSION: 4.8.0\r
+--DESCRIPTION--\r
+<p>\r
+  By default, HTML Purifier removes duplicate CSS properties,\r
+  like <code>color:red; color:blue</code>.  If this is set to\r
+  true, duplicate properties are allowed.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt
new file mode 100644 (file)
index 0000000..8096eb0
--- /dev/null
@@ -0,0 +1,8 @@
+CSS.AllowImportant\r
+TYPE: bool\r
+DEFAULT: false\r
+VERSION: 3.1.0\r
+--DESCRIPTION--\r
+This parameter determines whether or not !important cascade modifiers should\r
+be allowed in user CSS. If false, !important will stripped.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt
new file mode 100644 (file)
index 0000000..9d34deb
--- /dev/null
@@ -0,0 +1,11 @@
+CSS.AllowTricky\r
+TYPE: bool\r
+DEFAULT: false\r
+VERSION: 3.1.0\r
+--DESCRIPTION--\r
+This parameter determines whether or not to allow "tricky" CSS properties and\r
+values. Tricky CSS properties/values can drastically modify page layout or\r
+be used for deceptive practices but do not directly constitute a security risk.\r
+For example, <code>display:none;</code> is considered a tricky property that\r
+will only be allowed if this directive is set to true.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt
new file mode 100644 (file)
index 0000000..7c2b547
--- /dev/null
@@ -0,0 +1,12 @@
+CSS.AllowedFonts\r
+TYPE: lookup/null\r
+VERSION: 4.3.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+<p>\r
+    Allows you to manually specify a set of allowed fonts.  If\r
+    <code>NULL</code>, all fonts are allowed.  This directive\r
+    affects generic names (serif, sans-serif, monospace, cursive,\r
+    fantasy) as well as specific font families.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt
new file mode 100644 (file)
index 0000000..f1ba513
--- /dev/null
@@ -0,0 +1,18 @@
+CSS.AllowedProperties\r
+TYPE: lookup/null\r
+VERSION: 3.1.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    If HTML Purifier's style attributes set is unsatisfactory for your needs,\r
+    you can overload it with your own list of tags to allow.  Note that this\r
+    method is subtractive: it does its job by taking away from HTML Purifier\r
+    usual feature set, so you cannot add an attribute that HTML Purifier never\r
+    supported in the first place.\r
+</p>\r
+<p>\r
+    <strong>Warning:</strong> If another directive conflicts with the\r
+    elements here, <em>that</em> directive will win and override.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt
new file mode 100644 (file)
index 0000000..96b4108
--- /dev/null
@@ -0,0 +1,11 @@
+CSS.DefinitionRev\r
+TYPE: int\r
+VERSION: 2.0.0\r
+DEFAULT: 1\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Revision identifier for your custom definition. See\r
+    %HTML.DefinitionRev for details.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt
new file mode 100644 (file)
index 0000000..923e8e9
--- /dev/null
@@ -0,0 +1,13 @@
+CSS.ForbiddenProperties\r
+TYPE: lookup\r
+VERSION: 4.2.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+<p>\r
+    This is the logical inverse of %CSS.AllowedProperties, and it will\r
+    override that directive or any other directive.  If possible,\r
+    %CSS.AllowedProperties is recommended over this directive,\r
+    because it can sometimes be difficult to tell whether or not you've\r
+    forbidden all of the CSS properties you truly would like to disallow.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt
new file mode 100644 (file)
index 0000000..3808581
--- /dev/null
@@ -0,0 +1,16 @@
+CSS.MaxImgLength\r
+TYPE: string/null\r
+DEFAULT: '1200px'\r
+VERSION: 3.1.1\r
+--DESCRIPTION--\r
+<p>\r
+ This parameter sets the maximum allowed length on <code>img</code> tags,\r
+ effectively the <code>width</code> and <code>height</code> properties.\r
+ Only absolute units of measurement (in, pt, pc, mm, cm) and pixels (px) are allowed. This is\r
+ in place to prevent imagecrash attacks, disable with null at your own risk.\r
+ This directive is similar to %HTML.MaxImgLength, and both should be\r
+ concurrently edited, although there are\r
+ subtle differences in the input format (the CSS max is a number with\r
+ a unit).\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt
new file mode 100644 (file)
index 0000000..8a26f22
--- /dev/null
@@ -0,0 +1,10 @@
+CSS.Proprietary\r
+TYPE: bool\r
+VERSION: 3.0.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Whether or not to allow safe, proprietary CSS values.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt
new file mode 100644 (file)
index 0000000..917ec42
--- /dev/null
@@ -0,0 +1,9 @@
+CSS.Trusted\r
+TYPE: bool\r
+VERSION: 4.2.1\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+Indicates whether or not the user's CSS input is trusted or not. If the\r
+input is trusted, a more expansive set of allowed properties.  See\r
+also %HTML.Trusted.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt
new file mode 100644 (file)
index 0000000..afc6a87
--- /dev/null
@@ -0,0 +1,14 @@
+Cache.DefinitionImpl\r
+TYPE: string/null\r
+VERSION: 2.0.0\r
+DEFAULT: 'Serializer'\r
+--DESCRIPTION--\r
+\r
+This directive defines which method to use when caching definitions,\r
+the complex data-type that makes HTML Purifier tick. Set to null\r
+to disable caching (not recommended, as you will see a definite\r
+performance degradation).\r
+\r
+--ALIASES--\r
+Core.DefinitionCache\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt
new file mode 100644 (file)
index 0000000..668f248
--- /dev/null
@@ -0,0 +1,13 @@
+Cache.SerializerPath\r
+TYPE: string/null\r
+VERSION: 2.0.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Absolute path with no trailing slash to store serialized definitions in.\r
+    Default is within the\r
+    HTML Purifier library inside DefinitionCache/Serializer. This\r
+    path must be writable by the webserver.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt
new file mode 100644 (file)
index 0000000..f6059e6
--- /dev/null
@@ -0,0 +1,16 @@
+Cache.SerializerPermissions\r
+TYPE: int/null\r
+VERSION: 4.3.0\r
+DEFAULT: 0755\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Directory permissions of the files and directories created inside\r
+    the DefinitionCache/Serializer or other custom serializer path.\r
+</p>\r
+<p>\r
+    In HTML Purifier 4.8.0, this also supports <code>NULL</code>,\r
+    which means that no chmod'ing or directory creation shall\r
+    occur.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt
new file mode 100644 (file)
index 0000000..e0fa378
--- /dev/null
@@ -0,0 +1,18 @@
+Core.AggressivelyFixLt\r
+TYPE: bool\r
+VERSION: 2.1.0\r
+DEFAULT: true\r
+--DESCRIPTION--\r
+<p>\r
+    This directive enables aggressive pre-filter fixes HTML Purifier can\r
+    perform in order to ensure that open angled-brackets do not get killed\r
+    during parsing stage. Enabling this will result in two preg_replace_callback\r
+    calls and at least two preg_replace calls for every HTML document parsed;\r
+    if your users make very well-formed HTML, you can set this directive false.\r
+    This has no effect when DirectLex is used.\r
+</p>\r
+<p>\r
+    <strong>Notice:</strong> This directive's default turned from false to true\r
+    in HTML Purifier 3.2.0.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt
new file mode 100644 (file)
index 0000000..fb140b6
--- /dev/null
@@ -0,0 +1,16 @@
+Core.AggressivelyRemoveScript\r
+TYPE: bool\r
+VERSION: 4.9.0\r
+DEFAULT: true\r
+--DESCRIPTION--\r
+<p>\r
+    This directive enables aggressive pre-filter removal of\r
+    script tags.  This is not necessary for security,\r
+    but it can help work around a bug in libxml where embedded\r
+    HTML elements inside script sections cause the parser to\r
+    choke.  To revert to pre-4.9.0 behavior, set this to false.\r
+    This directive has no effect if %Core.Trusted is true,\r
+    %Core.RemoveScriptContents is false, or %Core.HiddenElements\r
+    does not contain script.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt
new file mode 100644 (file)
index 0000000..405d36f
--- /dev/null
@@ -0,0 +1,16 @@
+Core.AllowHostnameUnderscore\r
+TYPE: bool\r
+VERSION: 4.6.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+    By RFC 1123, underscores are not permitted in host names.\r
+    (This is in contrast to the specification for DNS, RFC\r
+    2181, which allows underscores.)\r
+    However, most browsers do the right thing when faced with\r
+    an underscore in the host name, and so some poorly written\r
+    websites are written with the expectation this should work.\r
+    Setting this parameter to true relaxes our allowed character\r
+    check so that underscores are permitted.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt
new file mode 100644 (file)
index 0000000..b4b9b10
--- /dev/null
@@ -0,0 +1,12 @@
+Core.AllowParseManyTags\r
+TYPE: bool\r
+DEFAULT: false\r
+VERSION: 4.10.1\r
+--DESCRIPTION--\r
+<p>\r
+    This directive allows parsing of many nested tags.\r
+    If you set true, relaxes any hardcoded limit from the parser.\r
+    However, in that case it may cause a Dos attack.\r
+    Be careful when enabling it.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt
new file mode 100644 (file)
index 0000000..c6ea069
--- /dev/null
@@ -0,0 +1,12 @@
+Core.CollectErrors\r
+TYPE: bool\r
+VERSION: 2.0.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+\r
+Whether or not to collect errors found while filtering the document. This\r
+is a useful way to give feedback to your users. <strong>Warning:</strong>\r
+Currently this feature is very patchy and experimental, with lots of\r
+possible error messages not yet implemented. It will not cause any\r
+problems, but it may not help your users either.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt
new file mode 100644 (file)
index 0000000..fc10086
--- /dev/null
@@ -0,0 +1,160 @@
+Core.ColorKeywords\r
+TYPE: hash\r
+VERSION: 2.0.0\r
+--DEFAULT--\r
+array (\r
+  'aliceblue' => '#F0F8FF',\r
+  'antiquewhite' => '#FAEBD7',\r
+  'aqua' => '#00FFFF',\r
+  'aquamarine' => '#7FFFD4',\r
+  'azure' => '#F0FFFF',\r
+  'beige' => '#F5F5DC',\r
+  'bisque' => '#FFE4C4',\r
+  'black' => '#000000',\r
+  'blanchedalmond' => '#FFEBCD',\r
+  'blue' => '#0000FF',\r
+  'blueviolet' => '#8A2BE2',\r
+  'brown' => '#A52A2A',\r
+  'burlywood' => '#DEB887',\r
+  'cadetblue' => '#5F9EA0',\r
+  'chartreuse' => '#7FFF00',\r
+  'chocolate' => '#D2691E',\r
+  'coral' => '#FF7F50',\r
+  'cornflowerblue' => '#6495ED',\r
+  'cornsilk' => '#FFF8DC',\r
+  'crimson' => '#DC143C',\r
+  'cyan' => '#00FFFF',\r
+  'darkblue' => '#00008B',\r
+  'darkcyan' => '#008B8B',\r
+  'darkgoldenrod' => '#B8860B',\r
+  'darkgray' => '#A9A9A9',\r
+  'darkgrey' => '#A9A9A9',\r
+  'darkgreen' => '#006400',\r
+  'darkkhaki' => '#BDB76B',\r
+  'darkmagenta' => '#8B008B',\r
+  'darkolivegreen' => '#556B2F',\r
+  'darkorange' => '#FF8C00',\r
+  'darkorchid' => '#9932CC',\r
+  'darkred' => '#8B0000',\r
+  'darksalmon' => '#E9967A',\r
+  'darkseagreen' => '#8FBC8F',\r
+  'darkslateblue' => '#483D8B',\r
+  'darkslategray' => '#2F4F4F',\r
+  'darkslategrey' => '#2F4F4F',\r
+  'darkturquoise' => '#00CED1',\r
+  'darkviolet' => '#9400D3',\r
+  'deeppink' => '#FF1493',\r
+  'deepskyblue' => '#00BFFF',\r
+  'dimgray' => '#696969',\r
+  'dimgrey' => '#696969',\r
+  'dodgerblue' => '#1E90FF',\r
+  'firebrick' => '#B22222',\r
+  'floralwhite' => '#FFFAF0',\r
+  'forestgreen' => '#228B22',\r
+  'fuchsia' => '#FF00FF',\r
+  'gainsboro' => '#DCDCDC',\r
+  'ghostwhite' => '#F8F8FF',\r
+  'gold' => '#FFD700',\r
+  'goldenrod' => '#DAA520',\r
+  'gray' => '#808080',\r
+  'grey' => '#808080',\r
+  'green' => '#008000',\r
+  'greenyellow' => '#ADFF2F',\r
+  'honeydew' => '#F0FFF0',\r
+  'hotpink' => '#FF69B4',\r
+  'indianred' => '#CD5C5C',\r
+  'indigo' => '#4B0082',\r
+  'ivory' => '#FFFFF0',\r
+  'khaki' => '#F0E68C',\r
+  'lavender' => '#E6E6FA',\r
+  'lavenderblush' => '#FFF0F5',\r
+  'lawngreen' => '#7CFC00',\r
+  'lemonchiffon' => '#FFFACD',\r
+  'lightblue' => '#ADD8E6',\r
+  'lightcoral' => '#F08080',\r
+  'lightcyan' => '#E0FFFF',\r
+  'lightgoldenrodyellow' => '#FAFAD2',\r
+  'lightgray' => '#D3D3D3',\r
+  'lightgrey' => '#D3D3D3',\r
+  'lightgreen' => '#90EE90',\r
+  'lightpink' => '#FFB6C1',\r
+  'lightsalmon' => '#FFA07A',\r
+  'lightseagreen' => '#20B2AA',\r
+  'lightskyblue' => '#87CEFA',\r
+  'lightslategray' => '#778899',\r
+  'lightslategrey' => '#778899',\r
+  'lightsteelblue' => '#B0C4DE',\r
+  'lightyellow' => '#FFFFE0',\r
+  'lime' => '#00FF00',\r
+  'limegreen' => '#32CD32',\r
+  'linen' => '#FAF0E6',\r
+  'magenta' => '#FF00FF',\r
+  'maroon' => '#800000',\r
+  'mediumaquamarine' => '#66CDAA',\r
+  'mediumblue' => '#0000CD',\r
+  'mediumorchid' => '#BA55D3',\r
+  'mediumpurple' => '#9370DB',\r
+  'mediumseagreen' => '#3CB371',\r
+  'mediumslateblue' => '#7B68EE',\r
+  'mediumspringgreen' => '#00FA9A',\r
+  'mediumturquoise' => '#48D1CC',\r
+  'mediumvioletred' => '#C71585',\r
+  'midnightblue' => '#191970',\r
+  'mintcream' => '#F5FFFA',\r
+  'mistyrose' => '#FFE4E1',\r
+  'moccasin' => '#FFE4B5',\r
+  'navajowhite' => '#FFDEAD',\r
+  'navy' => '#000080',\r
+  'oldlace' => '#FDF5E6',\r
+  'olive' => '#808000',\r
+  'olivedrab' => '#6B8E23',\r
+  'orange' => '#FFA500',\r
+  'orangered' => '#FF4500',\r
+  'orchid' => '#DA70D6',\r
+  'palegoldenrod' => '#EEE8AA',\r
+  'palegreen' => '#98FB98',\r
+  'paleturquoise' => '#AFEEEE',\r
+  'palevioletred' => '#DB7093',\r
+  'papayawhip' => '#FFEFD5',\r
+  'peachpuff' => '#FFDAB9',\r
+  'peru' => '#CD853F',\r
+  'pink' => '#FFC0CB',\r
+  'plum' => '#DDA0DD',\r
+  'powderblue' => '#B0E0E6',\r
+  'purple' => '#800080',\r
+  'rebeccapurple' => '#663399',\r
+  'red' => '#FF0000',\r
+  'rosybrown' => '#BC8F8F',\r
+  'royalblue' => '#4169E1',\r
+  'saddlebrown' => '#8B4513',\r
+  'salmon' => '#FA8072',\r
+  'sandybrown' => '#F4A460',\r
+  'seagreen' => '#2E8B57',\r
+  'seashell' => '#FFF5EE',\r
+  'sienna' => '#A0522D',\r
+  'silver' => '#C0C0C0',\r
+  'skyblue' => '#87CEEB',\r
+  'slateblue' => '#6A5ACD',\r
+  'slategray' => '#708090',\r
+  'slategrey' => '#708090',\r
+  'snow' => '#FFFAFA',\r
+  'springgreen' => '#00FF7F',\r
+  'steelblue' => '#4682B4',\r
+  'tan' => '#D2B48C',\r
+  'teal' => '#008080',\r
+  'thistle' => '#D8BFD8',\r
+  'tomato' => '#FF6347',\r
+  'turquoise' => '#40E0D0',\r
+  'violet' => '#EE82EE',\r
+  'wheat' => '#F5DEB3',\r
+  'white' => '#FFFFFF',\r
+  'whitesmoke' => '#F5F5F5',\r
+  'yellow' => '#FFFF00',\r
+  'yellowgreen' => '#9ACD32'\r
+)\r
+--DESCRIPTION--\r
+\r
+Lookup array of color names to six digit hexadecimal number corresponding\r
+to color, with preceding hash mark. Used when parsing colors.  The lookup\r
+is done in a case-insensitive manner.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt
new file mode 100644 (file)
index 0000000..656d378
--- /dev/null
@@ -0,0 +1,14 @@
+Core.ConvertDocumentToFragment\r
+TYPE: bool\r
+DEFAULT: true\r
+--DESCRIPTION--\r
+\r
+This parameter determines whether or not the filter should convert\r
+input that is a full document with html and body tags to a fragment\r
+of just the contents of a body tag. This parameter is simply something\r
+HTML Purifier can do during an edge-case: for most inputs, this\r
+processing is not necessary.\r
+\r
+--ALIASES--\r
+Core.AcceptFullDocuments\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt
new file mode 100644 (file)
index 0000000..2f54e46
--- /dev/null
@@ -0,0 +1,17 @@
+Core.DirectLexLineNumberSyncInterval\r
+TYPE: int\r
+VERSION: 2.0.0\r
+DEFAULT: 0\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  Specifies the number of tokens the DirectLex line number tracking\r
+  implementations should process before attempting to resyncronize the\r
+  current line count by manually counting all previous new-lines. When\r
+  at 0, this functionality is disabled. Lower values will decrease\r
+  performance, and this is only strictly necessary if the counting\r
+  algorithm is buggy (in which case you should report it as a bug).\r
+  This has no effect when %Core.MaintainLineNumbers is disabled or DirectLex is\r
+  not being used.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt
new file mode 100644 (file)
index 0000000..3c63c92
--- /dev/null
@@ -0,0 +1,14 @@
+Core.DisableExcludes\r
+TYPE: bool\r
+DEFAULT: false\r
+VERSION: 4.5.0\r
+--DESCRIPTION--\r
+<p>\r
+  This directive disables SGML-style exclusions, e.g. the exclusion of\r
+  <code>&lt;object&gt;</code> in any descendant of a\r
+  <code>&lt;pre&gt;</code> tag.  Disabling excludes will allow some\r
+  invalid documents to pass through HTML Purifier, but HTML Purifier\r
+  will also be less likely to accidentally remove large documents during\r
+  processing.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt
new file mode 100644 (file)
index 0000000..7f498e7
--- /dev/null
@@ -0,0 +1,9 @@
+Core.EnableIDNA\r
+TYPE: bool\r
+DEFAULT: false\r
+VERSION: 4.4.0\r
+--DESCRIPTION--\r
+Allows international domain names in URLs.  This configuration option\r
+requires the PEAR Net_IDNA2 module to be installed.  It operates by\r
+punycoding any internationalized host names for maximum portability.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt
new file mode 100644 (file)
index 0000000..89e2ae3
--- /dev/null
@@ -0,0 +1,15 @@
+Core.Encoding\r
+TYPE: istring\r
+DEFAULT: 'utf-8'\r
+--DESCRIPTION--\r
+If for some reason you are unable to convert all webpages to UTF-8, you can\r
+use this directive as a stop-gap compatibility change to let HTML Purifier\r
+deal with non UTF-8 input.  This technique has notable deficiencies:\r
+absolutely no characters outside of the selected character encoding will be\r
+preserved, not even the ones that have been ampersand escaped (this is due\r
+to a UTF-8 specific <em>feature</em> that automatically resolves all\r
+entities), making it pretty useless for anything except the most I18N-blind\r
+applications, although %Core.EscapeNonASCIICharacters offers fixes this\r
+trouble with another tradeoff. This directive only accepts ISO-8859-1 if\r
+iconv is not enabled.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt
new file mode 100644 (file)
index 0000000..1cc3fcd
--- /dev/null
@@ -0,0 +1,12 @@
+Core.EscapeInvalidChildren\r
+TYPE: bool\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p><strong>Warning:</strong> this configuration option is no longer does anything as of 4.6.0.</p>\r
+\r
+<p>When true, a child is found that is not allowed in the context of the\r
+parent element will be transformed into text as if it were ASCII. When\r
+false, that element and all internal tags will be dropped, though text will\r
+be preserved.  There is no option for dropping the element but preserving\r
+child nodes.</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt
new file mode 100644 (file)
index 0000000..299775f
--- /dev/null
@@ -0,0 +1,7 @@
+Core.EscapeInvalidTags\r
+TYPE: bool\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+When true, invalid tags will be written back to the document as plain text.\r
+Otherwise, they are silently dropped.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt
new file mode 100644 (file)
index 0000000..f50db2f
--- /dev/null
@@ -0,0 +1,13 @@
+Core.EscapeNonASCIICharacters\r
+TYPE: bool\r
+VERSION: 1.4.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+This directive overcomes a deficiency in %Core.Encoding by blindly\r
+converting all non-ASCII characters into decimal numeric entities before\r
+converting it to its native encoding. This means that even characters that\r
+can be expressed in the non-UTF-8 encoding will be entity-ized, which can\r
+be a real downer for encodings like Big5. It also assumes that the ASCII\r
+repetoire is available, although this is the case for almost all encodings.\r
+Anyway, use UTF-8!\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt
new file mode 100644 (file)
index 0000000..c337e47
--- /dev/null
@@ -0,0 +1,19 @@
+Core.HiddenElements\r
+TYPE: lookup\r
+--DEFAULT--\r
+array (\r
+  'script' => true,\r
+  'style' => true,\r
+)\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  This directive is a lookup array of elements which should have their\r
+  contents removed when they are not allowed by the HTML definition.\r
+  For example, the contents of a <code>script</code> tag are not\r
+  normally shown in a document, so if script tags are to be removed,\r
+  their contents should be removed to. This is opposed to a <code>b</code>\r
+  tag, which defines some presentational changes but does not hide its\r
+  contents.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.Language.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.Language.txt
new file mode 100644 (file)
index 0000000..ed1f39b
--- /dev/null
@@ -0,0 +1,10 @@
+Core.Language\r
+TYPE: string\r
+VERSION: 2.0.0\r
+DEFAULT: 'en'\r
+--DESCRIPTION--\r
+\r
+ISO 639 language code for localizable things in HTML Purifier to use,\r
+which is mainly error reporting. There is currently only an English (en)\r
+translation, so this directive is currently useless.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt
new file mode 100644 (file)
index 0000000..81d9ae4
--- /dev/null
@@ -0,0 +1,36 @@
+Core.LegacyEntityDecoder\r
+TYPE: bool\r
+VERSION: 4.9.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+    Prior to HTML Purifier 4.9.0, entities were decoded by performing\r
+    a global search replace for all entities whose decoded versions\r
+    did not have special meanings under HTML, and replaced them with\r
+    their decoded versions.  We would match all entities, even if they did\r
+    not have a trailing semicolon, but only if there weren't any trailing\r
+    alphanumeric characters.\r
+</p>\r
+<table>\r
+<tr><th>Original</th><th>Text</th><th>Attribute</th></tr>\r
+<tr><td>&amp;yen;</td><td>&yen;</td><td>&yen;</td></tr>\r
+<tr><td>&amp;yen</td><td>&yen;</td><td>&yen;</td></tr>\r
+<tr><td>&amp;yena</td><td>&amp;yena</td><td>&amp;yena</td></tr>\r
+<tr><td>&amp;yen=</td><td>&yen;=</td><td>&yen;=</td></tr>\r
+</table>\r
+<p>\r
+    In HTML Purifier 4.9.0, we changed the behavior of entity parsing\r
+    to match entities that had missing trailing semicolons in less\r
+    cases, to more closely match HTML5 parsing behavior:\r
+</p>\r
+<table>\r
+<tr><th>Original</th><th>Text</th><th>Attribute</th></tr>\r
+<tr><td>&amp;yen;</td><td>&yen;</td><td>&yen;</td></tr>\r
+<tr><td>&amp;yen</td><td>&yen;</td><td>&yen;</td></tr>\r
+<tr><td>&amp;yena</td><td>&yen;a</td><td>&amp;yena</td></tr>\r
+<tr><td>&amp;yen=</td><td>&yen;=</td><td>&amp;yen=</td></tr>\r
+</table>\r
+<p>\r
+    This flag reverts back to pre-HTML Purifier 4.9.0 behavior.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt
new file mode 100644 (file)
index 0000000..e11c015
--- /dev/null
@@ -0,0 +1,34 @@
+Core.LexerImpl\r
+TYPE: mixed/null\r
+VERSION: 2.0.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  This parameter determines what lexer implementation can be used. The\r
+  valid values are:\r
+</p>\r
+<dl>\r
+  <dt><em>null</em></dt>\r
+  <dd>\r
+    Recommended, the lexer implementation will be auto-detected based on\r
+    your PHP-version and configuration.\r
+  </dd>\r
+  <dt><em>string</em> lexer identifier</dt>\r
+  <dd>\r
+    This is a slim way of manually overridding the implementation.\r
+    Currently recognized values are: DOMLex (the default PHP5\r
+implementation)\r
+    and DirectLex (the default PHP4 implementation). Only use this if\r
+    you know what you are doing: usually, the auto-detection will\r
+    manage things for cases you aren't even aware of.\r
+  </dd>\r
+  <dt><em>object</em> lexer instance</dt>\r
+  <dd>\r
+    Super-advanced: you can specify your own, custom, implementation that\r
+    implements the interface defined by <code>HTMLPurifier_Lexer</code>.\r
+    I may remove this option simply because I don't expect anyone\r
+    to use it.\r
+  </dd>\r
+</dl>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt
new file mode 100644 (file)
index 0000000..838f10f
--- /dev/null
@@ -0,0 +1,16 @@
+Core.MaintainLineNumbers\r
+TYPE: bool/null\r
+VERSION: 2.0.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  If true, HTML Purifier will add line number information to all tokens.\r
+  This is useful when error reporting is turned on, but can result in\r
+  significant performance degradation and should not be used when\r
+  unnecessary. This directive must be used with the DirectLex lexer,\r
+  as the DOMLex lexer does not (yet) support this functionality.\r
+  If the value is null, an appropriate value will be selected based\r
+  on other configuration.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt
new file mode 100644 (file)
index 0000000..94a8860
--- /dev/null
@@ -0,0 +1,11 @@
+Core.NormalizeNewlines\r
+TYPE: bool\r
+VERSION: 4.2.0\r
+DEFAULT: true\r
+--DESCRIPTION--\r
+<p>\r
+    Whether or not to normalize newlines to the operating\r
+    system default.  When <code>false</code>, HTML Purifier\r
+    will attempt to preserve mixed newline files.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt
new file mode 100644 (file)
index 0000000..704ac56
--- /dev/null
@@ -0,0 +1,12 @@
+Core.RemoveInvalidImg\r
+TYPE: bool\r
+DEFAULT: true\r
+VERSION: 1.3.0\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  This directive enables pre-emptive URI checking in <code>img</code>\r
+  tags, as the attribute validation strategy is not authorized to\r
+  remove elements from the document. Revert to pre-1.3.0 behavior by setting to false.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt
new file mode 100644 (file)
index 0000000..ed6f134
--- /dev/null
@@ -0,0 +1,11 @@
+Core.RemoveProcessingInstructions\r
+TYPE: bool\r
+VERSION: 4.2.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+Instead of escaping processing instructions in the form <code>&lt;? ...\r
+?&gt;</code>, remove it out-right.  This may be useful if the HTML\r
+you are validating contains XML processing instruction gunk, however,\r
+it can also be user-unfriendly for people attempting to post PHP\r
+snippets.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt
new file mode 100644 (file)
index 0000000..efbe994
--- /dev/null
@@ -0,0 +1,12 @@
+Core.RemoveScriptContents\r
+TYPE: bool/null\r
+DEFAULT: NULL\r
+VERSION: 2.0.0\r
+DEPRECATED-VERSION: 2.1.0\r
+DEPRECATED-USE: Core.HiddenElements\r
+--DESCRIPTION--\r
+<p>\r
+  This directive enables HTML Purifier to remove not only script tags\r
+  but all of their contents.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt
new file mode 100644 (file)
index 0000000..861ae66
--- /dev/null
@@ -0,0 +1,11 @@
+Filter.Custom\r
+TYPE: list\r
+VERSION: 3.1.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+<p>\r
+  This directive can be used to add custom filters; it is nearly the\r
+  equivalent of the now deprecated <code>HTMLPurifier-&gt;addFilter()</code>\r
+  method. Specify an array of concrete implementations.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt
new file mode 100644 (file)
index 0000000..6960263
--- /dev/null
@@ -0,0 +1,14 @@
+Filter.ExtractStyleBlocks.Escaping\r
+TYPE: bool\r
+VERSION: 3.0.0\r
+DEFAULT: true\r
+ALIASES: Filter.ExtractStyleBlocksEscaping, FilterParam.ExtractStyleBlocksEscaping\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  Whether or not to escape the dangerous characters &lt;, &gt; and &amp;\r
+  as \3C, \3E and \26, respectively. This is can be safely set to false\r
+  if the contents of StyleBlocks will be placed in an external stylesheet,\r
+  where there is no risk of it being interpreted as HTML.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt
new file mode 100644 (file)
index 0000000..baa81ae
--- /dev/null
@@ -0,0 +1,29 @@
+Filter.ExtractStyleBlocks.Scope\r
+TYPE: string/null\r
+VERSION: 3.0.0\r
+DEFAULT: NULL\r
+ALIASES: Filter.ExtractStyleBlocksScope, FilterParam.ExtractStyleBlocksScope\r
+--DESCRIPTION--\r
+\r
+<p>\r
+  If you would like users to be able to define external stylesheets, but\r
+  only allow them to specify CSS declarations for a specific node and\r
+  prevent them from fiddling with other elements, use this directive.\r
+  It accepts any valid CSS selector, and will prepend this to any\r
+  CSS declaration extracted from the document. For example, if this\r
+  directive is set to <code>#user-content</code> and a user uses the\r
+  selector <code>a:hover</code>, the final selector will be\r
+  <code>#user-content a:hover</code>.\r
+</p>\r
+<p>\r
+  The comma shorthand may be used; consider the above example, with\r
+  <code>#user-content, #user-content2</code>, the final selector will\r
+  be <code>#user-content a:hover, #user-content2 a:hover</code>.\r
+</p>\r
+<p>\r
+  <strong>Warning:</strong> It is possible for users to bypass this measure\r
+  using a naughty + selector. This is a bug in CSS Tidy 1.3, not HTML\r
+  Purifier, and I am working to get it fixed. Until then, HTML Purifier\r
+  performs a basic check to prevent this.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt
new file mode 100644 (file)
index 0000000..3b70189
--- /dev/null
@@ -0,0 +1,16 @@
+Filter.ExtractStyleBlocks.TidyImpl\r
+TYPE: mixed/null\r
+VERSION: 3.1.0\r
+DEFAULT: NULL\r
+ALIASES: FilterParam.ExtractStyleBlocksTidyImpl\r
+--DESCRIPTION--\r
+<p>\r
+  If left NULL, HTML Purifier will attempt to instantiate a <code>csstidy</code>\r
+  class to use for internal cleaning. This will usually be good enough.\r
+</p>\r
+<p>\r
+  However, for trusted user input, you can set this to <code>false</code> to\r
+  disable cleaning. In addition, you can supply your own concrete implementation\r
+  of Tidy's interface to use, although I don't know why you'd want to do that.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt
new file mode 100644 (file)
index 0000000..be0177d
--- /dev/null
@@ -0,0 +1,74 @@
+Filter.ExtractStyleBlocks\r
+TYPE: bool\r
+VERSION: 3.1.0\r
+DEFAULT: false\r
+EXTERNAL: CSSTidy\r
+--DESCRIPTION--\r
+<p>\r
+  This directive turns on the style block extraction filter, which removes\r
+  <code>style</code> blocks from input HTML, cleans them up with CSSTidy,\r
+  and places them in the <code>StyleBlocks</code> context variable, for further\r
+  use by you, usually to be placed in an external stylesheet, or a\r
+  <code>style</code> block in the <code>head</code> of your document.\r
+</p>\r
+<p>\r
+  Sample usage:\r
+</p>\r
+<pre><![CDATA[\r
+<?php\r
+    header('Content-type: text/html; charset=utf-8');\r
+    echo '<?xml version="1.0" encoding="UTF-8"?>';\r
+?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\r
+  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">\r
+<head>\r
+  <title>Filter.ExtractStyleBlocks</title>\r
+<?php\r
+    require_once '/path/to/library/HTMLPurifier.auto.php';\r
+    require_once '/path/to/csstidy.class.php';\r
+\r
+    $dirty = '<style>body {color:#F00;}</style> Some text';\r
+\r
+    $config = HTMLPurifier_Config::createDefault();\r
+    $config->set('Filter', 'ExtractStyleBlocks', true);\r
+    $purifier = new HTMLPurifier($config);\r
+\r
+    $html = $purifier->purify($dirty);\r
+\r
+    // This implementation writes the stylesheets to the styles/ directory.\r
+    // You can also echo the styles inside the document, but it's a bit\r
+    // more difficult to make sure they get interpreted properly by\r
+    // browsers; try the usual CSS armoring techniques.\r
+    $styles = $purifier->context->get('StyleBlocks');\r
+    $dir = 'styles/';\r
+    if (!is_dir($dir)) mkdir($dir);\r
+    $hash = sha1($_GET['html']);\r
+    foreach ($styles as $i => $style) {\r
+        file_put_contents($name = $dir . $hash . "_$i");\r
+        echo '<link rel="stylesheet" type="text/css" href="'.$name.'" />';\r
+    }\r
+?>\r
+</head>\r
+<body>\r
+  <div>\r
+    <?php echo $html; ?>\r
+  </div>\r
+</b]]><![CDATA[ody>\r
+</html>\r
+]]></pre>\r
+<p>\r
+  <strong>Warning:</strong> It is possible for a user to mount an\r
+  imagecrash attack using this CSS. Counter-measures are difficult;\r
+  it is not simply enough to limit the range of CSS lengths (using\r
+  relative lengths with many nesting levels allows for large values\r
+  to be attained without actually specifying them in the stylesheet),\r
+  and the flexible nature of selectors makes it difficult to selectively\r
+  disable lengths on image tags (HTML Purifier, however, does disable\r
+  CSS width and height in inline styling). There are probably two effective\r
+  counter measures: an explicit width and height set to auto in all\r
+  images in your document (unlikely) or the disabling of width and\r
+  height (somewhat reasonable). Whether or not these measures should be\r
+  used is left to the reader.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt
new file mode 100644 (file)
index 0000000..8822186
--- /dev/null
@@ -0,0 +1,16 @@
+Filter.YouTube\r
+TYPE: bool\r
+VERSION: 3.1.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+  <strong>Warning:</strong> Deprecated in favor of %HTML.SafeObject and\r
+  %Output.FlashCompat (turn both on to allow YouTube videos and other\r
+  Flash content).\r
+</p>\r
+<p>\r
+  This directive enables YouTube video embedding in HTML Purifier. Check\r
+  <a href="http://htmlpurifier.org/docs/enduser-youtube.html">this document\r
+  on embedding videos</a> for more information on what this filter does.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt
new file mode 100644 (file)
index 0000000..afd48a0
--- /dev/null
@@ -0,0 +1,25 @@
+HTML.Allowed\r
+TYPE: itext/null\r
+VERSION: 2.0.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    This is a preferred convenience directive that combines\r
+    %HTML.AllowedElements and %HTML.AllowedAttributes.\r
+    Specify elements and attributes that are allowed using:\r
+    <code>element1[attr1|attr2],element2...</code>.  For example,\r
+    if you would like to only allow paragraphs and links, specify\r
+    <code>a[href],p</code>.  You can specify attributes that apply\r
+    to all elements using an asterisk, e.g. <code>*[lang]</code>.\r
+    You can also use newlines instead of commas to separate elements.\r
+</p>\r
+<p>\r
+    <strong>Warning</strong>:\r
+    All of the constraints on the component directives are still enforced.\r
+    The syntax is a <em>subset</em> of TinyMCE's <code>valid_elements</code>\r
+    whitelist: directly copy-pasting it here will probably result in\r
+    broken whitelists. If %HTML.AllowedElements or %HTML.AllowedAttributes\r
+    are set, this directive has no effect.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt
new file mode 100644 (file)
index 0000000..0e6ec54
--- /dev/null
@@ -0,0 +1,19 @@
+HTML.AllowedAttributes\r
+TYPE: lookup/null\r
+VERSION: 1.3.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    If HTML Purifier's attribute set is unsatisfactory, overload it!\r
+    The syntax is "tag.attr" or "*.attr" for the global attributes\r
+    (style, id, class, dir, lang, xml:lang).\r
+</p>\r
+<p>\r
+    <strong>Warning:</strong> If another directive conflicts with the\r
+    elements here, <em>that</em> directive will win and override. For\r
+    example, %HTML.EnableAttrID will take precedence over *.id in this\r
+    directive.  You must set that directive to true before you can use\r
+    IDs at all.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt
new file mode 100644 (file)
index 0000000..8440bc3
--- /dev/null
@@ -0,0 +1,10 @@
+HTML.AllowedComments\r
+TYPE: lookup\r
+VERSION: 4.4.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+A whitelist which indicates what explicit comment bodies should be\r
+allowed, modulo leading and trailing whitespace.  See also %HTML.AllowedCommentsRegexp\r
+(these directives are union'ed together, so a comment is considered\r
+valid if any directive deems it valid.)\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt
new file mode 100644 (file)
index 0000000..b1e65be
--- /dev/null
@@ -0,0 +1,15 @@
+HTML.AllowedCommentsRegexp\r
+TYPE: string/null\r
+VERSION: 4.4.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+A regexp, which if it matches the body of a comment, indicates that\r
+it should be allowed. Trailing and leading spaces are removed prior\r
+to running this regular expression.\r
+<strong>Warning:</strong> Make sure you specify\r
+correct anchor metacharacters <code>^regex$</code>, otherwise you may accept\r
+comments that you did not mean to! In particular, the regex <code>/foo|bar/</code>\r
+is probably not sufficiently strict, since it also allows <code>foobar</code>.\r
+See also %HTML.AllowedComments (these directives are union'ed together,\r
+so a comment is considered valid if any directive deems it valid.)\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt
new file mode 100644 (file)
index 0000000..ca3c13d
--- /dev/null
@@ -0,0 +1,23 @@
+HTML.AllowedElements\r
+TYPE: lookup/null\r
+VERSION: 1.3.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+<p>\r
+    If HTML Purifier's tag set is unsatisfactory for your needs, you can\r
+    overload it with your own list of tags to allow.  If you change\r
+    this, you probably also want to change %HTML.AllowedAttributes; see\r
+    also %HTML.Allowed which lets you set allowed elements and\r
+    attributes at the same time.\r
+</p>\r
+<p>\r
+    If you attempt to allow an element that HTML Purifier does not know\r
+    about, HTML Purifier will raise an error.  You will need to manually\r
+    tell HTML Purifier about this element by using the\r
+    <a href="http://htmlpurifier.org/docs/enduser-customize.html">advanced customization features.</a>\r
+</p>\r
+<p>\r
+    <strong>Warning:</strong> If another directive conflicts with the\r
+    elements here, <em>that</em> directive will win and override.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt
new file mode 100644 (file)
index 0000000..e373791
--- /dev/null
@@ -0,0 +1,20 @@
+HTML.AllowedModules\r
+TYPE: lookup/null\r
+VERSION: 2.0.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    A doctype comes with a set of usual modules to use. Without having\r
+    to mucking about with the doctypes, you can quickly activate or\r
+    disable these modules by specifying which modules you wish to allow\r
+    with this directive. This is most useful for unit testing specific\r
+    modules, although end users may find it useful for their own ends.\r
+</p>\r
+<p>\r
+    If you specify a module that does not exist, the manager will silently\r
+    fail to use it, so be careful! User-defined modules are not affected\r
+    by this directive. Modules defined in %HTML.CoreModules are not\r
+    affected by this directive.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt
new file mode 100644 (file)
index 0000000..75d680e
--- /dev/null
@@ -0,0 +1,11 @@
+HTML.Attr.Name.UseCDATA\r
+TYPE: bool\r
+DEFAULT: false\r
+VERSION: 4.0.0\r
+--DESCRIPTION--\r
+The W3C specification DTD defines the name attribute to be CDATA, not ID, due\r
+to limitations of DTD.  In certain documents, this relaxed behavior is desired,\r
+whether it is to specify duplicate names, or to specify names that would be\r
+illegal IDs (for example, names that begin with a digit.) Set this configuration\r
+directive to true to use the relaxed parsing rules.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt
new file mode 100644 (file)
index 0000000..f32b802
--- /dev/null
@@ -0,0 +1,18 @@
+HTML.BlockWrapper\r
+TYPE: string\r
+VERSION: 1.3.0\r
+DEFAULT: 'p'\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    String name of element to wrap inline elements that are inside a block\r
+    context.  This only occurs in the children of blockquote in strict mode.\r
+</p>\r
+<p>\r
+    Example: by default value,\r
+    <code>&lt;blockquote&gt;Foo&lt;/blockquote&gt;</code> would become\r
+    <code>&lt;blockquote&gt;&lt;p&gt;Foo&lt;/p&gt;&lt;/blockquote&gt;</code>.\r
+    The <code>&lt;p&gt;</code> tags can be replaced with whatever you desire,\r
+    as long as it is a block level element.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt
new file mode 100644 (file)
index 0000000..fc8e402
--- /dev/null
@@ -0,0 +1,23 @@
+HTML.CoreModules\r
+TYPE: lookup\r
+VERSION: 2.0.0\r
+--DEFAULT--\r
+array (\r
+  'Structure' => true,\r
+  'Text' => true,\r
+  'Hypertext' => true,\r
+  'List' => true,\r
+  'NonXMLCommonAttributes' => true,\r
+  'XMLCommonAttributes' => true,\r
+  'CommonAttributes' => true,\r
+)\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Certain modularized doctypes (XHTML, namely), have certain modules\r
+    that must be included for the doctype to be an conforming document\r
+    type: put those modules here. By default, XHTML's core modules\r
+    are used. You can set this to a blank array to disable core module\r
+    protection, but this is not recommended.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt
new file mode 100644 (file)
index 0000000..187c0a0
--- /dev/null
@@ -0,0 +1,9 @@
+HTML.CustomDoctype\r
+TYPE: string/null\r
+VERSION: 2.0.1\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+A custom doctype for power-users who defined their own document\r
+type. This directive only applies when %HTML.Doctype is blank.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt
new file mode 100644 (file)
index 0000000..f5433e3
--- /dev/null
@@ -0,0 +1,33 @@
+HTML.DefinitionID\r
+TYPE: string/null\r
+DEFAULT: NULL\r
+VERSION: 2.0.0\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Unique identifier for a custom-built HTML definition. If you edit\r
+    the raw version of the HTMLDefinition, introducing changes that the\r
+    configuration object does not reflect, you must specify this variable.\r
+    If you change your custom edits, you should change this directive, or\r
+    clear your cache. Example:\r
+</p>\r
+<pre>\r
+$config = HTMLPurifier_Config::createDefault();\r
+$config->set('HTML', 'DefinitionID', '1');\r
+$def = $config->getHTMLDefinition();\r
+$def->addAttribute('a', 'tabindex', 'Number');\r
+</pre>\r
+<p>\r
+    In the above example, the configuration is still at the defaults, but\r
+    using the advanced API, an extra attribute has been added. The\r
+    configuration object normally has no way of knowing that this change\r
+    has taken place, so it needs an extra directive: %HTML.DefinitionID.\r
+    If someone else attempts to use the default configuration, these two\r
+    pieces of code will not clobber each other in the cache, since one has\r
+    an extra directive attached to it.\r
+</p>\r
+<p>\r
+    You <em>must</em> specify a value to this directive to use the\r
+    advanced API features.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt
new file mode 100644 (file)
index 0000000..0bb5a71
--- /dev/null
@@ -0,0 +1,16 @@
+HTML.DefinitionRev\r
+TYPE: int\r
+VERSION: 2.0.0\r
+DEFAULT: 1\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Revision identifier for your custom definition specified in\r
+    %HTML.DefinitionID.  This serves the same purpose: uniquely identifying\r
+    your custom definition, but this one does so in a chronological\r
+    context: revision 3 is more up-to-date then revision 2.  Thus, when\r
+    this gets incremented, the cache handling is smart enough to clean\r
+    up any older revisions of your definition as well as flush the\r
+    cache.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt
new file mode 100644 (file)
index 0000000..a6969b9
--- /dev/null
@@ -0,0 +1,11 @@
+HTML.Doctype\r
+TYPE: string/null\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+Doctype to use during filtering. Technically speaking this is not actually\r
+a doctype (as it does not identify a corresponding DTD), but we are using\r
+this name for sake of simplicity. When non-blank, this will override any\r
+older directives like %HTML.XHTML or %HTML.Strict.\r
+--ALLOWED--\r
+'HTML 4.01 Transitional', 'HTML 4.01 Strict', 'XHTML 1.0 Transitional', 'XHTML 1.0 Strict', 'XHTML 1.1'\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt
new file mode 100644 (file)
index 0000000..08d641f
--- /dev/null
@@ -0,0 +1,11 @@
+HTML.FlashAllowFullScreen\r
+TYPE: bool\r
+VERSION: 4.2.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+    Whether or not to permit embedded Flash content from\r
+    %HTML.SafeObject to expand to the full screen.  Corresponds to\r
+    the <code>allowFullScreen</code> parameter.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt
new file mode 100644 (file)
index 0000000..2b8df97
--- /dev/null
@@ -0,0 +1,21 @@
+HTML.ForbiddenAttributes\r
+TYPE: lookup\r
+VERSION: 3.1.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+<p>\r
+    While this directive is similar to %HTML.AllowedAttributes, for\r
+    forwards-compatibility with XML, this attribute has a different syntax. Instead of\r
+    <code>tag.attr</code>, use <code>tag@attr</code>. To disallow <code>href</code>\r
+    attributes in <code>a</code> tags, set this directive to\r
+    <code>a@href</code>. You can also disallow an attribute globally with\r
+    <code>attr</code> or <code>*@attr</code> (either syntax is fine; the latter\r
+    is provided for consistency with %HTML.AllowedAttributes).\r
+</p>\r
+<p>\r
+    <strong>Warning:</strong> This directive complements %HTML.ForbiddenElements,\r
+    accordingly, check\r
+    out that directive for a discussion of why you\r
+    should think twice before using this directive.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt
new file mode 100644 (file)
index 0000000..40466c4
--- /dev/null
@@ -0,0 +1,20 @@
+HTML.ForbiddenElements\r
+TYPE: lookup\r
+VERSION: 3.1.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+<p>\r
+    This was, perhaps, the most requested feature ever in HTML\r
+    Purifier. Please don't abuse it! This is the logical inverse of\r
+    %HTML.AllowedElements, and it will override that directive, or any\r
+    other directive.\r
+</p>\r
+<p>\r
+    If possible, %HTML.Allowed is recommended over this directive, because it\r
+    can sometimes be difficult to tell whether or not you've forbidden all of\r
+    the behavior you would like to disallow. If you forbid <code>img</code>\r
+    with the expectation of preventing images on your site, you'll be in for\r
+    a nasty surprise when people start using the <code>background-image</code>\r
+    CSS property.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt
new file mode 100644 (file)
index 0000000..3197479
--- /dev/null
@@ -0,0 +1,14 @@
+HTML.MaxImgLength\r
+TYPE: int/null\r
+DEFAULT: 1200\r
+VERSION: 3.1.1\r
+--DESCRIPTION--\r
+<p>\r
+ This directive controls the maximum number of pixels in the width and\r
+ height attributes in <code>img</code> tags. This is\r
+ in place to prevent imagecrash attacks, disable with null at your own risk.\r
+ This directive is similar to %CSS.MaxImgLength, and both should be\r
+ concurrently edited, although there are\r
+ subtle differences in the input format (the HTML max is an integer).\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt
new file mode 100644 (file)
index 0000000..7aa3563
--- /dev/null
@@ -0,0 +1,7 @@
+HTML.Nofollow\r
+TYPE: bool\r
+VERSION: 4.3.0\r
+DEFAULT: FALSE\r
+--DESCRIPTION--\r
+If enabled, nofollow rel attributes are added to all outgoing links.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt
new file mode 100644 (file)
index 0000000..2d2fbd1
--- /dev/null
@@ -0,0 +1,12 @@
+HTML.Parent\r
+TYPE: string\r
+VERSION: 1.3.0\r
+DEFAULT: 'div'\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    String name of element that HTML fragment passed to library will be\r
+    inserted in.  An interesting variation would be using span as the\r
+    parent element, meaning that only inline tags would be allowed.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt
new file mode 100644 (file)
index 0000000..b3c45e1
--- /dev/null
@@ -0,0 +1,12 @@
+HTML.Proprietary\r
+TYPE: bool\r
+VERSION: 3.1.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+    Whether or not to allow proprietary elements and attributes in your\r
+    documents, as per <code>HTMLPurifier_HTMLModule_Proprietary</code>.\r
+    <strong>Warning:</strong> This can cause your documents to stop\r
+    validating!\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt
new file mode 100644 (file)
index 0000000..556fa67
--- /dev/null
@@ -0,0 +1,13 @@
+HTML.SafeEmbed\r
+TYPE: bool\r
+VERSION: 3.1.1\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+    Whether or not to permit embed tags in documents, with a number of extra\r
+    security features added to prevent script execution. This is similar to\r
+    what websites like MySpace do to embed tags. Embed is a proprietary\r
+    element and will cause your website to stop validating; you should\r
+    see if you can use %Output.FlashCompat with %HTML.SafeObject instead\r
+    first.</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt
new file mode 100644 (file)
index 0000000..295a8cf
--- /dev/null
@@ -0,0 +1,13 @@
+HTML.SafeIframe\r
+TYPE: bool\r
+VERSION: 4.4.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+    Whether or not to permit iframe tags in untrusted documents.  This\r
+    directive must be accompanied by a whitelist of permitted iframes,\r
+    such as %URI.SafeIframeRegexp, otherwise it will fatally error.\r
+    This directive has no effect on strict doctypes, as iframes are not\r
+    valid.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt
new file mode 100644 (file)
index 0000000..07f6e53
--- /dev/null
@@ -0,0 +1,13 @@
+HTML.SafeObject\r
+TYPE: bool\r
+VERSION: 3.1.1\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+    Whether or not to permit object tags in documents, with a number of extra\r
+    security features added to prevent script execution. This is similar to\r
+    what websites like MySpace do to object tags.  You should also enable\r
+    %Output.FlashCompat in order to generate Internet Explorer\r
+    compatibility code for your object tags.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt
new file mode 100644 (file)
index 0000000..641b4a8
--- /dev/null
@@ -0,0 +1,10 @@
+HTML.SafeScripting\r
+TYPE: lookup\r
+VERSION: 4.5.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+<p>\r
+    Whether or not to permit script tags to external scripts in documents.\r
+    Inline scripting is not allowed, and the script must match an explicit whitelist.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt
new file mode 100644 (file)
index 0000000..d99663a
--- /dev/null
@@ -0,0 +1,9 @@
+HTML.Strict\r
+TYPE: bool\r
+VERSION: 1.3.0\r
+DEFAULT: false\r
+DEPRECATED-VERSION: 1.7.0\r
+DEPRECATED-USE: HTML.Doctype\r
+--DESCRIPTION--\r
+Determines whether or not to use Transitional (loose) or Strict rulesets.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt
new file mode 100644 (file)
index 0000000..d65f0d0
--- /dev/null
@@ -0,0 +1,8 @@
+HTML.TargetBlank\r
+TYPE: bool\r
+VERSION: 4.4.0\r
+DEFAULT: FALSE\r
+--DESCRIPTION--\r
+If enabled, <code>target=blank</code> attributes are added to all outgoing links.\r
+(This includes links from an HTTPS version of a page to an HTTP version.)\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt
new file mode 100644 (file)
index 0000000..05cb342
--- /dev/null
@@ -0,0 +1,10 @@
+--# vim: et sw=4 sts=4\r
+HTML.TargetNoopener\r
+TYPE: bool\r
+VERSION: 4.8.0\r
+DEFAULT: TRUE\r
+--DESCRIPTION--\r
+If enabled, noopener rel attributes are added to links which have\r
+a target attribute associated with them.  This prevents malicious\r
+destinations from overwriting the original window.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt
new file mode 100644 (file)
index 0000000..993a817
--- /dev/null
@@ -0,0 +1,9 @@
+HTML.TargetNoreferrer\r
+TYPE: bool\r
+VERSION: 4.8.0\r
+DEFAULT: TRUE\r
+--DESCRIPTION--\r
+If enabled, noreferrer rel attributes are added to links which have\r
+a target attribute associated with them.  This prevents malicious\r
+destinations from overwriting the original window.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt
new file mode 100644 (file)
index 0000000..602453f
--- /dev/null
@@ -0,0 +1,8 @@
+HTML.TidyAdd\r
+TYPE: lookup\r
+VERSION: 2.0.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+\r
+Fixes to add to the default set of Tidy fixes as per your level.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt
new file mode 100644 (file)
index 0000000..bf943e8
--- /dev/null
@@ -0,0 +1,24 @@
+HTML.TidyLevel\r
+TYPE: string\r
+VERSION: 2.0.0\r
+DEFAULT: 'medium'\r
+--DESCRIPTION--\r
+\r
+<p>General level of cleanliness the Tidy module should enforce.\r
+There are four allowed values:</p>\r
+<dl>\r
+    <dt>none</dt>\r
+    <dd>No extra tidying should be done</dd>\r
+    <dt>light</dt>\r
+    <dd>Only fix elements that would be discarded otherwise due to\r
+    lack of support in doctype</dd>\r
+    <dt>medium</dt>\r
+    <dd>Enforce best practices</dd>\r
+    <dt>heavy</dt>\r
+    <dd>Transform all deprecated elements and attributes to standards\r
+    compliant equivalents</dd>\r
+</dl>\r
+\r
+--ALLOWED--\r
+'none', 'light', 'medium', 'heavy'\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt
new file mode 100644 (file)
index 0000000..92cca2a
--- /dev/null
@@ -0,0 +1,8 @@
+HTML.TidyRemove\r
+TYPE: lookup\r
+VERSION: 2.0.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+\r
+Fixes to remove from the default set of Tidy fixes as per your level.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt
new file mode 100644 (file)
index 0000000..bc8e654
--- /dev/null
@@ -0,0 +1,9 @@
+HTML.Trusted\r
+TYPE: bool\r
+VERSION: 2.0.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+Indicates whether or not the user input is trusted or not. If the input is\r
+trusted, a more expansive set of allowed tags and attributes will be used.\r
+See also %CSS.Trusted.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt
new file mode 100644 (file)
index 0000000..a3c2f42
--- /dev/null
@@ -0,0 +1,11 @@
+HTML.XHTML\r
+TYPE: bool\r
+DEFAULT: true\r
+VERSION: 1.1.0\r
+DEPRECATED-VERSION: 1.7.0\r
+DEPRECATED-USE: HTML.Doctype\r
+--DESCRIPTION--\r
+Determines whether or not output is XHTML 1.0 or HTML 4.01 flavor.\r
+--ALIASES--\r
+Core.XHTML\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt
new file mode 100644 (file)
index 0000000..2a13704
--- /dev/null
@@ -0,0 +1,10 @@
+Output.CommentScriptContents\r
+TYPE: bool\r
+VERSION: 2.0.0\r
+DEFAULT: true\r
+--DESCRIPTION--\r
+Determines whether or not HTML Purifier should attempt to fix up the\r
+contents of script tags for legacy browsers with comments.\r
+--ALIASES--\r
+Core.CommentScriptContents\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt
new file mode 100644 (file)
index 0000000..d215ba2
--- /dev/null
@@ -0,0 +1,15 @@
+Output.FixInnerHTML\r
+TYPE: bool\r
+VERSION: 4.3.0\r
+DEFAULT: true\r
+--DESCRIPTION--\r
+<p>\r
+  If true, HTML Purifier will protect against Internet Explorer's\r
+  mishandling of the <code>innerHTML</code> attribute by appending\r
+  a space to any attribute that does not contain angled brackets, spaces\r
+  or quotes, but contains a backtick.  This slightly changes the\r
+  semantics of any given attribute, so if this is unacceptable and\r
+  you do not use <code>innerHTML</code> on any of your pages, you can\r
+  turn this directive off.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt
new file mode 100644 (file)
index 0000000..e58f91a
--- /dev/null
@@ -0,0 +1,11 @@
+Output.FlashCompat\r
+TYPE: bool\r
+VERSION: 4.1.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+  If true, HTML Purifier will generate Internet Explorer compatibility\r
+  code for all object code.  This is highly recommended if you enable\r
+  %HTML.SafeObject.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt
new file mode 100644 (file)
index 0000000..4bb9025
--- /dev/null
@@ -0,0 +1,13 @@
+Output.Newline\r
+TYPE: string/null\r
+VERSION: 2.0.1\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Newline string to format final output with. If left null, HTML Purifier\r
+    will auto-detect the default newline type of the system and use that;\r
+    you can manually override it here. Remember, \r\n is Windows, \r\r
+    is Mac, and \n is Unix.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt
new file mode 100644 (file)
index 0000000..3223106
--- /dev/null
@@ -0,0 +1,14 @@
+Output.SortAttr\r
+TYPE: bool\r
+VERSION: 3.2.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+  If true, HTML Purifier will sort attributes by name before writing them back\r
+  to the document, converting a tag like: <code>&lt;el b="" a="" c="" /&gt;</code>\r
+  to <code>&lt;el a="" b="" c="" /&gt;</code>. This is a workaround for\r
+  a bug in FCKeditor which causes it to swap attributes order, adding noise\r
+  to text diffs. If you're not seeing this bug, chances are, you don't need\r
+  this directive.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt
new file mode 100644 (file)
index 0000000..23dd4d3
--- /dev/null
@@ -0,0 +1,25 @@
+Output.TidyFormat\r
+TYPE: bool\r
+VERSION: 1.1.1\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+    Determines whether or not to run Tidy on the final output for pretty\r
+    formatting reasons, such as indentation and wrap.\r
+</p>\r
+<p>\r
+    This can greatly improve readability for editors who are hand-editing\r
+    the HTML, but is by no means necessary as HTML Purifier has already\r
+    fixed all major errors the HTML may have had. Tidy is a non-default\r
+    extension, and this directive will silently fail if Tidy is not\r
+    available.\r
+</p>\r
+<p>\r
+    If you are looking to make the overall look of your page's source\r
+    better, I recommend running Tidy on the entire page rather than just\r
+    user-content (after all, the indentation relative to the containing\r
+    blocks will be incorrect).\r
+</p>\r
+--ALIASES--\r
+Core.TidyFormat\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt
new file mode 100644 (file)
index 0000000..d1820cd
--- /dev/null
@@ -0,0 +1,7 @@
+Test.ForceNoIconv\r
+TYPE: bool\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+When set to true, HTMLPurifier_Encoder will act as if iconv does not exist\r
+and use only pure PHP implementations.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt
new file mode 100644 (file)
index 0000000..0b0533a
--- /dev/null
@@ -0,0 +1,18 @@
+URI.AllowedSchemes\r
+TYPE: lookup\r
+--DEFAULT--\r
+array (\r
+  'http' => true,\r
+  'https' => true,\r
+  'mailto' => true,\r
+  'ftp' => true,\r
+  'nntp' => true,\r
+  'news' => true,\r
+  'tel' => true,\r
+)\r
+--DESCRIPTION--\r
+Whitelist that defines the schemes that a URI is allowed to have.  This\r
+prevents XSS attacks from using pseudo-schemes like javascript or mocha.\r
+There is also support for the <code>data</code> and <code>file</code>\r
+URI schemes, but they are not enabled by default.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Base.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Base.txt
new file mode 100644 (file)
index 0000000..ba47308
--- /dev/null
@@ -0,0 +1,17 @@
+URI.Base\r
+TYPE: string/null\r
+VERSION: 2.1.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    The base URI is the URI of the document this purified HTML will be\r
+    inserted into.  This information is important if HTML Purifier needs\r
+    to calculate absolute URIs from relative URIs, such as when %URI.MakeAbsolute\r
+    is on.  You may use a non-absolute URI for this value, but behavior\r
+    may vary (%URI.MakeAbsolute deals nicely with both absolute and\r
+    relative paths, but forwards-compatibility is not guaranteed).\r
+    <strong>Warning:</strong> If set, the scheme on this URI\r
+    overrides the one specified by %URI.DefaultScheme.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt
new file mode 100644 (file)
index 0000000..981e443
--- /dev/null
@@ -0,0 +1,15 @@
+URI.DefaultScheme\r
+TYPE: string/null\r
+DEFAULT: 'http'\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Defines through what scheme the output will be served, in order to\r
+    select the proper object validator when no scheme information is present.\r
+</p>\r
+\r
+<p>\r
+    Starting with HTML Purifier 4.9.0, the default scheme can be null, in\r
+    which case we reject all URIs which do not have explicit schemes.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt
new file mode 100644 (file)
index 0000000..523204c
--- /dev/null
@@ -0,0 +1,11 @@
+URI.DefinitionID\r
+TYPE: string/null\r
+VERSION: 2.1.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Unique identifier for a custom-built URI definition. If you  want\r
+    to add custom URIFilters, you must specify this value.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt
new file mode 100644 (file)
index 0000000..a9c07b1
--- /dev/null
@@ -0,0 +1,11 @@
+URI.DefinitionRev\r
+TYPE: int\r
+VERSION: 2.1.0\r
+DEFAULT: 1\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Revision identifier for your custom definition. See\r
+    %HTML.DefinitionRev for details.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt
new file mode 100644 (file)
index 0000000..b19ca1d
--- /dev/null
@@ -0,0 +1,14 @@
+URI.Disable\r
+TYPE: bool\r
+VERSION: 1.3.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Disables all URIs in all forms. Not sure why you'd want to do that\r
+    (after all, the Internet's founded on the notion of a hyperlink).\r
+</p>\r
+\r
+--ALIASES--\r
+Attr.DisableURI\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt
new file mode 100644 (file)
index 0000000..9132ea4
--- /dev/null
@@ -0,0 +1,11 @@
+URI.DisableExternal\r
+TYPE: bool\r
+VERSION: 1.2.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+Disables links to external websites.  This is a highly effective anti-spam\r
+and anti-pagerank-leech measure, but comes at a hefty price: nolinks or\r
+images outside of your domain will be allowed.  Non-linkified URIs will\r
+still be preserved.  If you want to be able to link to subdomains or use\r
+absolute URIs, specify %URI.Host for your website.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt
new file mode 100644 (file)
index 0000000..d74bc1e
--- /dev/null
@@ -0,0 +1,13 @@
+URI.DisableExternalResources\r
+TYPE: bool\r
+VERSION: 1.3.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+Disables the embedding of external resources, preventing users from\r
+embedding things like images from other hosts. This prevents access\r
+tracking (good for email viewers), bandwidth leeching, cross-site request\r
+forging, goatse.cx posting, and other nasties, but also results in a loss\r
+of end-user functionality (they can't directly post a pic they posted from\r
+Flickr anymore). Use it if you don't have a robust user-content moderation\r
+team.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt
new file mode 100644 (file)
index 0000000..6c10614
--- /dev/null
@@ -0,0 +1,15 @@
+URI.DisableResources\r
+TYPE: bool\r
+VERSION: 4.2.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+    Disables embedding resources, essentially meaning no pictures. You can\r
+    still link to them though. See %URI.DisableExternalResources for why\r
+    this might be a good idea.\r
+</p>\r
+<p>\r
+    <em>Note:</em> While this directive has been available since 1.3.0,\r
+    it didn't actually start doing anything until 4.2.0.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Host.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Host.txt
new file mode 100644 (file)
index 0000000..ba0e6bc
--- /dev/null
@@ -0,0 +1,19 @@
+URI.Host\r
+TYPE: string/null\r
+VERSION: 1.2.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Defines the domain name of the server, so we can determine whether or\r
+    an absolute URI is from your website or not.  Not strictly necessary,\r
+    as users should be using relative URIs to reference resources on your\r
+    website.  It will, however, let you use absolute URIs to link to\r
+    subdomains of the domain you post here: i.e. example.com will allow\r
+    sub.example.com.  However, higher up domains will still be excluded:\r
+    if you set %URI.Host to sub.example.com, example.com will be blocked.\r
+    <strong>Note:</strong> This directive overrides %URI.Base because\r
+    a given page may be on a sub-domain, but you wish HTML Purifier to be\r
+    more relaxed and allow some of the parent domains too.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt
new file mode 100644 (file)
index 0000000..825fef2
--- /dev/null
@@ -0,0 +1,9 @@
+URI.HostBlacklist\r
+TYPE: list\r
+VERSION: 1.3.0\r
+DEFAULT: array()\r
+--DESCRIPTION--\r
+List of strings that are forbidden in the host of any URI. Use it to kill\r
+domain names of spam, etc. Note that it will catch anything in the domain,\r
+so <tt>moo.com</tt> will catch <tt>moo.com.example.com</tt>.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt
new file mode 100644 (file)
index 0000000..eb58c7f
--- /dev/null
@@ -0,0 +1,13 @@
+URI.MakeAbsolute\r
+TYPE: bool\r
+VERSION: 2.1.0\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Converts all URIs into absolute forms. This is useful when the HTML\r
+    being filtered assumes a specific base path, but will actually be\r
+    viewed in a different context (and setting an alternate base URI is\r
+    not possible). %URI.Base must be set for this directive to work.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt
new file mode 100644 (file)
index 0000000..bedd610
--- /dev/null
@@ -0,0 +1,83 @@
+URI.Munge\r
+TYPE: string/null\r
+VERSION: 1.3.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+\r
+<p>\r
+    Munges all browsable (usually http, https and ftp)\r
+    absolute URIs into another URI, usually a URI redirection service.\r
+    This directive accepts a URI, formatted with a <code>%s</code> where\r
+    the url-encoded original URI should be inserted (sample:\r
+    <code>http://www.google.com/url?q=%s</code>).\r
+</p>\r
+<p>\r
+    Uses for this directive:\r
+</p>\r
+<ul>\r
+    <li>\r
+        Prevent PageRank leaks, while being fairly transparent\r
+        to users (you may also want to add some client side JavaScript to\r
+        override the text in the statusbar). <strong>Notice</strong>:\r
+        Many security experts believe that this form of protection does not deter spam-bots.\r
+    </li>\r
+    <li>\r
+        Redirect users to a splash page telling them they are leaving your\r
+        website. While this is poor usability practice, it is often mandated\r
+        in corporate environments.\r
+    </li>\r
+</ul>\r
+<p>\r
+    Prior to HTML Purifier 3.1.1, this directive also enabled the munging\r
+    of browsable external resources, which could break things if your redirection\r
+    script was a splash page or used <code>meta</code> tags. To revert to\r
+    previous behavior, please use %URI.MungeResources.\r
+</p>\r
+<p>\r
+    You may want to also use %URI.MungeSecretKey along with this directive\r
+    in order to enforce what URIs your redirector script allows. Open\r
+    redirector scripts can be a security risk and negatively affect the\r
+    reputation of your domain name.\r
+</p>\r
+<p>\r
+    Starting with HTML Purifier 3.1.1, there is also these substitutions:\r
+</p>\r
+<table>\r
+    <thead>\r
+        <tr>\r
+            <th>Key</th>\r
+            <th>Description</th>\r
+            <th>Example <code>&lt;a href=""&gt;</code></th>\r
+        </tr>\r
+    </thead>\r
+    <tbody>\r
+        <tr>\r
+            <td>%r</td>\r
+            <td>1 - The URI embeds a resource<br />(blank) - The URI is merely a link</td>\r
+            <td></td>\r
+        </tr>\r
+        <tr>\r
+            <td>%n</td>\r
+            <td>The name of the tag this URI came from</td>\r
+            <td>a</td>\r
+        </tr>\r
+        <tr>\r
+            <td>%m</td>\r
+            <td>The name of the attribute this URI came from</td>\r
+            <td>href</td>\r
+        </tr>\r
+        <tr>\r
+            <td>%p</td>\r
+            <td>The name of the CSS property this URI came from, or blank if irrelevant</td>\r
+            <td></td>\r
+        </tr>\r
+    </tbody>\r
+</table>\r
+<p>\r
+    Admittedly, these letters are somewhat arbitrary; the only stipulation\r
+    was that they couldn't be a through f. r is for resource (I would have preferred\r
+    e, but you take what you can get), n is for name, m\r
+    was picked because it came after n (and I couldn't use a), p is for\r
+    property.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt
new file mode 100644 (file)
index 0000000..ed4b5b0
--- /dev/null
@@ -0,0 +1,17 @@
+URI.MungeResources\r
+TYPE: bool\r
+VERSION: 3.1.1\r
+DEFAULT: false\r
+--DESCRIPTION--\r
+<p>\r
+    If true, any URI munging directives like %URI.Munge\r
+    will also apply to embedded resources, such as <code>&lt;img src=""&gt;</code>.\r
+    Be careful enabling this directive if you have a redirector script\r
+    that does not use the <code>Location</code> HTTP header; all of your images\r
+    and other embedded resources will break.\r
+</p>\r
+<p>\r
+    <strong>Warning:</strong> It is strongly advised you use this in conjunction\r
+    %URI.MungeSecretKey to mitigate the security risk of an open redirector.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt
new file mode 100644 (file)
index 0000000..123b6e2
--- /dev/null
@@ -0,0 +1,30 @@
+URI.MungeSecretKey\r
+TYPE: string/null\r
+VERSION: 3.1.1\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+<p>\r
+    This directive enables secure checksum generation along with %URI.Munge.\r
+    It should be set to a secure key that is not shared with anyone else.\r
+    The checksum can be placed in the URI using %t. Use of this checksum\r
+    affords an additional level of protection by allowing a redirector\r
+    to check if a URI has passed through HTML Purifier with this line:\r
+</p>\r
+\r
+<pre>$checksum === hash_hmac("sha256", $url, $secret_key)</pre>\r
+\r
+<p>\r
+    If the output is TRUE, the redirector script should accept the URI.\r
+</p>\r
+\r
+<p>\r
+    Please note that it would still be possible for an attacker to procure\r
+    secure hashes en-mass by abusing your website's Preview feature or the\r
+    like, but this service affords an additional level of protection\r
+    that should be combined with website blacklisting.\r
+</p>\r
+\r
+<p>\r
+    Remember this has no effect if %URI.Munge is not on.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt
new file mode 100644 (file)
index 0000000..8b387de
--- /dev/null
@@ -0,0 +1,9 @@
+URI.OverrideAllowedSchemes\r
+TYPE: bool\r
+DEFAULT: true\r
+--DESCRIPTION--\r
+If this is set to true (which it is by default), you can override\r
+%URI.AllowedSchemes by simply registering a HTMLPurifier_URIScheme to the\r
+registry.  If false, you will also have to update that directive in order\r
+to add more schemes.\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt
new file mode 100644 (file)
index 0000000..7e1f227
--- /dev/null
@@ -0,0 +1,22 @@
+URI.SafeIframeRegexp\r
+TYPE: string/null\r
+VERSION: 4.4.0\r
+DEFAULT: NULL\r
+--DESCRIPTION--\r
+<p>\r
+    A PCRE regular expression that will be matched against an iframe URI.  This is\r
+    a relatively inflexible scheme, but works well enough for the most common\r
+    use-case of iframes: embedded video.  This directive only has an effect if\r
+    %HTML.SafeIframe is enabled.  Here are some example values:\r
+</p>\r
+<ul>\r
+    <li><code>%^http://www.youtube.com/embed/%</code> - Allow YouTube videos</li>\r
+    <li><code>%^http://player.vimeo.com/video/%</code> - Allow Vimeo videos</li>\r
+    <li><code>%^http://(www.youtube.com/embed/|player.vimeo.com/video/)%</code> - Allow both</li>\r
+</ul>\r
+<p>\r
+    Note that this directive does not give you enough granularity to, say, disable\r
+    all <code>autoplay</code> videos.  Pipe up on the HTML Purifier forums if this\r
+    is a capability you want.\r
+</p>\r
+--# vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/info.ini b/code/backend/standalone/HTMLPurifier/ConfigSchema/schema/info.ini
new file mode 100644 (file)
index 0000000..58e0ce4
--- /dev/null
@@ -0,0 +1,3 @@
+name = "HTML Purifier"\r
+\r
+; vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/EntityLookup/entities.ser b/code/backend/standalone/HTMLPurifier/EntityLookup/entities.ser
new file mode 100644 (file)
index 0000000..e8b0812
--- /dev/null
@@ -0,0 +1 @@
+a:253:{s:4:"fnof";s:2:"ƒ";s:5:"Alpha";s:2:"Α";s:4:"Beta";s:2:"Β";s:5:"Gamma";s:2:"Γ";s:5:"Delta";s:2:"Δ";s:7:"Epsilon";s:2:"Ε";s:4:"Zeta";s:2:"Ζ";s:3:"Eta";s:2:"Η";s:5:"Theta";s:2:"Θ";s:4:"Iota";s:2:"Ι";s:5:"Kappa";s:2:"Κ";s:6:"Lambda";s:2:"Λ";s:2:"Mu";s:2:"Μ";s:2:"Nu";s:2:"Ν";s:2:"Xi";s:2:"Ξ";s:7:"Omicron";s:2:"Ο";s:2:"Pi";s:2:"Π";s:3:"Rho";s:2:"Ρ";s:5:"Sigma";s:2:"Σ";s:3:"Tau";s:2:"Τ";s:7:"Upsilon";s:2:"Υ";s:3:"Phi";s:2:"Φ";s:3:"Chi";s:2:"Χ";s:3:"Psi";s:2:"Ψ";s:5:"Omega";s:2:"Ω";s:5:"alpha";s:2:"α";s:4:"beta";s:2:"β";s:5:"gamma";s:2:"γ";s:5:"delta";s:2:"δ";s:7:"epsilon";s:2:"ε";s:4:"zeta";s:2:"ζ";s:3:"eta";s:2:"η";s:5:"theta";s:2:"θ";s:4:"iota";s:2:"ι";s:5:"kappa";s:2:"κ";s:6:"lambda";s:2:"λ";s:2:"mu";s:2:"μ";s:2:"nu";s:2:"ν";s:2:"xi";s:2:"ξ";s:7:"omicron";s:2:"ο";s:2:"pi";s:2:"π";s:3:"rho";s:2:"ρ";s:6:"sigmaf";s:2:"ς";s:5:"sigma";s:2:"σ";s:3:"tau";s:2:"τ";s:7:"upsilon";s:2:"υ";s:3:"phi";s:2:"φ";s:3:"chi";s:2:"χ";s:3:"psi";s:2:"ψ";s:5:"omega";s:2:"ω";s:8:"thetasym";s:2:"ϑ";s:5:"upsih";s:2:"ϒ";s:3:"piv";s:2:"ϖ";s:4:"bull";s:3:"•";s:6:"hellip";s:3:"…";s:5:"prime";s:3:"′";s:5:"Prime";s:3:"″";s:5:"oline";s:3:"‾";s:5:"frasl";s:3:"⁄";s:6:"weierp";s:3:"℘";s:5:"image";s:3:"ℑ";s:4:"real";s:3:"ℜ";s:5:"trade";s:3:"™";s:7:"alefsym";s:3:"ℵ";s:4:"larr";s:3:"←";s:4:"uarr";s:3:"↑";s:4:"rarr";s:3:"→";s:4:"darr";s:3:"↓";s:4:"harr";s:3:"↔";s:5:"crarr";s:3:"↵";s:4:"lArr";s:3:"⇐";s:4:"uArr";s:3:"⇑";s:4:"rArr";s:3:"⇒";s:4:"dArr";s:3:"⇓";s:4:"hArr";s:3:"⇔";s:6:"forall";s:3:"∀";s:4:"part";s:3:"∂";s:5:"exist";s:3:"∃";s:5:"empty";s:3:"∅";s:5:"nabla";s:3:"∇";s:4:"isin";s:3:"∈";s:5:"notin";s:3:"∉";s:2:"ni";s:3:"∋";s:4:"prod";s:3:"∏";s:3:"sum";s:3:"∑";s:5:"minus";s:3:"−";s:6:"lowast";s:3:"∗";s:5:"radic";s:3:"√";s:4:"prop";s:3:"∝";s:5:"infin";s:3:"∞";s:3:"ang";s:3:"∠";s:3:"and";s:3:"∧";s:2:"or";s:3:"∨";s:3:"cap";s:3:"∩";s:3:"cup";s:3:"∪";s:3:"int";s:3:"∫";s:6:"there4";s:3:"∴";s:3:"sim";s:3:"∼";s:4:"cong";s:3:"≅";s:5:"asymp";s:3:"≈";s:2:"ne";s:3:"≠";s:5:"equiv";s:3:"≡";s:2:"le";s:3:"≤";s:2:"ge";s:3:"≥";s:3:"sub";s:3:"⊂";s:3:"sup";s:3:"⊃";s:4:"nsub";s:3:"⊄";s:4:"sube";s:3:"⊆";s:4:"supe";s:3:"⊇";s:5:"oplus";s:3:"⊕";s:6:"otimes";s:3:"⊗";s:4:"perp";s:3:"⊥";s:4:"sdot";s:3:"⋅";s:5:"lceil";s:3:"⌈";s:5:"rceil";s:3:"⌉";s:6:"lfloor";s:3:"⌊";s:6:"rfloor";s:3:"⌋";s:4:"lang";s:3:"〈";s:4:"rang";s:3:"〉";s:3:"loz";s:3:"◊";s:6:"spades";s:3:"♠";s:5:"clubs";s:3:"♣";s:6:"hearts";s:3:"♥";s:5:"diams";s:3:"♦";s:4:"quot";s:1:""";s:3:"amp";s:1:"&";s:2:"lt";s:1:"<";s:2:"gt";s:1:">";s:4:"apos";s:1:"'";s:5:"OElig";s:2:"Œ";s:5:"oelig";s:2:"œ";s:6:"Scaron";s:2:"Š";s:6:"scaron";s:2:"š";s:4:"Yuml";s:2:"Ÿ";s:4:"circ";s:2:"ˆ";s:5:"tilde";s:2:"˜";s:4:"ensp";s:3:" ";s:4:"emsp";s:3:" ";s:6:"thinsp";s:3:" ";s:4:"zwnj";s:3:"‌";s:3:"zwj";s:3:"‍";s:3:"lrm";s:3:"‎";s:3:"rlm";s:3:"‏";s:5:"ndash";s:3:"–";s:5:"mdash";s:3:"—";s:5:"lsquo";s:3:"‘";s:5:"rsquo";s:3:"’";s:5:"sbquo";s:3:"‚";s:5:"ldquo";s:3:"“";s:5:"rdquo";s:3:"”";s:5:"bdquo";s:3:"„";s:6:"dagger";s:3:"†";s:6:"Dagger";s:3:"‡";s:6:"permil";s:3:"‰";s:6:"lsaquo";s:3:"‹";s:6:"rsaquo";s:3:"›";s:4:"euro";s:3:"€";s:4:"nbsp";s:2:" ";s:5:"iexcl";s:2:"¡";s:4:"cent";s:2:"¢";s:5:"pound";s:2:"£";s:6:"curren";s:2:"¤";s:3:"yen";s:2:"¥";s:6:"brvbar";s:2:"¦";s:4:"sect";s:2:"§";s:3:"uml";s:2:"¨";s:4:"copy";s:2:"©";s:4:"ordf";s:2:"ª";s:5:"laquo";s:2:"«";s:3:"not";s:2:"¬";s:3:"shy";s:2:"­";s:3:"reg";s:2:"®";s:4:"macr";s:2:"¯";s:3:"deg";s:2:"°";s:6:"plusmn";s:2:"±";s:4:"sup2";s:2:"²";s:4:"sup3";s:2:"³";s:5:"acute";s:2:"´";s:5:"micro";s:2:"µ";s:4:"para";s:2:"¶";s:6:"middot";s:2:"·";s:5:"cedil";s:2:"¸";s:4:"sup1";s:2:"¹";s:4:"ordm";s:2:"º";s:5:"raquo";s:2:"»";s:6:"frac14";s:2:"¼";s:6:"frac12";s:2:"½";s:6:"frac34";s:2:"¾";s:6:"iquest";s:2:"¿";s:6:"Agrave";s:2:"À";s:6:"Aacute";s:2:"Á";s:5:"Acirc";s:2:"Â";s:6:"Atilde";s:2:"Ã";s:4:"Auml";s:2:"Ä";s:5:"Aring";s:2:"Å";s:5:"AElig";s:2:"Æ";s:6:"Ccedil";s:2:"Ç";s:6:"Egrave";s:2:"È";s:6:"Eacute";s:2:"É";s:5:"Ecirc";s:2:"Ê";s:4:"Euml";s:2:"Ë";s:6:"Igrave";s:2:"Ì";s:6:"Iacute";s:2:"Í";s:5:"Icirc";s:2:"Î";s:4:"Iuml";s:2:"Ï";s:3:"ETH";s:2:"Ð";s:6:"Ntilde";s:2:"Ñ";s:6:"Ograve";s:2:"Ò";s:6:"Oacute";s:2:"Ó";s:5:"Ocirc";s:2:"Ô";s:6:"Otilde";s:2:"Õ";s:4:"Ouml";s:2:"Ö";s:5:"times";s:2:"×";s:6:"Oslash";s:2:"Ø";s:6:"Ugrave";s:2:"Ù";s:6:"Uacute";s:2:"Ú";s:5:"Ucirc";s:2:"Û";s:4:"Uuml";s:2:"Ü";s:6:"Yacute";s:2:"Ý";s:5:"THORN";s:2:"Þ";s:5:"szlig";s:2:"ß";s:6:"agrave";s:2:"à";s:6:"aacute";s:2:"á";s:5:"acirc";s:2:"â";s:6:"atilde";s:2:"ã";s:4:"auml";s:2:"ä";s:5:"aring";s:2:"å";s:5:"aelig";s:2:"æ";s:6:"ccedil";s:2:"ç";s:6:"egrave";s:2:"è";s:6:"eacute";s:2:"é";s:5:"ecirc";s:2:"ê";s:4:"euml";s:2:"ë";s:6:"igrave";s:2:"ì";s:6:"iacute";s:2:"í";s:5:"icirc";s:2:"î";s:4:"iuml";s:2:"ï";s:3:"eth";s:2:"ð";s:6:"ntilde";s:2:"ñ";s:6:"ograve";s:2:"ò";s:6:"oacute";s:2:"ó";s:5:"ocirc";s:2:"ô";s:6:"otilde";s:2:"õ";s:4:"ouml";s:2:"ö";s:6:"divide";s:2:"÷";s:6:"oslash";s:2:"ø";s:6:"ugrave";s:2:"ù";s:6:"uacute";s:2:"ú";s:5:"ucirc";s:2:"û";s:4:"uuml";s:2:"ü";s:6:"yacute";s:2:"ý";s:5:"thorn";s:2:"þ";s:4:"yuml";s:2:"ÿ";}
\ No newline at end of file
diff --git a/code/backend/standalone/HTMLPurifier/Filter/ExtractStyleBlocks.php b/code/backend/standalone/HTMLPurifier/Filter/ExtractStyleBlocks.php
new file mode 100644 (file)
index 0000000..5af24c2
--- /dev/null
@@ -0,0 +1,341 @@
+<?php\r
+\r
+// why is this a top level function? Because PHP 5.2.0 doesn't seem to\r
+// understand how to interpret this filter if it's a static method.\r
+// It's all really silly, but if we go this route it might be reasonable\r
+// to coalesce all of these methods into one.\r
+function htmlpurifier_filter_extractstyleblocks_muteerrorhandler()\r
+{\r
+}\r
+\r
+/**\r
+ * This filter extracts <style> blocks from input HTML, cleans them up\r
+ * using CSSTidy, and then places them in $purifier->context->get('StyleBlocks')\r
+ * so they can be used elsewhere in the document.\r
+ *\r
+ * @note\r
+ *      See tests/HTMLPurifier/Filter/ExtractStyleBlocksTest.php for\r
+ *      sample usage.\r
+ *\r
+ * @note\r
+ *      This filter can also be used on stylesheets not included in the\r
+ *      document--something purists would probably prefer. Just directly\r
+ *      call HTMLPurifier_Filter_ExtractStyleBlocks->cleanCSS()\r
+ */\r
+class HTMLPurifier_Filter_ExtractStyleBlocks extends HTMLPurifier_Filter\r
+{\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'ExtractStyleBlocks';\r
+\r
+    /**\r
+     * @type array\r
+     */\r
+    private $_styleMatches = array();\r
+\r
+    /**\r
+     * @type csstidy\r
+     */\r
+    private $_tidy;\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrDef_HTML_ID\r
+     */\r
+    private $_id_attrdef;\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrDef_CSS_Ident\r
+     */\r
+    private $_class_attrdef;\r
+\r
+    /**\r
+     * @type HTMLPurifier_AttrDef_Enum\r
+     */\r
+    private $_enum_attrdef;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->_tidy = new csstidy();\r
+        $this->_tidy->set_cfg('lowercase_s', false);\r
+        $this->_id_attrdef = new HTMLPurifier_AttrDef_HTML_ID(true);\r
+        $this->_class_attrdef = new HTMLPurifier_AttrDef_CSS_Ident();\r
+        $this->_enum_attrdef = new HTMLPurifier_AttrDef_Enum(\r
+            array(\r
+                'first-child',\r
+                'link',\r
+                'visited',\r
+                'active',\r
+                'hover',\r
+                'focus'\r
+            )\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Save the contents of CSS blocks to style matches\r
+     * @param array $matches preg_replace style $matches array\r
+     */\r
+    protected function styleCallback($matches)\r
+    {\r
+        $this->_styleMatches[] = $matches[1];\r
+    }\r
+\r
+    /**\r
+     * Removes inline <style> tags from HTML, saves them for later use\r
+     * @param string $html\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     * @todo Extend to indicate non-text/css style blocks\r
+     */\r
+    public function preFilter($html, $config, $context)\r
+    {\r
+        $tidy = $config->get('Filter.ExtractStyleBlocks.TidyImpl');\r
+        if ($tidy !== null) {\r
+            $this->_tidy = $tidy;\r
+        }\r
+        // NB: this must be NON-greedy because if we have\r
+        // <style>foo</style>  <style>bar</style>\r
+        // we must not grab foo</style>  <style>bar\r
+        $html = preg_replace_callback('#<style(?:\s.*)?>(.*)<\/style>#isU', array($this, 'styleCallback'), $html);\r
+        $style_blocks = $this->_styleMatches;\r
+        $this->_styleMatches = array(); // reset\r
+        $context->register('StyleBlocks', $style_blocks); // $context must not be reused\r
+        if ($this->_tidy) {\r
+            foreach ($style_blocks as &$style) {\r
+                $style = $this->cleanCSS($style, $config, $context);\r
+            }\r
+        }\r
+        return $html;\r
+    }\r
+\r
+    /**\r
+     * Takes CSS (the stuff found in <style>) and cleans it.\r
+     * @warning Requires CSSTidy <http://csstidy.sourceforge.net/>\r
+     * @param string $css CSS styling to clean\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @throws HTMLPurifier_Exception\r
+     * @return string Cleaned CSS\r
+     */\r
+    public function cleanCSS($css, $config, $context)\r
+    {\r
+        // prepare scope\r
+        $scope = $config->get('Filter.ExtractStyleBlocks.Scope');\r
+        if ($scope !== null) {\r
+            $scopes = array_map('trim', explode(',', $scope));\r
+        } else {\r
+            $scopes = array();\r
+        }\r
+        // remove comments from CSS\r
+        $css = trim($css);\r
+        if (strncmp('<!--', $css, 4) === 0) {\r
+            $css = substr($css, 4);\r
+        }\r
+        if (strlen($css) > 3 && substr($css, -3) == '-->') {\r
+            $css = substr($css, 0, -3);\r
+        }\r
+        $css = trim($css);\r
+        set_error_handler('htmlpurifier_filter_extractstyleblocks_muteerrorhandler');\r
+        $this->_tidy->parse($css);\r
+        restore_error_handler();\r
+        $css_definition = $config->getDefinition('CSS');\r
+        $html_definition = $config->getDefinition('HTML');\r
+        $new_css = array();\r
+        foreach ($this->_tidy->css as $k => $decls) {\r
+            // $decls are all CSS declarations inside an @ selector\r
+            $new_decls = array();\r
+            foreach ($decls as $selector => $style) {\r
+                $selector = trim($selector);\r
+                if ($selector === '') {\r
+                    continue;\r
+                } // should not happen\r
+                // Parse the selector\r
+                // Here is the relevant part of the CSS grammar:\r
+                //\r
+                // ruleset\r
+                //   : selector [ ',' S* selector ]* '{' ...\r
+                // selector\r
+                //   : simple_selector [ combinator selector | S+ [ combinator? selector ]? ]?\r
+                // combinator\r
+                //   : '+' S*\r
+                //   : '>' S*\r
+                // simple_selector\r
+                //   : element_name [ HASH | class | attrib | pseudo ]*\r
+                //   | [ HASH | class | attrib | pseudo ]+\r
+                // element_name\r
+                //   : IDENT | '*'\r
+                //   ;\r
+                // class\r
+                //   : '.' IDENT\r
+                //   ;\r
+                // attrib\r
+                //   : '[' S* IDENT S* [ [ '=' | INCLUDES | DASHMATCH ] S*\r
+                //     [ IDENT | STRING ] S* ]? ']'\r
+                //   ;\r
+                // pseudo\r
+                //   : ':' [ IDENT | FUNCTION S* [IDENT S*]? ')' ]\r
+                //   ;\r
+                //\r
+                // For reference, here are the relevant tokens:\r
+                //\r
+                // HASH         #{name}\r
+                // IDENT        {ident}\r
+                // INCLUDES     ==\r
+                // DASHMATCH    |=\r
+                // STRING       {string}\r
+                // FUNCTION     {ident}\(\r
+                //\r
+                // And the lexical scanner tokens\r
+                //\r
+                // name         {nmchar}+\r
+                // nmchar       [_a-z0-9-]|{nonascii}|{escape}\r
+                // nonascii     [\240-\377]\r
+                // escape       {unicode}|\\[^\r\n\f0-9a-f]\r
+                // unicode      \\{h}}{1,6}(\r\n|[ \t\r\n\f])?\r
+                // ident        -?{nmstart}{nmchar*}\r
+                // nmstart      [_a-z]|{nonascii}|{escape}\r
+                // string       {string1}|{string2}\r
+                // string1      \"([^\n\r\f\\"]|\\{nl}|{escape})*\"\r
+                // string2      \'([^\n\r\f\\"]|\\{nl}|{escape})*\'\r
+                //\r
+                // We'll implement a subset (in order to reduce attack\r
+                // surface); in particular:\r
+                //\r
+                //      - No Unicode support\r
+                //      - No escapes support\r
+                //      - No string support (by proxy no attrib support)\r
+                //      - element_name is matched against allowed\r
+                //        elements (some people might find this\r
+                //        annoying...)\r
+                //      - Pseudo-elements one of :first-child, :link,\r
+                //        :visited, :active, :hover, :focus\r
+\r
+                // handle ruleset\r
+                $selectors = array_map('trim', explode(',', $selector));\r
+                $new_selectors = array();\r
+                foreach ($selectors as $sel) {\r
+                    // split on +, > and spaces\r
+                    $basic_selectors = preg_split('/\s*([+> ])\s*/', $sel, -1, PREG_SPLIT_DELIM_CAPTURE);\r
+                    // even indices are chunks, odd indices are\r
+                    // delimiters\r
+                    $nsel = null;\r
+                    $delim = null; // guaranteed to be non-null after\r
+                    // two loop iterations\r
+                    for ($i = 0, $c = count($basic_selectors); $i < $c; $i++) {\r
+                        $x = $basic_selectors[$i];\r
+                        if ($i % 2) {\r
+                            // delimiter\r
+                            if ($x === ' ') {\r
+                                $delim = ' ';\r
+                            } else {\r
+                                $delim = ' ' . $x . ' ';\r
+                            }\r
+                        } else {\r
+                            // simple selector\r
+                            $components = preg_split('/([#.:])/', $x, -1, PREG_SPLIT_DELIM_CAPTURE);\r
+                            $sdelim = null;\r
+                            $nx = null;\r
+                            for ($j = 0, $cc = count($components); $j < $cc; $j++) {\r
+                                $y = $components[$j];\r
+                                if ($j === 0) {\r
+                                    if ($y === '*' || isset($html_definition->info[$y = strtolower($y)])) {\r
+                                        $nx = $y;\r
+                                    } else {\r
+                                        // $nx stays null; this matters\r
+                                        // if we don't manage to find\r
+                                        // any valid selector content,\r
+                                        // in which case we ignore the\r
+                                        // outer $delim\r
+                                    }\r
+                                } elseif ($j % 2) {\r
+                                    // set delimiter\r
+                                    $sdelim = $y;\r
+                                } else {\r
+                                    $attrdef = null;\r
+                                    if ($sdelim === '#') {\r
+                                        $attrdef = $this->_id_attrdef;\r
+                                    } elseif ($sdelim === '.') {\r
+                                        $attrdef = $this->_class_attrdef;\r
+                                    } elseif ($sdelim === ':') {\r
+                                        $attrdef = $this->_enum_attrdef;\r
+                                    } else {\r
+                                        throw new HTMLPurifier_Exception('broken invariant sdelim and preg_split');\r
+                                    }\r
+                                    $r = $attrdef->validate($y, $config, $context);\r
+                                    if ($r !== false) {\r
+                                        if ($r !== true) {\r
+                                            $y = $r;\r
+                                        }\r
+                                        if ($nx === null) {\r
+                                            $nx = '';\r
+                                        }\r
+                                        $nx .= $sdelim . $y;\r
+                                    }\r
+                                }\r
+                            }\r
+                            if ($nx !== null) {\r
+                                if ($nsel === null) {\r
+                                    $nsel = $nx;\r
+                                } else {\r
+                                    $nsel .= $delim . $nx;\r
+                                }\r
+                            } else {\r
+                                // delimiters to the left of invalid\r
+                                // basic selector ignored\r
+                            }\r
+                        }\r
+                    }\r
+                    if ($nsel !== null) {\r
+                        if (!empty($scopes)) {\r
+                            foreach ($scopes as $s) {\r
+                                $new_selectors[] = "$s $nsel";\r
+                            }\r
+                        } else {\r
+                            $new_selectors[] = $nsel;\r
+                        }\r
+                    }\r
+                }\r
+                if (empty($new_selectors)) {\r
+                    continue;\r
+                }\r
+                $selector = implode(', ', $new_selectors);\r
+                foreach ($style as $name => $value) {\r
+                    if (!isset($css_definition->info[$name])) {\r
+                        unset($style[$name]);\r
+                        continue;\r
+                    }\r
+                    $def = $css_definition->info[$name];\r
+                    $ret = $def->validate($value, $config, $context);\r
+                    if ($ret === false) {\r
+                        unset($style[$name]);\r
+                    } else {\r
+                        $style[$name] = $ret;\r
+                    }\r
+                }\r
+                $new_decls[$selector] = $style;\r
+            }\r
+            $new_css[$k] = $new_decls;\r
+        }\r
+        // remove stuff that shouldn't be used, could be reenabled\r
+        // after security risks are analyzed\r
+        $this->_tidy->css = $new_css;\r
+        $this->_tidy->import = array();\r
+        $this->_tidy->charset = null;\r
+        $this->_tidy->namespace = null;\r
+        $css = $this->_tidy->print->plain();\r
+        // we are going to escape any special characters <>& to ensure\r
+        // that no funny business occurs (i.e. </style> in a font-family prop).\r
+        if ($config->get('Filter.ExtractStyleBlocks.Escaping')) {\r
+            $css = str_replace(\r
+                array('<', '>', '&'),\r
+                array('\3C ', '\3E ', '\26 '),\r
+                $css\r
+            );\r
+        }\r
+        return $css;\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/Filter/YouTube.php b/code/backend/standalone/HTMLPurifier/Filter/YouTube.php
new file mode 100644 (file)
index 0000000..b90ddf7
--- /dev/null
@@ -0,0 +1,65 @@
+<?php\r
+\r
+class HTMLPurifier_Filter_YouTube extends HTMLPurifier_Filter\r
+{\r
+\r
+    /**\r
+     * @type string\r
+     */\r
+    public $name = 'YouTube';\r
+\r
+    /**\r
+     * @param string $html\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     */\r
+    public function preFilter($html, $config, $context)\r
+    {\r
+        $pre_regex = '#<object[^>]+>.+?' .\r
+            '(?:http:)?//www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s';\r
+        $pre_replace = '<span class="youtube-embed">\1</span>';\r
+        return preg_replace($pre_regex, $pre_replace, $html);\r
+    }\r
+\r
+    /**\r
+     * @param string $html\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return string\r
+     */\r
+    public function postFilter($html, $config, $context)\r
+    {\r
+        $post_regex = '#<span class="youtube-embed">((?:v|cp)/[A-Za-z0-9\-_=]+)</span>#';\r
+        return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html);\r
+    }\r
+\r
+    /**\r
+     * @param $url\r
+     * @return string\r
+     */\r
+    protected function armorUrl($url)\r
+    {\r
+        return str_replace('--', '-&#45;', $url);\r
+    }\r
+\r
+    /**\r
+     * @param array $matches\r
+     * @return string\r
+     */\r
+    protected function postFilterCallback($matches)\r
+    {\r
+        $url = $this->armorUrl($matches[1]);\r
+        return '<object width="425" height="350" type="application/x-shockwave-flash" ' .\r
+        'data="//www.youtube.com/' . $url . '">' .\r
+        '<param name="movie" value="//www.youtube.com/' . $url . '"></param>' .\r
+        '<!--[if IE]>' .\r
+        '<embed src="//www.youtube.com/' . $url . '"' .\r
+        'type="application/x-shockwave-flash"' .\r
+        'wmode="transparent" width="425" height="350" />' .\r
+        '<![endif]-->' .\r
+        '</object>';\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/Language/classes/en-x-test.php b/code/backend/standalone/HTMLPurifier/Language/classes/en-x-test.php
new file mode 100644 (file)
index 0000000..a6f8d16
--- /dev/null
@@ -0,0 +1,9 @@
+<?php\r
+\r
+// private class for unit testing\r
+\r
+class HTMLPurifier_Language_en_x_test extends HTMLPurifier_Language\r
+{\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/Language/messages/en-x-test.php b/code/backend/standalone/HTMLPurifier/Language/messages/en-x-test.php
new file mode 100644 (file)
index 0000000..8328054
--- /dev/null
@@ -0,0 +1,13 @@
+<?php\r
+\r
+// private language message file for unit testing purposes\r
+\r
+$fallback = 'en';\r
+\r
+$messages = array(\r
+    'HTMLPurifier' => 'HTML Purifier X'\r
+);\r
+\r
+$errorNames = array();\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/Language/messages/en-x-testmini.php b/code/backend/standalone/HTMLPurifier/Language/messages/en-x-testmini.php
new file mode 100644 (file)
index 0000000..b6d1c99
--- /dev/null
@@ -0,0 +1,14 @@
+<?php\r
+\r
+// private language message file for unit testing purposes\r
+// this language file has no class associated with it\r
+\r
+$fallback = 'en';\r
+\r
+$messages = array(\r
+    'HTMLPurifier' => 'HTML Purifier XNone'\r
+);\r
+\r
+$errorNames = array();\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/Language/messages/en.php b/code/backend/standalone/HTMLPurifier/Language/messages/en.php
new file mode 100644 (file)
index 0000000..1fa30bd
--- /dev/null
@@ -0,0 +1,55 @@
+<?php\r
+\r
+$fallback = false;\r
+\r
+$messages = array(\r
+\r
+    'HTMLPurifier' => 'HTML Purifier',\r
+// for unit testing purposes\r
+    'LanguageFactoryTest: Pizza' => 'Pizza',\r
+    'LanguageTest: List' => '$1',\r
+    'LanguageTest: Hash' => '$1.Keys; $1.Values',\r
+    'Item separator' => ', ',\r
+    'Item separator last' => ' and ', // non-Harvard style\r
+\r
+    'ErrorCollector: No errors' => 'No errors detected. However, because error reporting is still incomplete, there may have been errors that the error collector was not notified of; please inspect the output HTML carefully.',\r
+    'ErrorCollector: At line' => ' at line $line',\r
+    'ErrorCollector: Incidental errors' => 'Incidental errors',\r
+    'Lexer: Unclosed comment' => 'Unclosed comment',\r
+    'Lexer: Unescaped lt' => 'Unescaped less-than sign (<) should be &lt;',\r
+    'Lexer: Missing gt' => 'Missing greater-than sign (>), previous less-than sign (<) should be escaped',\r
+    'Lexer: Missing attribute key' => 'Attribute declaration has no key',\r
+    'Lexer: Missing end quote' => 'Attribute declaration has no end quote',\r
+    'Lexer: Extracted body' => 'Removed document metadata tags',\r
+    'Strategy_RemoveForeignElements: Tag transform' => '<$1> element transformed into $CurrentToken.Serialized',\r
+    'Strategy_RemoveForeignElements: Missing required attribute' => '$CurrentToken.Compact element missing required attribute $1',\r
+    'Strategy_RemoveForeignElements: Foreign element to text' => 'Unrecognized $CurrentToken.Serialized tag converted to text',\r
+    'Strategy_RemoveForeignElements: Foreign element removed' => 'Unrecognized $CurrentToken.Serialized tag removed',\r
+    'Strategy_RemoveForeignElements: Comment removed' => 'Comment containing "$CurrentToken.Data" removed',\r
+    'Strategy_RemoveForeignElements: Foreign meta element removed' => 'Unrecognized $CurrentToken.Serialized meta tag and all descendants removed',\r
+    'Strategy_RemoveForeignElements: Token removed to end' => 'Tags and text starting from $1 element where removed to end',\r
+    'Strategy_RemoveForeignElements: Trailing hyphen in comment removed' => 'Trailing hyphen(s) in comment removed',\r
+    'Strategy_RemoveForeignElements: Hyphens in comment collapsed' => 'Double hyphens in comments are not allowed, and were collapsed into single hyphens',\r
+    'Strategy_MakeWellFormed: Unnecessary end tag removed' => 'Unnecessary $CurrentToken.Serialized tag removed',\r
+    'Strategy_MakeWellFormed: Unnecessary end tag to text' => 'Unnecessary $CurrentToken.Serialized tag converted to text',\r
+    'Strategy_MakeWellFormed: Tag auto closed' => '$1.Compact started on line $1.Line auto-closed by $CurrentToken.Compact',\r
+    'Strategy_MakeWellFormed: Tag carryover' => '$1.Compact started on line $1.Line auto-continued into $CurrentToken.Compact',\r
+    'Strategy_MakeWellFormed: Stray end tag removed' => 'Stray $CurrentToken.Serialized tag removed',\r
+    'Strategy_MakeWellFormed: Stray end tag to text' => 'Stray $CurrentToken.Serialized tag converted to text',\r
+    'Strategy_MakeWellFormed: Tag closed by element end' => '$1.Compact tag started on line $1.Line closed by end of $CurrentToken.Serialized',\r
+    'Strategy_MakeWellFormed: Tag closed by document end' => '$1.Compact tag started on line $1.Line closed by end of document',\r
+    'Strategy_FixNesting: Node removed' => '$CurrentToken.Compact node removed',\r
+    'Strategy_FixNesting: Node excluded' => '$CurrentToken.Compact node removed due to descendant exclusion by ancestor element',\r
+    'Strategy_FixNesting: Node reorganized' => 'Contents of $CurrentToken.Compact node reorganized to enforce its content model',\r
+    'Strategy_FixNesting: Node contents removed' => 'Contents of $CurrentToken.Compact node removed',\r
+    'AttrValidator: Attributes transformed' => 'Attributes on $CurrentToken.Compact transformed from $1.Keys to $2.Keys',\r
+    'AttrValidator: Attribute removed' => '$CurrentAttr.Name attribute on $CurrentToken.Compact removed',\r
+);\r
+\r
+$errorNames = array(\r
+    E_ERROR => 'Error',\r
+    E_WARNING => 'Warning',\r
+    E_NOTICE => 'Notice'\r
+);\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/Lexer/PH5P.php b/code/backend/standalone/HTMLPurifier/Lexer/PH5P.php
new file mode 100644 (file)
index 0000000..6b281a5
--- /dev/null
@@ -0,0 +1,4788 @@
+<?php\r
+\r
+/**\r
+ * Experimental HTML5-based parser using Jeroen van der Meer's PH5P library.\r
+ * Occupies space in the HTML5 pseudo-namespace, which may cause conflicts.\r
+ *\r
+ * @note\r
+ *    Recent changes to PHP's DOM extension have resulted in some fatal\r
+ *    error conditions with the original version of PH5P. Pending changes,\r
+ *    this lexer will punt to DirectLex if DOM throws an exception.\r
+ */\r
+\r
+class HTMLPurifier_Lexer_PH5P extends HTMLPurifier_Lexer_DOMLex\r
+{\r
+    /**\r
+     * @param string $html\r
+     * @param HTMLPurifier_Config $config\r
+     * @param HTMLPurifier_Context $context\r
+     * @return HTMLPurifier_Token[]\r
+     */\r
+    public function tokenizeHTML($html, $config, $context)\r
+    {\r
+        $new_html = $this->normalize($html, $config, $context);\r
+        $new_html = $this->wrapHTML($new_html, $config, $context, false /* no div */);\r
+        try {\r
+            $parser = new HTML5($new_html);\r
+            $doc = $parser->save();\r
+        } catch (DOMException $e) {\r
+            // Uh oh, it failed. Punt to DirectLex.\r
+            $lexer = new HTMLPurifier_Lexer_DirectLex();\r
+            $context->register('PH5PError', $e); // save the error, so we can detect it\r
+            return $lexer->tokenizeHTML($html, $config, $context); // use original HTML\r
+        }\r
+        $tokens = array();\r
+        $this->tokenizeDOM(\r
+            $doc->getElementsByTagName('html')->item(0)-> // <html>\r
+                  getElementsByTagName('body')->item(0) //   <body>\r
+            ,\r
+            $tokens, $config\r
+        );\r
+        return $tokens;\r
+    }\r
+}\r
+\r
+/*\r
+\r
+Copyright 2007 Jeroen van der Meer <http://jero.net/>\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a\r
+copy of this software and associated documentation files (the\r
+"Software"), to deal in the Software without restriction, including\r
+without limitation the rights to use, copy, modify, merge, publish,\r
+distribute, sublicense, and/or sell copies of the Software, and to\r
+permit persons to whom the Software is furnished to do so, subject to\r
+the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included\r
+in all copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\r
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\r
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+\r
+*/\r
+\r
+class HTML5\r
+{\r
+    private $data;\r
+    private $char;\r
+    private $EOF;\r
+    private $state;\r
+    private $tree;\r
+    private $token;\r
+    private $content_model;\r
+    private $escape = false;\r
+    private $entities = array(\r
+        'AElig;',\r
+        'AElig',\r
+        'AMP;',\r
+        'AMP',\r
+        'Aacute;',\r
+        'Aacute',\r
+        'Acirc;',\r
+        'Acirc',\r
+        'Agrave;',\r
+        'Agrave',\r
+        'Alpha;',\r
+        'Aring;',\r
+        'Aring',\r
+        'Atilde;',\r
+        'Atilde',\r
+        'Auml;',\r
+        'Auml',\r
+        'Beta;',\r
+        'COPY;',\r
+        'COPY',\r
+        'Ccedil;',\r
+        'Ccedil',\r
+        'Chi;',\r
+        'Dagger;',\r
+        'Delta;',\r
+        'ETH;',\r
+        'ETH',\r
+        'Eacute;',\r
+        'Eacute',\r
+        'Ecirc;',\r
+        'Ecirc',\r
+        'Egrave;',\r
+        'Egrave',\r
+        'Epsilon;',\r
+        'Eta;',\r
+        'Euml;',\r
+        'Euml',\r
+        'GT;',\r
+        'GT',\r
+        'Gamma;',\r
+        'Iacute;',\r
+        'Iacute',\r
+        'Icirc;',\r
+        'Icirc',\r
+        'Igrave;',\r
+        'Igrave',\r
+        'Iota;',\r
+        'Iuml;',\r
+        'Iuml',\r
+        'Kappa;',\r
+        'LT;',\r
+        'LT',\r
+        'Lambda;',\r
+        'Mu;',\r
+        'Ntilde;',\r
+        'Ntilde',\r
+        'Nu;',\r
+        'OElig;',\r
+        'Oacute;',\r
+        'Oacute',\r
+        'Ocirc;',\r
+        'Ocirc',\r
+        'Ograve;',\r
+        'Ograve',\r
+        'Omega;',\r
+        'Omicron;',\r
+        'Oslash;',\r
+        'Oslash',\r
+        'Otilde;',\r
+        'Otilde',\r
+        'Ouml;',\r
+        'Ouml',\r
+        'Phi;',\r
+        'Pi;',\r
+        'Prime;',\r
+        'Psi;',\r
+        'QUOT;',\r
+        'QUOT',\r
+        'REG;',\r
+        'REG',\r
+        'Rho;',\r
+        'Scaron;',\r
+        'Sigma;',\r
+        'THORN;',\r
+        'THORN',\r
+        'TRADE;',\r
+        'Tau;',\r
+        'Theta;',\r
+        'Uacute;',\r
+        'Uacute',\r
+        'Ucirc;',\r
+        'Ucirc',\r
+        'Ugrave;',\r
+        'Ugrave',\r
+        'Upsilon;',\r
+        'Uuml;',\r
+        'Uuml',\r
+        'Xi;',\r
+        'Yacute;',\r
+        'Yacute',\r
+        'Yuml;',\r
+        'Zeta;',\r
+        'aacute;',\r
+        'aacute',\r
+        'acirc;',\r
+        'acirc',\r
+        'acute;',\r
+        'acute',\r
+        'aelig;',\r
+        'aelig',\r
+        'agrave;',\r
+        'agrave',\r
+        'alefsym;',\r
+        'alpha;',\r
+        'amp;',\r
+        'amp',\r
+        'and;',\r
+        'ang;',\r
+        'apos;',\r
+        'aring;',\r
+        'aring',\r
+        'asymp;',\r
+        'atilde;',\r
+        'atilde',\r
+        'auml;',\r
+        'auml',\r
+        'bdquo;',\r
+        'beta;',\r
+        'brvbar;',\r
+        'brvbar',\r
+        'bull;',\r
+        'cap;',\r
+        'ccedil;',\r
+        'ccedil',\r
+        'cedil;',\r
+        'cedil',\r
+        'cent;',\r
+        'cent',\r
+        'chi;',\r
+        'circ;',\r
+        'clubs;',\r
+        'cong;',\r
+        'copy;',\r
+        'copy',\r
+        'crarr;',\r
+        'cup;',\r
+        'curren;',\r
+        'curren',\r
+        'dArr;',\r
+        'dagger;',\r
+        'darr;',\r
+        'deg;',\r
+        'deg',\r
+        'delta;',\r
+        'diams;',\r
+        'divide;',\r
+        'divide',\r
+        'eacute;',\r
+        'eacute',\r
+        'ecirc;',\r
+        'ecirc',\r
+        'egrave;',\r
+        'egrave',\r
+        'empty;',\r
+        'emsp;',\r
+        'ensp;',\r
+        'epsilon;',\r
+        'equiv;',\r
+        'eta;',\r
+        'eth;',\r
+        'eth',\r
+        'euml;',\r
+        'euml',\r
+        'euro;',\r
+        'exist;',\r
+        'fnof;',\r
+        'forall;',\r
+        'frac12;',\r
+        'frac12',\r
+        'frac14;',\r
+        'frac14',\r
+        'frac34;',\r
+        'frac34',\r
+        'frasl;',\r
+        'gamma;',\r
+        'ge;',\r
+        'gt;',\r
+        'gt',\r
+        'hArr;',\r
+        'harr;',\r
+        'hearts;',\r
+        'hellip;',\r
+        'iacute;',\r
+        'iacute',\r
+        'icirc;',\r
+        'icirc',\r
+        'iexcl;',\r
+        'iexcl',\r
+        'igrave;',\r
+        'igrave',\r
+        'image;',\r
+        'infin;',\r
+        'int;',\r
+        'iota;',\r
+        'iquest;',\r
+        'iquest',\r
+        'isin;',\r
+        'iuml;',\r
+        'iuml',\r
+        'kappa;',\r
+        'lArr;',\r
+        'lambda;',\r
+        'lang;',\r
+        'laquo;',\r
+        'laquo',\r
+        'larr;',\r
+        'lceil;',\r
+        'ldquo;',\r
+        'le;',\r
+        'lfloor;',\r
+        'lowast;',\r
+        'loz;',\r
+        'lrm;',\r
+        'lsaquo;',\r
+        'lsquo;',\r
+        'lt;',\r
+        'lt',\r
+        'macr;',\r
+        'macr',\r
+        'mdash;',\r
+        'micro;',\r
+        'micro',\r
+        'middot;',\r
+        'middot',\r
+        'minus;',\r
+        'mu;',\r
+        'nabla;',\r
+        'nbsp;',\r
+        'nbsp',\r
+        'ndash;',\r
+        'ne;',\r
+        'ni;',\r
+        'not;',\r
+        'not',\r
+        'notin;',\r
+        'nsub;',\r
+        'ntilde;',\r
+        'ntilde',\r
+        'nu;',\r
+        'oacute;',\r
+        'oacute',\r
+        'ocirc;',\r
+        'ocirc',\r
+        'oelig;',\r
+        'ograve;',\r
+        'ograve',\r
+        'oline;',\r
+        'omega;',\r
+        'omicron;',\r
+        'oplus;',\r
+        'or;',\r
+        'ordf;',\r
+        'ordf',\r
+        'ordm;',\r
+        'ordm',\r
+        'oslash;',\r
+        'oslash',\r
+        'otilde;',\r
+        'otilde',\r
+        'otimes;',\r
+        'ouml;',\r
+        'ouml',\r
+        'para;',\r
+        'para',\r
+        'part;',\r
+        'permil;',\r
+        'perp;',\r
+        'phi;',\r
+        'pi;',\r
+        'piv;',\r
+        'plusmn;',\r
+        'plusmn',\r
+        'pound;',\r
+        'pound',\r
+        'prime;',\r
+        'prod;',\r
+        'prop;',\r
+        'psi;',\r
+        'quot;',\r
+        'quot',\r
+        'rArr;',\r
+        'radic;',\r
+        'rang;',\r
+        'raquo;',\r
+        'raquo',\r
+        'rarr;',\r
+        'rceil;',\r
+        'rdquo;',\r
+        'real;',\r
+        'reg;',\r
+        'reg',\r
+        'rfloor;',\r
+        'rho;',\r
+        'rlm;',\r
+        'rsaquo;',\r
+        'rsquo;',\r
+        'sbquo;',\r
+        'scaron;',\r
+        'sdot;',\r
+        'sect;',\r
+        'sect',\r
+        'shy;',\r
+        'shy',\r
+        'sigma;',\r
+        'sigmaf;',\r
+        'sim;',\r
+        'spades;',\r
+        'sub;',\r
+        'sube;',\r
+        'sum;',\r
+        'sup1;',\r
+        'sup1',\r
+        'sup2;',\r
+        'sup2',\r
+        'sup3;',\r
+        'sup3',\r
+        'sup;',\r
+        'supe;',\r
+        'szlig;',\r
+        'szlig',\r
+        'tau;',\r
+        'there4;',\r
+        'theta;',\r
+        'thetasym;',\r
+        'thinsp;',\r
+        'thorn;',\r
+        'thorn',\r
+        'tilde;',\r
+        'times;',\r
+        'times',\r
+        'trade;',\r
+        'uArr;',\r
+        'uacute;',\r
+        'uacute',\r
+        'uarr;',\r
+        'ucirc;',\r
+        'ucirc',\r
+        'ugrave;',\r
+        'ugrave',\r
+        'uml;',\r
+        'uml',\r
+        'upsih;',\r
+        'upsilon;',\r
+        'uuml;',\r
+        'uuml',\r
+        'weierp;',\r
+        'xi;',\r
+        'yacute;',\r
+        'yacute',\r
+        'yen;',\r
+        'yen',\r
+        'yuml;',\r
+        'yuml',\r
+        'zeta;',\r
+        'zwj;',\r
+        'zwnj;'\r
+    );\r
+\r
+    const PCDATA = 0;\r
+    const RCDATA = 1;\r
+    const CDATA = 2;\r
+    const PLAINTEXT = 3;\r
+\r
+    const DOCTYPE = 0;\r
+    const STARTTAG = 1;\r
+    const ENDTAG = 2;\r
+    const COMMENT = 3;\r
+    const CHARACTR = 4;\r
+    const EOF = 5;\r
+\r
+    public function __construct($data)\r
+    {\r
+        $this->data = $data;\r
+        $this->char = -1;\r
+        $this->EOF = strlen($data);\r
+        $this->tree = new HTML5TreeConstructer;\r
+        $this->content_model = self::PCDATA;\r
+\r
+        $this->state = 'data';\r
+\r
+        while ($this->state !== null) {\r
+            $this->{$this->state . 'State'}();\r
+        }\r
+    }\r
+\r
+    public function save()\r
+    {\r
+        return $this->tree->save();\r
+    }\r
+\r
+    private function char()\r
+    {\r
+        return ($this->char < $this->EOF)\r
+            ? $this->data[$this->char]\r
+            : false;\r
+    }\r
+\r
+    private function character($s, $l = 0)\r
+    {\r
+        if ($s + $l < $this->EOF) {\r
+            if ($l === 0) {\r
+                return $this->data[$s];\r
+            } else {\r
+                return substr($this->data, $s, $l);\r
+            }\r
+        }\r
+    }\r
+\r
+    private function characters($char_class, $start)\r
+    {\r
+        return preg_replace('#^([' . $char_class . ']+).*#s', '\\1', substr($this->data, $start));\r
+    }\r
+\r
+    private function dataState()\r
+    {\r
+        // Consume the next input character\r
+        $this->char++;\r
+        $char = $this->char();\r
+\r
+        if ($char === '&' && ($this->content_model === self::PCDATA || $this->content_model === self::RCDATA)) {\r
+            /* U+0026 AMPERSAND (&)\r
+            When the content model flag is set to one of the PCDATA or RCDATA\r
+            states: switch to the entity data state. Otherwise: treat it as per\r
+            the "anything else"    entry below. */\r
+            $this->state = 'entityData';\r
+\r
+        } elseif ($char === '-') {\r
+            /* If the content model flag is set to either the RCDATA state or\r
+            the CDATA state, and the escape flag is false, and there are at\r
+            least three characters before this one in the input stream, and the\r
+            last four characters in the input stream, including this one, are\r
+            U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS,\r
+            and U+002D HYPHEN-MINUS ("<!--"), then set the escape flag to true. */\r
+            if (($this->content_model === self::RCDATA || $this->content_model ===\r
+                    self::CDATA) && $this->escape === false &&\r
+                $this->char >= 3 && $this->character($this->char - 4, 4) === '<!--'\r
+            ) {\r
+                $this->escape = true;\r
+            }\r
+\r
+            /* In any case, emit the input character as a character token. Stay\r
+            in the data state. */\r
+            $this->emitToken(\r
+                array(\r
+                    'type' => self::CHARACTR,\r
+                    'data' => $char\r
+                )\r
+            );\r
+\r
+            /* U+003C LESS-THAN SIGN (<) */\r
+        } elseif ($char === '<' && ($this->content_model === self::PCDATA ||\r
+                (($this->content_model === self::RCDATA ||\r
+                        $this->content_model === self::CDATA) && $this->escape === false))\r
+        ) {\r
+            /* When the content model flag is set to the PCDATA state: switch\r
+            to the tag open state.\r
+\r
+            When the content model flag is set to either the RCDATA state or\r
+            the CDATA state and the escape flag is false: switch to the tag\r
+            open state.\r
+\r
+            Otherwise: treat it as per the "anything else" entry below. */\r
+            $this->state = 'tagOpen';\r
+\r
+            /* U+003E GREATER-THAN SIGN (>) */\r
+        } elseif ($char === '>') {\r
+            /* If the content model flag is set to either the RCDATA state or\r
+            the CDATA state, and the escape flag is true, and the last three\r
+            characters in the input stream including this one are U+002D\r
+            HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN ("-->"),\r
+            set the escape flag to false. */\r
+            if (($this->content_model === self::RCDATA ||\r
+                    $this->content_model === self::CDATA) && $this->escape === true &&\r
+                $this->character($this->char, 3) === '-->'\r
+            ) {\r
+                $this->escape = false;\r
+            }\r
+\r
+            /* In any case, emit the input character as a character token.\r
+            Stay in the data state. */\r
+            $this->emitToken(\r
+                array(\r
+                    'type' => self::CHARACTR,\r
+                    'data' => $char\r
+                )\r
+            );\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            /* EOF\r
+            Emit an end-of-file token. */\r
+            $this->EOF();\r
+\r
+        } elseif ($this->content_model === self::PLAINTEXT) {\r
+            /* When the content model flag is set to the PLAINTEXT state\r
+            THIS DIFFERS GREATLY FROM THE SPEC: Get the remaining characters of\r
+            the text and emit it as a character token. */\r
+            $this->emitToken(\r
+                array(\r
+                    'type' => self::CHARACTR,\r
+                    'data' => substr($this->data, $this->char)\r
+                )\r
+            );\r
+\r
+            $this->EOF();\r
+\r
+        } else {\r
+            /* Anything else\r
+            THIS DIFFERS GREATLY FROM THE SPEC: Get as many character that\r
+            otherwise would also be treated as a character token and emit it\r
+            as a single character token. Stay in the data state. */\r
+            $len = strcspn($this->data, '<&', $this->char);\r
+            $char = substr($this->data, $this->char, $len);\r
+            $this->char += $len - 1;\r
+\r
+            $this->emitToken(\r
+                array(\r
+                    'type' => self::CHARACTR,\r
+                    'data' => $char\r
+                )\r
+            );\r
+\r
+            $this->state = 'data';\r
+        }\r
+    }\r
+\r
+    private function entityDataState()\r
+    {\r
+        // Attempt to consume an entity.\r
+        $entity = $this->entity();\r
+\r
+        // If nothing is returned, emit a U+0026 AMPERSAND character token.\r
+        // Otherwise, emit the character token that was returned.\r
+        $char = (!$entity) ? '&' : $entity;\r
+        $this->emitToken(\r
+            array(\r
+                'type' => self::CHARACTR,\r
+                'data' => $char\r
+            )\r
+        );\r
+\r
+        // Finally, switch to the data state.\r
+        $this->state = 'data';\r
+    }\r
+\r
+    private function tagOpenState()\r
+    {\r
+        switch ($this->content_model) {\r
+            case self::RCDATA:\r
+            case self::CDATA:\r
+                /* If the next input character is a U+002F SOLIDUS (/) character,\r
+                consume it and switch to the close tag open state. If the next\r
+                input character is not a U+002F SOLIDUS (/) character, emit a\r
+                U+003C LESS-THAN SIGN character token and switch to the data\r
+                state to process the next input character. */\r
+                if ($this->character($this->char + 1) === '/') {\r
+                    $this->char++;\r
+                    $this->state = 'closeTagOpen';\r
+\r
+                } else {\r
+                    $this->emitToken(\r
+                        array(\r
+                            'type' => self::CHARACTR,\r
+                            'data' => '<'\r
+                        )\r
+                    );\r
+\r
+                    $this->state = 'data';\r
+                }\r
+                break;\r
+\r
+            case self::PCDATA:\r
+                // If the content model flag is set to the PCDATA state\r
+                // Consume the next input character:\r
+                $this->char++;\r
+                $char = $this->char();\r
+\r
+                if ($char === '!') {\r
+                    /* U+0021 EXCLAMATION MARK (!)\r
+                    Switch to the markup declaration open state. */\r
+                    $this->state = 'markupDeclarationOpen';\r
+\r
+                } elseif ($char === '/') {\r
+                    /* U+002F SOLIDUS (/)\r
+                    Switch to the close tag open state. */\r
+                    $this->state = 'closeTagOpen';\r
+\r
+                } elseif (preg_match('/^[A-Za-z]$/', $char)) {\r
+                    /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z\r
+                    Create a new start tag token, set its tag name to the lowercase\r
+                    version of the input character (add 0x0020 to the character's code\r
+                    point), then switch to the tag name state. (Don't emit the token\r
+                    yet; further details will be filled in before it is emitted.) */\r
+                    $this->token = array(\r
+                        'name' => strtolower($char),\r
+                        'type' => self::STARTTAG,\r
+                        'attr' => array()\r
+                    );\r
+\r
+                    $this->state = 'tagName';\r
+\r
+                } elseif ($char === '>') {\r
+                    /* U+003E GREATER-THAN SIGN (>)\r
+                    Parse error. Emit a U+003C LESS-THAN SIGN character token and a\r
+                    U+003E GREATER-THAN SIGN character token. Switch to the data state. */\r
+                    $this->emitToken(\r
+                        array(\r
+                            'type' => self::CHARACTR,\r
+                            'data' => '<>'\r
+                        )\r
+                    );\r
+\r
+                    $this->state = 'data';\r
+\r
+                } elseif ($char === '?') {\r
+                    /* U+003F QUESTION MARK (?)\r
+                    Parse error. Switch to the bogus comment state. */\r
+                    $this->state = 'bogusComment';\r
+\r
+                } else {\r
+                    /* Anything else\r
+                    Parse error. Emit a U+003C LESS-THAN SIGN character token and\r
+                    reconsume the current input character in the data state. */\r
+                    $this->emitToken(\r
+                        array(\r
+                            'type' => self::CHARACTR,\r
+                            'data' => '<'\r
+                        )\r
+                    );\r
+\r
+                    $this->char--;\r
+                    $this->state = 'data';\r
+                }\r
+                break;\r
+        }\r
+    }\r
+\r
+    private function closeTagOpenState()\r
+    {\r
+        $next_node = strtolower($this->characters('A-Za-z', $this->char + 1));\r
+        $the_same = count($this->tree->stack) > 0 && $next_node === end($this->tree->stack)->nodeName;\r
+\r
+        if (($this->content_model === self::RCDATA || $this->content_model === self::CDATA) &&\r
+            (!$the_same || ($the_same && (!preg_match(\r
+                            '/[\t\n\x0b\x0c >\/]/',\r
+                            $this->character($this->char + 1 + strlen($next_node))\r
+                        ) || $this->EOF === $this->char)))\r
+        ) {\r
+            /* If the content model flag is set to the RCDATA or CDATA states then\r
+            examine the next few characters. If they do not match the tag name of\r
+            the last start tag token emitted (case insensitively), or if they do but\r
+            they are not immediately followed by one of the following characters:\r
+                * U+0009 CHARACTER TABULATION\r
+                * U+000A LINE FEED (LF)\r
+                * U+000B LINE TABULATION\r
+                * U+000C FORM FEED (FF)\r
+                * U+0020 SPACE\r
+                * U+003E GREATER-THAN SIGN (>)\r
+                * U+002F SOLIDUS (/)\r
+                * EOF\r
+            ...then there is a parse error. Emit a U+003C LESS-THAN SIGN character\r
+            token, a U+002F SOLIDUS character token, and switch to the data state\r
+            to process the next input character. */\r
+            $this->emitToken(\r
+                array(\r
+                    'type' => self::CHARACTR,\r
+                    'data' => '</'\r
+                )\r
+            );\r
+\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            /* Otherwise, if the content model flag is set to the PCDATA state,\r
+            or if the next few characters do match that tag name, consume the\r
+            next input character: */\r
+            $this->char++;\r
+            $char = $this->char();\r
+\r
+            if (preg_match('/^[A-Za-z]$/', $char)) {\r
+                /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z\r
+                Create a new end tag token, set its tag name to the lowercase version\r
+                of the input character (add 0x0020 to the character's code point), then\r
+                switch to the tag name state. (Don't emit the token yet; further details\r
+                will be filled in before it is emitted.) */\r
+                $this->token = array(\r
+                    'name' => strtolower($char),\r
+                    'type' => self::ENDTAG\r
+                );\r
+\r
+                $this->state = 'tagName';\r
+\r
+            } elseif ($char === '>') {\r
+                /* U+003E GREATER-THAN SIGN (>)\r
+                Parse error. Switch to the data state. */\r
+                $this->state = 'data';\r
+\r
+            } elseif ($this->char === $this->EOF) {\r
+                /* EOF\r
+                Parse error. Emit a U+003C LESS-THAN SIGN character token and a U+002F\r
+                SOLIDUS character token. Reconsume the EOF character in the data state. */\r
+                $this->emitToken(\r
+                    array(\r
+                        'type' => self::CHARACTR,\r
+                        'data' => '</'\r
+                    )\r
+                );\r
+\r
+                $this->char--;\r
+                $this->state = 'data';\r
+\r
+            } else {\r
+                /* Parse error. Switch to the bogus comment state. */\r
+                $this->state = 'bogusComment';\r
+            }\r
+        }\r
+    }\r
+\r
+    private function tagNameState()\r
+    {\r
+        // Consume the next input character:\r
+        $this->char++;\r
+        $char = $this->character($this->char);\r
+\r
+        if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {\r
+            /* U+0009 CHARACTER TABULATION\r
+            U+000A LINE FEED (LF)\r
+            U+000B LINE TABULATION\r
+            U+000C FORM FEED (FF)\r
+            U+0020 SPACE\r
+            Switch to the before attribute name state. */\r
+            $this->state = 'beforeAttributeName';\r
+\r
+        } elseif ($char === '>') {\r
+            /* U+003E GREATER-THAN SIGN (>)\r
+            Emit the current tag token. Switch to the data state. */\r
+            $this->emitToken($this->token);\r
+            $this->state = 'data';\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            /* EOF\r
+            Parse error. Emit the current tag token. Reconsume the EOF\r
+            character in the data state. */\r
+            $this->emitToken($this->token);\r
+\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } elseif ($char === '/') {\r
+            /* U+002F SOLIDUS (/)\r
+            Parse error unless this is a permitted slash. Switch to the before\r
+            attribute name state. */\r
+            $this->state = 'beforeAttributeName';\r
+\r
+        } else {\r
+            /* Anything else\r
+            Append the current input character to the current tag token's tag name.\r
+            Stay in the tag name state. */\r
+            $this->token['name'] .= strtolower($char);\r
+            $this->state = 'tagName';\r
+        }\r
+    }\r
+\r
+    private function beforeAttributeNameState()\r
+    {\r
+        // Consume the next input character:\r
+        $this->char++;\r
+        $char = $this->character($this->char);\r
+\r
+        if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {\r
+            /* U+0009 CHARACTER TABULATION\r
+            U+000A LINE FEED (LF)\r
+            U+000B LINE TABULATION\r
+            U+000C FORM FEED (FF)\r
+            U+0020 SPACE\r
+            Stay in the before attribute name state. */\r
+            $this->state = 'beforeAttributeName';\r
+\r
+        } elseif ($char === '>') {\r
+            /* U+003E GREATER-THAN SIGN (>)\r
+            Emit the current tag token. Switch to the data state. */\r
+            $this->emitToken($this->token);\r
+            $this->state = 'data';\r
+\r
+        } elseif ($char === '/') {\r
+            /* U+002F SOLIDUS (/)\r
+            Parse error unless this is a permitted slash. Stay in the before\r
+            attribute name state. */\r
+            $this->state = 'beforeAttributeName';\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            /* EOF\r
+            Parse error. Emit the current tag token. Reconsume the EOF\r
+            character in the data state. */\r
+            $this->emitToken($this->token);\r
+\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            /* Anything else\r
+            Start a new attribute in the current tag token. Set that attribute's\r
+            name to the current input character, and its value to the empty string.\r
+            Switch to the attribute name state. */\r
+            $this->token['attr'][] = array(\r
+                'name' => strtolower($char),\r
+                'value' => null\r
+            );\r
+\r
+            $this->state = 'attributeName';\r
+        }\r
+    }\r
+\r
+    private function attributeNameState()\r
+    {\r
+        // Consume the next input character:\r
+        $this->char++;\r
+        $char = $this->character($this->char);\r
+\r
+        if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {\r
+            /* U+0009 CHARACTER TABULATION\r
+            U+000A LINE FEED (LF)\r
+            U+000B LINE TABULATION\r
+            U+000C FORM FEED (FF)\r
+            U+0020 SPACE\r
+            Stay in the before attribute name state. */\r
+            $this->state = 'afterAttributeName';\r
+\r
+        } elseif ($char === '=') {\r
+            /* U+003D EQUALS SIGN (=)\r
+            Switch to the before attribute value state. */\r
+            $this->state = 'beforeAttributeValue';\r
+\r
+        } elseif ($char === '>') {\r
+            /* U+003E GREATER-THAN SIGN (>)\r
+            Emit the current tag token. Switch to the data state. */\r
+            $this->emitToken($this->token);\r
+            $this->state = 'data';\r
+\r
+        } elseif ($char === '/' && $this->character($this->char + 1) !== '>') {\r
+            /* U+002F SOLIDUS (/)\r
+            Parse error unless this is a permitted slash. Switch to the before\r
+            attribute name state. */\r
+            $this->state = 'beforeAttributeName';\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            /* EOF\r
+            Parse error. Emit the current tag token. Reconsume the EOF\r
+            character in the data state. */\r
+            $this->emitToken($this->token);\r
+\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            /* Anything else\r
+            Append the current input character to the current attribute's name.\r
+            Stay in the attribute name state. */\r
+            $last = count($this->token['attr']) - 1;\r
+            $this->token['attr'][$last]['name'] .= strtolower($char);\r
+\r
+            $this->state = 'attributeName';\r
+        }\r
+    }\r
+\r
+    private function afterAttributeNameState()\r
+    {\r
+        // Consume the next input character:\r
+        $this->char++;\r
+        $char = $this->character($this->char);\r
+\r
+        if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {\r
+            /* U+0009 CHARACTER TABULATION\r
+            U+000A LINE FEED (LF)\r
+            U+000B LINE TABULATION\r
+            U+000C FORM FEED (FF)\r
+            U+0020 SPACE\r
+            Stay in the after attribute name state. */\r
+            $this->state = 'afterAttributeName';\r
+\r
+        } elseif ($char === '=') {\r
+            /* U+003D EQUALS SIGN (=)\r
+            Switch to the before attribute value state. */\r
+            $this->state = 'beforeAttributeValue';\r
+\r
+        } elseif ($char === '>') {\r
+            /* U+003E GREATER-THAN SIGN (>)\r
+            Emit the current tag token. Switch to the data state. */\r
+            $this->emitToken($this->token);\r
+            $this->state = 'data';\r
+\r
+        } elseif ($char === '/' && $this->character($this->char + 1) !== '>') {\r
+            /* U+002F SOLIDUS (/)\r
+            Parse error unless this is a permitted slash. Switch to the\r
+            before attribute name state. */\r
+            $this->state = 'beforeAttributeName';\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            /* EOF\r
+            Parse error. Emit the current tag token. Reconsume the EOF\r
+            character in the data state. */\r
+            $this->emitToken($this->token);\r
+\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            /* Anything else\r
+            Start a new attribute in the current tag token. Set that attribute's\r
+            name to the current input character, and its value to the empty string.\r
+            Switch to the attribute name state. */\r
+            $this->token['attr'][] = array(\r
+                'name' => strtolower($char),\r
+                'value' => null\r
+            );\r
+\r
+            $this->state = 'attributeName';\r
+        }\r
+    }\r
+\r
+    private function beforeAttributeValueState()\r
+    {\r
+        // Consume the next input character:\r
+        $this->char++;\r
+        $char = $this->character($this->char);\r
+\r
+        if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {\r
+            /* U+0009 CHARACTER TABULATION\r
+            U+000A LINE FEED (LF)\r
+            U+000B LINE TABULATION\r
+            U+000C FORM FEED (FF)\r
+            U+0020 SPACE\r
+            Stay in the before attribute value state. */\r
+            $this->state = 'beforeAttributeValue';\r
+\r
+        } elseif ($char === '"') {\r
+            /* U+0022 QUOTATION MARK (")\r
+            Switch to the attribute value (double-quoted) state. */\r
+            $this->state = 'attributeValueDoubleQuoted';\r
+\r
+        } elseif ($char === '&') {\r
+            /* U+0026 AMPERSAND (&)\r
+            Switch to the attribute value (unquoted) state and reconsume\r
+            this input character. */\r
+            $this->char--;\r
+            $this->state = 'attributeValueUnquoted';\r
+\r
+        } elseif ($char === '\'') {\r
+            /* U+0027 APOSTROPHE (')\r
+            Switch to the attribute value (single-quoted) state. */\r
+            $this->state = 'attributeValueSingleQuoted';\r
+\r
+        } elseif ($char === '>') {\r
+            /* U+003E GREATER-THAN SIGN (>)\r
+            Emit the current tag token. Switch to the data state. */\r
+            $this->emitToken($this->token);\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            /* Anything else\r
+            Append the current input character to the current attribute's value.\r
+            Switch to the attribute value (unquoted) state. */\r
+            $last = count($this->token['attr']) - 1;\r
+            $this->token['attr'][$last]['value'] .= $char;\r
+\r
+            $this->state = 'attributeValueUnquoted';\r
+        }\r
+    }\r
+\r
+    private function attributeValueDoubleQuotedState()\r
+    {\r
+        // Consume the next input character:\r
+        $this->char++;\r
+        $char = $this->character($this->char);\r
+\r
+        if ($char === '"') {\r
+            /* U+0022 QUOTATION MARK (")\r
+            Switch to the before attribute name state. */\r
+            $this->state = 'beforeAttributeName';\r
+\r
+        } elseif ($char === '&') {\r
+            /* U+0026 AMPERSAND (&)\r
+            Switch to the entity in attribute value state. */\r
+            $this->entityInAttributeValueState('double');\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            /* EOF\r
+            Parse error. Emit the current tag token. Reconsume the character\r
+            in the data state. */\r
+            $this->emitToken($this->token);\r
+\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            /* Anything else\r
+            Append the current input character to the current attribute's value.\r
+            Stay in the attribute value (double-quoted) state. */\r
+            $last = count($this->token['attr']) - 1;\r
+            $this->token['attr'][$last]['value'] .= $char;\r
+\r
+            $this->state = 'attributeValueDoubleQuoted';\r
+        }\r
+    }\r
+\r
+    private function attributeValueSingleQuotedState()\r
+    {\r
+        // Consume the next input character:\r
+        $this->char++;\r
+        $char = $this->character($this->char);\r
+\r
+        if ($char === '\'') {\r
+            /* U+0022 QUOTATION MARK (')\r
+            Switch to the before attribute name state. */\r
+            $this->state = 'beforeAttributeName';\r
+\r
+        } elseif ($char === '&') {\r
+            /* U+0026 AMPERSAND (&)\r
+            Switch to the entity in attribute value state. */\r
+            $this->entityInAttributeValueState('single');\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            /* EOF\r
+            Parse error. Emit the current tag token. Reconsume the character\r
+            in the data state. */\r
+            $this->emitToken($this->token);\r
+\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            /* Anything else\r
+            Append the current input character to the current attribute's value.\r
+            Stay in the attribute value (single-quoted) state. */\r
+            $last = count($this->token['attr']) - 1;\r
+            $this->token['attr'][$last]['value'] .= $char;\r
+\r
+            $this->state = 'attributeValueSingleQuoted';\r
+        }\r
+    }\r
+\r
+    private function attributeValueUnquotedState()\r
+    {\r
+        // Consume the next input character:\r
+        $this->char++;\r
+        $char = $this->character($this->char);\r
+\r
+        if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {\r
+            /* U+0009 CHARACTER TABULATION\r
+            U+000A LINE FEED (LF)\r
+            U+000B LINE TABULATION\r
+            U+000C FORM FEED (FF)\r
+            U+0020 SPACE\r
+            Switch to the before attribute name state. */\r
+            $this->state = 'beforeAttributeName';\r
+\r
+        } elseif ($char === '&') {\r
+            /* U+0026 AMPERSAND (&)\r
+            Switch to the entity in attribute value state. */\r
+            $this->entityInAttributeValueState();\r
+\r
+        } elseif ($char === '>') {\r
+            /* U+003E GREATER-THAN SIGN (>)\r
+            Emit the current tag token. Switch to the data state. */\r
+            $this->emitToken($this->token);\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            /* Anything else\r
+            Append the current input character to the current attribute's value.\r
+            Stay in the attribute value (unquoted) state. */\r
+            $last = count($this->token['attr']) - 1;\r
+            $this->token['attr'][$last]['value'] .= $char;\r
+\r
+            $this->state = 'attributeValueUnquoted';\r
+        }\r
+    }\r
+\r
+    private function entityInAttributeValueState()\r
+    {\r
+        // Attempt to consume an entity.\r
+        $entity = $this->entity();\r
+\r
+        // If nothing is returned, append a U+0026 AMPERSAND character to the\r
+        // current attribute's value. Otherwise, emit the character token that\r
+        // was returned.\r
+        $char = (!$entity)\r
+            ? '&'\r
+            : $entity;\r
+\r
+        $last = count($this->token['attr']) - 1;\r
+        $this->token['attr'][$last]['value'] .= $char;\r
+    }\r
+\r
+    private function bogusCommentState()\r
+    {\r
+        /* Consume every character up to the first U+003E GREATER-THAN SIGN\r
+        character (>) or the end of the file (EOF), whichever comes first. Emit\r
+        a comment token whose data is the concatenation of all the characters\r
+        starting from and including the character that caused the state machine\r
+        to switch into the bogus comment state, up to and including the last\r
+        consumed character before the U+003E character, if any, or up to the\r
+        end of the file otherwise. (If the comment was started by the end of\r
+        the file (EOF), the token is empty.) */\r
+        $data = $this->characters('^>', $this->char);\r
+        $this->emitToken(\r
+            array(\r
+                'data' => $data,\r
+                'type' => self::COMMENT\r
+            )\r
+        );\r
+\r
+        $this->char += strlen($data);\r
+\r
+        /* Switch to the data state. */\r
+        $this->state = 'data';\r
+\r
+        /* If the end of the file was reached, reconsume the EOF character. */\r
+        if ($this->char === $this->EOF) {\r
+            $this->char = $this->EOF - 1;\r
+        }\r
+    }\r
+\r
+    private function markupDeclarationOpenState()\r
+    {\r
+        /* If the next two characters are both U+002D HYPHEN-MINUS (-)\r
+        characters, consume those two characters, create a comment token whose\r
+        data is the empty string, and switch to the comment state. */\r
+        if ($this->character($this->char + 1, 2) === '--') {\r
+            $this->char += 2;\r
+            $this->state = 'comment';\r
+            $this->token = array(\r
+                'data' => null,\r
+                'type' => self::COMMENT\r
+            );\r
+\r
+            /* Otherwise if the next seven chacacters are a case-insensitive match\r
+            for the word "DOCTYPE", then consume those characters and switch to the\r
+            DOCTYPE state. */\r
+        } elseif (strtolower($this->character($this->char + 1, 7)) === 'doctype') {\r
+            $this->char += 7;\r
+            $this->state = 'doctype';\r
+\r
+            /* Otherwise, is is a parse error. Switch to the bogus comment state.\r
+            The next character that is consumed, if any, is the first character\r
+            that will be in the comment. */\r
+        } else {\r
+            $this->char++;\r
+            $this->state = 'bogusComment';\r
+        }\r
+    }\r
+\r
+    private function commentState()\r
+    {\r
+        /* Consume the next input character: */\r
+        $this->char++;\r
+        $char = $this->char();\r
+\r
+        /* U+002D HYPHEN-MINUS (-) */\r
+        if ($char === '-') {\r
+            /* Switch to the comment dash state  */\r
+            $this->state = 'commentDash';\r
+\r
+            /* EOF */\r
+        } elseif ($this->char === $this->EOF) {\r
+            /* Parse error. Emit the comment token. Reconsume the EOF character\r
+            in the data state. */\r
+            $this->emitToken($this->token);\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Append the input character to the comment token's data. Stay in\r
+            the comment state. */\r
+            $this->token['data'] .= $char;\r
+        }\r
+    }\r
+\r
+    private function commentDashState()\r
+    {\r
+        /* Consume the next input character: */\r
+        $this->char++;\r
+        $char = $this->char();\r
+\r
+        /* U+002D HYPHEN-MINUS (-) */\r
+        if ($char === '-') {\r
+            /* Switch to the comment end state  */\r
+            $this->state = 'commentEnd';\r
+\r
+            /* EOF */\r
+        } elseif ($this->char === $this->EOF) {\r
+            /* Parse error. Emit the comment token. Reconsume the EOF character\r
+            in the data state. */\r
+            $this->emitToken($this->token);\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Append a U+002D HYPHEN-MINUS (-) character and the input\r
+            character to the comment token's data. Switch to the comment state. */\r
+            $this->token['data'] .= '-' . $char;\r
+            $this->state = 'comment';\r
+        }\r
+    }\r
+\r
+    private function commentEndState()\r
+    {\r
+        /* Consume the next input character: */\r
+        $this->char++;\r
+        $char = $this->char();\r
+\r
+        if ($char === '>') {\r
+            $this->emitToken($this->token);\r
+            $this->state = 'data';\r
+\r
+        } elseif ($char === '-') {\r
+            $this->token['data'] .= '-';\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            $this->emitToken($this->token);\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            $this->token['data'] .= '--' . $char;\r
+            $this->state = 'comment';\r
+        }\r
+    }\r
+\r
+    private function doctypeState()\r
+    {\r
+        /* Consume the next input character: */\r
+        $this->char++;\r
+        $char = $this->char();\r
+\r
+        if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {\r
+            $this->state = 'beforeDoctypeName';\r
+\r
+        } else {\r
+            $this->char--;\r
+            $this->state = 'beforeDoctypeName';\r
+        }\r
+    }\r
+\r
+    private function beforeDoctypeNameState()\r
+    {\r
+        /* Consume the next input character: */\r
+        $this->char++;\r
+        $char = $this->char();\r
+\r
+        if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {\r
+            // Stay in the before DOCTYPE name state.\r
+\r
+        } elseif (preg_match('/^[a-z]$/', $char)) {\r
+            $this->token = array(\r
+                'name' => strtoupper($char),\r
+                'type' => self::DOCTYPE,\r
+                'error' => true\r
+            );\r
+\r
+            $this->state = 'doctypeName';\r
+\r
+        } elseif ($char === '>') {\r
+            $this->emitToken(\r
+                array(\r
+                    'name' => null,\r
+                    'type' => self::DOCTYPE,\r
+                    'error' => true\r
+                )\r
+            );\r
+\r
+            $this->state = 'data';\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            $this->emitToken(\r
+                array(\r
+                    'name' => null,\r
+                    'type' => self::DOCTYPE,\r
+                    'error' => true\r
+                )\r
+            );\r
+\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            $this->token = array(\r
+                'name' => $char,\r
+                'type' => self::DOCTYPE,\r
+                'error' => true\r
+            );\r
+\r
+            $this->state = 'doctypeName';\r
+        }\r
+    }\r
+\r
+    private function doctypeNameState()\r
+    {\r
+        /* Consume the next input character: */\r
+        $this->char++;\r
+        $char = $this->char();\r
+\r
+        if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {\r
+            $this->state = 'AfterDoctypeName';\r
+\r
+        } elseif ($char === '>') {\r
+            $this->emitToken($this->token);\r
+            $this->state = 'data';\r
+\r
+        } elseif (preg_match('/^[a-z]$/', $char)) {\r
+            $this->token['name'] .= strtoupper($char);\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            $this->emitToken($this->token);\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            $this->token['name'] .= $char;\r
+        }\r
+\r
+        $this->token['error'] = ($this->token['name'] === 'HTML')\r
+            ? false\r
+            : true;\r
+    }\r
+\r
+    private function afterDoctypeNameState()\r
+    {\r
+        /* Consume the next input character: */\r
+        $this->char++;\r
+        $char = $this->char();\r
+\r
+        if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {\r
+            // Stay in the DOCTYPE name state.\r
+\r
+        } elseif ($char === '>') {\r
+            $this->emitToken($this->token);\r
+            $this->state = 'data';\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            $this->emitToken($this->token);\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            $this->token['error'] = true;\r
+            $this->state = 'bogusDoctype';\r
+        }\r
+    }\r
+\r
+    private function bogusDoctypeState()\r
+    {\r
+        /* Consume the next input character: */\r
+        $this->char++;\r
+        $char = $this->char();\r
+\r
+        if ($char === '>') {\r
+            $this->emitToken($this->token);\r
+            $this->state = 'data';\r
+\r
+        } elseif ($this->char === $this->EOF) {\r
+            $this->emitToken($this->token);\r
+            $this->char--;\r
+            $this->state = 'data';\r
+\r
+        } else {\r
+            // Stay in the bogus DOCTYPE state.\r
+        }\r
+    }\r
+\r
+    private function entity()\r
+    {\r
+        $start = $this->char;\r
+\r
+        // This section defines how to consume an entity. This definition is\r
+        // used when parsing entities in text and in attributes.\r
+\r
+        // The behaviour depends on the identity of the next character (the\r
+        // one immediately after the U+0026 AMPERSAND character):\r
+\r
+        switch ($this->character($this->char + 1)) {\r
+            // U+0023 NUMBER SIGN (#)\r
+            case '#':\r
+\r
+                // The behaviour further depends on the character after the\r
+                // U+0023 NUMBER SIGN:\r
+                switch ($this->character($this->char + 1)) {\r
+                    // U+0078 LATIN SMALL LETTER X\r
+                    // U+0058 LATIN CAPITAL LETTER X\r
+                    case 'x':\r
+                    case 'X':\r
+                        // Follow the steps below, but using the range of\r
+                        // characters U+0030 DIGIT ZERO through to U+0039 DIGIT\r
+                        // NINE, U+0061 LATIN SMALL LETTER A through to U+0066\r
+                        // LATIN SMALL LETTER F, and U+0041 LATIN CAPITAL LETTER\r
+                        // A, through to U+0046 LATIN CAPITAL LETTER F (in other\r
+                        // words, 0-9, A-F, a-f).\r
+                        $char = 1;\r
+                        $char_class = '0-9A-Fa-f';\r
+                        break;\r
+\r
+                    // Anything else\r
+                    default:\r
+                        // Follow the steps below, but using the range of\r
+                        // characters U+0030 DIGIT ZERO through to U+0039 DIGIT\r
+                        // NINE (i.e. just 0-9).\r
+                        $char = 0;\r
+                        $char_class = '0-9';\r
+                        break;\r
+                }\r
+\r
+                // Consume as many characters as match the range of characters\r
+                // given above.\r
+                $this->char++;\r
+                $e_name = $this->characters($char_class, $this->char + $char + 1);\r
+                $entity = $this->character($start, $this->char);\r
+                $cond = strlen($e_name) > 0;\r
+\r
+                // The rest of the parsing happens below.\r
+                break;\r
+\r
+            // Anything else\r
+            default:\r
+                // Consume the maximum number of characters possible, with the\r
+                // consumed characters case-sensitively matching one of the\r
+                // identifiers in the first column of the entities table.\r
+\r
+                $e_name = $this->characters('0-9A-Za-z;', $this->char + 1);\r
+                $len = strlen($e_name);\r
+\r
+                for ($c = 1; $c <= $len; $c++) {\r
+                    $id = substr($e_name, 0, $c);\r
+                    $this->char++;\r
+\r
+                    if (in_array($id, $this->entities)) {\r
+                        if ($e_name[$c - 1] !== ';') {\r
+                            if ($c < $len && $e_name[$c] == ';') {\r
+                                $this->char++; // consume extra semicolon\r
+                            }\r
+                        }\r
+                        $entity = $id;\r
+                        break;\r
+                    }\r
+                }\r
+\r
+                $cond = isset($entity);\r
+                // The rest of the parsing happens below.\r
+                break;\r
+        }\r
+\r
+        if (!$cond) {\r
+            // If no match can be made, then this is a parse error. No\r
+            // characters are consumed, and nothing is returned.\r
+            $this->char = $start;\r
+            return false;\r
+        }\r
+\r
+        // Return a character token for the character corresponding to the\r
+        // entity name (as given by the second column of the entities table).\r
+        return html_entity_decode('&' . rtrim($entity, ';') . ';', ENT_QUOTES, 'UTF-8');\r
+    }\r
+\r
+    private function emitToken($token)\r
+    {\r
+        $emit = $this->tree->emitToken($token);\r
+\r
+        if (is_int($emit)) {\r
+            $this->content_model = $emit;\r
+\r
+        } elseif ($token['type'] === self::ENDTAG) {\r
+            $this->content_model = self::PCDATA;\r
+        }\r
+    }\r
+\r
+    private function EOF()\r
+    {\r
+        $this->state = null;\r
+        $this->tree->emitToken(\r
+            array(\r
+                'type' => self::EOF\r
+            )\r
+        );\r
+    }\r
+}\r
+\r
+class HTML5TreeConstructer\r
+{\r
+    public $stack = array();\r
+\r
+    private $phase;\r
+    private $mode;\r
+    private $dom;\r
+    private $foster_parent = null;\r
+    private $a_formatting = array();\r
+\r
+    private $head_pointer = null;\r
+    private $form_pointer = null;\r
+\r
+    private $scoping = array('button', 'caption', 'html', 'marquee', 'object', 'table', 'td', 'th');\r
+    private $formatting = array(\r
+        'a',\r
+        'b',\r
+        'big',\r
+        'em',\r
+        'font',\r
+        'i',\r
+        'nobr',\r
+        's',\r
+        'small',\r
+        'strike',\r
+        'strong',\r
+        'tt',\r
+        'u'\r
+    );\r
+    private $special = array(\r
+        'address',\r
+        'area',\r
+        'base',\r
+        'basefont',\r
+        'bgsound',\r
+        'blockquote',\r
+        'body',\r
+        'br',\r
+        'center',\r
+        'col',\r
+        'colgroup',\r
+        'dd',\r
+        'dir',\r
+        'div',\r
+        'dl',\r
+        'dt',\r
+        'embed',\r
+        'fieldset',\r
+        'form',\r
+        'frame',\r
+        'frameset',\r
+        'h1',\r
+        'h2',\r
+        'h3',\r
+        'h4',\r
+        'h5',\r
+        'h6',\r
+        'head',\r
+        'hr',\r
+        'iframe',\r
+        'image',\r
+        'img',\r
+        'input',\r
+        'isindex',\r
+        'li',\r
+        'link',\r
+        'listing',\r
+        'menu',\r
+        'meta',\r
+        'noembed',\r
+        'noframes',\r
+        'noscript',\r
+        'ol',\r
+        'optgroup',\r
+        'option',\r
+        'p',\r
+        'param',\r
+        'plaintext',\r
+        'pre',\r
+        'script',\r
+        'select',\r
+        'spacer',\r
+        'style',\r
+        'tbody',\r
+        'textarea',\r
+        'tfoot',\r
+        'thead',\r
+        'title',\r
+        'tr',\r
+        'ul',\r
+        'wbr'\r
+    );\r
+\r
+    // The different phases.\r
+    const INIT_PHASE = 0;\r
+    const ROOT_PHASE = 1;\r
+    const MAIN_PHASE = 2;\r
+    const END_PHASE = 3;\r
+\r
+    // The different insertion modes for the main phase.\r
+    const BEFOR_HEAD = 0;\r
+    const IN_HEAD = 1;\r
+    const AFTER_HEAD = 2;\r
+    const IN_BODY = 3;\r
+    const IN_TABLE = 4;\r
+    const IN_CAPTION = 5;\r
+    const IN_CGROUP = 6;\r
+    const IN_TBODY = 7;\r
+    const IN_ROW = 8;\r
+    const IN_CELL = 9;\r
+    const IN_SELECT = 10;\r
+    const AFTER_BODY = 11;\r
+    const IN_FRAME = 12;\r
+    const AFTR_FRAME = 13;\r
+\r
+    // The different types of elements.\r
+    const SPECIAL = 0;\r
+    const SCOPING = 1;\r
+    const FORMATTING = 2;\r
+    const PHRASING = 3;\r
+\r
+    const MARKER = 0;\r
+\r
+    public function __construct()\r
+    {\r
+        $this->phase = self::INIT_PHASE;\r
+        $this->mode = self::BEFOR_HEAD;\r
+        $this->dom = new DOMDocument;\r
+\r
+        $this->dom->encoding = 'UTF-8';\r
+        $this->dom->preserveWhiteSpace = true;\r
+        $this->dom->substituteEntities = true;\r
+        $this->dom->strictErrorChecking = false;\r
+    }\r
+\r
+    // Process tag tokens\r
+    public function emitToken($token)\r
+    {\r
+        switch ($this->phase) {\r
+            case self::INIT_PHASE:\r
+                return $this->initPhase($token);\r
+                break;\r
+            case self::ROOT_PHASE:\r
+                return $this->rootElementPhase($token);\r
+                break;\r
+            case self::MAIN_PHASE:\r
+                return $this->mainPhase($token);\r
+                break;\r
+            case self::END_PHASE :\r
+                return $this->trailingEndPhase($token);\r
+                break;\r
+        }\r
+    }\r
+\r
+    private function initPhase($token)\r
+    {\r
+        /* Initially, the tree construction stage must handle each token\r
+        emitted from the tokenisation stage as follows: */\r
+\r
+        /* A DOCTYPE token that is marked as being in error\r
+        A comment token\r
+        A start tag token\r
+        An end tag token\r
+        A character token that is not one of one of U+0009 CHARACTER TABULATION,\r
+            U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+            or U+0020 SPACE\r
+        An end-of-file token */\r
+        if ((isset($token['error']) && $token['error']) ||\r
+            $token['type'] === HTML5::COMMENT ||\r
+            $token['type'] === HTML5::STARTTAG ||\r
+            $token['type'] === HTML5::ENDTAG ||\r
+            $token['type'] === HTML5::EOF ||\r
+            ($token['type'] === HTML5::CHARACTR && isset($token['data']) &&\r
+                !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']))\r
+        ) {\r
+            /* This specification does not define how to handle this case. In\r
+            particular, user agents may ignore the entirety of this specification\r
+            altogether for such documents, and instead invoke special parse modes\r
+            with a greater emphasis on backwards compatibility. */\r
+\r
+            $this->phase = self::ROOT_PHASE;\r
+            return $this->rootElementPhase($token);\r
+\r
+            /* A DOCTYPE token marked as being correct */\r
+        } elseif (isset($token['error']) && !$token['error']) {\r
+            /* Append a DocumentType node to the Document  node, with the name\r
+            attribute set to the name given in the DOCTYPE token (which will be\r
+            "HTML"), and the other attributes specific to DocumentType objects\r
+            set to null, empty lists, or the empty string as appropriate. */\r
+            $doctype = new DOMDocumentType(null, null, 'HTML');\r
+\r
+            /* Then, switch to the root element phase of the tree construction\r
+            stage. */\r
+            $this->phase = self::ROOT_PHASE;\r
+\r
+            /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+            U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+            or U+0020 SPACE */\r
+        } elseif (isset($token['data']) && preg_match(\r
+                '/^[\t\n\x0b\x0c ]+$/',\r
+                $token['data']\r
+            )\r
+        ) {\r
+            /* Append that character  to the Document node. */\r
+            $text = $this->dom->createTextNode($token['data']);\r
+            $this->dom->appendChild($text);\r
+        }\r
+    }\r
+\r
+    private function rootElementPhase($token)\r
+    {\r
+        /* After the initial phase, as each token is emitted from the tokenisation\r
+        stage, it must be processed as described in this section. */\r
+\r
+        /* A DOCTYPE token */\r
+        if ($token['type'] === HTML5::DOCTYPE) {\r
+            // Parse error. Ignore the token.\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the Document object with the data\r
+            attribute set to the data given in the comment token. */\r
+            $comment = $this->dom->createComment($token['data']);\r
+            $this->dom->appendChild($comment);\r
+\r
+            /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+            U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+            or U+0020 SPACE */\r
+        } elseif ($token['type'] === HTML5::CHARACTR &&\r
+            preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])\r
+        ) {\r
+            /* Append that character  to the Document node. */\r
+            $text = $this->dom->createTextNode($token['data']);\r
+            $this->dom->appendChild($text);\r
+\r
+            /* A character token that is not one of U+0009 CHARACTER TABULATION,\r
+                U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED\r
+                (FF), or U+0020 SPACE\r
+            A start tag token\r
+            An end tag token\r
+            An end-of-file token */\r
+        } elseif (($token['type'] === HTML5::CHARACTR &&\r
+                !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) ||\r
+            $token['type'] === HTML5::STARTTAG ||\r
+            $token['type'] === HTML5::ENDTAG ||\r
+            $token['type'] === HTML5::EOF\r
+        ) {\r
+            /* Create an HTMLElement node with the tag name html, in the HTML\r
+            namespace. Append it to the Document object. Switch to the main\r
+            phase and reprocess the current token. */\r
+            $html = $this->dom->createElement('html');\r
+            $this->dom->appendChild($html);\r
+            $this->stack[] = $html;\r
+\r
+            $this->phase = self::MAIN_PHASE;\r
+            return $this->mainPhase($token);\r
+        }\r
+    }\r
+\r
+    private function mainPhase($token)\r
+    {\r
+        /* Tokens in the main phase must be handled as follows: */\r
+\r
+        /* A DOCTYPE token */\r
+        if ($token['type'] === HTML5::DOCTYPE) {\r
+            // Parse error. Ignore the token.\r
+\r
+            /* A start tag token with the tag name "html" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'html') {\r
+            /* If this start tag token was not the first start tag token, then\r
+            it is a parse error. */\r
+\r
+            /* For each attribute on the token, check to see if the attribute\r
+            is already present on the top element of the stack of open elements.\r
+            If it is not, add the attribute and its corresponding value to that\r
+            element. */\r
+            foreach ($token['attr'] as $attr) {\r
+                if (!$this->stack[0]->hasAttribute($attr['name'])) {\r
+                    $this->stack[0]->setAttribute($attr['name'], $attr['value']);\r
+                }\r
+            }\r
+\r
+            /* An end-of-file token */\r
+        } elseif ($token['type'] === HTML5::EOF) {\r
+            /* Generate implied end tags. */\r
+            $this->generateImpliedEndTags();\r
+\r
+            /* Anything else. */\r
+        } else {\r
+            /* Depends on the insertion mode: */\r
+            switch ($this->mode) {\r
+                case self::BEFOR_HEAD:\r
+                    return $this->beforeHead($token);\r
+                    break;\r
+                case self::IN_HEAD:\r
+                    return $this->inHead($token);\r
+                    break;\r
+                case self::AFTER_HEAD:\r
+                    return $this->afterHead($token);\r
+                    break;\r
+                case self::IN_BODY:\r
+                    return $this->inBody($token);\r
+                    break;\r
+                case self::IN_TABLE:\r
+                    return $this->inTable($token);\r
+                    break;\r
+                case self::IN_CAPTION:\r
+                    return $this->inCaption($token);\r
+                    break;\r
+                case self::IN_CGROUP:\r
+                    return $this->inColumnGroup($token);\r
+                    break;\r
+                case self::IN_TBODY:\r
+                    return $this->inTableBody($token);\r
+                    break;\r
+                case self::IN_ROW:\r
+                    return $this->inRow($token);\r
+                    break;\r
+                case self::IN_CELL:\r
+                    return $this->inCell($token);\r
+                    break;\r
+                case self::IN_SELECT:\r
+                    return $this->inSelect($token);\r
+                    break;\r
+                case self::AFTER_BODY:\r
+                    return $this->afterBody($token);\r
+                    break;\r
+                case self::IN_FRAME:\r
+                    return $this->inFrameset($token);\r
+                    break;\r
+                case self::AFTR_FRAME:\r
+                    return $this->afterFrameset($token);\r
+                    break;\r
+                case self::END_PHASE:\r
+                    return $this->trailingEndPhase($token);\r
+                    break;\r
+            }\r
+        }\r
+    }\r
+\r
+    private function beforeHead($token)\r
+    {\r
+        /* Handle the token as follows: */\r
+\r
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+        or U+0020 SPACE */\r
+        if ($token['type'] === HTML5::CHARACTR &&\r
+            preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])\r
+        ) {\r
+            /* Append the character to the current node. */\r
+            $this->insertText($token['data']);\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the current node with the data attribute\r
+            set to the data given in the comment token. */\r
+            $this->insertComment($token['data']);\r
+\r
+            /* A start tag token with the tag name "head" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') {\r
+            /* Create an element for the token, append the new element to the\r
+            current node and push it onto the stack of open elements. */\r
+            $element = $this->insertElement($token);\r
+\r
+            /* Set the head element pointer to this new element node. */\r
+            $this->head_pointer = $element;\r
+\r
+            /* Change the insertion mode to "in head". */\r
+            $this->mode = self::IN_HEAD;\r
+\r
+            /* A start tag token whose tag name is one of: "base", "link", "meta",\r
+            "script", "style", "title". Or an end tag with the tag name "html".\r
+            Or a character token that is not one of U+0009 CHARACTER TABULATION,\r
+            U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+            or U+0020 SPACE. Or any other start tag token */\r
+        } elseif ($token['type'] === HTML5::STARTTAG ||\r
+            ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') ||\r
+            ($token['type'] === HTML5::CHARACTR && !preg_match(\r
+                    '/^[\t\n\x0b\x0c ]$/',\r
+                    $token['data']\r
+                ))\r
+        ) {\r
+            /* Act as if a start tag token with the tag name "head" and no\r
+            attributes had been seen, then reprocess the current token. */\r
+            $this->beforeHead(\r
+                array(\r
+                    'name' => 'head',\r
+                    'type' => HTML5::STARTTAG,\r
+                    'attr' => array()\r
+                )\r
+            );\r
+\r
+            return $this->inHead($token);\r
+\r
+            /* Any other end tag */\r
+        } elseif ($token['type'] === HTML5::ENDTAG) {\r
+            /* Parse error. Ignore the token. */\r
+        }\r
+    }\r
+\r
+    private function inHead($token)\r
+    {\r
+        /* Handle the token as follows: */\r
+\r
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+        or U+0020 SPACE.\r
+\r
+        THIS DIFFERS FROM THE SPEC: If the current node is either a title, style\r
+        or script element, append the character to the current node regardless\r
+        of its content. */\r
+        if (($token['type'] === HTML5::CHARACTR &&\r
+                preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || (\r
+                $token['type'] === HTML5::CHARACTR && in_array(\r
+                    end($this->stack)->nodeName,\r
+                    array('title', 'style', 'script')\r
+                ))\r
+        ) {\r
+            /* Append the character to the current node. */\r
+            $this->insertText($token['data']);\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the current node with the data attribute\r
+            set to the data given in the comment token. */\r
+            $this->insertComment($token['data']);\r
+\r
+        } elseif ($token['type'] === HTML5::ENDTAG &&\r
+            in_array($token['name'], array('title', 'style', 'script'))\r
+        ) {\r
+            array_pop($this->stack);\r
+            return HTML5::PCDATA;\r
+\r
+            /* A start tag with the tag name "title" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'title') {\r
+            /* Create an element for the token and append the new element to the\r
+            node pointed to by the head element pointer, or, if that is null\r
+            (innerHTML case), to the current node. */\r
+            if ($this->head_pointer !== null) {\r
+                $element = $this->insertElement($token, false);\r
+                $this->head_pointer->appendChild($element);\r
+\r
+            } else {\r
+                $element = $this->insertElement($token);\r
+            }\r
+\r
+            /* Switch the tokeniser's content model flag  to the RCDATA state. */\r
+            return HTML5::RCDATA;\r
+\r
+            /* A start tag with the tag name "style" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'style') {\r
+            /* Create an element for the token and append the new element to the\r
+            node pointed to by the head element pointer, or, if that is null\r
+            (innerHTML case), to the current node. */\r
+            if ($this->head_pointer !== null) {\r
+                $element = $this->insertElement($token, false);\r
+                $this->head_pointer->appendChild($element);\r
+\r
+            } else {\r
+                $this->insertElement($token);\r
+            }\r
+\r
+            /* Switch the tokeniser's content model flag  to the CDATA state. */\r
+            return HTML5::CDATA;\r
+\r
+            /* A start tag with the tag name "script" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'script') {\r
+            /* Create an element for the token. */\r
+            $element = $this->insertElement($token, false);\r
+            $this->head_pointer->appendChild($element);\r
+\r
+            /* Switch the tokeniser's content model flag  to the CDATA state. */\r
+            return HTML5::CDATA;\r
+\r
+            /* A start tag with the tag name "base", "link", or "meta" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && in_array(\r
+                $token['name'],\r
+                array('base', 'link', 'meta')\r
+            )\r
+        ) {\r
+            /* Create an element for the token and append the new element to the\r
+            node pointed to by the head element pointer, or, if that is null\r
+            (innerHTML case), to the current node. */\r
+            if ($this->head_pointer !== null) {\r
+                $element = $this->insertElement($token, false);\r
+                $this->head_pointer->appendChild($element);\r
+                array_pop($this->stack);\r
+\r
+            } else {\r
+                $this->insertElement($token);\r
+            }\r
+\r
+            /* An end tag with the tag name "head" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'head') {\r
+            /* If the current node is a head element, pop the current node off\r
+            the stack of open elements. */\r
+            if ($this->head_pointer->isSameNode(end($this->stack))) {\r
+                array_pop($this->stack);\r
+\r
+                /* Otherwise, this is a parse error. */\r
+            } else {\r
+                // k\r
+            }\r
+\r
+            /* Change the insertion mode to "after head". */\r
+            $this->mode = self::AFTER_HEAD;\r
+\r
+            /* A start tag with the tag name "head" or an end tag except "html". */\r
+        } elseif (($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') ||\r
+            ($token['type'] === HTML5::ENDTAG && $token['name'] !== 'html')\r
+        ) {\r
+            // Parse error. Ignore the token.\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* If the current node is a head element, act as if an end tag\r
+            token with the tag name "head" had been seen. */\r
+            if ($this->head_pointer->isSameNode(end($this->stack))) {\r
+                $this->inHead(\r
+                    array(\r
+                        'name' => 'head',\r
+                        'type' => HTML5::ENDTAG\r
+                    )\r
+                );\r
+\r
+                /* Otherwise, change the insertion mode to "after head". */\r
+            } else {\r
+                $this->mode = self::AFTER_HEAD;\r
+            }\r
+\r
+            /* Then, reprocess the current token. */\r
+            return $this->afterHead($token);\r
+        }\r
+    }\r
+\r
+    private function afterHead($token)\r
+    {\r
+        /* Handle the token as follows: */\r
+\r
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+        or U+0020 SPACE */\r
+        if ($token['type'] === HTML5::CHARACTR &&\r
+            preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])\r
+        ) {\r
+            /* Append the character to the current node. */\r
+            $this->insertText($token['data']);\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the current node with the data attribute\r
+            set to the data given in the comment token. */\r
+            $this->insertComment($token['data']);\r
+\r
+            /* A start tag token with the tag name "body" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'body') {\r
+            /* Insert a body element for the token. */\r
+            $this->insertElement($token);\r
+\r
+            /* Change the insertion mode to "in body". */\r
+            $this->mode = self::IN_BODY;\r
+\r
+            /* A start tag token with the tag name "frameset" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'frameset') {\r
+            /* Insert a frameset element for the token. */\r
+            $this->insertElement($token);\r
+\r
+            /* Change the insertion mode to "in frameset". */\r
+            $this->mode = self::IN_FRAME;\r
+\r
+            /* A start tag token whose tag name is one of: "base", "link", "meta",\r
+            "script", "style", "title" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && in_array(\r
+                $token['name'],\r
+                array('base', 'link', 'meta', 'script', 'style', 'title')\r
+            )\r
+        ) {\r
+            /* Parse error. Switch the insertion mode back to "in head" and\r
+            reprocess the token. */\r
+            $this->mode = self::IN_HEAD;\r
+            return $this->inHead($token);\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Act as if a start tag token with the tag name "body" and no\r
+            attributes had been seen, and then reprocess the current token. */\r
+            $this->afterHead(\r
+                array(\r
+                    'name' => 'body',\r
+                    'type' => HTML5::STARTTAG,\r
+                    'attr' => array()\r
+                )\r
+            );\r
+\r
+            return $this->inBody($token);\r
+        }\r
+    }\r
+\r
+    private function inBody($token)\r
+    {\r
+        /* Handle the token as follows: */\r
+\r
+        switch ($token['type']) {\r
+            /* A character token */\r
+            case HTML5::CHARACTR:\r
+                /* Reconstruct the active formatting elements, if any. */\r
+                $this->reconstructActiveFormattingElements();\r
+\r
+                /* Append the token's character to the current node. */\r
+                $this->insertText($token['data']);\r
+                break;\r
+\r
+            /* A comment token */\r
+            case HTML5::COMMENT:\r
+                /* Append a Comment node to the current node with the data\r
+                attribute set to the data given in the comment token. */\r
+                $this->insertComment($token['data']);\r
+                break;\r
+\r
+            case HTML5::STARTTAG:\r
+                switch ($token['name']) {\r
+                    /* A start tag token whose tag name is one of: "script",\r
+                    "style" */\r
+                    case 'script':\r
+                    case 'style':\r
+                        /* Process the token as if the insertion mode had been "in\r
+                        head". */\r
+                        return $this->inHead($token);\r
+                        break;\r
+\r
+                    /* A start tag token whose tag name is one of: "base", "link",\r
+                    "meta", "title" */\r
+                    case 'base':\r
+                    case 'link':\r
+                    case 'meta':\r
+                    case 'title':\r
+                        /* Parse error. Process the token as if the insertion mode\r
+                        had    been "in head". */\r
+                        return $this->inHead($token);\r
+                        break;\r
+\r
+                    /* A start tag token with the tag name "body" */\r
+                    case 'body':\r
+                        /* Parse error. If the second element on the stack of open\r
+                        elements is not a body element, or, if the stack of open\r
+                        elements has only one node on it, then ignore the token.\r
+                        (innerHTML case) */\r
+                        if (count($this->stack) === 1 || $this->stack[1]->nodeName !== 'body') {\r
+                            // Ignore\r
+\r
+                            /* Otherwise, for each attribute on the token, check to see\r
+                            if the attribute is already present on the body element (the\r
+                            second element)    on the stack of open elements. If it is not,\r
+                            add the attribute and its corresponding value to that\r
+                            element. */\r
+                        } else {\r
+                            foreach ($token['attr'] as $attr) {\r
+                                if (!$this->stack[1]->hasAttribute($attr['name'])) {\r
+                                    $this->stack[1]->setAttribute($attr['name'], $attr['value']);\r
+                                }\r
+                            }\r
+                        }\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is one of: "address",\r
+                    "blockquote", "center", "dir", "div", "dl", "fieldset",\r
+                    "listing", "menu", "ol", "p", "ul" */\r
+                    case 'address':\r
+                    case 'blockquote':\r
+                    case 'center':\r
+                    case 'dir':\r
+                    case 'div':\r
+                    case 'dl':\r
+                    case 'fieldset':\r
+                    case 'listing':\r
+                    case 'menu':\r
+                    case 'ol':\r
+                    case 'p':\r
+                    case 'ul':\r
+                        /* If the stack of open elements has a p element in scope,\r
+                        then act as if an end tag with the tag name p had been\r
+                        seen. */\r
+                        if ($this->elementInScope('p')) {\r
+                            $this->emitToken(\r
+                                array(\r
+                                    'name' => 'p',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+                        }\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $this->insertElement($token);\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is "form" */\r
+                    case 'form':\r
+                        /* If the form element pointer is not null, ignore the\r
+                        token with a parse error. */\r
+                        if ($this->form_pointer !== null) {\r
+                            // Ignore.\r
+\r
+                            /* Otherwise: */\r
+                        } else {\r
+                            /* If the stack of open elements has a p element in\r
+                            scope, then act as if an end tag with the tag name p\r
+                            had been seen. */\r
+                            if ($this->elementInScope('p')) {\r
+                                $this->emitToken(\r
+                                    array(\r
+                                        'name' => 'p',\r
+                                        'type' => HTML5::ENDTAG\r
+                                    )\r
+                                );\r
+                            }\r
+\r
+                            /* Insert an HTML element for the token, and set the\r
+                            form element pointer to point to the element created. */\r
+                            $element = $this->insertElement($token);\r
+                            $this->form_pointer = $element;\r
+                        }\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is "li", "dd" or "dt" */\r
+                    case 'li':\r
+                    case 'dd':\r
+                    case 'dt':\r
+                        /* If the stack of open elements has a p  element in scope,\r
+                        then act as if an end tag with the tag name p had been\r
+                        seen. */\r
+                        if ($this->elementInScope('p')) {\r
+                            $this->emitToken(\r
+                                array(\r
+                                    'name' => 'p',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+                        }\r
+\r
+                        $stack_length = count($this->stack) - 1;\r
+\r
+                        for ($n = $stack_length; 0 <= $n; $n--) {\r
+                            /* 1. Initialise node to be the current node (the\r
+                            bottommost node of the stack). */\r
+                            $stop = false;\r
+                            $node = $this->stack[$n];\r
+                            $cat = $this->getElementCategory($node->tagName);\r
+\r
+                            /* 2. If node is an li, dd or dt element, then pop all\r
+                            the    nodes from the current node up to node, including\r
+                            node, then stop this algorithm. */\r
+                            if ($token['name'] === $node->tagName || ($token['name'] !== 'li'\r
+                                    && ($node->tagName === 'dd' || $node->tagName === 'dt'))\r
+                            ) {\r
+                                for ($x = $stack_length; $x >= $n; $x--) {\r
+                                    array_pop($this->stack);\r
+                                }\r
+\r
+                                break;\r
+                            }\r
+\r
+                            /* 3. If node is not in the formatting category, and is\r
+                            not    in the phrasing category, and is not an address or\r
+                            div element, then stop this algorithm. */\r
+                            if ($cat !== self::FORMATTING && $cat !== self::PHRASING &&\r
+                                $node->tagName !== 'address' && $node->tagName !== 'div'\r
+                            ) {\r
+                                break;\r
+                            }\r
+                        }\r
+\r
+                        /* Finally, insert an HTML element with the same tag\r
+                        name as the    token's. */\r
+                        $this->insertElement($token);\r
+                        break;\r
+\r
+                    /* A start tag token whose tag name is "plaintext" */\r
+                    case 'plaintext':\r
+                        /* If the stack of open elements has a p  element in scope,\r
+                        then act as if an end tag with the tag name p had been\r
+                        seen. */\r
+                        if ($this->elementInScope('p')) {\r
+                            $this->emitToken(\r
+                                array(\r
+                                    'name' => 'p',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+                        }\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $this->insertElement($token);\r
+\r
+                        return HTML5::PLAINTEXT;\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is one of: "h1", "h2", "h3", "h4",\r
+                    "h5", "h6" */\r
+                    case 'h1':\r
+                    case 'h2':\r
+                    case 'h3':\r
+                    case 'h4':\r
+                    case 'h5':\r
+                    case 'h6':\r
+                        /* If the stack of open elements has a p  element in scope,\r
+                        then act as if an end tag with the tag name p had been seen. */\r
+                        if ($this->elementInScope('p')) {\r
+                            $this->emitToken(\r
+                                array(\r
+                                    'name' => 'p',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+                        }\r
+\r
+                        /* If the stack of open elements has in scope an element whose\r
+                        tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then\r
+                        this is a parse error; pop elements from the stack until an\r
+                        element with one of those tag names has been popped from the\r
+                        stack. */\r
+                        while ($this->elementInScope(array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))) {\r
+                            array_pop($this->stack);\r
+                        }\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $this->insertElement($token);\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is "a" */\r
+                    case 'a':\r
+                        /* If the list of active formatting elements contains\r
+                        an element whose tag name is "a" between the end of the\r
+                        list and the last marker on the list (or the start of\r
+                        the list if there is no marker on the list), then this\r
+                        is a parse error; act as if an end tag with the tag name\r
+                        "a" had been seen, then remove that element from the list\r
+                        of active formatting elements and the stack of open\r
+                        elements if the end tag didn't already remove it (it\r
+                        might not have if the element is not in table scope). */\r
+                        $leng = count($this->a_formatting);\r
+\r
+                        for ($n = $leng - 1; $n >= 0; $n--) {\r
+                            if ($this->a_formatting[$n] === self::MARKER) {\r
+                                break;\r
+\r
+                            } elseif ($this->a_formatting[$n]->nodeName === 'a') {\r
+                                $this->emitToken(\r
+                                    array(\r
+                                        'name' => 'a',\r
+                                        'type' => HTML5::ENDTAG\r
+                                    )\r
+                                );\r
+                                break;\r
+                            }\r
+                        }\r
+\r
+                        /* Reconstruct the active formatting elements, if any. */\r
+                        $this->reconstructActiveFormattingElements();\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $el = $this->insertElement($token);\r
+\r
+                        /* Add that element to the list of active formatting\r
+                        elements. */\r
+                        $this->a_formatting[] = $el;\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is one of: "b", "big", "em", "font",\r
+                    "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */\r
+                    case 'b':\r
+                    case 'big':\r
+                    case 'em':\r
+                    case 'font':\r
+                    case 'i':\r
+                    case 'nobr':\r
+                    case 's':\r
+                    case 'small':\r
+                    case 'strike':\r
+                    case 'strong':\r
+                    case 'tt':\r
+                    case 'u':\r
+                        /* Reconstruct the active formatting elements, if any. */\r
+                        $this->reconstructActiveFormattingElements();\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $el = $this->insertElement($token);\r
+\r
+                        /* Add that element to the list of active formatting\r
+                        elements. */\r
+                        $this->a_formatting[] = $el;\r
+                        break;\r
+\r
+                    /* A start tag token whose tag name is "button" */\r
+                    case 'button':\r
+                        /* If the stack of open elements has a button element in scope,\r
+                        then this is a parse error; act as if an end tag with the tag\r
+                        name "button" had been seen, then reprocess the token. (We don't\r
+                        do that. Unnecessary.) */\r
+                        if ($this->elementInScope('button')) {\r
+                            $this->inBody(\r
+                                array(\r
+                                    'name' => 'button',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+                        }\r
+\r
+                        /* Reconstruct the active formatting elements, if any. */\r
+                        $this->reconstructActiveFormattingElements();\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $this->insertElement($token);\r
+\r
+                        /* Insert a marker at the end of the list of active\r
+                        formatting elements. */\r
+                        $this->a_formatting[] = self::MARKER;\r
+                        break;\r
+\r
+                    /* A start tag token whose tag name is one of: "marquee", "object" */\r
+                    case 'marquee':\r
+                    case 'object':\r
+                        /* Reconstruct the active formatting elements, if any. */\r
+                        $this->reconstructActiveFormattingElements();\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $this->insertElement($token);\r
+\r
+                        /* Insert a marker at the end of the list of active\r
+                        formatting elements. */\r
+                        $this->a_formatting[] = self::MARKER;\r
+                        break;\r
+\r
+                    /* A start tag token whose tag name is "xmp" */\r
+                    case 'xmp':\r
+                        /* Reconstruct the active formatting elements, if any. */\r
+                        $this->reconstructActiveFormattingElements();\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $this->insertElement($token);\r
+\r
+                        /* Switch the content model flag to the CDATA state. */\r
+                        return HTML5::CDATA;\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is "table" */\r
+                    case 'table':\r
+                        /* If the stack of open elements has a p element in scope,\r
+                        then act as if an end tag with the tag name p had been seen. */\r
+                        if ($this->elementInScope('p')) {\r
+                            $this->emitToken(\r
+                                array(\r
+                                    'name' => 'p',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+                        }\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $this->insertElement($token);\r
+\r
+                        /* Change the insertion mode to "in table". */\r
+                        $this->mode = self::IN_TABLE;\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is one of: "area", "basefont",\r
+                    "bgsound", "br", "embed", "img", "param", "spacer", "wbr" */\r
+                    case 'area':\r
+                    case 'basefont':\r
+                    case 'bgsound':\r
+                    case 'br':\r
+                    case 'embed':\r
+                    case 'img':\r
+                    case 'param':\r
+                    case 'spacer':\r
+                    case 'wbr':\r
+                        /* Reconstruct the active formatting elements, if any. */\r
+                        $this->reconstructActiveFormattingElements();\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $this->insertElement($token);\r
+\r
+                        /* Immediately pop the current node off the stack of open elements. */\r
+                        array_pop($this->stack);\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is "hr" */\r
+                    case 'hr':\r
+                        /* If the stack of open elements has a p element in scope,\r
+                        then act as if an end tag with the tag name p had been seen. */\r
+                        if ($this->elementInScope('p')) {\r
+                            $this->emitToken(\r
+                                array(\r
+                                    'name' => 'p',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+                        }\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $this->insertElement($token);\r
+\r
+                        /* Immediately pop the current node off the stack of open elements. */\r
+                        array_pop($this->stack);\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is "image" */\r
+                    case 'image':\r
+                        /* Parse error. Change the token's tag name to "img" and\r
+                        reprocess it. (Don't ask.) */\r
+                        $token['name'] = 'img';\r
+                        return $this->inBody($token);\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is "input" */\r
+                    case 'input':\r
+                        /* Reconstruct the active formatting elements, if any. */\r
+                        $this->reconstructActiveFormattingElements();\r
+\r
+                        /* Insert an input element for the token. */\r
+                        $element = $this->insertElement($token, false);\r
+\r
+                        /* If the form element pointer is not null, then associate the\r
+                        input element with the form element pointed to by the form\r
+                        element pointer. */\r
+                        $this->form_pointer !== null\r
+                            ? $this->form_pointer->appendChild($element)\r
+                            : end($this->stack)->appendChild($element);\r
+\r
+                        /* Pop that input element off the stack of open elements. */\r
+                        array_pop($this->stack);\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is "isindex" */\r
+                    case 'isindex':\r
+                        /* Parse error. */\r
+                        // w/e\r
+\r
+                        /* If the form element pointer is not null,\r
+                        then ignore the token. */\r
+                        if ($this->form_pointer === null) {\r
+                            /* Act as if a start tag token with the tag name "form" had\r
+                            been seen. */\r
+                            $this->inBody(\r
+                                array(\r
+                                    'name' => 'body',\r
+                                    'type' => HTML5::STARTTAG,\r
+                                    'attr' => array()\r
+                                )\r
+                            );\r
+\r
+                            /* Act as if a start tag token with the tag name "hr" had\r
+                            been seen. */\r
+                            $this->inBody(\r
+                                array(\r
+                                    'name' => 'hr',\r
+                                    'type' => HTML5::STARTTAG,\r
+                                    'attr' => array()\r
+                                )\r
+                            );\r
+\r
+                            /* Act as if a start tag token with the tag name "p" had\r
+                            been seen. */\r
+                            $this->inBody(\r
+                                array(\r
+                                    'name' => 'p',\r
+                                    'type' => HTML5::STARTTAG,\r
+                                    'attr' => array()\r
+                                )\r
+                            );\r
+\r
+                            /* Act as if a start tag token with the tag name "label"\r
+                            had been seen. */\r
+                            $this->inBody(\r
+                                array(\r
+                                    'name' => 'label',\r
+                                    'type' => HTML5::STARTTAG,\r
+                                    'attr' => array()\r
+                                )\r
+                            );\r
+\r
+                            /* Act as if a stream of character tokens had been seen. */\r
+                            $this->insertText(\r
+                                'This is a searchable index. ' .\r
+                                'Insert your search keywords here: '\r
+                            );\r
+\r
+                            /* Act as if a start tag token with the tag name "input"\r
+                            had been seen, with all the attributes from the "isindex"\r
+                            token, except with the "name" attribute set to the value\r
+                            "isindex" (ignoring any explicit "name" attribute). */\r
+                            $attr = $token['attr'];\r
+                            $attr[] = array('name' => 'name', 'value' => 'isindex');\r
+\r
+                            $this->inBody(\r
+                                array(\r
+                                    'name' => 'input',\r
+                                    'type' => HTML5::STARTTAG,\r
+                                    'attr' => $attr\r
+                                )\r
+                            );\r
+\r
+                            /* Act as if a stream of character tokens had been seen\r
+                            (see below for what they should say). */\r
+                            $this->insertText(\r
+                                'This is a searchable index. ' .\r
+                                'Insert your search keywords here: '\r
+                            );\r
+\r
+                            /* Act as if an end tag token with the tag name "label"\r
+                            had been seen. */\r
+                            $this->inBody(\r
+                                array(\r
+                                    'name' => 'label',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+\r
+                            /* Act as if an end tag token with the tag name "p" had\r
+                            been seen. */\r
+                            $this->inBody(\r
+                                array(\r
+                                    'name' => 'p',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+\r
+                            /* Act as if a start tag token with the tag name "hr" had\r
+                            been seen. */\r
+                            $this->inBody(\r
+                                array(\r
+                                    'name' => 'hr',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+\r
+                            /* Act as if an end tag token with the tag name "form" had\r
+                            been seen. */\r
+                            $this->inBody(\r
+                                array(\r
+                                    'name' => 'form',\r
+                                    'type' => HTML5::ENDTAG\r
+                                )\r
+                            );\r
+                        }\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is "textarea" */\r
+                    case 'textarea':\r
+                        $this->insertElement($token);\r
+\r
+                        /* Switch the tokeniser's content model flag to the\r
+                        RCDATA state. */\r
+                        return HTML5::RCDATA;\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is one of: "iframe", "noembed",\r
+                    "noframes" */\r
+                    case 'iframe':\r
+                    case 'noembed':\r
+                    case 'noframes':\r
+                        $this->insertElement($token);\r
+\r
+                        /* Switch the tokeniser's content model flag to the CDATA state. */\r
+                        return HTML5::CDATA;\r
+                        break;\r
+\r
+                    /* A start tag whose tag name is "select" */\r
+                    case 'select':\r
+                        /* Reconstruct the active formatting elements, if any. */\r
+                        $this->reconstructActiveFormattingElements();\r
+\r
+                        /* Insert an HTML element for the token. */\r
+                        $this->insertElement($token);\r
+\r
+                        /* Change the insertion mode to "in select". */\r
+                        $this->mode = self::IN_SELECT;\r
+                        break;\r
+\r
+                    /* A start or end tag whose tag name is one of: "caption", "col",\r
+                    "colgroup", "frame", "frameset", "head", "option", "optgroup",\r
+                    "tbody", "td", "tfoot", "th", "thead", "tr". */\r
+                    case 'caption':\r
+                    case 'col':\r
+                    case 'colgroup':\r
+                    case 'frame':\r
+                    case 'frameset':\r
+                    case 'head':\r
+                    case 'option':\r
+                    case 'optgroup':\r
+                    case 'tbody':\r
+                    case 'td':\r
+                    case 'tfoot':\r
+                    case 'th':\r
+                    case 'thead':\r
+                    case 'tr':\r
+                        // Parse error. Ignore the token.\r
+                        break;\r
+\r
+                    /* A start or end tag whose tag name is one of: "event-source",\r
+                    "section", "nav", "article", "aside", "header", "footer",\r
+                    "datagrid", "command" */\r
+                    case 'event-source':\r
+                    case 'section':\r
+                    case 'nav':\r
+                    case 'article':\r
+                    case 'aside':\r
+                    case 'header':\r
+                    case 'footer':\r
+                    case 'datagrid':\r
+                    case 'command':\r
+                        // Work in progress!\r
+                        break;\r
+\r
+                    /* A start tag token not covered by the previous entries */\r
+                    default:\r
+                        /* Reconstruct the active formatting elements, if any. */\r
+                        $this->reconstructActiveFormattingElements();\r
+\r
+                        $this->insertElement($token, true, true);\r
+                        break;\r
+                }\r
+                break;\r
+\r
+            case HTML5::ENDTAG:\r
+                switch ($token['name']) {\r
+                    /* An end tag with the tag name "body" */\r
+                    case 'body':\r
+                        /* If the second element in the stack of open elements is\r
+                        not a body element, this is a parse error. Ignore the token.\r
+                        (innerHTML case) */\r
+                        if (count($this->stack) < 2 || $this->stack[1]->nodeName !== 'body') {\r
+                            // Ignore.\r
+\r
+                            /* If the current node is not the body element, then this\r
+                            is a parse error. */\r
+                        } elseif (end($this->stack)->nodeName !== 'body') {\r
+                            // Parse error.\r
+                        }\r
+\r
+                        /* Change the insertion mode to "after body". */\r
+                        $this->mode = self::AFTER_BODY;\r
+                        break;\r
+\r
+                    /* An end tag with the tag name "html" */\r
+                    case 'html':\r
+                        /* Act as if an end tag with tag name "body" had been seen,\r
+                        then, if that token wasn't ignored, reprocess the current\r
+                        token. */\r
+                        $this->inBody(\r
+                            array(\r
+                                'name' => 'body',\r
+                                'type' => HTML5::ENDTAG\r
+                            )\r
+                        );\r
+\r
+                        return $this->afterBody($token);\r
+                        break;\r
+\r
+                    /* An end tag whose tag name is one of: "address", "blockquote",\r
+                    "center", "dir", "div", "dl", "fieldset", "listing", "menu",\r
+                    "ol", "pre", "ul" */\r
+                    case 'address':\r
+                    case 'blockquote':\r
+                    case 'center':\r
+                    case 'dir':\r
+                    case 'div':\r
+                    case 'dl':\r
+                    case 'fieldset':\r
+                    case 'listing':\r
+                    case 'menu':\r
+                    case 'ol':\r
+                    case 'pre':\r
+                    case 'ul':\r
+                        /* If the stack of open elements has an element in scope\r
+                        with the same tag name as that of the token, then generate\r
+                        implied end tags. */\r
+                        if ($this->elementInScope($token['name'])) {\r
+                            $this->generateImpliedEndTags();\r
+\r
+                            /* Now, if the current node is not an element with\r
+                            the same tag name as that of the token, then this\r
+                            is a parse error. */\r
+                            // w/e\r
+\r
+                            /* If the stack of open elements has an element in\r
+                            scope with the same tag name as that of the token,\r
+                            then pop elements from this stack until an element\r
+                            with that tag name has been popped from the stack. */\r
+                            for ($n = count($this->stack) - 1; $n >= 0; $n--) {\r
+                                if ($this->stack[$n]->nodeName === $token['name']) {\r
+                                    $n = -1;\r
+                                }\r
+\r
+                                array_pop($this->stack);\r
+                            }\r
+                        }\r
+                        break;\r
+\r
+                    /* An end tag whose tag name is "form" */\r
+                    case 'form':\r
+                        /* If the stack of open elements has an element in scope\r
+                        with the same tag name as that of the token, then generate\r
+                        implied    end tags. */\r
+                        if ($this->elementInScope($token['name'])) {\r
+                            $this->generateImpliedEndTags();\r
+\r
+                        }\r
+\r
+                        if (end($this->stack)->nodeName !== $token['name']) {\r
+                            /* Now, if the current node is not an element with the\r
+                            same tag name as that of the token, then this is a parse\r
+                            error. */\r
+                            // w/e\r
+\r
+                        } else {\r
+                            /* Otherwise, if the current node is an element with\r
+                            the same tag name as that of the token pop that element\r
+                            from the stack. */\r
+                            array_pop($this->stack);\r
+                        }\r
+\r
+                        /* In any case, set the form element pointer to null. */\r
+                        $this->form_pointer = null;\r
+                        break;\r
+\r
+                    /* An end tag whose tag name is "p" */\r
+                    case 'p':\r
+                        /* If the stack of open elements has a p element in scope,\r
+                        then generate implied end tags, except for p elements. */\r
+                        if ($this->elementInScope('p')) {\r
+                            $this->generateImpliedEndTags(array('p'));\r
+\r
+                            /* If the current node is not a p element, then this is\r
+                            a parse error. */\r
+                            // k\r
+\r
+                            /* If the stack of open elements has a p element in\r
+                            scope, then pop elements from this stack until the stack\r
+                            no longer has a p element in scope. */\r
+                            for ($n = count($this->stack) - 1; $n >= 0; $n--) {\r
+                                if ($this->elementInScope('p')) {\r
+                                    array_pop($this->stack);\r
+\r
+                                } else {\r
+                                    break;\r
+                                }\r
+                            }\r
+                        }\r
+                        break;\r
+\r
+                    /* An end tag whose tag name is "dd", "dt", or "li" */\r
+                    case 'dd':\r
+                    case 'dt':\r
+                    case 'li':\r
+                        /* If the stack of open elements has an element in scope\r
+                        whose tag name matches the tag name of the token, then\r
+                        generate implied end tags, except for elements with the\r
+                        same tag name as the token. */\r
+                        if ($this->elementInScope($token['name'])) {\r
+                            $this->generateImpliedEndTags(array($token['name']));\r
+\r
+                            /* If the current node is not an element with the same\r
+                            tag name as the token, then this is a parse error. */\r
+                            // w/e\r
+\r
+                            /* If the stack of open elements has an element in scope\r
+                            whose tag name matches the tag name of the token, then\r
+                            pop elements from this stack until an element with that\r
+                            tag name has been popped from the stack. */\r
+                            for ($n = count($this->stack) - 1; $n >= 0; $n--) {\r
+                                if ($this->stack[$n]->nodeName === $token['name']) {\r
+                                    $n = -1;\r
+                                }\r
+\r
+                                array_pop($this->stack);\r
+                            }\r
+                        }\r
+                        break;\r
+\r
+                    /* An end tag whose tag name is one of: "h1", "h2", "h3", "h4",\r
+                    "h5", "h6" */\r
+                    case 'h1':\r
+                    case 'h2':\r
+                    case 'h3':\r
+                    case 'h4':\r
+                    case 'h5':\r
+                    case 'h6':\r
+                        $elements = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6');\r
+\r
+                        /* If the stack of open elements has in scope an element whose\r
+                        tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then\r
+                        generate implied end tags. */\r
+                        if ($this->elementInScope($elements)) {\r
+                            $this->generateImpliedEndTags();\r
+\r
+                            /* Now, if the current node is not an element with the same\r
+                            tag name as that of the token, then this is a parse error. */\r
+                            // w/e\r
+\r
+                            /* If the stack of open elements has in scope an element\r
+                            whose tag name is one of "h1", "h2", "h3", "h4", "h5", or\r
+                            "h6", then pop elements from the stack until an element\r
+                            with one of those tag names has been popped from the stack. */\r
+                            while ($this->elementInScope($elements)) {\r
+                                array_pop($this->stack);\r
+                            }\r
+                        }\r
+                        break;\r
+\r
+                    /* An end tag whose tag name is one of: "a", "b", "big", "em",\r
+                    "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */\r
+                    case 'a':\r
+                    case 'b':\r
+                    case 'big':\r
+                    case 'em':\r
+                    case 'font':\r
+                    case 'i':\r
+                    case 'nobr':\r
+                    case 's':\r
+                    case 'small':\r
+                    case 'strike':\r
+                    case 'strong':\r
+                    case 'tt':\r
+                    case 'u':\r
+                        /* 1. Let the formatting element be the last element in\r
+                        the list of active formatting elements that:\r
+                            * is between the end of the list and the last scope\r
+                            marker in the list, if any, or the start of the list\r
+                            otherwise, and\r
+                            * has the same tag name as the token.\r
+                        */\r
+                        while (true) {\r
+                            for ($a = count($this->a_formatting) - 1; $a >= 0; $a--) {\r
+                                if ($this->a_formatting[$a] === self::MARKER) {\r
+                                    break;\r
+\r
+                                } elseif ($this->a_formatting[$a]->tagName === $token['name']) {\r
+                                    $formatting_element = $this->a_formatting[$a];\r
+                                    $in_stack = in_array($formatting_element, $this->stack, true);\r
+                                    $fe_af_pos = $a;\r
+                                    break;\r
+                                }\r
+                            }\r
+\r
+                            /* If there is no such node, or, if that node is\r
+                            also in the stack of open elements but the element\r
+                            is not in scope, then this is a parse error. Abort\r
+                            these steps. The token is ignored. */\r
+                            if (!isset($formatting_element) || ($in_stack &&\r
+                                    !$this->elementInScope($token['name']))\r
+                            ) {\r
+                                break;\r
+\r
+                                /* Otherwise, if there is such a node, but that node\r
+                                is not in the stack of open elements, then this is a\r
+                                parse error; remove the element from the list, and\r
+                                abort these steps. */\r
+                            } elseif (isset($formatting_element) && !$in_stack) {\r
+                                unset($this->a_formatting[$fe_af_pos]);\r
+                                $this->a_formatting = array_merge($this->a_formatting);\r
+                                break;\r
+                            }\r
+\r
+                            /* 2. Let the furthest block be the topmost node in the\r
+                            stack of open elements that is lower in the stack\r
+                            than the formatting element, and is not an element in\r
+                            the phrasing or formatting categories. There might\r
+                            not be one. */\r
+                            $fe_s_pos = array_search($formatting_element, $this->stack, true);\r
+                            $length = count($this->stack);\r
+\r
+                            for ($s = $fe_s_pos + 1; $s < $length; $s++) {\r
+                                $category = $this->getElementCategory($this->stack[$s]->nodeName);\r
+\r
+                                if ($category !== self::PHRASING && $category !== self::FORMATTING) {\r
+                                    $furthest_block = $this->stack[$s];\r
+                                }\r
+                            }\r
+\r
+                            /* 3. If there is no furthest block, then the UA must\r
+                            skip the subsequent steps and instead just pop all\r
+                            the nodes from the bottom of the stack of open\r
+                            elements, from the current node up to the formatting\r
+                            element, and remove the formatting element from the\r
+                            list of active formatting elements. */\r
+                            if (!isset($furthest_block)) {\r
+                                for ($n = $length - 1; $n >= $fe_s_pos; $n--) {\r
+                                    array_pop($this->stack);\r
+                                }\r
+\r
+                                unset($this->a_formatting[$fe_af_pos]);\r
+                                $this->a_formatting = array_merge($this->a_formatting);\r
+                                break;\r
+                            }\r
+\r
+                            /* 4. Let the common ancestor be the element\r
+                            immediately above the formatting element in the stack\r
+                            of open elements. */\r
+                            $common_ancestor = $this->stack[$fe_s_pos - 1];\r
+\r
+                            /* 5. If the furthest block has a parent node, then\r
+                            remove the furthest block from its parent node. */\r
+                            if ($furthest_block->parentNode !== null) {\r
+                                $furthest_block->parentNode->removeChild($furthest_block);\r
+                            }\r
+\r
+                            /* 6. Let a bookmark note the position of the\r
+                            formatting element in the list of active formatting\r
+                            elements relative to the elements on either side\r
+                            of it in the list. */\r
+                            $bookmark = $fe_af_pos;\r
+\r
+                            /* 7. Let node and last node  be the furthest block.\r
+                            Follow these steps: */\r
+                            $node = $furthest_block;\r
+                            $last_node = $furthest_block;\r
+\r
+                            while (true) {\r
+                                for ($n = array_search($node, $this->stack, true) - 1; $n >= 0; $n--) {\r
+                                    /* 7.1 Let node be the element immediately\r
+                                    prior to node in the stack of open elements. */\r
+                                    $node = $this->stack[$n];\r
+\r
+                                    /* 7.2 If node is not in the list of active\r
+                                    formatting elements, then remove node from\r
+                                    the stack of open elements and then go back\r
+                                    to step 1. */\r
+                                    if (!in_array($node, $this->a_formatting, true)) {\r
+                                        unset($this->stack[$n]);\r
+                                        $this->stack = array_merge($this->stack);\r
+\r
+                                    } else {\r
+                                        break;\r
+                                    }\r
+                                }\r
+\r
+                                /* 7.3 Otherwise, if node is the formatting\r
+                                element, then go to the next step in the overall\r
+                                algorithm. */\r
+                                if ($node === $formatting_element) {\r
+                                    break;\r
+\r
+                                    /* 7.4 Otherwise, if last node is the furthest\r
+                                    block, then move the aforementioned bookmark to\r
+                                    be immediately after the node in the list of\r
+                                    active formatting elements. */\r
+                                } elseif ($last_node === $furthest_block) {\r
+                                    $bookmark = array_search($node, $this->a_formatting, true) + 1;\r
+                                }\r
+\r
+                                /* 7.5 If node has any children, perform a\r
+                                shallow clone of node, replace the entry for\r
+                                node in the list of active formatting elements\r
+                                with an entry for the clone, replace the entry\r
+                                for node in the stack of open elements with an\r
+                                entry for the clone, and let node be the clone. */\r
+                                if ($node->hasChildNodes()) {\r
+                                    $clone = $node->cloneNode();\r
+                                    $s_pos = array_search($node, $this->stack, true);\r
+                                    $a_pos = array_search($node, $this->a_formatting, true);\r
+\r
+                                    $this->stack[$s_pos] = $clone;\r
+                                    $this->a_formatting[$a_pos] = $clone;\r
+                                    $node = $clone;\r
+                                }\r
+\r
+                                /* 7.6 Insert last node into node, first removing\r
+                                it from its previous parent node if any. */\r
+                                if ($last_node->parentNode !== null) {\r
+                                    $last_node->parentNode->removeChild($last_node);\r
+                                }\r
+\r
+                                $node->appendChild($last_node);\r
+\r
+                                /* 7.7 Let last node be node. */\r
+                                $last_node = $node;\r
+                            }\r
+\r
+                            /* 8. Insert whatever last node ended up being in\r
+                            the previous step into the common ancestor node,\r
+                            first removing it from its previous parent node if\r
+                            any. */\r
+                            if ($last_node->parentNode !== null) {\r
+                                $last_node->parentNode->removeChild($last_node);\r
+                            }\r
+\r
+                            $common_ancestor->appendChild($last_node);\r
+\r
+                            /* 9. Perform a shallow clone of the formatting\r
+                            element. */\r
+                            $clone = $formatting_element->cloneNode();\r
+\r
+                            /* 10. Take all of the child nodes of the furthest\r
+                            block and append them to the clone created in the\r
+                            last step. */\r
+                            while ($furthest_block->hasChildNodes()) {\r
+                                $child = $furthest_block->firstChild;\r
+                                $furthest_block->removeChild($child);\r
+                                $clone->appendChild($child);\r
+                            }\r
+\r
+                            /* 11. Append that clone to the furthest block. */\r
+                            $furthest_block->appendChild($clone);\r
+\r
+                            /* 12. Remove the formatting element from the list\r
+                            of active formatting elements, and insert the clone\r
+                            into the list of active formatting elements at the\r
+                            position of the aforementioned bookmark. */\r
+                            $fe_af_pos = array_search($formatting_element, $this->a_formatting, true);\r
+                            unset($this->a_formatting[$fe_af_pos]);\r
+                            $this->a_formatting = array_merge($this->a_formatting);\r
+\r
+                            $af_part1 = array_slice($this->a_formatting, 0, $bookmark - 1);\r
+                            $af_part2 = array_slice($this->a_formatting, $bookmark, count($this->a_formatting));\r
+                            $this->a_formatting = array_merge($af_part1, array($clone), $af_part2);\r
+\r
+                            /* 13. Remove the formatting element from the stack\r
+                            of open elements, and insert the clone into the stack\r
+                            of open elements immediately after (i.e. in a more\r
+                            deeply nested position than) the position of the\r
+                            furthest block in that stack. */\r
+                            $fe_s_pos = array_search($formatting_element, $this->stack, true);\r
+                            $fb_s_pos = array_search($furthest_block, $this->stack, true);\r
+                            unset($this->stack[$fe_s_pos]);\r
+\r
+                            $s_part1 = array_slice($this->stack, 0, $fb_s_pos);\r
+                            $s_part2 = array_slice($this->stack, $fb_s_pos + 1, count($this->stack));\r
+                            $this->stack = array_merge($s_part1, array($clone), $s_part2);\r
+\r
+                            /* 14. Jump back to step 1 in this series of steps. */\r
+                            unset($formatting_element, $fe_af_pos, $fe_s_pos, $furthest_block);\r
+                        }\r
+                        break;\r
+\r
+                    /* An end tag token whose tag name is one of: "button",\r
+                    "marquee", "object" */\r
+                    case 'button':\r
+                    case 'marquee':\r
+                    case 'object':\r
+                        /* If the stack of open elements has an element in scope whose\r
+                        tag name matches the tag name of the token, then generate implied\r
+                        tags. */\r
+                        if ($this->elementInScope($token['name'])) {\r
+                            $this->generateImpliedEndTags();\r
+\r
+                            /* Now, if the current node is not an element with the same\r
+                            tag name as the token, then this is a parse error. */\r
+                            // k\r
+\r
+                            /* Now, if the stack of open elements has an element in scope\r
+                            whose tag name matches the tag name of the token, then pop\r
+                            elements from the stack until that element has been popped from\r
+                            the stack, and clear the list of active formatting elements up\r
+                            to the last marker. */\r
+                            for ($n = count($this->stack) - 1; $n >= 0; $n--) {\r
+                                if ($this->stack[$n]->nodeName === $token['name']) {\r
+                                    $n = -1;\r
+                                }\r
+\r
+                                array_pop($this->stack);\r
+                            }\r
+\r
+                            $marker = end(array_keys($this->a_formatting, self::MARKER, true));\r
+\r
+                            for ($n = count($this->a_formatting) - 1; $n > $marker; $n--) {\r
+                                array_pop($this->a_formatting);\r
+                            }\r
+                        }\r
+                        break;\r
+\r
+                    /* Or an end tag whose tag name is one of: "area", "basefont",\r
+                    "bgsound", "br", "embed", "hr", "iframe", "image", "img",\r
+                    "input", "isindex", "noembed", "noframes", "param", "select",\r
+                    "spacer", "table", "textarea", "wbr" */\r
+                    case 'area':\r
+                    case 'basefont':\r
+                    case 'bgsound':\r
+                    case 'br':\r
+                    case 'embed':\r
+                    case 'hr':\r
+                    case 'iframe':\r
+                    case 'image':\r
+                    case 'img':\r
+                    case 'input':\r
+                    case 'isindex':\r
+                    case 'noembed':\r
+                    case 'noframes':\r
+                    case 'param':\r
+                    case 'select':\r
+                    case 'spacer':\r
+                    case 'table':\r
+                    case 'textarea':\r
+                    case 'wbr':\r
+                        // Parse error. Ignore the token.\r
+                        break;\r
+\r
+                    /* An end tag token not covered by the previous entries */\r
+                    default:\r
+                        for ($n = count($this->stack) - 1; $n >= 0; $n--) {\r
+                            /* Initialise node to be the current node (the bottommost\r
+                            node of the stack). */\r
+                            $node = end($this->stack);\r
+\r
+                            /* If node has the same tag name as the end tag token,\r
+                            then: */\r
+                            if ($token['name'] === $node->nodeName) {\r
+                                /* Generate implied end tags. */\r
+                                $this->generateImpliedEndTags();\r
+\r
+                                /* If the tag name of the end tag token does not\r
+                                match the tag name of the current node, this is a\r
+                                parse error. */\r
+                                // k\r
+\r
+                                /* Pop all the nodes from the current node up to\r
+                                node, including node, then stop this algorithm. */\r
+                                for ($x = count($this->stack) - $n; $x >= $n; $x--) {\r
+                                    array_pop($this->stack);\r
+                                }\r
+\r
+                            } else {\r
+                                $category = $this->getElementCategory($node);\r
+\r
+                                if ($category !== self::SPECIAL && $category !== self::SCOPING) {\r
+                                    /* Otherwise, if node is in neither the formatting\r
+                                    category nor the phrasing category, then this is a\r
+                                    parse error. Stop this algorithm. The end tag token\r
+                                    is ignored. */\r
+                                    return false;\r
+                                }\r
+                            }\r
+                        }\r
+                        break;\r
+                }\r
+                break;\r
+        }\r
+    }\r
+\r
+    private function inTable($token)\r
+    {\r
+        $clear = array('html', 'table');\r
+\r
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+        or U+0020 SPACE */\r
+        if ($token['type'] === HTML5::CHARACTR &&\r
+            preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])\r
+        ) {\r
+            /* Append the character to the current node. */\r
+            $text = $this->dom->createTextNode($token['data']);\r
+            end($this->stack)->appendChild($text);\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the current node with the data\r
+            attribute set to the data given in the comment token. */\r
+            $comment = $this->dom->createComment($token['data']);\r
+            end($this->stack)->appendChild($comment);\r
+\r
+            /* A start tag whose tag name is "caption" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG &&\r
+            $token['name'] === 'caption'\r
+        ) {\r
+            /* Clear the stack back to a table context. */\r
+            $this->clearStackToTableContext($clear);\r
+\r
+            /* Insert a marker at the end of the list of active\r
+            formatting elements. */\r
+            $this->a_formatting[] = self::MARKER;\r
+\r
+            /* Insert an HTML element for the token, then switch the\r
+            insertion mode to "in caption". */\r
+            $this->insertElement($token);\r
+            $this->mode = self::IN_CAPTION;\r
+\r
+            /* A start tag whose tag name is "colgroup" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG &&\r
+            $token['name'] === 'colgroup'\r
+        ) {\r
+            /* Clear the stack back to a table context. */\r
+            $this->clearStackToTableContext($clear);\r
+\r
+            /* Insert an HTML element for the token, then switch the\r
+            insertion mode to "in column group". */\r
+            $this->insertElement($token);\r
+            $this->mode = self::IN_CGROUP;\r
+\r
+            /* A start tag whose tag name is "col" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG &&\r
+            $token['name'] === 'col'\r
+        ) {\r
+            $this->inTable(\r
+                array(\r
+                    'name' => 'colgroup',\r
+                    'type' => HTML5::STARTTAG,\r
+                    'attr' => array()\r
+                )\r
+            );\r
+\r
+            $this->inColumnGroup($token);\r
+\r
+            /* A start tag whose tag name is one of: "tbody", "tfoot", "thead" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && in_array(\r
+                $token['name'],\r
+                array('tbody', 'tfoot', 'thead')\r
+            )\r
+        ) {\r
+            /* Clear the stack back to a table context. */\r
+            $this->clearStackToTableContext($clear);\r
+\r
+            /* Insert an HTML element for the token, then switch the insertion\r
+            mode to "in table body". */\r
+            $this->insertElement($token);\r
+            $this->mode = self::IN_TBODY;\r
+\r
+            /* A start tag whose tag name is one of: "td", "th", "tr" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG &&\r
+            in_array($token['name'], array('td', 'th', 'tr'))\r
+        ) {\r
+            /* Act as if a start tag token with the tag name "tbody" had been\r
+            seen, then reprocess the current token. */\r
+            $this->inTable(\r
+                array(\r
+                    'name' => 'tbody',\r
+                    'type' => HTML5::STARTTAG,\r
+                    'attr' => array()\r
+                )\r
+            );\r
+\r
+            return $this->inTableBody($token);\r
+\r
+            /* A start tag whose tag name is "table" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG &&\r
+            $token['name'] === 'table'\r
+        ) {\r
+            /* Parse error. Act as if an end tag token with the tag name "table"\r
+            had been seen, then, if that token wasn't ignored, reprocess the\r
+            current token. */\r
+            $this->inTable(\r
+                array(\r
+                    'name' => 'table',\r
+                    'type' => HTML5::ENDTAG\r
+                )\r
+            );\r
+\r
+            return $this->mainPhase($token);\r
+\r
+            /* An end tag whose tag name is "table" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG &&\r
+            $token['name'] === 'table'\r
+        ) {\r
+            /* If the stack of open elements does not have an element in table\r
+            scope with the same tag name as the token, this is a parse error.\r
+            Ignore the token. (innerHTML case) */\r
+            if (!$this->elementInScope($token['name'], true)) {\r
+                return false;\r
+\r
+                /* Otherwise: */\r
+            } else {\r
+                /* Generate implied end tags. */\r
+                $this->generateImpliedEndTags();\r
+\r
+                /* Now, if the current node is not a table element, then this\r
+                is a parse error. */\r
+                // w/e\r
+\r
+                /* Pop elements from this stack until a table element has been\r
+                popped from the stack. */\r
+                while (true) {\r
+                    $current = end($this->stack)->nodeName;\r
+                    array_pop($this->stack);\r
+\r
+                    if ($current === 'table') {\r
+                        break;\r
+                    }\r
+                }\r
+\r
+                /* Reset the insertion mode appropriately. */\r
+                $this->resetInsertionMode();\r
+            }\r
+\r
+            /* An end tag whose tag name is one of: "body", "caption", "col",\r
+            "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG && in_array(\r
+                $token['name'],\r
+                array(\r
+                    'body',\r
+                    'caption',\r
+                    'col',\r
+                    'colgroup',\r
+                    'html',\r
+                    'tbody',\r
+                    'td',\r
+                    'tfoot',\r
+                    'th',\r
+                    'thead',\r
+                    'tr'\r
+                )\r
+            )\r
+        ) {\r
+            // Parse error. Ignore the token.\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Parse error. Process the token as if the insertion mode was "in\r
+            body", with the following exception: */\r
+\r
+            /* If the current node is a table, tbody, tfoot, thead, or tr\r
+            element, then, whenever a node would be inserted into the current\r
+            node, it must instead be inserted into the foster parent element. */\r
+            if (in_array(\r
+                end($this->stack)->nodeName,\r
+                array('table', 'tbody', 'tfoot', 'thead', 'tr')\r
+            )\r
+            ) {\r
+                /* The foster parent element is the parent element of the last\r
+                table element in the stack of open elements, if there is a\r
+                table element and it has such a parent element. If there is no\r
+                table element in the stack of open elements (innerHTML case),\r
+                then the foster parent element is the first element in the\r
+                stack of open elements (the html  element). Otherwise, if there\r
+                is a table element in the stack of open elements, but the last\r
+                table element in the stack of open elements has no parent, or\r
+                its parent node is not an element, then the foster parent\r
+                element is the element before the last table element in the\r
+                stack of open elements. */\r
+                for ($n = count($this->stack) - 1; $n >= 0; $n--) {\r
+                    if ($this->stack[$n]->nodeName === 'table') {\r
+                        $table = $this->stack[$n];\r
+                        break;\r
+                    }\r
+                }\r
+\r
+                if (isset($table) && $table->parentNode !== null) {\r
+                    $this->foster_parent = $table->parentNode;\r
+\r
+                } elseif (!isset($table)) {\r
+                    $this->foster_parent = $this->stack[0];\r
+\r
+                } elseif (isset($table) && ($table->parentNode === null ||\r
+                        $table->parentNode->nodeType !== XML_ELEMENT_NODE)\r
+                ) {\r
+                    $this->foster_parent = $this->stack[$n - 1];\r
+                }\r
+            }\r
+\r
+            $this->inBody($token);\r
+        }\r
+    }\r
+\r
+    private function inCaption($token)\r
+    {\r
+        /* An end tag whose tag name is "caption" */\r
+        if ($token['type'] === HTML5::ENDTAG && $token['name'] === 'caption') {\r
+            /* If the stack of open elements does not have an element in table\r
+            scope with the same tag name as the token, this is a parse error.\r
+            Ignore the token. (innerHTML case) */\r
+            if (!$this->elementInScope($token['name'], true)) {\r
+                // Ignore\r
+\r
+                /* Otherwise: */\r
+            } else {\r
+                /* Generate implied end tags. */\r
+                $this->generateImpliedEndTags();\r
+\r
+                /* Now, if the current node is not a caption element, then this\r
+                is a parse error. */\r
+                // w/e\r
+\r
+                /* Pop elements from this stack until a caption element has\r
+                been popped from the stack. */\r
+                while (true) {\r
+                    $node = end($this->stack)->nodeName;\r
+                    array_pop($this->stack);\r
+\r
+                    if ($node === 'caption') {\r
+                        break;\r
+                    }\r
+                }\r
+\r
+                /* Clear the list of active formatting elements up to the last\r
+                marker. */\r
+                $this->clearTheActiveFormattingElementsUpToTheLastMarker();\r
+\r
+                /* Switch the insertion mode to "in table". */\r
+                $this->mode = self::IN_TABLE;\r
+            }\r
+\r
+            /* A start tag whose tag name is one of: "caption", "col", "colgroup",\r
+            "tbody", "td", "tfoot", "th", "thead", "tr", or an end tag whose tag\r
+            name is "table" */\r
+        } elseif (($token['type'] === HTML5::STARTTAG && in_array(\r
+                    $token['name'],\r
+                    array(\r
+                        'caption',\r
+                        'col',\r
+                        'colgroup',\r
+                        'tbody',\r
+                        'td',\r
+                        'tfoot',\r
+                        'th',\r
+                        'thead',\r
+                        'tr'\r
+                    )\r
+                )) || ($token['type'] === HTML5::ENDTAG &&\r
+                $token['name'] === 'table')\r
+        ) {\r
+            /* Parse error. Act as if an end tag with the tag name "caption"\r
+            had been seen, then, if that token wasn't ignored, reprocess the\r
+            current token. */\r
+            $this->inCaption(\r
+                array(\r
+                    'name' => 'caption',\r
+                    'type' => HTML5::ENDTAG\r
+                )\r
+            );\r
+\r
+            return $this->inTable($token);\r
+\r
+            /* An end tag whose tag name is one of: "body", "col", "colgroup",\r
+            "html", "tbody", "td", "tfoot", "th", "thead", "tr" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG && in_array(\r
+                $token['name'],\r
+                array(\r
+                    'body',\r
+                    'col',\r
+                    'colgroup',\r
+                    'html',\r
+                    'tbody',\r
+                    'tfoot',\r
+                    'th',\r
+                    'thead',\r
+                    'tr'\r
+                )\r
+            )\r
+        ) {\r
+            // Parse error. Ignore the token.\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Process the token as if the insertion mode was "in body". */\r
+            $this->inBody($token);\r
+        }\r
+    }\r
+\r
+    private function inColumnGroup($token)\r
+    {\r
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+        or U+0020 SPACE */\r
+        if ($token['type'] === HTML5::CHARACTR &&\r
+            preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])\r
+        ) {\r
+            /* Append the character to the current node. */\r
+            $text = $this->dom->createTextNode($token['data']);\r
+            end($this->stack)->appendChild($text);\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the current node with the data\r
+            attribute set to the data given in the comment token. */\r
+            $comment = $this->dom->createComment($token['data']);\r
+            end($this->stack)->appendChild($comment);\r
+\r
+            /* A start tag whose tag name is "col" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'col') {\r
+            /* Insert a col element for the token. Immediately pop the current\r
+            node off the stack of open elements. */\r
+            $this->insertElement($token);\r
+            array_pop($this->stack);\r
+\r
+            /* An end tag whose tag name is "colgroup" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG &&\r
+            $token['name'] === 'colgroup'\r
+        ) {\r
+            /* If the current node is the root html element, then this is a\r
+            parse error, ignore the token. (innerHTML case) */\r
+            if (end($this->stack)->nodeName === 'html') {\r
+                // Ignore\r
+\r
+                /* Otherwise, pop the current node (which will be a colgroup\r
+                element) from the stack of open elements. Switch the insertion\r
+                mode to "in table". */\r
+            } else {\r
+                array_pop($this->stack);\r
+                $this->mode = self::IN_TABLE;\r
+            }\r
+\r
+            /* An end tag whose tag name is "col" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'col') {\r
+            /* Parse error. Ignore the token. */\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Act as if an end tag with the tag name "colgroup" had been seen,\r
+            and then, if that token wasn't ignored, reprocess the current token. */\r
+            $this->inColumnGroup(\r
+                array(\r
+                    'name' => 'colgroup',\r
+                    'type' => HTML5::ENDTAG\r
+                )\r
+            );\r
+\r
+            return $this->inTable($token);\r
+        }\r
+    }\r
+\r
+    private function inTableBody($token)\r
+    {\r
+        $clear = array('tbody', 'tfoot', 'thead', 'html');\r
+\r
+        /* A start tag whose tag name is "tr" */\r
+        if ($token['type'] === HTML5::STARTTAG && $token['name'] === 'tr') {\r
+            /* Clear the stack back to a table body context. */\r
+            $this->clearStackToTableContext($clear);\r
+\r
+            /* Insert a tr element for the token, then switch the insertion\r
+            mode to "in row". */\r
+            $this->insertElement($token);\r
+            $this->mode = self::IN_ROW;\r
+\r
+            /* A start tag whose tag name is one of: "th", "td" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG &&\r
+            ($token['name'] === 'th' || $token['name'] === 'td')\r
+        ) {\r
+            /* Parse error. Act as if a start tag with the tag name "tr" had\r
+            been seen, then reprocess the current token. */\r
+            $this->inTableBody(\r
+                array(\r
+                    'name' => 'tr',\r
+                    'type' => HTML5::STARTTAG,\r
+                    'attr' => array()\r
+                )\r
+            );\r
+\r
+            return $this->inRow($token);\r
+\r
+            /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG &&\r
+            in_array($token['name'], array('tbody', 'tfoot', 'thead'))\r
+        ) {\r
+            /* If the stack of open elements does not have an element in table\r
+            scope with the same tag name as the token, this is a parse error.\r
+            Ignore the token. */\r
+            if (!$this->elementInScope($token['name'], true)) {\r
+                // Ignore\r
+\r
+                /* Otherwise: */\r
+            } else {\r
+                /* Clear the stack back to a table body context. */\r
+                $this->clearStackToTableContext($clear);\r
+\r
+                /* Pop the current node from the stack of open elements. Switch\r
+                the insertion mode to "in table". */\r
+                array_pop($this->stack);\r
+                $this->mode = self::IN_TABLE;\r
+            }\r
+\r
+            /* A start tag whose tag name is one of: "caption", "col", "colgroup",\r
+            "tbody", "tfoot", "thead", or an end tag whose tag name is "table" */\r
+        } elseif (($token['type'] === HTML5::STARTTAG && in_array(\r
+                    $token['name'],\r
+                    array('caption', 'col', 'colgroup', 'tbody', 'tfoor', 'thead')\r
+                )) ||\r
+            ($token['type'] === HTML5::STARTTAG && $token['name'] === 'table')\r
+        ) {\r
+            /* If the stack of open elements does not have a tbody, thead, or\r
+            tfoot element in table scope, this is a parse error. Ignore the\r
+            token. (innerHTML case) */\r
+            if (!$this->elementInScope(array('tbody', 'thead', 'tfoot'), true)) {\r
+                // Ignore.\r
+\r
+                /* Otherwise: */\r
+            } else {\r
+                /* Clear the stack back to a table body context. */\r
+                $this->clearStackToTableContext($clear);\r
+\r
+                /* Act as if an end tag with the same tag name as the current\r
+                node ("tbody", "tfoot", or "thead") had been seen, then\r
+                reprocess the current token. */\r
+                $this->inTableBody(\r
+                    array(\r
+                        'name' => end($this->stack)->nodeName,\r
+                        'type' => HTML5::ENDTAG\r
+                    )\r
+                );\r
+\r
+                return $this->mainPhase($token);\r
+            }\r
+\r
+            /* An end tag whose tag name is one of: "body", "caption", "col",\r
+            "colgroup", "html", "td", "th", "tr" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG && in_array(\r
+                $token['name'],\r
+                array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr')\r
+            )\r
+        ) {\r
+            /* Parse error. Ignore the token. */\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Process the token as if the insertion mode was "in table". */\r
+            $this->inTable($token);\r
+        }\r
+    }\r
+\r
+    private function inRow($token)\r
+    {\r
+        $clear = array('tr', 'html');\r
+\r
+        /* A start tag whose tag name is one of: "th", "td" */\r
+        if ($token['type'] === HTML5::STARTTAG &&\r
+            ($token['name'] === 'th' || $token['name'] === 'td')\r
+        ) {\r
+            /* Clear the stack back to a table row context. */\r
+            $this->clearStackToTableContext($clear);\r
+\r
+            /* Insert an HTML element for the token, then switch the insertion\r
+            mode to "in cell". */\r
+            $this->insertElement($token);\r
+            $this->mode = self::IN_CELL;\r
+\r
+            /* Insert a marker at the end of the list of active formatting\r
+            elements. */\r
+            $this->a_formatting[] = self::MARKER;\r
+\r
+            /* An end tag whose tag name is "tr" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'tr') {\r
+            /* If the stack of open elements does not have an element in table\r
+            scope with the same tag name as the token, this is a parse error.\r
+            Ignore the token. (innerHTML case) */\r
+            if (!$this->elementInScope($token['name'], true)) {\r
+                // Ignore.\r
+\r
+                /* Otherwise: */\r
+            } else {\r
+                /* Clear the stack back to a table row context. */\r
+                $this->clearStackToTableContext($clear);\r
+\r
+                /* Pop the current node (which will be a tr element) from the\r
+                stack of open elements. Switch the insertion mode to "in table\r
+                body". */\r
+                array_pop($this->stack);\r
+                $this->mode = self::IN_TBODY;\r
+            }\r
+\r
+            /* A start tag whose tag name is one of: "caption", "col", "colgroup",\r
+            "tbody", "tfoot", "thead", "tr" or an end tag whose tag name is "table" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && in_array(\r
+                $token['name'],\r
+                array('caption', 'col', 'colgroup', 'tbody', 'tfoot', 'thead', 'tr')\r
+            )\r
+        ) {\r
+            /* Act as if an end tag with the tag name "tr" had been seen, then,\r
+            if that token wasn't ignored, reprocess the current token. */\r
+            $this->inRow(\r
+                array(\r
+                    'name' => 'tr',\r
+                    'type' => HTML5::ENDTAG\r
+                )\r
+            );\r
+\r
+            return $this->inCell($token);\r
+\r
+            /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG &&\r
+            in_array($token['name'], array('tbody', 'tfoot', 'thead'))\r
+        ) {\r
+            /* If the stack of open elements does not have an element in table\r
+            scope with the same tag name as the token, this is a parse error.\r
+            Ignore the token. */\r
+            if (!$this->elementInScope($token['name'], true)) {\r
+                // Ignore.\r
+\r
+                /* Otherwise: */\r
+            } else {\r
+                /* Otherwise, act as if an end tag with the tag name "tr" had\r
+                been seen, then reprocess the current token. */\r
+                $this->inRow(\r
+                    array(\r
+                        'name' => 'tr',\r
+                        'type' => HTML5::ENDTAG\r
+                    )\r
+                );\r
+\r
+                return $this->inCell($token);\r
+            }\r
+\r
+            /* An end tag whose tag name is one of: "body", "caption", "col",\r
+            "colgroup", "html", "td", "th" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG && in_array(\r
+                $token['name'],\r
+                array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr')\r
+            )\r
+        ) {\r
+            /* Parse error. Ignore the token. */\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Process the token as if the insertion mode was "in table". */\r
+            $this->inTable($token);\r
+        }\r
+    }\r
+\r
+    private function inCell($token)\r
+    {\r
+        /* An end tag whose tag name is one of: "td", "th" */\r
+        if ($token['type'] === HTML5::ENDTAG &&\r
+            ($token['name'] === 'td' || $token['name'] === 'th')\r
+        ) {\r
+            /* If the stack of open elements does not have an element in table\r
+            scope with the same tag name as that of the token, then this is a\r
+            parse error and the token must be ignored. */\r
+            if (!$this->elementInScope($token['name'], true)) {\r
+                // Ignore.\r
+\r
+                /* Otherwise: */\r
+            } else {\r
+                /* Generate implied end tags, except for elements with the same\r
+                tag name as the token. */\r
+                $this->generateImpliedEndTags(array($token['name']));\r
+\r
+                /* Now, if the current node is not an element with the same tag\r
+                name as the token, then this is a parse error. */\r
+                // k\r
+\r
+                /* Pop elements from this stack until an element with the same\r
+                tag name as the token has been popped from the stack. */\r
+                while (true) {\r
+                    $node = end($this->stack)->nodeName;\r
+                    array_pop($this->stack);\r
+\r
+                    if ($node === $token['name']) {\r
+                        break;\r
+                    }\r
+                }\r
+\r
+                /* Clear the list of active formatting elements up to the last\r
+                marker. */\r
+                $this->clearTheActiveFormattingElementsUpToTheLastMarker();\r
+\r
+                /* Switch the insertion mode to "in row". (The current node\r
+                will be a tr element at this point.) */\r
+                $this->mode = self::IN_ROW;\r
+            }\r
+\r
+            /* A start tag whose tag name is one of: "caption", "col", "colgroup",\r
+            "tbody", "td", "tfoot", "th", "thead", "tr" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && in_array(\r
+                $token['name'],\r
+                array(\r
+                    'caption',\r
+                    'col',\r
+                    'colgroup',\r
+                    'tbody',\r
+                    'td',\r
+                    'tfoot',\r
+                    'th',\r
+                    'thead',\r
+                    'tr'\r
+                )\r
+            )\r
+        ) {\r
+            /* If the stack of open elements does not have a td or th element\r
+            in table scope, then this is a parse error; ignore the token.\r
+            (innerHTML case) */\r
+            if (!$this->elementInScope(array('td', 'th'), true)) {\r
+                // Ignore.\r
+\r
+                /* Otherwise, close the cell (see below) and reprocess the current\r
+                token. */\r
+            } else {\r
+                $this->closeCell();\r
+                return $this->inRow($token);\r
+            }\r
+\r
+            /* A start tag whose tag name is one of: "caption", "col", "colgroup",\r
+            "tbody", "td", "tfoot", "th", "thead", "tr" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG && in_array(\r
+                $token['name'],\r
+                array(\r
+                    'caption',\r
+                    'col',\r
+                    'colgroup',\r
+                    'tbody',\r
+                    'td',\r
+                    'tfoot',\r
+                    'th',\r
+                    'thead',\r
+                    'tr'\r
+                )\r
+            )\r
+        ) {\r
+            /* If the stack of open elements does not have a td or th element\r
+            in table scope, then this is a parse error; ignore the token.\r
+            (innerHTML case) */\r
+            if (!$this->elementInScope(array('td', 'th'), true)) {\r
+                // Ignore.\r
+\r
+                /* Otherwise, close the cell (see below) and reprocess the current\r
+                token. */\r
+            } else {\r
+                $this->closeCell();\r
+                return $this->inRow($token);\r
+            }\r
+\r
+            /* An end tag whose tag name is one of: "body", "caption", "col",\r
+            "colgroup", "html" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG && in_array(\r
+                $token['name'],\r
+                array('body', 'caption', 'col', 'colgroup', 'html')\r
+            )\r
+        ) {\r
+            /* Parse error. Ignore the token. */\r
+\r
+            /* An end tag whose tag name is one of: "table", "tbody", "tfoot",\r
+            "thead", "tr" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG && in_array(\r
+                $token['name'],\r
+                array('table', 'tbody', 'tfoot', 'thead', 'tr')\r
+            )\r
+        ) {\r
+            /* If the stack of open elements does not have an element in table\r
+            scope with the same tag name as that of the token (which can only\r
+            happen for "tbody", "tfoot" and "thead", or, in the innerHTML case),\r
+            then this is a parse error and the token must be ignored. */\r
+            if (!$this->elementInScope($token['name'], true)) {\r
+                // Ignore.\r
+\r
+                /* Otherwise, close the cell (see below) and reprocess the current\r
+                token. */\r
+            } else {\r
+                $this->closeCell();\r
+                return $this->inRow($token);\r
+            }\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Process the token as if the insertion mode was "in body". */\r
+            $this->inBody($token);\r
+        }\r
+    }\r
+\r
+    private function inSelect($token)\r
+    {\r
+        /* Handle the token as follows: */\r
+\r
+        /* A character token */\r
+        if ($token['type'] === HTML5::CHARACTR) {\r
+            /* Append the token's character to the current node. */\r
+            $this->insertText($token['data']);\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the current node with the data\r
+            attribute set to the data given in the comment token. */\r
+            $this->insertComment($token['data']);\r
+\r
+            /* A start tag token whose tag name is "option" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG &&\r
+            $token['name'] === 'option'\r
+        ) {\r
+            /* If the current node is an option element, act as if an end tag\r
+            with the tag name "option" had been seen. */\r
+            if (end($this->stack)->nodeName === 'option') {\r
+                $this->inSelect(\r
+                    array(\r
+                        'name' => 'option',\r
+                        'type' => HTML5::ENDTAG\r
+                    )\r
+                );\r
+            }\r
+\r
+            /* Insert an HTML element for the token. */\r
+            $this->insertElement($token);\r
+\r
+            /* A start tag token whose tag name is "optgroup" */\r
+        } elseif ($token['type'] === HTML5::STARTTAG &&\r
+            $token['name'] === 'optgroup'\r
+        ) {\r
+            /* If the current node is an option element, act as if an end tag\r
+            with the tag name "option" had been seen. */\r
+            if (end($this->stack)->nodeName === 'option') {\r
+                $this->inSelect(\r
+                    array(\r
+                        'name' => 'option',\r
+                        'type' => HTML5::ENDTAG\r
+                    )\r
+                );\r
+            }\r
+\r
+            /* If the current node is an optgroup element, act as if an end tag\r
+            with the tag name "optgroup" had been seen. */\r
+            if (end($this->stack)->nodeName === 'optgroup') {\r
+                $this->inSelect(\r
+                    array(\r
+                        'name' => 'optgroup',\r
+                        'type' => HTML5::ENDTAG\r
+                    )\r
+                );\r
+            }\r
+\r
+            /* Insert an HTML element for the token. */\r
+            $this->insertElement($token);\r
+\r
+            /* An end tag token whose tag name is "optgroup" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG &&\r
+            $token['name'] === 'optgroup'\r
+        ) {\r
+            /* First, if the current node is an option element, and the node\r
+            immediately before it in the stack of open elements is an optgroup\r
+            element, then act as if an end tag with the tag name "option" had\r
+            been seen. */\r
+            $elements_in_stack = count($this->stack);\r
+\r
+            if ($this->stack[$elements_in_stack - 1]->nodeName === 'option' &&\r
+                $this->stack[$elements_in_stack - 2]->nodeName === 'optgroup'\r
+            ) {\r
+                $this->inSelect(\r
+                    array(\r
+                        'name' => 'option',\r
+                        'type' => HTML5::ENDTAG\r
+                    )\r
+                );\r
+            }\r
+\r
+            /* If the current node is an optgroup element, then pop that node\r
+            from the stack of open elements. Otherwise, this is a parse error,\r
+            ignore the token. */\r
+            if ($this->stack[$elements_in_stack - 1] === 'optgroup') {\r
+                array_pop($this->stack);\r
+            }\r
+\r
+            /* An end tag token whose tag name is "option" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG &&\r
+            $token['name'] === 'option'\r
+        ) {\r
+            /* If the current node is an option element, then pop that node\r
+            from the stack of open elements. Otherwise, this is a parse error,\r
+            ignore the token. */\r
+            if (end($this->stack)->nodeName === 'option') {\r
+                array_pop($this->stack);\r
+            }\r
+\r
+            /* An end tag whose tag name is "select" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG &&\r
+            $token['name'] === 'select'\r
+        ) {\r
+            /* If the stack of open elements does not have an element in table\r
+            scope with the same tag name as the token, this is a parse error.\r
+            Ignore the token. (innerHTML case) */\r
+            if (!$this->elementInScope($token['name'], true)) {\r
+                // w/e\r
+\r
+                /* Otherwise: */\r
+            } else {\r
+                /* Pop elements from the stack of open elements until a select\r
+                element has been popped from the stack. */\r
+                while (true) {\r
+                    $current = end($this->stack)->nodeName;\r
+                    array_pop($this->stack);\r
+\r
+                    if ($current === 'select') {\r
+                        break;\r
+                    }\r
+                }\r
+\r
+                /* Reset the insertion mode appropriately. */\r
+                $this->resetInsertionMode();\r
+            }\r
+\r
+            /* A start tag whose tag name is "select" */\r
+        } elseif ($token['name'] === 'select' &&\r
+            $token['type'] === HTML5::STARTTAG\r
+        ) {\r
+            /* Parse error. Act as if the token had been an end tag with the\r
+            tag name "select" instead. */\r
+            $this->inSelect(\r
+                array(\r
+                    'name' => 'select',\r
+                    'type' => HTML5::ENDTAG\r
+                )\r
+            );\r
+\r
+            /* An end tag whose tag name is one of: "caption", "table", "tbody",\r
+            "tfoot", "thead", "tr", "td", "th" */\r
+        } elseif (in_array(\r
+                $token['name'],\r
+                array(\r
+                    'caption',\r
+                    'table',\r
+                    'tbody',\r
+                    'tfoot',\r
+                    'thead',\r
+                    'tr',\r
+                    'td',\r
+                    'th'\r
+                )\r
+            ) && $token['type'] === HTML5::ENDTAG\r
+        ) {\r
+            /* Parse error. */\r
+            // w/e\r
+\r
+            /* If the stack of open elements has an element in table scope with\r
+            the same tag name as that of the token, then act as if an end tag\r
+            with the tag name "select" had been seen, and reprocess the token.\r
+            Otherwise, ignore the token. */\r
+            if ($this->elementInScope($token['name'], true)) {\r
+                $this->inSelect(\r
+                    array(\r
+                        'name' => 'select',\r
+                        'type' => HTML5::ENDTAG\r
+                    )\r
+                );\r
+\r
+                $this->mainPhase($token);\r
+            }\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Parse error. Ignore the token. */\r
+        }\r
+    }\r
+\r
+    private function afterBody($token)\r
+    {\r
+        /* Handle the token as follows: */\r
+\r
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+        or U+0020 SPACE */\r
+        if ($token['type'] === HTML5::CHARACTR &&\r
+            preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])\r
+        ) {\r
+            /* Process the token as it would be processed if the insertion mode\r
+            was "in body". */\r
+            $this->inBody($token);\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the first element in the stack of open\r
+            elements (the html element), with the data attribute set to the\r
+            data given in the comment token. */\r
+            $comment = $this->dom->createComment($token['data']);\r
+            $this->stack[0]->appendChild($comment);\r
+\r
+            /* An end tag with the tag name "html" */\r
+        } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') {\r
+            /* If the parser was originally created in order to handle the\r
+            setting of an element's innerHTML attribute, this is a parse error;\r
+            ignore the token. (The element will be an html element in this\r
+            case.) (innerHTML case) */\r
+\r
+            /* Otherwise, switch to the trailing end phase. */\r
+            $this->phase = self::END_PHASE;\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Parse error. Set the insertion mode to "in body" and reprocess\r
+            the token. */\r
+            $this->mode = self::IN_BODY;\r
+            return $this->inBody($token);\r
+        }\r
+    }\r
+\r
+    private function inFrameset($token)\r
+    {\r
+        /* Handle the token as follows: */\r
+\r
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+        U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */\r
+        if ($token['type'] === HTML5::CHARACTR &&\r
+            preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])\r
+        ) {\r
+            /* Append the character to the current node. */\r
+            $this->insertText($token['data']);\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the current node with the data\r
+            attribute set to the data given in the comment token. */\r
+            $this->insertComment($token['data']);\r
+\r
+            /* A start tag with the tag name "frameset" */\r
+        } elseif ($token['name'] === 'frameset' &&\r
+            $token['type'] === HTML5::STARTTAG\r
+        ) {\r
+            $this->insertElement($token);\r
+\r
+            /* An end tag with the tag name "frameset" */\r
+        } elseif ($token['name'] === 'frameset' &&\r
+            $token['type'] === HTML5::ENDTAG\r
+        ) {\r
+            /* If the current node is the root html element, then this is a\r
+            parse error; ignore the token. (innerHTML case) */\r
+            if (end($this->stack)->nodeName === 'html') {\r
+                // Ignore\r
+\r
+            } else {\r
+                /* Otherwise, pop the current node from the stack of open\r
+                elements. */\r
+                array_pop($this->stack);\r
+\r
+                /* If the parser was not originally created in order to handle\r
+                the setting of an element's innerHTML attribute (innerHTML case),\r
+                and the current node is no longer a frameset element, then change\r
+                the insertion mode to "after frameset". */\r
+                $this->mode = self::AFTR_FRAME;\r
+            }\r
+\r
+            /* A start tag with the tag name "frame" */\r
+        } elseif ($token['name'] === 'frame' &&\r
+            $token['type'] === HTML5::STARTTAG\r
+        ) {\r
+            /* Insert an HTML element for the token. */\r
+            $this->insertElement($token);\r
+\r
+            /* Immediately pop the current node off the stack of open elements. */\r
+            array_pop($this->stack);\r
+\r
+            /* A start tag with the tag name "noframes" */\r
+        } elseif ($token['name'] === 'noframes' &&\r
+            $token['type'] === HTML5::STARTTAG\r
+        ) {\r
+            /* Process the token as if the insertion mode had been "in body". */\r
+            $this->inBody($token);\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Parse error. Ignore the token. */\r
+        }\r
+    }\r
+\r
+    private function afterFrameset($token)\r
+    {\r
+        /* Handle the token as follows: */\r
+\r
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+        U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */\r
+        if ($token['type'] === HTML5::CHARACTR &&\r
+            preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])\r
+        ) {\r
+            /* Append the character to the current node. */\r
+            $this->insertText($token['data']);\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the current node with the data\r
+            attribute set to the data given in the comment token. */\r
+            $this->insertComment($token['data']);\r
+\r
+            /* An end tag with the tag name "html" */\r
+        } elseif ($token['name'] === 'html' &&\r
+            $token['type'] === HTML5::ENDTAG\r
+        ) {\r
+            /* Switch to the trailing end phase. */\r
+            $this->phase = self::END_PHASE;\r
+\r
+            /* A start tag with the tag name "noframes" */\r
+        } elseif ($token['name'] === 'noframes' &&\r
+            $token['type'] === HTML5::STARTTAG\r
+        ) {\r
+            /* Process the token as if the insertion mode had been "in body". */\r
+            $this->inBody($token);\r
+\r
+            /* Anything else */\r
+        } else {\r
+            /* Parse error. Ignore the token. */\r
+        }\r
+    }\r
+\r
+    private function trailingEndPhase($token)\r
+    {\r
+        /* After the main phase, as each token is emitted from the tokenisation\r
+        stage, it must be processed as described in this section. */\r
+\r
+        /* A DOCTYPE token */\r
+        if ($token['type'] === HTML5::DOCTYPE) {\r
+            // Parse error. Ignore the token.\r
+\r
+            /* A comment token */\r
+        } elseif ($token['type'] === HTML5::COMMENT) {\r
+            /* Append a Comment node to the Document object with the data\r
+            attribute set to the data given in the comment token. */\r
+            $comment = $this->dom->createComment($token['data']);\r
+            $this->dom->appendChild($comment);\r
+\r
+            /* A character token that is one of one of U+0009 CHARACTER TABULATION,\r
+            U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+            or U+0020 SPACE */\r
+        } elseif ($token['type'] === HTML5::CHARACTR &&\r
+            preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])\r
+        ) {\r
+            /* Process the token as it would be processed in the main phase. */\r
+            $this->mainPhase($token);\r
+\r
+            /* A character token that is not one of U+0009 CHARACTER TABULATION,\r
+            U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),\r
+            or U+0020 SPACE. Or a start tag token. Or an end tag token. */\r
+        } elseif (($token['type'] === HTML5::CHARACTR &&\r
+                preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) ||\r
+            $token['type'] === HTML5::STARTTAG || $token['type'] === HTML5::ENDTAG\r
+        ) {\r
+            /* Parse error. Switch back to the main phase and reprocess the\r
+            token. */\r
+            $this->phase = self::MAIN_PHASE;\r
+            return $this->mainPhase($token);\r
+\r
+            /* An end-of-file token */\r
+        } elseif ($token['type'] === HTML5::EOF) {\r
+            /* OMG DONE!! */\r
+        }\r
+    }\r
+\r
+    private function insertElement($token, $append = true, $check = false)\r
+    {\r
+        // Proprietary workaround for libxml2's limitations with tag names\r
+        if ($check) {\r
+            // Slightly modified HTML5 tag-name modification,\r
+            // removing anything that's not an ASCII letter, digit, or hyphen\r
+            $token['name'] = preg_replace('/[^a-z0-9-]/i', '', $token['name']);\r
+            // Remove leading hyphens and numbers\r
+            $token['name'] = ltrim($token['name'], '-0..9');\r
+            // In theory, this should ever be needed, but just in case\r
+            if ($token['name'] === '') {\r
+                $token['name'] = 'span';\r
+            } // arbitrary generic choice\r
+        }\r
+\r
+        $el = $this->dom->createElement($token['name']);\r
+\r
+        foreach ($token['attr'] as $attr) {\r
+            if (!$el->hasAttribute($attr['name'])) {\r
+                $el->setAttribute($attr['name'], $attr['value']);\r
+            }\r
+        }\r
+\r
+        $this->appendToRealParent($el);\r
+        $this->stack[] = $el;\r
+\r
+        return $el;\r
+    }\r
+\r
+    private function insertText($data)\r
+    {\r
+        $text = $this->dom->createTextNode($data);\r
+        $this->appendToRealParent($text);\r
+    }\r
+\r
+    private function insertComment($data)\r
+    {\r
+        $comment = $this->dom->createComment($data);\r
+        $this->appendToRealParent($comment);\r
+    }\r
+\r
+    private function appendToRealParent($node)\r
+    {\r
+        if ($this->foster_parent === null) {\r
+            end($this->stack)->appendChild($node);\r
+\r
+        } elseif ($this->foster_parent !== null) {\r
+            /* If the foster parent element is the parent element of the\r
+            last table element in the stack of open elements, then the new\r
+            node must be inserted immediately before the last table element\r
+            in the stack of open elements in the foster parent element;\r
+            otherwise, the new node must be appended to the foster parent\r
+            element. */\r
+            for ($n = count($this->stack) - 1; $n >= 0; $n--) {\r
+                if ($this->stack[$n]->nodeName === 'table' &&\r
+                    $this->stack[$n]->parentNode !== null\r
+                ) {\r
+                    $table = $this->stack[$n];\r
+                    break;\r
+                }\r
+            }\r
+\r
+            if (isset($table) && $this->foster_parent->isSameNode($table->parentNode)) {\r
+                $this->foster_parent->insertBefore($node, $table);\r
+            } else {\r
+                $this->foster_parent->appendChild($node);\r
+            }\r
+\r
+            $this->foster_parent = null;\r
+        }\r
+    }\r
+\r
+    private function elementInScope($el, $table = false)\r
+    {\r
+        if (is_array($el)) {\r
+            foreach ($el as $element) {\r
+                if ($this->elementInScope($element, $table)) {\r
+                    return true;\r
+                }\r
+            }\r
+\r
+            return false;\r
+        }\r
+\r
+        $leng = count($this->stack);\r
+\r
+        for ($n = 0; $n < $leng; $n++) {\r
+            /* 1. Initialise node to be the current node (the bottommost node of\r
+            the stack). */\r
+            $node = $this->stack[$leng - 1 - $n];\r
+\r
+            if ($node->tagName === $el) {\r
+                /* 2. If node is the target node, terminate in a match state. */\r
+                return true;\r
+\r
+            } elseif ($node->tagName === 'table') {\r
+                /* 3. Otherwise, if node is a table element, terminate in a failure\r
+                state. */\r
+                return false;\r
+\r
+            } elseif ($table === true && in_array(\r
+                    $node->tagName,\r
+                    array(\r
+                        'caption',\r
+                        'td',\r
+                        'th',\r
+                        'button',\r
+                        'marquee',\r
+                        'object'\r
+                    )\r
+                )\r
+            ) {\r
+                /* 4. Otherwise, if the algorithm is the "has an element in scope"\r
+                variant (rather than the "has an element in table scope" variant),\r
+                and node is one of the following, terminate in a failure state. */\r
+                return false;\r
+\r
+            } elseif ($node === $node->ownerDocument->documentElement) {\r
+                /* 5. Otherwise, if node is an html element (root element), terminate\r
+                in a failure state. (This can only happen if the node is the topmost\r
+                node of the    stack of open elements, and prevents the next step from\r
+                being invoked if there are no more elements in the stack.) */\r
+                return false;\r
+            }\r
+\r
+            /* Otherwise, set node to the previous entry in the stack of open\r
+            elements and return to step 2. (This will never fail, since the loop\r
+            will always terminate in the previous step if the top of the stack\r
+            is reached.) */\r
+        }\r
+    }\r
+\r
+    private function reconstructActiveFormattingElements()\r
+    {\r
+        /* 1. If there are no entries in the list of active formatting elements,\r
+        then there is nothing to reconstruct; stop this algorithm. */\r
+        $formatting_elements = count($this->a_formatting);\r
+\r
+        if ($formatting_elements === 0) {\r
+            return false;\r
+        }\r
+\r
+        /* 3. Let entry be the last (most recently added) element in the list\r
+        of active formatting elements. */\r
+        $entry = end($this->a_formatting);\r
+\r
+        /* 2. If the last (most recently added) entry in the list of active\r
+        formatting elements is a marker, or if it is an element that is in the\r
+        stack of open elements, then there is nothing to reconstruct; stop this\r
+        algorithm. */\r
+        if ($entry === self::MARKER || in_array($entry, $this->stack, true)) {\r
+            return false;\r
+        }\r
+\r
+        for ($a = $formatting_elements - 1; $a >= 0; true) {\r
+            /* 4. If there are no entries before entry in the list of active\r
+            formatting elements, then jump to step 8. */\r
+            if ($a === 0) {\r
+                $step_seven = false;\r
+                break;\r
+            }\r
+\r
+            /* 5. Let entry be the entry one earlier than entry in the list of\r
+            active formatting elements. */\r
+            $a--;\r
+            $entry = $this->a_formatting[$a];\r
+\r
+            /* 6. If entry is neither a marker nor an element that is also in\r
+            thetack of open elements, go to step 4. */\r
+            if ($entry === self::MARKER || in_array($entry, $this->stack, true)) {\r
+                break;\r
+            }\r
+        }\r
+\r
+        while (true) {\r
+            /* 7. Let entry be the element one later than entry in the list of\r
+            active formatting elements. */\r
+            if (isset($step_seven) && $step_seven === true) {\r
+                $a++;\r
+                $entry = $this->a_formatting[$a];\r
+            }\r
+\r
+            /* 8. Perform a shallow clone of the element entry to obtain clone. */\r
+            $clone = $entry->cloneNode();\r
+\r
+            /* 9. Append clone to the current node and push it onto the stack\r
+            of open elements  so that it is the new current node. */\r
+            end($this->stack)->appendChild($clone);\r
+            $this->stack[] = $clone;\r
+\r
+            /* 10. Replace the entry for entry in the list with an entry for\r
+            clone. */\r
+            $this->a_formatting[$a] = $clone;\r
+\r
+            /* 11. If the entry for clone in the list of active formatting\r
+            elements is not the last entry in the list, return to step 7. */\r
+            if (end($this->a_formatting) !== $clone) {\r
+                $step_seven = true;\r
+            } else {\r
+                break;\r
+            }\r
+        }\r
+    }\r
+\r
+    private function clearTheActiveFormattingElementsUpToTheLastMarker()\r
+    {\r
+        /* When the steps below require the UA to clear the list of active\r
+        formatting elements up to the last marker, the UA must perform the\r
+        following steps: */\r
+\r
+        while (true) {\r
+            /* 1. Let entry be the last (most recently added) entry in the list\r
+            of active formatting elements. */\r
+            $entry = end($this->a_formatting);\r
+\r
+            /* 2. Remove entry from the list of active formatting elements. */\r
+            array_pop($this->a_formatting);\r
+\r
+            /* 3. If entry was a marker, then stop the algorithm at this point.\r
+            The list has been cleared up to the last marker. */\r
+            if ($entry === self::MARKER) {\r
+                break;\r
+            }\r
+        }\r
+    }\r
+\r
+    private function generateImpliedEndTags($exclude = array())\r
+    {\r
+        /* When the steps below require the UA to generate implied end tags,\r
+        then, if the current node is a dd element, a dt element, an li element,\r
+        a p element, a td element, a th  element, or a tr element, the UA must\r
+        act as if an end tag with the respective tag name had been seen and\r
+        then generate implied end tags again. */\r
+        $node = end($this->stack);\r
+        $elements = array_diff(array('dd', 'dt', 'li', 'p', 'td', 'th', 'tr'), $exclude);\r
+\r
+        while (in_array(end($this->stack)->nodeName, $elements)) {\r
+            array_pop($this->stack);\r
+        }\r
+    }\r
+\r
+    private function getElementCategory($node)\r
+    {\r
+        $name = $node->tagName;\r
+        if (in_array($name, $this->special)) {\r
+            return self::SPECIAL;\r
+        } elseif (in_array($name, $this->scoping)) {\r
+            return self::SCOPING;\r
+        } elseif (in_array($name, $this->formatting)) {\r
+            return self::FORMATTING;\r
+        } else {\r
+            return self::PHRASING;\r
+        }\r
+    }\r
+\r
+    private function clearStackToTableContext($elements)\r
+    {\r
+        /* When the steps above require the UA to clear the stack back to a\r
+        table context, it means that the UA must, while the current node is not\r
+        a table element or an html element, pop elements from the stack of open\r
+        elements. If this causes any elements to be popped from the stack, then\r
+        this is a parse error. */\r
+        while (true) {\r
+            $node = end($this->stack)->nodeName;\r
+\r
+            if (in_array($node, $elements)) {\r
+                break;\r
+            } else {\r
+                array_pop($this->stack);\r
+            }\r
+        }\r
+    }\r
+\r
+    private function resetInsertionMode()\r
+    {\r
+        /* 1. Let last be false. */\r
+        $last = false;\r
+        $leng = count($this->stack);\r
+\r
+        for ($n = $leng - 1; $n >= 0; $n--) {\r
+            /* 2. Let node be the last node in the stack of open elements. */\r
+            $node = $this->stack[$n];\r
+\r
+            /* 3. If node is the first node in the stack of open elements, then\r
+            set last to true. If the element whose innerHTML  attribute is being\r
+            set is neither a td  element nor a th element, then set node to the\r
+            element whose innerHTML  attribute is being set. (innerHTML  case) */\r
+            if ($this->stack[0]->isSameNode($node)) {\r
+                $last = true;\r
+            }\r
+\r
+            /* 4. If node is a select element, then switch the insertion mode to\r
+            "in select" and abort these steps. (innerHTML case) */\r
+            if ($node->nodeName === 'select') {\r
+                $this->mode = self::IN_SELECT;\r
+                break;\r
+\r
+                /* 5. If node is a td or th element, then switch the insertion mode\r
+                to "in cell" and abort these steps. */\r
+            } elseif ($node->nodeName === 'td' || $node->nodeName === 'th') {\r
+                $this->mode = self::IN_CELL;\r
+                break;\r
+\r
+                /* 6. If node is a tr element, then switch the insertion mode to\r
+                "in    row" and abort these steps. */\r
+            } elseif ($node->nodeName === 'tr') {\r
+                $this->mode = self::IN_ROW;\r
+                break;\r
+\r
+                /* 7. If node is a tbody, thead, or tfoot element, then switch the\r
+                insertion mode to "in table body" and abort these steps. */\r
+            } elseif (in_array($node->nodeName, array('tbody', 'thead', 'tfoot'))) {\r
+                $this->mode = self::IN_TBODY;\r
+                break;\r
+\r
+                /* 8. If node is a caption element, then switch the insertion mode\r
+                to "in caption" and abort these steps. */\r
+            } elseif ($node->nodeName === 'caption') {\r
+                $this->mode = self::IN_CAPTION;\r
+                break;\r
+\r
+                /* 9. If node is a colgroup element, then switch the insertion mode\r
+                to "in column group" and abort these steps. (innerHTML case) */\r
+            } elseif ($node->nodeName === 'colgroup') {\r
+                $this->mode = self::IN_CGROUP;\r
+                break;\r
+\r
+                /* 10. If node is a table element, then switch the insertion mode\r
+                to "in table" and abort these steps. */\r
+            } elseif ($node->nodeName === 'table') {\r
+                $this->mode = self::IN_TABLE;\r
+                break;\r
+\r
+                /* 11. If node is a head element, then switch the insertion mode\r
+                to "in body" ("in body"! not "in head"!) and abort these steps.\r
+                (innerHTML case) */\r
+            } elseif ($node->nodeName === 'head') {\r
+                $this->mode = self::IN_BODY;\r
+                break;\r
+\r
+                /* 12. If node is a body element, then switch the insertion mode to\r
+                "in body" and abort these steps. */\r
+            } elseif ($node->nodeName === 'body') {\r
+                $this->mode = self::IN_BODY;\r
+                break;\r
+\r
+                /* 13. If node is a frameset element, then switch the insertion\r
+                mode to "in frameset" and abort these steps. (innerHTML case) */\r
+            } elseif ($node->nodeName === 'frameset') {\r
+                $this->mode = self::IN_FRAME;\r
+                break;\r
+\r
+                /* 14. If node is an html element, then: if the head element\r
+                pointer is null, switch the insertion mode to "before head",\r
+                otherwise, switch the insertion mode to "after head". In either\r
+                case, abort these steps. (innerHTML case) */\r
+            } elseif ($node->nodeName === 'html') {\r
+                $this->mode = ($this->head_pointer === null)\r
+                    ? self::BEFOR_HEAD\r
+                    : self::AFTER_HEAD;\r
+\r
+                break;\r
+\r
+                /* 15. If last is true, then set the insertion mode to "in body"\r
+                and    abort these steps. (innerHTML case) */\r
+            } elseif ($last) {\r
+                $this->mode = self::IN_BODY;\r
+                break;\r
+            }\r
+        }\r
+    }\r
+\r
+    private function closeCell()\r
+    {\r
+        /* If the stack of open elements has a td or th element in table scope,\r
+        then act as if an end tag token with that tag name had been seen. */\r
+        foreach (array('td', 'th') as $cell) {\r
+            if ($this->elementInScope($cell, true)) {\r
+                $this->inCell(\r
+                    array(\r
+                        'name' => $cell,\r
+                        'type' => HTML5::ENDTAG\r
+                    )\r
+                );\r
+\r
+                break;\r
+            }\r
+        }\r
+    }\r
+\r
+    public function save()\r
+    {\r
+        return $this->dom;\r
+    }\r
+}\r
diff --git a/code/backend/standalone/HTMLPurifier/Printer.php b/code/backend/standalone/HTMLPurifier/Printer.php
new file mode 100644 (file)
index 0000000..16acd41
--- /dev/null
@@ -0,0 +1,218 @@
+<?php\r
+\r
+// OUT OF DATE, NEEDS UPDATING!\r
+// USE XMLWRITER!\r
+\r
+class HTMLPurifier_Printer\r
+{\r
+\r
+    /**\r
+     * For HTML generation convenience funcs.\r
+     * @type HTMLPurifier_Generator\r
+     */\r
+    protected $generator;\r
+\r
+    /**\r
+     * For easy access.\r
+     * @type HTMLPurifier_Config\r
+     */\r
+    protected $config;\r
+\r
+    /**\r
+     * Initialize $generator.\r
+     */\r
+    public function __construct()\r
+    {\r
+    }\r
+\r
+    /**\r
+     * Give generator necessary configuration if possible\r
+     * @param HTMLPurifier_Config $config\r
+     */\r
+    public function prepareGenerator($config)\r
+    {\r
+        $all = $config->getAll();\r
+        $context = new HTMLPurifier_Context();\r
+        $this->generator = new HTMLPurifier_Generator($config, $context);\r
+    }\r
+\r
+    /**\r
+     * Main function that renders object or aspect of that object\r
+     * @note Parameters vary depending on printer\r
+     */\r
+    // function render() {}\r
+\r
+    /**\r
+     * Returns a start tag\r
+     * @param string $tag Tag name\r
+     * @param array $attr Attribute array\r
+     * @return string\r
+     */\r
+    protected function start($tag, $attr = array())\r
+    {\r
+        return $this->generator->generateFromToken(\r
+            new HTMLPurifier_Token_Start($tag, $attr ? $attr : array())\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Returns an end tag\r
+     * @param string $tag Tag name\r
+     * @return string\r
+     */\r
+    protected function end($tag)\r
+    {\r
+        return $this->generator->generateFromToken(\r
+            new HTMLPurifier_Token_End($tag)\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Prints a complete element with content inside\r
+     * @param string $tag Tag name\r
+     * @param string $contents Element contents\r
+     * @param array $attr Tag attributes\r
+     * @param bool $escape whether or not to escape contents\r
+     * @return string\r
+     */\r
+    protected function element($tag, $contents, $attr = array(), $escape = true)\r
+    {\r
+        return $this->start($tag, $attr) .\r
+            ($escape ? $this->escape($contents) : $contents) .\r
+            $this->end($tag);\r
+    }\r
+\r
+    /**\r
+     * @param string $tag\r
+     * @param array $attr\r
+     * @return string\r
+     */\r
+    protected function elementEmpty($tag, $attr = array())\r
+    {\r
+        return $this->generator->generateFromToken(\r
+            new HTMLPurifier_Token_Empty($tag, $attr)\r
+        );\r
+    }\r
+\r
+    /**\r
+     * @param string $text\r
+     * @return string\r
+     */\r
+    protected function text($text)\r
+    {\r
+        return $this->generator->generateFromToken(\r
+            new HTMLPurifier_Token_Text($text)\r
+        );\r
+    }\r
+\r
+    /**\r
+     * Prints a simple key/value row in a table.\r
+     * @param string $name Key\r
+     * @param mixed $value Value\r
+     * @return string\r
+     */\r
+    protected function row($name, $value)\r
+    {\r
+        if (is_bool($value)) {\r
+            $value = $value ? 'On' : 'Off';\r
+        }\r
+        return\r
+            $this->start('tr') . "\n" .\r
+            $this->element('th', $name) . "\n" .\r
+            $this->element('td', $value) . "\n" .\r
+            $this->end('tr');\r
+    }\r
+\r
+    /**\r
+     * Escapes a string for HTML output.\r
+     * @param string $string String to escape\r
+     * @return string\r
+     */\r
+    protected function escape($string)\r
+    {\r
+        $string = HTMLPurifier_Encoder::cleanUTF8($string);\r
+        $string = htmlspecialchars($string, ENT_COMPAT, 'UTF-8');\r
+        return $string;\r
+    }\r
+\r
+    /**\r
+     * Takes a list of strings and turns them into a single list\r
+     * @param string[] $array List of strings\r
+     * @param bool $polite Bool whether or not to add an end before the last\r
+     * @return string\r
+     */\r
+    protected function listify($array, $polite = false)\r
+    {\r
+        if (empty($array)) {\r
+            return 'None';\r
+        }\r
+        $ret = '';\r
+        $i = count($array);\r
+        foreach ($array as $value) {\r
+            $i--;\r
+            $ret .= $value;\r
+            if ($i > 0 && !($polite && $i == 1)) {\r
+                $ret .= ', ';\r
+            }\r
+            if ($polite && $i == 1) {\r
+                $ret .= 'and ';\r
+            }\r
+        }\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Retrieves the class of an object without prefixes, as well as metadata\r
+     * @param object $obj Object to determine class of\r
+     * @param string $sec_prefix Further prefix to remove\r
+     * @return string\r
+     */\r
+    protected function getClass($obj, $sec_prefix = '')\r
+    {\r
+        static $five = null;\r
+        if ($five === null) {\r
+            $five = version_compare(PHP_VERSION, '5', '>=');\r
+        }\r
+        $prefix = 'HTMLPurifier_' . $sec_prefix;\r
+        if (!$five) {\r
+            $prefix = strtolower($prefix);\r
+        }\r
+        $class = str_replace($prefix, '', get_class($obj));\r
+        $lclass = strtolower($class);\r
+        $class .= '(';\r
+        switch ($lclass) {\r
+            case 'enum':\r
+                $values = array();\r
+                foreach ($obj->valid_values as $value => $bool) {\r
+                    $values[] = $value;\r
+                }\r
+                $class .= implode(', ', $values);\r
+                break;\r
+            case 'css_composite':\r
+                $values = array();\r
+                foreach ($obj->defs as $def) {\r
+                    $values[] = $this->getClass($def, $sec_prefix);\r
+                }\r
+                $class .= implode(', ', $values);\r
+                break;\r
+            case 'css_multiple':\r
+                $class .= $this->getClass($obj->single, $sec_prefix) . ', ';\r
+                $class .= $obj->max;\r
+                break;\r
+            case 'css_denyelementdecorator':\r
+                $class .= $this->getClass($obj->def, $sec_prefix) . ', ';\r
+                $class .= $obj->element;\r
+                break;\r
+            case 'css_importantdecorator':\r
+                $class .= $this->getClass($obj->def, $sec_prefix);\r
+                if ($obj->allow) {\r
+                    $class .= ', !important';\r
+                }\r
+                break;\r
+        }\r
+        $class .= ')';\r
+        return $class;\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/Printer/CSSDefinition.php b/code/backend/standalone/HTMLPurifier/Printer/CSSDefinition.php
new file mode 100644 (file)
index 0000000..afc8c18
--- /dev/null
@@ -0,0 +1,44 @@
+<?php\r
+\r
+class HTMLPurifier_Printer_CSSDefinition extends HTMLPurifier_Printer\r
+{\r
+    /**\r
+     * @type HTMLPurifier_CSSDefinition\r
+     */\r
+    protected $def;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return string\r
+     */\r
+    public function render($config)\r
+    {\r
+        $this->def = $config->getCSSDefinition();\r
+        $ret = '';\r
+\r
+        $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer'));\r
+        $ret .= $this->start('table');\r
+\r
+        $ret .= $this->element('caption', 'Properties ($info)');\r
+\r
+        $ret .= $this->start('thead');\r
+        $ret .= $this->start('tr');\r
+        $ret .= $this->element('th', 'Property', array('class' => 'heavy'));\r
+        $ret .= $this->element('th', 'Definition', array('class' => 'heavy', 'style' => 'width:auto;'));\r
+        $ret .= $this->end('tr');\r
+        $ret .= $this->end('thead');\r
+\r
+        ksort($this->def->info);\r
+        foreach ($this->def->info as $property => $obj) {\r
+            $name = $this->getClass($obj, 'AttrDef_');\r
+            $ret .= $this->row($property, $name);\r
+        }\r
+\r
+        $ret .= $this->end('table');\r
+        $ret .= $this->end('div');\r
+\r
+        return $ret;\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/Printer/ConfigForm.css b/code/backend/standalone/HTMLPurifier/Printer/ConfigForm.css
new file mode 100644 (file)
index 0000000..7af30fc
--- /dev/null
@@ -0,0 +1,10 @@
+\r
+.hp-config {}\r
+\r
+.hp-config tbody th {text-align:right; padding-right:0.5em;}\r
+.hp-config thead, .hp-config .namespace {background:#3C578C; color:#FFF;}\r
+.hp-config .namespace th {text-align:center;}\r
+.hp-config .verbose {display:none;}\r
+.hp-config .controls {text-align:center;}\r
+\r
+/* vim: et sw=4 sts=4 */\r
diff --git a/code/backend/standalone/HTMLPurifier/Printer/ConfigForm.js b/code/backend/standalone/HTMLPurifier/Printer/ConfigForm.js
new file mode 100644 (file)
index 0000000..83e0655
--- /dev/null
@@ -0,0 +1,5 @@
+function toggleWriteability(id_of_patient, checked) {\r
+    document.getElementById(id_of_patient).disabled = checked;\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/Printer/ConfigForm.php b/code/backend/standalone/HTMLPurifier/Printer/ConfigForm.php
new file mode 100644 (file)
index 0000000..8897002
--- /dev/null
@@ -0,0 +1,451 @@
+<?php\r
+\r
+/**\r
+ * @todo Rewrite to use Interchange objects\r
+ */\r
+class HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer\r
+{\r
+\r
+    /**\r
+     * Printers for specific fields.\r
+     * @type HTMLPurifier_Printer[]\r
+     */\r
+    protected $fields = array();\r
+\r
+    /**\r
+     * Documentation URL, can have fragment tagged on end.\r
+     * @type string\r
+     */\r
+    protected $docURL;\r
+\r
+    /**\r
+     * Name of form element to stuff config in.\r
+     * @type string\r
+     */\r
+    protected $name;\r
+\r
+    /**\r
+     * Whether or not to compress directive names, clipping them off\r
+     * after a certain amount of letters. False to disable or integer letters\r
+     * before clipping.\r
+     * @type bool\r
+     */\r
+    protected $compress = false;\r
+\r
+    /**\r
+     * @param string $name Form element name for directives to be stuffed into\r
+     * @param string $doc_url String documentation URL, will have fragment tagged on\r
+     * @param bool $compress Integer max length before compressing a directive name, set to false to turn off\r
+     */\r
+    public function __construct(\r
+        $name,\r
+        $doc_url = null,\r
+        $compress = false\r
+    ) {\r
+        parent::__construct();\r
+        $this->docURL = $doc_url;\r
+        $this->name = $name;\r
+        $this->compress = $compress;\r
+        // initialize sub-printers\r
+        $this->fields[0] = new HTMLPurifier_Printer_ConfigForm_default();\r
+        $this->fields[HTMLPurifier_VarParser::C_BOOL] = new HTMLPurifier_Printer_ConfigForm_bool();\r
+    }\r
+\r
+    /**\r
+     * Sets default column and row size for textareas in sub-printers\r
+     * @param $cols Integer columns of textarea, null to use default\r
+     * @param $rows Integer rows of textarea, null to use default\r
+     */\r
+    public function setTextareaDimensions($cols = null, $rows = null)\r
+    {\r
+        if ($cols) {\r
+            $this->fields['default']->cols = $cols;\r
+        }\r
+        if ($rows) {\r
+            $this->fields['default']->rows = $rows;\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Retrieves styling, in case it is not accessible by webserver\r
+     */\r
+    public static function getCSS()\r
+    {\r
+        return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.css');\r
+    }\r
+\r
+    /**\r
+     * Retrieves JavaScript, in case it is not accessible by webserver\r
+     */\r
+    public static function getJavaScript()\r
+    {\r
+        return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.js');\r
+    }\r
+\r
+    /**\r
+     * Returns HTML output for a configuration form\r
+     * @param HTMLPurifier_Config|array $config Configuration object of current form state, or an array\r
+     *        where [0] has an HTML namespace and [1] is being rendered.\r
+     * @param array|bool $allowed Optional namespace(s) and directives to restrict form to.\r
+     * @param bool $render_controls\r
+     * @return string\r
+     */\r
+    public function render($config, $allowed = true, $render_controls = true)\r
+    {\r
+        if (is_array($config) && isset($config[0])) {\r
+            $gen_config = $config[0];\r
+            $config = $config[1];\r
+        } else {\r
+            $gen_config = $config;\r
+        }\r
+\r
+        $this->config = $config;\r
+        $this->genConfig = $gen_config;\r
+        $this->prepareGenerator($gen_config);\r
+\r
+        $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $config->def);\r
+        $all = array();\r
+        foreach ($allowed as $key) {\r
+            list($ns, $directive) = $key;\r
+            $all[$ns][$directive] = $config->get($ns . '.' . $directive);\r
+        }\r
+\r
+        $ret = '';\r
+        $ret .= $this->start('table', array('class' => 'hp-config'));\r
+        $ret .= $this->start('thead');\r
+        $ret .= $this->start('tr');\r
+        $ret .= $this->element('th', 'Directive', array('class' => 'hp-directive'));\r
+        $ret .= $this->element('th', 'Value', array('class' => 'hp-value'));\r
+        $ret .= $this->end('tr');\r
+        $ret .= $this->end('thead');\r
+        foreach ($all as $ns => $directives) {\r
+            $ret .= $this->renderNamespace($ns, $directives);\r
+        }\r
+        if ($render_controls) {\r
+            $ret .= $this->start('tbody');\r
+            $ret .= $this->start('tr');\r
+            $ret .= $this->start('td', array('colspan' => 2, 'class' => 'controls'));\r
+            $ret .= $this->elementEmpty('input', array('type' => 'submit', 'value' => 'Submit'));\r
+            $ret .= '[<a href="?">Reset</a>]';\r
+            $ret .= $this->end('td');\r
+            $ret .= $this->end('tr');\r
+            $ret .= $this->end('tbody');\r
+        }\r
+        $ret .= $this->end('table');\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Renders a single namespace\r
+     * @param $ns String namespace name\r
+     * @param array $directives array of directives to values\r
+     * @return string\r
+     */\r
+    protected function renderNamespace($ns, $directives)\r
+    {\r
+        $ret = '';\r
+        $ret .= $this->start('tbody', array('class' => 'namespace'));\r
+        $ret .= $this->start('tr');\r
+        $ret .= $this->element('th', $ns, array('colspan' => 2));\r
+        $ret .= $this->end('tr');\r
+        $ret .= $this->end('tbody');\r
+        $ret .= $this->start('tbody');\r
+        foreach ($directives as $directive => $value) {\r
+            $ret .= $this->start('tr');\r
+            $ret .= $this->start('th');\r
+            if ($this->docURL) {\r
+                $url = str_replace('%s', urlencode("$ns.$directive"), $this->docURL);\r
+                $ret .= $this->start('a', array('href' => $url));\r
+            }\r
+            $attr = array('for' => "{$this->name}:$ns.$directive");\r
+\r
+            // crop directive name if it's too long\r
+            if (!$this->compress || (strlen($directive) < $this->compress)) {\r
+                $directive_disp = $directive;\r
+            } else {\r
+                $directive_disp = substr($directive, 0, $this->compress - 2) . '...';\r
+                $attr['title'] = $directive;\r
+            }\r
+\r
+            $ret .= $this->element(\r
+                'label',\r
+                $directive_disp,\r
+                // component printers must create an element with this id\r
+                $attr\r
+            );\r
+            if ($this->docURL) {\r
+                $ret .= $this->end('a');\r
+            }\r
+            $ret .= $this->end('th');\r
+\r
+            $ret .= $this->start('td');\r
+            $def = $this->config->def->info["$ns.$directive"];\r
+            if (is_int($def)) {\r
+                $allow_null = $def < 0;\r
+                $type = abs($def);\r
+            } else {\r
+                $type = $def->type;\r
+                $allow_null = isset($def->allow_null);\r
+            }\r
+            if (!isset($this->fields[$type])) {\r
+                $type = 0;\r
+            } // default\r
+            $type_obj = $this->fields[$type];\r
+            if ($allow_null) {\r
+                $type_obj = new HTMLPurifier_Printer_ConfigForm_NullDecorator($type_obj);\r
+            }\r
+            $ret .= $type_obj->render($ns, $directive, $value, $this->name, array($this->genConfig, $this->config));\r
+            $ret .= $this->end('td');\r
+            $ret .= $this->end('tr');\r
+        }\r
+        $ret .= $this->end('tbody');\r
+        return $ret;\r
+    }\r
+\r
+}\r
+\r
+/**\r
+ * Printer decorator for directives that accept null\r
+ */\r
+class HTMLPurifier_Printer_ConfigForm_NullDecorator extends HTMLPurifier_Printer\r
+{\r
+    /**\r
+     * Printer being decorated\r
+     * @type HTMLPurifier_Printer\r
+     */\r
+    protected $obj;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Printer $obj Printer to decorate\r
+     */\r
+    public function __construct($obj)\r
+    {\r
+        parent::__construct();\r
+        $this->obj = $obj;\r
+    }\r
+\r
+    /**\r
+     * @param string $ns\r
+     * @param string $directive\r
+     * @param string $value\r
+     * @param string $name\r
+     * @param HTMLPurifier_Config|array $config\r
+     * @return string\r
+     */\r
+    public function render($ns, $directive, $value, $name, $config)\r
+    {\r
+        if (is_array($config) && isset($config[0])) {\r
+            $gen_config = $config[0];\r
+            $config = $config[1];\r
+        } else {\r
+            $gen_config = $config;\r
+        }\r
+        $this->prepareGenerator($gen_config);\r
+\r
+        $ret = '';\r
+        $ret .= $this->start('label', array('for' => "$name:Null_$ns.$directive"));\r
+        $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));\r
+        $ret .= $this->text(' Null/Disabled');\r
+        $ret .= $this->end('label');\r
+        $attr = array(\r
+            'type' => 'checkbox',\r
+            'value' => '1',\r
+            'class' => 'null-toggle',\r
+            'name' => "$name" . "[Null_$ns.$directive]",\r
+            'id' => "$name:Null_$ns.$directive",\r
+            'onclick' => "toggleWriteability('$name:$ns.$directive',checked)" // INLINE JAVASCRIPT!!!!\r
+        );\r
+        if ($this->obj instanceof HTMLPurifier_Printer_ConfigForm_bool) {\r
+            // modify inline javascript slightly\r
+            $attr['onclick'] =\r
+                "toggleWriteability('$name:Yes_$ns.$directive',checked);" .\r
+                "toggleWriteability('$name:No_$ns.$directive',checked)";\r
+        }\r
+        if ($value === null) {\r
+            $attr['checked'] = 'checked';\r
+        }\r
+        $ret .= $this->elementEmpty('input', $attr);\r
+        $ret .= $this->text(' or ');\r
+        $ret .= $this->elementEmpty('br');\r
+        $ret .= $this->obj->render($ns, $directive, $value, $name, array($gen_config, $config));\r
+        return $ret;\r
+    }\r
+}\r
+\r
+/**\r
+ * Swiss-army knife configuration form field printer\r
+ */\r
+class HTMLPurifier_Printer_ConfigForm_default extends HTMLPurifier_Printer\r
+{\r
+    /**\r
+     * @type int\r
+     */\r
+    public $cols = 18;\r
+\r
+    /**\r
+     * @type int\r
+     */\r
+    public $rows = 5;\r
+\r
+    /**\r
+     * @param string $ns\r
+     * @param string $directive\r
+     * @param string $value\r
+     * @param string $name\r
+     * @param HTMLPurifier_Config|array $config\r
+     * @return string\r
+     */\r
+    public function render($ns, $directive, $value, $name, $config)\r
+    {\r
+        if (is_array($config) && isset($config[0])) {\r
+            $gen_config = $config[0];\r
+            $config = $config[1];\r
+        } else {\r
+            $gen_config = $config;\r
+        }\r
+        $this->prepareGenerator($gen_config);\r
+        // this should probably be split up a little\r
+        $ret = '';\r
+        $def = $config->def->info["$ns.$directive"];\r
+        if (is_int($def)) {\r
+            $type = abs($def);\r
+        } else {\r
+            $type = $def->type;\r
+        }\r
+        if (is_array($value)) {\r
+            switch ($type) {\r
+                case HTMLPurifier_VarParser::LOOKUP:\r
+                    $array = $value;\r
+                    $value = array();\r
+                    foreach ($array as $val => $b) {\r
+                        $value[] = $val;\r
+                    }\r
+                    //TODO does this need a break?\r
+                case HTMLPurifier_VarParser::ALIST:\r
+                    $value = implode(PHP_EOL, $value);\r
+                    break;\r
+                case HTMLPurifier_VarParser::HASH:\r
+                    $nvalue = '';\r
+                    foreach ($value as $i => $v) {\r
+                        if (is_array($v)) {\r
+                            // HACK\r
+                            $v = implode(";", $v);\r
+                        }\r
+                        $nvalue .= "$i:$v" . PHP_EOL;\r
+                    }\r
+                    $value = $nvalue;\r
+                    break;\r
+                default:\r
+                    $value = '';\r
+            }\r
+        }\r
+        if ($type === HTMLPurifier_VarParser::C_MIXED) {\r
+            return 'Not supported';\r
+            $value = serialize($value);\r
+        }\r
+        $attr = array(\r
+            'name' => "$name" . "[$ns.$directive]",\r
+            'id' => "$name:$ns.$directive"\r
+        );\r
+        if ($value === null) {\r
+            $attr['disabled'] = 'disabled';\r
+        }\r
+        if (isset($def->allowed)) {\r
+            $ret .= $this->start('select', $attr);\r
+            foreach ($def->allowed as $val => $b) {\r
+                $attr = array();\r
+                if ($value == $val) {\r
+                    $attr['selected'] = 'selected';\r
+                }\r
+                $ret .= $this->element('option', $val, $attr);\r
+            }\r
+            $ret .= $this->end('select');\r
+        } elseif ($type === HTMLPurifier_VarParser::TEXT ||\r
+                $type === HTMLPurifier_VarParser::ITEXT ||\r
+                $type === HTMLPurifier_VarParser::ALIST ||\r
+                $type === HTMLPurifier_VarParser::HASH ||\r
+                $type === HTMLPurifier_VarParser::LOOKUP) {\r
+            $attr['cols'] = $this->cols;\r
+            $attr['rows'] = $this->rows;\r
+            $ret .= $this->start('textarea', $attr);\r
+            $ret .= $this->text($value);\r
+            $ret .= $this->end('textarea');\r
+        } else {\r
+            $attr['value'] = $value;\r
+            $attr['type'] = 'text';\r
+            $ret .= $this->elementEmpty('input', $attr);\r
+        }\r
+        return $ret;\r
+    }\r
+}\r
+\r
+/**\r
+ * Bool form field printer\r
+ */\r
+class HTMLPurifier_Printer_ConfigForm_bool extends HTMLPurifier_Printer\r
+{\r
+    /**\r
+     * @param string $ns\r
+     * @param string $directive\r
+     * @param string $value\r
+     * @param string $name\r
+     * @param HTMLPurifier_Config|array $config\r
+     * @return string\r
+     */\r
+    public function render($ns, $directive, $value, $name, $config)\r
+    {\r
+        if (is_array($config) && isset($config[0])) {\r
+            $gen_config = $config[0];\r
+            $config = $config[1];\r
+        } else {\r
+            $gen_config = $config;\r
+        }\r
+        $this->prepareGenerator($gen_config);\r
+        $ret = '';\r
+        $ret .= $this->start('div', array('id' => "$name:$ns.$directive"));\r
+\r
+        $ret .= $this->start('label', array('for' => "$name:Yes_$ns.$directive"));\r
+        $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));\r
+        $ret .= $this->text(' Yes');\r
+        $ret .= $this->end('label');\r
+\r
+        $attr = array(\r
+            'type' => 'radio',\r
+            'name' => "$name" . "[$ns.$directive]",\r
+            'id' => "$name:Yes_$ns.$directive",\r
+            'value' => '1'\r
+        );\r
+        if ($value === true) {\r
+            $attr['checked'] = 'checked';\r
+        }\r
+        if ($value === null) {\r
+            $attr['disabled'] = 'disabled';\r
+        }\r
+        $ret .= $this->elementEmpty('input', $attr);\r
+\r
+        $ret .= $this->start('label', array('for' => "$name:No_$ns.$directive"));\r
+        $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));\r
+        $ret .= $this->text(' No');\r
+        $ret .= $this->end('label');\r
+\r
+        $attr = array(\r
+            'type' => 'radio',\r
+            'name' => "$name" . "[$ns.$directive]",\r
+            'id' => "$name:No_$ns.$directive",\r
+            'value' => '0'\r
+        );\r
+        if ($value === false) {\r
+            $attr['checked'] = 'checked';\r
+        }\r
+        if ($value === null) {\r
+            $attr['disabled'] = 'disabled';\r
+        }\r
+        $ret .= $this->elementEmpty('input', $attr);\r
+\r
+        $ret .= $this->end('div');\r
+\r
+        return $ret;\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/backend/standalone/HTMLPurifier/Printer/HTMLDefinition.php b/code/backend/standalone/HTMLPurifier/Printer/HTMLDefinition.php
new file mode 100644 (file)
index 0000000..679d19b
--- /dev/null
@@ -0,0 +1,324 @@
+<?php\r
+\r
+class HTMLPurifier_Printer_HTMLDefinition extends HTMLPurifier_Printer\r
+{\r
+\r
+    /**\r
+     * @type HTMLPurifier_HTMLDefinition, for easy access\r
+     */\r
+    protected $def;\r
+\r
+    /**\r
+     * @param HTMLPurifier_Config $config\r
+     * @return string\r
+     */\r
+    public function render($config)\r
+    {\r
+        $ret = '';\r
+        $this->config =& $config;\r
+\r
+        $this->def = $config->getHTMLDefinition();\r
+\r
+        $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer'));\r
+\r
+        $ret .= $this->renderDoctype();\r
+        $ret .= $this->renderEnvironment();\r
+        $ret .= $this->renderContentSets();\r
+        $ret .= $this->renderInfo();\r
+\r
+        $ret .= $this->end('div');\r
+\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Renders the Doctype table\r
+     * @return string\r
+     */\r
+    protected function renderDoctype()\r
+    {\r
+        $doctype = $this->def->doctype;\r
+        $ret = '';\r
+        $ret .= $this->start('table');\r
+        $ret .= $this->element('caption', 'Doctype');\r
+        $ret .= $this->row('Name', $doctype->name);\r
+        $ret .= $this->row('XML', $doctype->xml ? 'Yes' : 'No');\r
+        $ret .= $this->row('Default Modules', implode($doctype->modules, ', '));\r
+        $ret .= $this->row('Default Tidy Modules', implode($doctype->tidyModules, ', '));\r
+        $ret .= $this->end('table');\r
+        return $ret;\r
+    }\r
+\r
+\r
+    /**\r
+     * Renders environment table, which is miscellaneous info\r
+     * @return string\r
+     */\r
+    protected function renderEnvironment()\r
+    {\r
+        $def = $this->def;\r
+\r
+        $ret = '';\r
+\r
+        $ret .= $this->start('table');\r
+        $ret .= $this->element('caption', 'Environment');\r
+\r
+        $ret .= $this->row('Parent of fragment', $def->info_parent);\r
+        $ret .= $this->renderChildren($def->info_parent_def->child);\r
+        $ret .= $this->row('Block wrap name', $def->info_block_wrapper);\r
+\r
+        $ret .= $this->start('tr');\r
+        $ret .= $this->element('th', 'Global attributes');\r
+        $ret .= $this->element('td', $this->listifyAttr($def->info_global_attr), null, 0);\r
+        $ret .= $this->end('tr');\r
+\r
+        $ret .= $this->start('tr');\r
+        $ret .= $this->element('th', 'Tag transforms');\r
+        $list = array();\r
+        foreach ($def->info_tag_transform as $old => $new) {\r
+            $new = $this->getClass($new, 'TagTransform_');\r
+            $list[] = "<$old> with $new";\r
+        }\r
+        $ret .= $this->element('td', $this->listify($list));\r
+        $ret .= $this->end('tr');\r
+\r
+        $ret .= $this->start('tr');\r
+        $ret .= $this->element('th', 'Pre-AttrTransform');\r
+        $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_pre));\r
+        $ret .= $this->end('tr');\r
+\r
+        $ret .= $this->start('tr');\r
+        $ret .= $this->element('th', 'Post-AttrTransform');\r
+        $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_post));\r
+        $ret .= $this->end('tr');\r
+\r
+        $ret .= $this->end('table');\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Renders the Content Sets table\r
+     * @return string\r
+     */\r
+    protected function renderContentSets()\r
+    {\r
+        $ret = '';\r
+        $ret .= $this->start('table');\r
+        $ret .= $this->element('caption', 'Content Sets');\r
+        foreach ($this->def->info_content_sets as $name => $lookup) {\r
+            $ret .= $this->heavyHeader($name);\r
+            $ret .= $this->start('tr');\r
+            $ret .= $this->element('td', $this->listifyTagLookup($lookup));\r
+            $ret .= $this->end('tr');\r
+        }\r
+        $ret .= $this->end('table');\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Renders the Elements ($info) table\r
+     * @return string\r
+     */\r
+    protected function renderInfo()\r
+    {\r
+        $ret = '';\r
+        $ret .= $this->start('table');\r
+        $ret .= $this->element('caption', 'Elements ($info)');\r
+        ksort($this->def->info);\r
+        $ret .= $this->heavyHeader('Allowed tags', 2);\r
+        $ret .= $this->start('tr');\r
+        $ret .= $this->element('td', $this->listifyTagLookup($this->def->info), array('colspan' => 2));\r
+        $ret .= $this->end('tr');\r
+        foreach ($this->def->info as $name => $def) {\r
+            $ret .= $this->start('tr');\r
+            $ret .= $this->element('th', "<$name>", array('class' => 'heavy', 'colspan' => 2));\r
+            $ret .= $this->end('tr');\r
+            $ret .= $this->start('tr');\r
+            $ret .= $this->element('th', 'Inline content');\r
+            $ret .= $this->element('td', $def->descendants_are_inline ? 'Yes' : 'No');\r
+            $ret .= $this->end('tr');\r
+            if (!empty($def->excludes)) {\r
+                $ret .= $this->start('tr');\r
+                $ret .= $this->element('th', 'Excludes');\r
+                $ret .= $this->element('td', $this->listifyTagLookup($def->excludes));\r
+                $ret .= $this->end('tr');\r
+            }\r
+            if (!empty($def->attr_transform_pre)) {\r
+                $ret .= $this->start('tr');\r
+                $ret .= $this->element('th', 'Pre-AttrTransform');\r
+                $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_pre));\r
+                $ret .= $this->end('tr');\r
+            }\r
+            if (!empty($def->attr_transform_post)) {\r
+                $ret .= $this->start('tr');\r
+                $ret .= $this->element('th', 'Post-AttrTransform');\r
+                $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_post));\r
+                $ret .= $this->end('tr');\r
+            }\r
+            if (!empty($def->auto_close)) {\r
+                $ret .= $this->start('tr');\r
+                $ret .= $this->element('th', 'Auto closed by');\r
+                $ret .= $this->element('td', $this->listifyTagLookup($def->auto_close));\r
+                $ret .= $this->end('tr');\r
+            }\r
+            $ret .= $this->start('tr');\r
+            $ret .= $this->element('th', 'Allowed attributes');\r
+            $ret .= $this->element('td', $this->listifyAttr($def->attr), array(), 0);\r
+            $ret .= $this->end('tr');\r
+\r
+            if (!empty($def->required_attr)) {\r
+                $ret .= $this->row('Required attributes', $this->listify($def->required_attr));\r
+            }\r
+\r
+            $ret .= $this->renderChildren($def->child);\r
+        }\r
+        $ret .= $this->end('table');\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Renders a row describing the allowed children of an element\r
+     * @param HTMLPurifier_ChildDef $def HTMLPurifier_ChildDef of pertinent element\r
+     * @return string\r
+     */\r
+    protected function renderChildren($def)\r
+    {\r
+        $context = new HTMLPurifier_Context();\r
+        $ret = '';\r
+        $ret .= $this->start('tr');\r
+        $elements = array();\r
+        $attr = array();\r
+        if (isset($def->elements)) {\r
+            if ($def->type == 'strictblockquote') {\r
+                $def->validateChildren(array(), $this->config, $context);\r
+            }\r
+            $elements = $def->elements;\r
+        }\r
+        if ($def->type == 'chameleon') {\r
+            $attr['rowspan'] = 2;\r
+        } elseif ($def->type == 'empty') {\r
+            $elements = array();\r
+        } elseif ($def->type == 'table') {\r
+            $elements = array_flip(\r
+                array(\r
+                    'col',\r
+                    'caption',\r
+                    'colgroup',\r
+                    'thead',\r
+                    'tfoot',\r
+                    'tbody',\r
+                    'tr'\r
+                )\r
+            );\r
+        }\r
+        $ret .= $this->element('th', 'Allowed children', $attr);\r
+\r
+        if ($def->type == 'chameleon') {\r
+\r
+            $ret .= $this->element(\r
+                'td',\r
+                '<em>Block</em>: ' .\r
+                $this->escape($this->listifyTagLookup($def->block->elements)),\r
+                null,\r
+                0\r
+            );\r
+            $ret .= $this->end('tr');\r
+            $ret .= $this->start('tr');\r
+            $ret .= $this->element(\r
+                'td',\r
+                '<em>Inline</em>: ' .\r
+                $this->escape($this->listifyTagLookup($def->inline->elements)),\r
+                null,\r
+                0\r
+            );\r
+\r
+        } elseif ($def->type == 'custom') {\r
+\r
+            $ret .= $this->element(\r
+                'td',\r
+                '<em>' . ucfirst($def->type) . '</em>: ' .\r
+                $def->dtd_regex\r
+            );\r
+\r
+        } else {\r
+            $ret .= $this->element(\r
+                'td',\r
+                '<em>' . ucfirst($def->type) . '</em>: ' .\r
+                $this->escape($this->listifyTagLookup($elements)),\r
+                null,\r
+                0\r
+            );\r
+        }\r
+        $ret .= $this->end('tr');\r
+        return $ret;\r
+    }\r
+\r
+    /**\r
+     * Listifies a tag lookup table.\r
+     * @param array $array Tag lookup array in form of array('tagname' => true)\r
+     * @return string\r
+     */\r
+    protected function listifyTagLookup($array)\r
+    {\r
+        ksort($array);\r
+        $list = array();\r
+        foreach ($array as $name => $discard) {\r
+            if ($name !== '#PCDATA' && !isset($this->def->info[$name])) {\r
+                continue;\r
+            }\r
+            $list[] = $name;\r
+        }\r
+        return $this->listify($list);\r
+    }\r
+\r
+    /**\r
+     * Listifies a list of objects by retrieving class names and internal state\r
+     * @param array $array List of objects\r
+     * @return string\r
+     * @todo Also add information about internal state\r
+     */\r
+    protected function listifyObjectList($array)\r
+    {\r
+        ksort($array);\r
+        $list = array();\r
+        foreach ($array as $obj) {\r
+            $list[] = $this->getClass($obj, 'AttrTransform_');\r
+        }\r
+        return $this->listify($list);\r
+    }\r
+\r
+    /**\r
+     * Listifies a hash of attributes to AttrDef classes\r
+     * @param array $array Array hash in form of array('attrname' => HTMLPurifier_AttrDef)\r
+     * @return string\r
+     */\r
+    protected function listifyAttr($array)\r
+    {\r
+        ksort($array);\r
+        $list = array();\r
+        foreach ($array as $name => $obj) {\r
+            if ($obj === false) {\r
+                continue;\r
+            }\r
+            $list[] = "$name&nbsp;=&nbsp;<i>" . $this->getClass($obj, 'AttrDef_') . '</i>';\r
+        }\r
+        return $this->listify($list);\r
+    }\r
+\r
+    /**\r
+     * Creates a heavy header row\r
+     * @param string $text\r
+     * @param int $num\r
+     * @return string\r
+     */\r
+    protected function heavyHeader($text, $num = 1)\r
+    {\r
+        $ret = '';\r
+        $ret .= $this->start('tr');\r
+        $ret .= $this->element('th', $text, array('colspan' => $num, 'class' => 'heavy'));\r
+        $ret .= $this->end('tr');\r
+        return $ret;\r
+    }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r
diff --git a/code/clientlib/3.00/plan.php b/code/clientlib/3.00/plan.php
new file mode 100644 (file)
index 0000000..433eb54
--- /dev/null
@@ -0,0 +1,57 @@
+
+<?php
+
+
+/* SEND CATEGORY VERBS FOR PLANWORLD CLIENT LAYER. */
+
+function planGet($arrayRestInputs){
+  if((file_exists($arrayRestInputs['enginebasedir'] . '/lib/User.php')) && (file_exists($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php')) ){
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/User.php');
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php');
+    $objectToken = new NodeToken ();
+    if(($objectToken->retrieveToken($arrayRestInputs['token'])) && (count($arrayRestInputs['arguments']) > 0)){
+      $thisUserUid = $objectToken->uid;
+      $thisUserObject = new User($thisUserUid);
+      $arguments = $arrayRestInputs['arguments'];
+      $userPlanToGet = $arguments[0];
+      if(Planworld::isUser($userPlanToGet)){
+        $userPlanToGetObject = new User($userPlanToGet);
+        return $userPlanToGetObject->getPlanSimple($thisUserObject);
+      }
+      else{
+        return '';
+      }
+    }
+    else{
+      return '';
+    }
+  }
+  else{
+    return '';
+  }
+}
+
+
+function planPost($arrayRestInputs){
+  $boolSuccess = false;
+  if((file_exists($arrayRestInputs['enginebasedir'] . '/lib/User.php')) && (file_exists($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php')) && (file_exists($arrayRestInputs['enginebasedir'] . '/backend/HTMLPurifier.standalone.php')) ){
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/User.php');
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php');
+    require_once($arrayRestInputs['enginebasedir'] . '/backend/HTMLPurifier.standalone.php');
+    $objectToken = new NodeToken ();
+    if(($objectToken->retrieveToken($arrayRestInputs['token'])) && (!(empty($arrayRestInputs['post'])))){
+      $thisUserUid = $objectToken->uid;
+      $thisUserObject = new User($thisUserUid);
+      $arguments = $arrayRestInputs['arguments'];
+      $rawPlanNew = $arrayRestInputs['post'];
+      $hpConfig = HTMLPurifier_Config::createDefault();
+      $hp = new HTMLPurifier($hpConfig);
+      $finalPlanNew = $hp->purify($rawPlanNew);
+      $boolSuccess = $thisUserObject->setPlanSimple($finalPlanNew);
+    }
+  }
+  return $boolSuccess;
+}
+
+
+?>
\ No newline at end of file
diff --git a/code/clientlib/3.00/watchlist.php b/code/clientlib/3.00/watchlist.php
new file mode 100644 (file)
index 0000000..e752f0f
--- /dev/null
@@ -0,0 +1,143 @@
+<?php
+
+
+/* WATCHLIST CATEGORY VERBS FOR PLANWORLD CLIENT LAYER. */
+
+
+
+function watchlistGet($arrayRestInputs){
+  if((file_exists($arrayRestInputs['enginebasedir'] . '/lib/Planwatch.php')) && (file_exists($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php')) ){
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/Planwatch.php');
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php');
+    $objectToken = new NodeToken ();
+    if($objectToken->retrieveToken($arrayRestInputs['token'])){
+      $thisUserUid = $objectToken->uid;
+      $thisUserObject = new User($thisUserUid);
+      $thisPlanwatch = new Planwatch($thisUserObject);
+      return $thisPlanwatch->getInteroperableWatchlist();
+    }
+    else{
+      return '';
+    }
+  }
+  else{
+    return '';
+  }
+}
+
+
+function watchlistgroupGet($arrayRestInputs){
+  if((file_exists($arrayRestInputs['enginebasedir'] . '/lib/Planwatch.php')) && (file_exists($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php')) ){
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/Planwatch.php');
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php');
+    $objectToken = new NodeToken ();
+    if($objectToken->retrieveToken($arrayRestInputs['token'])){
+      $thisUserUid = $objectToken->uid;
+      $thisUserObject = new User($thisUserUid);
+      $thisPlanwatch = new Planwatch($thisUserObject);
+      return $thisPlanwatch->getInteroperableWatchlistGroups();
+    }
+    else{
+      return '';
+    }
+  }
+  else{
+    return '';
+  }
+}
+
+
+function groupcreatePost($arrayRestInputs){
+  $boolReturn = false;
+  if((file_exists($arrayRestInputs['enginebasedir'] . '/lib/Planwatch.php')) && (file_exists($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php')) ){
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/Planwatch.php');
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php');
+    $objectToken = new NodeToken ();
+    if(($objectToken->retrieveToken($arrayRestInputs['token'])) && (count($arrayRestInputs['arguments']) > 0)){
+      $arguments = $arrayRestInputs['arguments'];
+      $stringNewGroupName = $arguments[0];
+      if(Planworld::isValidWatchlistGroupName($stringNewGroupName)){
+        $thisUserUid = $objectToken->uid;
+        $thisUserObject = new User($thisUserUid);
+        $thisPlanwatch = new Planwatch($thisUserObject);
+        $boolNameDoesNotAlreadyExist = true;
+        $arrayOfCurrentGroupNames = $thisPlanwatch->getGroupNames();
+        foreach($arrayOfCurrentGroupNames as $currentGroupName){
+          if(strcasecmp($currentGroupName, $stringNewGroupName) == 0){
+            $boolNameDoesNotAlreadyExist = false;
+          }
+        }
+        if($boolNameDoesNotAlreadyExists){
+          $boolReturn = $thisPlanwatch->addGroup($stringNewGroupName);
+          $thisPlanwatch->save();
+        }
+      }
+    }
+  }
+  return $boolReturn;
+}
+
+
+// WOAHWOAHWOAH I MAY BE DOING POSTING WRONG HERE. CHECK WHERE THE POST DATA IS COMING FROM. THESE MIGHT BE GETS OR NOT NOT SURE
+
+function groupmoveuserPost($arrayRestInputs){
+  $boolReturn = false;
+  if((file_exists($arrayRestInputs['enginebasedir'] . '/lib/Planwatch.php')) && (file_exists($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php')) ){
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/Planwatch.php');
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php');
+    $objectToken = new NodeToken ();
+    if(($objectToken->retrieveToken($arrayRestInputs['token'])) && (count($arrayRestInputs['arguments']) > 0)){
+      $arguments = $arrayRestInputs['arguments'];
+      $stringUserToMove = $arguments[0];
+      $stringGroupToMoveTo = $arguments[1];
+      if((Planworld::isValidWatchlistGroupName($stringGroupToMoveTo)) && (Planworld::isUser($stringUserToMove))){
+        $thisUserUid = $objectToken->uid;
+        $thisUserObject = new User($thisUserUid);
+        $thisPlanwatch = new Planwatch($thisUserObject);
+        $boolGroupExists = false;
+        $boolUserInPlanwatch = $thisPlanwatch->inPlanwatch($stringUserToMove);
+        $matrixGroups = $thisPlanwatch->getGroups();
+        $intGidForGroupMove = -1;
+        foreach($matrixGroups as $nameGroup => $rowGroup){
+          if(strcasecmp($nameGroup, $stringGroupToMoveTo) == 0){
+            $boolGroupExists = true;
+            $intGidForGroupMove = $rowGroup['gid'];
+          }
+        }
+        if($boolGroupExists && $boolUserInPlanwatch){
+          $boolReturn = $thisPlanwatch->move($stringUserToMove, $intGidForGroupMove);
+          $thisPlanwatch->save();
+        }
+      }
+    }
+  }
+  return $boolReturn;
+}
+
+
+function addPost($arrayRestInputs){
+  $boolReturn = false;
+  if((file_exists($arrayRestInputs['enginebasedir'] . '/lib/Planwatch.php')) && (file_exists($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php')) ){
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/Planwatch.php');
+    require_once($arrayRestInputs['enginebasedir'] . '/lib/NodeToken.php');
+    $objectToken = new NodeToken ();
+    if(($objectToken->retrieveToken($arrayRestInputs['token'])) && (count($arrayRestInputs['arguments']) > 0)){
+      $arguments = $arrayRestInputs['arguments'];
+      $stringUserToAdd = $arguments[0];
+      if((Planworld::isUser($stringUserToAdd))){
+        $thisUserUid = $objectToken->uid;
+        $thisUserObject = new User($thisUserUid);
+        $thisPlanwatch = new Planwatch($thisUserObject);
+        $boolUserInPlanwatch = $thisPlanwatch->inPlanwatch($stringUserToAdd);
+        if(!$boolUserInPlanwatch){
+          $boolReturn = $thisPlanwatch->add($stringUserToAdd);
+          $thisPlanwatch->save();
+        }
+      }
+    }
+  }
+  return $boolReturn;
+}
+
+
+?>
\ No newline at end of file
diff --git a/code/lib/Online.php b/code/lib/Online.php
new file mode 100644 (file)
index 0000000..593f2a4
--- /dev/null
@@ -0,0 +1,106 @@
+<?php
+/**
+ * $Id: Online.php,v 1.6.2.2 2003/11/02 16:12:35 seth Exp $
+ * Utility class for determining online users.
+ */
+
+require_once($_base . 'lib/User.php');
+require_once($_base . 'lib/Planworld.php');
+date_default_timezone_set(PW_TIMEZONE);
+
+class Online {
+  /**
+   * void Online::clearIdle ()
+   * Removes users who have been idle too long
+   */
+  function clearIdle () {
+    $dbh = Planworld::_connect();
+
+    $query = "DELETE FROM online WHERE last_access < " . (mktime() - PW_IDLE_TIMEOUT);
+    $dbh->query($query);
+  }
+
+  /**
+   * void Online::updateUser (&$user, &$target)
+   * Update's $user's status to $target
+   */
+  function updateUser (&$user, &$target) {
+    $dbh = Planworld::_connect();
+
+    $query = "UPDATE online SET last_access=" . mktime() . ", what='";
+    if (is_object($target)) {
+      $query .= $target->getUsername();
+    } else {
+      $query .= addslashes($target);
+    }
+    $query .= "' WHERE uid=" . $user->getUserID();
+
+    $result = $dbh->query($query);
+    if (isset($result) && !DB::isError($result)) {
+      if ($dbh->affectedRows() < 1) {
+       return Online::addUser($user, $target);
+      } else {
+       return true;
+      }
+    } else {
+      return PLANWORLD_ERROR;
+    }
+  }
+
+  /**
+   * void Online::addUser($user, $target)
+   * Adds $user to the list of online users (with status $target)
+   */
+  function addUser (&$user, $target) {
+    $dbh = Planworld::_connect();
+
+    $query = "INSERT INTO online (uid, login, last_access, what) VALUES (" . $user->getUserID() . ", " . mktime() . ", " . mktime() . ", '";
+
+    if (is_object($target)) {
+      $query .= $target->getUserName();
+    } else {
+      $query .= $target;
+    }
+
+    $query .= "')";
+
+    $dbh->query($query);
+  }
+
+  /**
+   * void Online::removeUser ($user)
+   * Removes $user from the list of online users
+   */
+  function removeUser (&$user) {
+    $dbh = Planworld::_connect();
+
+    $query = "DELETE FROM online WHERE uid=" . $user->getUserID();
+    $dbh->query($query);
+  }
+
+  /**
+   * array Online::getOnlineUsers ()
+   * Returns a list of all users who are currently online.
+   */
+  function getOnlineUsers () {
+    $dbh = Planworld::_connect();
+
+    $query = "SELECT users.username, online.last_access, online.login, online.what FROM users, online WHERE users.id = online.uid ORDER BY last_access DESC";
+
+    /* execute the query */
+    $result = $dbh->query($query);
+    if (isset($result) && !DB::isError($result)) {
+      $return = array();
+      while ($row = $result->fetchRow()) {
+       $return[] = array('name' => $row['username'],
+                         'lastAccess' => (int) $row['last_access'],
+                         'login' => (int) $row['login'],
+                         'what' => $row['what']);
+      }
+      return $return;
+    } else {
+      return PLANWORLD_ERROR;
+    }
+  }
+}
+?>
\ No newline at end of file
diff --git a/code/lib/Planwatch.php b/code/lib/Planwatch.php
new file mode 100644 (file)
index 0000000..f3f97df
--- /dev/null
@@ -0,0 +1,413 @@
+<?php
+/* $Id: Planwatch.php,v 1.9.2.7 2003/11/02 16:12:35 seth Exp $ */
+
+/* Basic Setup */
+$_base = dirname(__FILE__) . '/../';
+require_once($_base . 'lib/Planworld.php');
+require_once($_base . 'lib/Snoop.php');
+date_default_timezone_set(PW_TIMEZONE);
+
+/**
+ * Planwatch
+ */
+class Planwatch {
+  var $changed;
+  var $dbh;
+  var $planwatch;
+  var $groupData;
+  var $groups;
+  var $numNew = 0;
+  var $user;
+
+  /* Creates a planwatch object for $user
+   */
+  function __construct (&$user) {
+    $this->user = $user;
+    $this->dbh = Planworld::_connect();
+    if(!$this->dbh){
+      throw new PDOException('Database connection not initialized.');
+    }
+    if ($this->user->isUser()) {
+      $this->load();
+    }
+  }
+
+
+  /* Loads planwatch data into this object.
+   * Previous versions used a sort variable as an argument. This has now been removed because it is up to the client to sort. */
+  function load() {
+    /* One major change from the original code is that we do all the DB calls at once to clear any locks and reduce overall latency. */
+    try{
+      $currentUid = $this->user->getUserID();
+      $query1 = $this->dbh->prepare('SELECT u.username, u.id, p.last_view, u.last_update, g.name AS name, g.gid AS gid, g.uid AS owner, m.seen AS hasmessage FROM (pw_groups AS g, planwatch AS p, users AS u) LEFT JOIN message AS m ON (m.uid=p.w_uid AND m.to_uid=p.uid) WHERE p.uid=:uid AND p.w_uid=u.id AND g.gid=p.gid');
+      $query2 = $this->dbh->prepare('SELECT u.username, u.id, u.last_update FROM users AS u INNER JOIN message ON u.id=message.uid LEFT JOIN online ON message.uid=online.uid WHERE message.to_uid=:uid AND message.seen=0');
+      $query3 = $this->dbh->prepare('SELECT username, id, last_update, sent, seen FROM send, users WHERE send.uid=users.id AND to_uid=:uid AND seen=0 ORDER BY username');
+      $queryArray = array('uid' => $currentUid);
+      $query1->execute($queryArray);
+      $result1=$query1->fetchAll();
+      $query2->execute($queryArray);
+      $result2=$query2->fetchAll();
+      $query3->execute($queryArray);
+      $result3=$query3->fetchAll();
+
+      if (!($result1)){
+        return PLANWORLD_ERROR;
+      }
+      else {
+        $this->planwatch = array();
+        $this->groupData = array();
+        $this->groupData['Send'] = array();
+        $this->groups = array();
+        foreach($result1 as $row) {
+          $watchuser = addslashes($row['username']);
+          $group = $row['name'];
+          $this->planwatch[$watchuser] = array((int) $row['id'],
+            (int) $row['last_update'],
+            (int) $row['last_view'],
+            false,
+            ((isset($row['hasmessage']) && $row['hasmessage'] == 0) ? true : false)
+          );
+          /* create a pointer to this entry within the appropriate group */
+          $this->groupData[$group][$watchuser] = &$this->planwatch[$watchuser];
+          /* if it's new, increment the number of new plans */
+          if (($row['last_update']) > ($row['last_view'])) {
+            $this->numNew++;
+          }
+        }
+      }
+
+      /* Get snoop group */
+      foreach (Snoop::getReferences($this->user) as $u) {
+        $username = $u['userName'];
+        if (!isset($this->planwatch[$username])) {
+          /* Create a new planwatch entry if one doesn't already exist */
+          $this->planwatch[$username] = array($u['userID'], $u['lastUpdate'], 9999999999);
+        } else {
+          $this->planwatch[$username]['count'] = 2;
+        }
+        $this->groupData['Snoop'][$username] = &$this->planwatch[$username];
+      }
+
+    }
+    catch(PDOException $badquery){
+      return PLANWORLD_ERROR;
+    }
+
+
+    /* Everything from this point on is additive. */
+
+    /* Get primary send group */
+    if (isset($result2)) {
+      foreach($result2 as $row) {
+        $username = $row['username'];
+        if (!isset($this->planwatch[$username])) {
+          $this->planwatch[$username] = array($row['id'], $row['last_update'], 9999999999, false, true);
+        }
+        else if (isset($this->groupData['Snoop'][$username])) {
+            $this->planwatch[$username]['count'] = 3;
+          }
+        else {
+          $this->planwatch[$username]['count'] = 2;
+        }
+      }
+    }
+
+    /* get secondary send group */
+    if (isset($result3)) {
+      foreach($result3 as $row) {
+        $username = $row['username'];
+        if (!isset($this->planwatch[$username])) {
+          $this->planwatch[$username] = array($row['id'], $row['last_update'], 9999999999, false, true);
+        } else if (isset($this->groupData['Snoop'][$username])) {
+            $this->planwatch[$username]['count'] = 3;
+          } else {
+          $this->planwatch[$username]['count'] = 2;
+        }
+        $this->groupData['Send'][$username] = &$this->planwatch[$username];
+      }
+    }
+    if (empty($this->groupData['Send'])) unset($this->groupData['Send']);
+    $this->changed = false;
+  }
+
+  /**
+   * void save ()
+   * Saves planwatch data.
+   */
+  function save(){
+    if ($this->changed) {
+      $this->dbh = Planworld::_connect();
+      foreach ($this->planwatch as $u=>$entry) {
+        if (isset($entry[3]) && $entry[3]) {
+          try{
+            $currentUid = $this->user->getUserID();
+            $watchUid = Planworld::nameToID($u);
+            $entry1 = $entry[1];
+            $query = $this->dbh->prepare('UPDATE planwatch SET last_view=:entry1 WHERE uid=:uid and w_uid=:wuid');
+            $queryArray = array('uid' => $currentUid, 'wuid' => $watchUid, 'entry1' => $entry1);
+            $query->execute($queryArray);
+          }
+          catch(PDOException $badquery){
+            return PLANWORLD_ERROR;
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * bool inPlanwatch ($uid)
+   * Returns whether $uid is in this user's planwatch or not.
+   */
+  function inPlanwatch ($uid) {
+    if (is_object($uid)) {
+      $username = $uid->getUsername();
+    } else if (is_string($uid)) {
+        $username = $uid;
+      } else {
+      return false;
+    }
+
+    if (isset($this->planwatch[$username]) && $this->planwatch[$username][2] != 9999999999) {
+      return true;
+    } else {
+      return false;
+    }
+  }
+
+  /**
+   * void markSeen ($uid)
+   * Marks $uid as having had his/her plan read.
+   */
+  function markSeen ($uid) {
+    if (is_object($uid)) {
+      if ($this->planwatch[$uid->getUsername()][1] > $this->planwatch[$uid->getUsername()][2]) {
+        $this->numNew--;
+      }
+
+      /* update in-place and mark as changed */
+      /* set view time to now */
+      $this->planwatch[$uid->getUsername()][2] = mktime();
+      /* set changed flag to true */
+      $this->planwatch[$uid->getUsername()][3] = true;
+
+      $this->changed = true;
+    }
+  }
+
+  /**
+   * int getNumNew ()
+   * Returns the number of users that are marked as new.
+   */
+  function getNumNew () {
+    return $this->numNew;
+  }
+
+  /**
+   * int getNum ()
+   * Returns the number of users on said planwatch.
+   */
+  function getNum () {
+    return sizeof($this->planwatch);
+  }
+
+  /**
+   * array getList ()
+   * Returns an array containing this user's planwatch.
+   */
+  function &getList () {
+    return $this->groupData;
+  }
+
+
+  /**
+   * array getGroups ()
+   * Returns an array with all of the groups.
+   */
+  function getGroups () {
+    $this->groups = array();
+    try{
+      $currentUid = $this->user->getUserID();
+      $query = $this->dbh->prepare('SELECT gid, uid AS owner, name, pos FROM pw_groups WHERE uid=0 OR uid IS NULL OR uid=:uid ORDER BY pos, name');
+      $queryArray = array('uid' => $currentUid);
+      $query->execute($queryArray);
+      $result=$query->fetchAll();
+      if (!($result)){
+        return PLANWORLD_ERROR;
+      }
+      else{
+        foreach($result as $row) {
+          $group = $row['name'];
+          $this->groups[$group] = array((int) $row['gid'],
+            ($row['owner'] == $this->user->getUserID()) ? true : false,
+            (int) $row['pos']);
+        }
+        return $this->groups;
+      }
+    }
+    catch(PDOException $badquery){
+      return PLANWORLD_ERROR;
+    }
+  }
+
+  function getGroupNames () {
+    $arrayGroupNames = array();
+    try{
+      $currentUid = $this->user->getUserID();
+      $query = $this->dbh->prepare('SELECT name FROM pw_groups WHERE uid=0 OR uid IS NULL OR uid=:uid ORDER BY name');
+      $queryArray = array('uid' => $currentUid);
+      $query->execute($queryArray);
+      $result=$query->fetchAll();
+      if (!($result)){
+        return PLANWORLD_ERROR;
+      }
+      else{
+        foreach($result as $row) {
+          $arrayGroupNames[] = $row['name'];
+        }
+        return $arrayGroupNames;
+      }
+    }
+    catch(PDOException $badquery){
+      return PLANWORLD_ERROR;
+    }
+  }
+
+
+  /**
+   * void move ($uid, $gid)
+   * Moves $uid into group $gid.
+   */
+  function move ($uid, $gid) {
+    $intUid = $this->user->getUserID();
+    $intWUid = -1;
+    if(is_int($uid)){
+      $intWUid = $uid;
+    }
+    else{
+      $intWUid = Planworld::nameToID($uid);
+    }
+    $query = $this->dbh->prepare('UPDATE planwatch SET gid=:gid WHERE w_uid=:wuid AND uid=:uid');
+    $queryArray = array('wuid' => $intWUid, 'uid' => $intUid, 'gid' => $gid);
+    $query->execute($queryArray);
+  }
+
+
+  /**
+   * int addGroup ($name)
+   * Create a group named $name
+   */
+  function addGroup ($name) {
+    try{
+      $intUid = $this->user->getUserID();
+      $id = (int) $this->dbh->nextId('groupid');
+      $query = $this->dbh->prepare('INSERT INTO pw_groups (gid, uid, name) VALUES (:id, :uid, :name)');
+      $queryArray = array('id' => $id, 'uid' => $intUid, 'name' => $name);
+      $query->execute($queryArray);
+      return true;
+    }
+    catch(PDOException $badquery){
+      return false;
+    }
+  }
+
+  /**
+   * void removeGroup ($gid)
+   * Remove group with id $gid.
+   */
+  function removeGroup ($gid) {
+    $intUid = $this->user->getUserID();
+    $queryArray = array('gid' => $gid, 'uid' => $intUid);
+    /* delete the group */
+    $query = $this->dbh->prepare('DELETE FROM pw_groups WHERE gid=:gid AND uid=:uid');
+    $query1->execute($queryArray);
+    /* move entries from that group into the unsorted category */
+    $query2 = $this->dbh->prepare('UPDATE planwatch SET gid=1 WHERE gid=:gid AND uid=:uid');
+    $query2->execute($queryArray);
+  }
+
+
+  function renameGroup ($gid, $name) {
+    $intUid = $this->user->getUserID();
+    $query = $this->dbh->prepare('UPDATE pw_groups SET name=:name WHERE gid=:gid AND uid=:uid');
+    $queryArray = array('gid' => $gid, 'uid' => $intUid, 'name' => $name);
+    $query->execute($queryArray);
+  }
+
+  /**
+   * void remove ($uid)
+   * Removes $uid from this user's planwatch.
+   */
+  function remove ($uid) {
+    unset($this->planwatch[$uid]);
+    $intUid = $this->user->getUserID();
+    $intWUid = -1;
+    if(is_int($uid)){
+      $intWUid = $uid;
+    }
+    else{
+      $intWUid = Planworld::nameToID($uid);
+    }
+    $query = $this->dbh->prepare('DELETE FROM planwatch WHERE w_uid=:wuid AND uid=:uid');
+    $queryArray = array('wuid' => $intWUid, 'uid' => $intUid);
+    $query->execute($queryArray);
+  }
+
+  /**
+   * void add ($uid)
+   * Adds $uid to this user's planwatch.
+   */
+  function add ($uid) {
+    /* no need to fill this entry, as the planwatch will probably be reloaded before it's used */
+    $intUid = $this->user->getUserID();
+    $intWUid = -1;
+    if(is_int($uid)){
+      $intWUid = $uid;
+    }
+    else{
+      $intWUid = Planworld::nameToID($uid);
+    }
+    $query = $this->dbh->prepare('INSERT INTO planwatch (w_uid, uid) VALUES (:wuid, :uid)');
+    $queryArray = array('wuid' => $intWUid, 'uid' => $intUid);
+    $query->execute($queryArray);
+  }
+
+  /* JLO2 20191005 - This can't possibly be as simple as I think it is. */
+  function getInteroperableWatchlist(){
+    $arrayInteroperableList = array();
+    foreach ($this->planwatch as $username => $watchrow){
+      $watchlineArray = array(
+        'username' => $username,
+        'lastupdate' => date(DATE_ATOM, $watchrow[1]),
+        'lastview' => date(DATE_ATOM, $watchrow[2]),
+        'hasmessage' => $watchrow[3]
+      );
+      $arrayInteroperableList[] = $watchlineArray;
+    }
+    return $arrayInteroperableList;
+  }
+
+
+  /* Separate call to get group information. */
+  function getInteroperableWatchlistGroups(){
+    $arrayGroupLevelList = array();
+    foreach ($this->groupData as $groupname => $grouparray){
+      $arrayGroupLevelList[$groupname] = array();
+      foreach ($grouparray as $username => $watchrow){
+        $watchlineArray = array(
+          'username' => $username,
+          'lastupdate' => date(DATE_ATOM, $watchrow[1]),
+          'lastview' => date(DATE_ATOM, $watchrow[2]),
+          'hasmessage' => $watchrow[3]
+        );
+        $arrayGroupLevelList[$groupname][] = $watchlineArray;
+      }
+    }
+    return $arrayGroupLevelList;
+  }
+
+
+
+
+}
+?>
\ No newline at end of file
index 0b14445..b5e2ac8 100644 (file)
@@ -105,6 +105,32 @@ class Planworld {
                return PLANWORLD_ERROR;
        }
 
+
+   /* There is a debate on how one ought to iterate through strings in php ... https://stackoverflow.com/questions/4601032/php-iterate-on-string-characters */
+   public static function isValidWatchlistGroupName($stringName){
+     $boolReturn = true;
+     $stringNameArray = str_split($stringName);
+     foreach($stringNameArray as $char){
+       if((!(ctype_alnum($char))) && ($char != "_") && ($char != "-") && ($char != " ")){
+         $boolReturn = false;
+       }
+     }
+     return $boolReturn;
+   }
+
+
+   public static function isValidUserName($stringName){
+     $boolReturn = true;
+     $stringNameArray = str_split($stringName);
+     foreach($stringNameArray as $char){
+       if((!(ctype_alnum($char))) && ($char != "@")){
+         $boolReturn = false;
+       }
+     }
+     return $boolReturn;
+   }
+
+
        /*
    int Planworld::nameToID ($uid)
    converts textual $uid to numeric representation
@@ -463,8 +489,11 @@ public static function isUser ($uid, $force=false) {
                        }
                        else {
                                $return = array();
+                               /* Rudimentary data sanitization, but we need to validate the DB too as an administrative function. */
                                foreach($result as $row){
-                                       $return[] = $row['username'];
+                                       if(ctype_alnum(trim($row['username']))){
+                                               $return[] = trim($row['username']);
+                                       }
                                }
                                return $return;
                        }
diff --git a/code/lib/Snoop.php b/code/lib/Snoop.php
new file mode 100644 (file)
index 0000000..e6f6606
--- /dev/null
@@ -0,0 +1,252 @@
+<?php
+/* Snoop.php
+ * v. 3.0beta 20190703 JLO2
+ * v 1.10.2.2 2003/11/02 16:12:35 seth Exp $ */
+
+/* Includes and Housekeeping */
+require_once($_base . 'lib/Planworld.php');
+require_once($_base . 'backend/epi-utils.php');
+date_default_timezone_set(PW_TIMEZONE);
+
+class Snoop
+{
+    /**
+     * Calls a remote method via xml-rpc.
+     * @param method Method to call.
+     * @param params Parameters to use.
+     * @private
+     */
+    public function _call($server, $method, $params=null)
+    {
+        return xu_rpc_http_concise(array('method' => $method,
+                     'args'   => $params,
+                     'host'   => $server['Hostname'],
+                     'uri'    => $server['Path'],
+                     'port'   => $server['Port'],
+                     'debug'  => 0)); // 0=none, 1=some, 2=more
+    }
+
+    /**
+     * Pulls references from $content.
+     * @param content Content to search.
+     * @returns matches Array of references.
+     * @private
+     */
+    public function _getReferences($content)
+    {
+        /* find references in plan */
+        preg_match_all("/!([a-z0-9\-\.@]+)(!|:[^!]+!)/i", $content, $matches, PREG_PATTERN_ORDER);
+        return $matches;
+    }
+
+    /**
+     * void Snoop::addReference ($from, $to)
+     * Add a snoop reference by $from for $to
+     */
+    public function addReference($from, $to, $date=null)
+    {
+        $dbh = Planworld::_connect();
+
+        if (!isset($date)) {
+            $date = mktime();
+        }
+
+        if ($from == 0 || $from == '' || $to == 0 || $to == '') {
+            return false;
+        }
+      
+        $query = $dbh->prepare('INSERT INTO snoop (uid, s_uid, referenced) VALUES(:to, :from, :date)');
+        $queryArray = array('to' => $to, 'from' => $from, 'date' => $date);
+        $result = $query->execute($queryArray);
+        if ($result) {
+            return PLANWORLD_OK;
+        } else {
+            return PLANWORLD_ERROR;
+        }
+        return PLANWORLD_ERROR;
+    }
+
+    /**
+     * void Snoop::removeReference ($from, $to)
+     * Removes a snoop reference by $from for $to
+     */
+    public function removeReference($from, $to)
+    {
+        $dbh = Planworld::_connect();
+        $query = $dbh->prepare('DELETE FROM snoop WHERE uid=:to AND s_uid=:from');
+        $queryArray = array('to' => $to, 'from' => $from);
+        $result = $query->execute($queryArray);
+        if ($result) {
+            return PLANWORLD_OK;
+        } else {
+            return PLANWORLD_ERROR;
+        }
+        return PLANWORLD_ERROR;
+    }
+
+    /**
+     * void Snoop::clearReferences ($uid)
+     * Clear all snoop references by $uid
+     */
+    public function clearReferences($uid)
+    {
+        $dbh = Planworld::_connect();
+        $query = $dbh->prepare('DELETE FROM snoop WHERE uid=:uid');
+        $queryArray = array('uid' => $uid);
+        $result = $query->execute($queryArray);
+        if ($result) {
+            return PLANWORLD_OK;
+        } else {
+            return PLANWORLD_ERROR;
+        }
+        return PLANWORLD_ERROR;
+    }
+
+    /**
+     * void Snoop::clearRemoteReferences ($uid)
+     * Clear all remote snoop references by $uid
+     */
+    public function clearRemoteReferences($node, $uid)
+    {
+        Snoop::_call($node, 'planworld.snoop.clear', $uid . '@' . PW_NAME);
+    }
+
+    /**
+     * Case-insensitive array diff that prunes duplicates
+     */
+    public function snoop_diff($old, $new)
+    {
+        $old = array_map('strtolower', $old);
+        $new = array_map('strtolower', $new);
+        return array_unique(array_diff($old, $new));
+    }
+
+    /**
+     * void Snoop::process ($user, $new, $old)
+     * Find new / removed snoop references in $user's plan.
+     */
+    public function process(&$user, $new, $old)
+    {
+
+    /* find references in old plan */
+        $dbh = Planworld::_connect();
+        try {
+            if (!$dbh) {
+                throw new PDOException('Database connection not initialized.');
+            }
+            $query = $dbh->prepare('SELECT username FROM snoop, users WHERE snoop.uid = users.id AND s_uid = :uid');
+            $queryArray = array('uid' => $user->getUserID());
+            $query->execute($queryArray);
+            $old_matches = $query->fetchAll(PDO::FETCH_COLUMN);
+            if (!$old_matches) {
+                return PLANWORLD_ERROR;
+            } else {
+                /* find references in new plan */
+                $new_matches = Snoop::_getReferences($new);
+
+                /* find differences */
+                $users_to_add = Snoop::snoop_diff($new_matches[1], $old_matches);
+                $users_to_del = Snoop::snoop_diff($old_matches, $new_matches[1]);
+
+                $success = true;
+                foreach ($users_to_add as $u) {
+                    if (strstr($u, '@')) {
+                        list($username, $host) = explode('@', $u);
+                    }
+
+                    $sid = Planworld::nameToID($u);
+                    /* valid local user */
+                    if (!isset($host) && $sid > 0) {
+                        $success = $success && Snoop::addReference($user->getUserID(), $sid);
+                    }
+                    /* remote planworld user */
+
+                    elseif (isset($host) && $node = Planworld::getNodeInfo($host)) {
+                        unset($host); /* JLO2 4/12/10 Required to stop permasnoops after calling remote users. */
+
+                        if ($node['Version'] < 2) {
+                            Snoop::_call($node, 'snoop.addReference', array($username, $user->getUsername() . '@' . PW_NAME));
+                        } else {
+                            Snoop::_call($node, 'planworld.snoop.add', array($username, $user->getUsername() . '@' . PW_NAME));
+                        }
+                    }
+                }
+
+                foreach ($users_to_del as $u) {
+                    if (strstr($u, '@')) {
+                        list($username, $host) = explode('@', $u);
+                    }
+
+                    $sid = Planworld::nameToID($u);
+                    if (!isset($host) && $sid > 0) {
+                        /* valid local user */
+
+                        $success = $success && Snoop::removeReference($user->getUserID(), $sid);
+                    } elseif (isset($host) && $node = Planworld::getNodeInfo($host)) {
+                        /* remote planworld user */
+                        unset($host); /* JLO2 4/12/10 Required to stop permasnoops after calling remote users. */
+
+                        if ($node['Version'] < 2) {
+                            Snoop::_call($node, 'snoop.removeReference', array($username, $user->getUsername() . '@' . PW_NAME));
+                        } else {
+                            Snoop::_call($node, 'planworld.snoop.remove', array($username, $user->getUsername() . '@' . PW_NAME));
+                        }
+                    }
+                }
+                return $success;
+            }
+        } catch (PDOException $badquery) {
+            return PLANWORLD_ERROR;
+        }
+    }
+
+
+    /* Previous version had sort arguments. The client should do the sorting, so we removed them.
+     * The code allows users to be sent in as usernames, objects, or user ids, and the original code did a different query based on that.
+     * We have simplified so that user id is always used. */
+    public static function getReferences(&$user)
+    {
+        $dbh = Planworld::_connect();
+        $userid = -1;
+        if (is_int($user)) {
+            $userid = $user;
+        } elseif (is_string($user)) {
+            $userid = Planworld::nameToID($user);
+        } elseif (is_object($user)) {
+            $userid = $user->getUserID();
+        }
+        try {
+            if (!$dbh) {
+                throw new PDOException('Database connection not initialized.');
+            }
+            $query = $dbh->prepare('SELECT s_uid, referenced, username, last_update FROM snoop,users WHERE uid=:uid AND users.id=s_uid');
+            $queryArray = array('uid' => $userid);
+            $query->execute($queryArray);
+            $result = $query->fetchAll();
+            if (!$result) {
+                return array();
+            } else {
+                $return = array();
+                /* April fool's easter egg */
+                if (date('n-j') == '4-1') {
+                    $uid = Planworld::getRandomUser();
+                    $return[] = array("userID" => $uid,
+              "userName" => Planworld::idToName($uid),
+              "date" => mktime(0, 0, 0, 4, 1, date('Y')),
+              "lastUpdate" => Planworld::getLastUpdate($uid));
+                }
+
+                foreach ($result as $row) {
+                    $return[] = array("userID" => (int) $row['s_uid'],
+                    "userName" => $row['username'],
+                    "date" => (int) $row['referenced'],
+                    "lastUpdate" => (int) $row['last_update']);
+                }
+
+                return $return;
+            }
+        } catch (PDOException $badquery) {
+            return PLANWORLD_ERROR;
+        }
+    }
+}
index 7bb3bb3..db39367 100755 (executable)
@@ -2,9 +2,9 @@
 
 /* _Includes_ */
 $_base = dirname(__FILE__) . '/../';
-require_once('Planworld.php'); //stand-in for Planworld
-//require_once('Planwatch.php'); Re-Enable when we have Planwatch in implementation
-
+require_once($_base . 'lib/Planworld.php');
+require_once($_base . 'lib/Planwatch.php');
+require_once($_base . 'lib/Snoop.php');
 
 /**
  * User class for planworld.
@@ -12,1049 +12,1172 @@ require_once('Planworld.php'); //stand-in for Planworld
  */
 class User {
 
-       /** general user information */
-       var $archive;
-       var $lastLogin;
-       var $lastUpdate;
-       var $last_ip;
-       var $plan;
-       var $planwatch;
-       var $snitchDisplayNum;
-       var $snitchEnabled;
-       var $theme;
-       var $timezone = PW_TIMEZONE;
-       var $type;
-       var $userID;
-       var $userInfo;
-       var $username;
-       var $views;
-       var $watchOrder;
-       var $prefs;
-       var $editor;
-
-       /** flags (booleans) */
-       var $admin;
-       var $remoteUser;
-       var $shared = false;
-       var $snitch;
-       var $valid;
-       var $world;
-
-       var $changed = false;
-
-       var $dbh;
-
-       /**
-        * Factory
-        * @param uid User to initialize
-        * @public
-        * @static
-        * @returns User
-        */
-       static function &factory ($uid) {
-               if (Planworld::isUser($uid) && !Planworld::isRemoteUser($uid)) {
-                       $temp = new User($uid);
-                       return $temp;
-               }
-               else if (!Planworld::isUser($uid) && !strstr($uid, '@')) {
-                               $temp = new User($uid);
-                               return $temp;
-                       }
-               else {
-                       list(,$host) = split('@', $uid);
-                       $nodeinfo = Planworld::getNodeInfo($host);
-                       $temp = new RemoteUser($uid, $nodeinfo);
-                       return $temp;
-               }
-       }
-
-
-       function User ($uid) {
-               /* establish a database connection */
-               $this->dbh = Planworld::_connect();
-               $this->type = 'local';
-               if (is_string($uid)) {
-                       $this->username = $uid;
-               }
-               else if (is_int($uid)) {
-                               $this->userID = (int)$uid;
-                       }
-               /* check if this user exists */
-               if (isset($this->userID) || $this->isUser()) {
-                       $this->load();
-               }
-       }
-
-
-
-       /*      The original version of this function returns false rather than Planworld error, so we continue that habit.
+  /** general user information */
+  var $archive;
+  var $lastLogin;
+  var $lastUpdate;
+  var $last_ip;
+  var $plan;
+  var $planwatch;
+  var $snitchDisplayNum;
+  var $snitchEnabled;
+  var $theme;
+  var $timezone = PW_TIMEZONE;
+  var $type;
+  var $userID;
+  var $userInfo;
+  var $username;
+  var $views;
+  var $watchOrder;
+  var $prefs;
+  var $editor;
+
+  /** flags (booleans) */
+  var $admin;
+  var $remoteUser;
+  var $shared = false;
+  var $snitch;
+  var $valid;
+  var $world;
+
+  var $changed = false;
+
+  var $dbh;
+
+  /**
+   * Factory
+   * @param uid User to initialize
+   * @public
+   * @static
+   * @returns User
+   */
+  static function &factory ($uid) {
+    if (Planworld::isUser($uid) && !Planworld::isRemoteUser($uid)) {
+      $temp = new User($uid);
+      return $temp;
+    }
+    else if (!Planworld::isUser($uid) && !strstr($uid, '@')) {
+        $temp = new User($uid);
+        return $temp;
+      }
+    else {
+      list(,$host) = split('@', $uid);
+      $nodeinfo = Planworld::getNodeInfo($host);
+      $temp = new RemoteUser($uid, $nodeinfo);
+      return $temp;
+    }
+  }
+
+
+  function __construct ($uid) {
+    /* establish a database connection */
+    $this->dbh = Planworld::_connect();
+    $this->type = 'local';
+    if (is_string($uid)) {
+      $this->username = $uid;
+    }
+    else if (is_int($uid)) {
+        $this->userID = (int)$uid;
+      }
+    /* check if this user exists */
+    if (isset($this->userID) || $this->isUser()) {
+      $this->load();
+    }
+  }
+
+
+
+  /*   The original version of this function returns false rather than Planworld error, so we continue that habit.
                        Obviously the function loads user information.
        */
-       function load(){
-               $continue = false;
-               $query = ''; /* Placed here to define. Handled appropriately if continues null. */
-               $queryArray = array();
-               try{
-                       if(!$this->dbh){
-                               throw new PDOException('Database connection not initialized.');
-                       }
-                       if (isset($this->username)){
-                               $query = $this->dbh->prepare('SELECT * FROM users WHERE username= :username');
-                               $queryArray = array('username' => addslashes($this->username));
-                               $continue = true;
-                       }
-                       else if (isset($this->userID)){
-                                       $query = $this->dbh->prepare('SELECT * FROM users WHERE id= :uid');
-                                       $queryArray = array('uid' => $this->userID);
-                                       $continue = true;
-                               }
-                       else{
-                               $continue = false;
-                       }
-               }
-               catch(PDOException $badquery){
-                       $continue = false;
-               }
-               if($continue){
-                       try{
-                               $query->execute($queryArray);
-                               $result = $query->fetch();
-                               if (!$result){
-                                       return false;
-                               }
-                               else{
-                                       $this->userID = (int) $result['id'];
-                                       $this->username = $result['username'];
-                                       $this->remoteUser = ($result['remote'] == 'Y') ? true : false;
-                                       $this->world = ($result['world'] == 'Y') ? true : false;
-                                       $this->snitch = ($result['snitch'] == 'Y') ? true : false;
-                                       $this->archive = $result['archive'];
-                                       $this->snitchDisplayNum = $result['snitch_views'];
-                                       $this->views = $result['views'];
-                                       $this->watchOrder = $result['watch_order'];
-                                       $this->theme = $result['theme_id'];
-                                       $this->snitchEnabled = $result['snitch_activated'];
-                                       $this->lastLogin = $result['last_login'];
-                                       $this->lastUpdate = $result['last_update'];
-                                       if ($tz = $this->getPreference('timezone')) {
-                                               $this->timezone = $tz;
-                                       }
-                                       $this->changed = false;
-                                       return true;
-                               }
-                       }
-                       catch(PDOException $badquery){
-                               return false;
-                       }
-               }
-               else{
-                       return false;
-               }
-               return false;
-
-       }
-
-
-
-
-
-       /**
-        * Create this user
-        */
-       function create () {
-               /* create the user */
-               if (isset($this->username)){
-                               $this->userID = Planworld::addUser($this->username);
-               }
-
-               /* set the valid flag */
-               $this->valid = true;
-       }
-
-
-       /**
-        * Fetches a preference for this user.
-        */
-       function getPreference ($name) {
-               if (isset($this->prefs[$name])){
-                       return $this->prefs[$name];
-               }
-               else if((!empty(trim($name))) && (in_array($name, Planworld::getArrayOfAllowedPreferences()))){
-                               try{
-                                       if(!$this->dbh){
-                                               throw new PDOException('Database connection not initialized.');
-                                       }
-                                       $query = $this->dbh->prepare('SELECT value FROM preferences WHERE uid= :uid AND name= :name');
-                                       $queryArray = array('uid' => $this->userID, 'name' => $name);
-                                       $query->execute($queryArray);
-                                       $result = $query->fetch();
-                                       if(isset($result['value'])){
-                                               if((strcasecmp($result['value'], 'true')) == 0){
-                                                       $this->prefs[$name] = true;
-                                                       return true;
-                                               }
-                                               else if((strcasecmp($result['value'], 'false')) == 0){
-                                                               $this->prefs[$name] = false;
-                                                               return false;
-                                                       }
-                                               else{
-                                                       $this->prefs[$name] = $result['value'];
-                                                       return $result['value'];
-                                               }
-                                       }
-                                       else{
-                                               $this->prefs[$name] = false;
-                                               return false;
-                                       }
-                               }
-                               catch(PDOException $badquery){
-                                       $this->prefs[$name] = false;
-                                       return false;
-                               }
-                       }
-               else{
-                       return false;
-               }
-               return false;
-       }
-
-
-
-    /**
-     * Sets a preference for this user.
-     * @public
-     * @returns string
-     */
-    function setPreference ($name, $val) {
-                       $success = false;
-               if(!(in_array($name, Planworld::getArrayOfAllowedPreferences()))){
-                       $success = false;
-               }
-         else{
-                 $this->clearPreference ($name); /* Don't check for true return because the preference may start out blank. */
-                       /* A huge flaw in this method is that preference calues are not checked for validity.
+  function load(){
+    $continue = false;
+    $query = ''; /* Placed here to define. Handled appropriately if continues null. */
+    $queryArray = array();
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      if (isset($this->username)){
+        $query = $this->dbh->prepare('SELECT * FROM users WHERE username= :username');
+        $queryArray = array('username' => addslashes($this->username));
+        $continue = true;
+      }
+      else if (isset($this->userID)){
+          $query = $this->dbh->prepare('SELECT * FROM users WHERE id= :uid');
+          $queryArray = array('uid' => $this->userID);
+          $continue = true;
+        }
+      else{
+        $continue = false;
+      }
+    }
+    catch(PDOException $badquery){
+      $continue = false;
+    }
+    if($continue){
+      try{
+        $query->execute($queryArray);
+        $result = $query->fetch();
+        if (!$result){
+          return false;
+        }
+        else{
+          $this->userID = (int) $result['id'];
+          $this->username = $result['username'];
+          $this->remoteUser = ($result['remote'] == 'Y') ? true : false;
+          $this->world = ($result['world'] == 'Y') ? true : false;
+          $this->snitch = ($result['snitch'] == 'Y') ? true : false;
+          $this->archive = $result['archive'];
+          $this->snitchDisplayNum = $result['snitch_views'];
+          $this->views = $result['views'];
+          $this->watchOrder = $result['watch_order'];
+          $this->theme = $result['theme_id'];
+          $this->snitchEnabled = $result['snitch_activated'];
+          $this->lastLogin = $result['last_login'];
+          $this->lastUpdate = $result['last_update'];
+          if ($tz = $this->getPreference('timezone')) {
+            $this->timezone = $tz;
+          }
+          $this->changed = false;
+          return true;
+        }
+      }
+      catch(PDOException $badquery){
+        return false;
+      }
+    }
+    else{
+      return false;
+    }
+    return false;
+
+  }
+
+
+
+
+
+  /**
+   * Create this user
+   */
+  function create () {
+    /* create the user */
+    if (isset($this->username)){
+      $this->userID = Planworld::addUser($this->username);
+    }
+
+    /* set the valid flag */
+    $this->valid = true;
+  }
+
+
+  /**
+   * Fetches a preference for this user.
+   */
+  function getPreference ($name) {
+    if (isset($this->prefs[$name])){
+      return $this->prefs[$name];
+    }
+    else if((!empty(trim($name))) && (in_array($name, Planworld::getArrayOfAllowedPreferences()))){
+        try{
+          if(!$this->dbh){
+            throw new PDOException('Database connection not initialized.');
+          }
+          $query = $this->dbh->prepare('SELECT value FROM preferences WHERE uid= :uid AND name= :name');
+          $queryArray = array('uid' => $this->userID, 'name' => $name);
+          $query->execute($queryArray);
+          $result = $query->fetch();
+          if(isset($result['value'])){
+            if((strcasecmp($result['value'], 'true')) == 0){
+              $this->prefs[$name] = true;
+              return true;
+            }
+            else if((strcasecmp($result['value'], 'false')) == 0){
+                $this->prefs[$name] = false;
+                return false;
+              }
+            else{
+              $this->prefs[$name] = $result['value'];
+              return $result['value'];
+            }
+          }
+          else{
+            $this->prefs[$name] = false;
+            return false;
+          }
+        }
+        catch(PDOException $badquery){
+          $this->prefs[$name] = false;
+          return false;
+        }
+      }
+    else{
+      return false;
+    }
+    return false;
+  }
+
+
+
+  /**
+   * Sets a preference for this user.
+   * @public
+   * @returns string
+   */
+  function setPreference ($name, $val) {
+    $success = false;
+    if(!(in_array($name, Planworld::getArrayOfAllowedPreferences()))){
+      $success = false;
+    }
+    else{
+      $this->clearPreference ($name); /* Don't check for true return because the preference may start out blank. */
+      /* A huge flaw in this method is that preference calues are not checked for validity.
                                But then, right now the journal divider preference is sort of impossible to check and awful.
                                We might consider breaking it out into a separate table along with shared. */
 
 
-         }
+    }
+
 
+    $query = "DELETE FROM preferences WHERE uid=" . $this->userID . " AND name='" . $name . "'";
+    $this->dbh->query($query);
 
-      $query = "DELETE FROM preferences WHERE uid=" . $this->userID . " AND name='" . $name . "'";
+    /* don't add false preferences (lack is assumed to be false) */
+    if (!$val || strtolower($val) != 'false' || $val != '') {
+      $query = "INSERT INTO preferences (uid, name, value) VALUES (" . $this->userID . ", '{$name}', '{$val}')";
       $this->dbh->query($query);
+    }
+
+    $this->prefs[$name] = $val;
+  }
+
 
-      /* don't add false preferences (lack is assumed to be false) */
-      if (!$val || strtolower($val) != 'false' || $val != '') {
-       $query = "INSERT INTO preferences (uid, name, value) VALUES (" . $this->userID . ", '{$name}', '{$val}')";
-       $this->dbh->query($query);
+
+  /**
+   * Clears a preference for this user.
+   */
+  function clearPreference ($name) {
+    $success = false;
+    if(!(in_array($name, Planworld::getArrayOfAllowedPreferences()))){
+      $success = false;
+    }
+    else{
+      try{
+        if(!$this->dbh){
+          throw new PDOException('Database connection not initialized.');
+        }
+        $query = $this->dbh->prepare('DELETE FROM preferences WHERE uid= :uid AND name LIKE(:prefname)');
+        $queryArray = array('uid' => $this->userID, 'prefname' => $name);
+        $success = $query->execute($queryArray);
+        /* We do this after the query but within the block so that if it blows up the catch will still give us a false return.
+                               The point is that if we get a false, we should re-investigate because preference state is likely unpredictable. */
+        unset($this->prefs[$name]);
+      }
+      catch(PDOException $badquery){
+        $success = false;
+      }
+    }
+    return $success;
+  }
+
+
+
+
+  /**
+   * Saves user information.
+   * @public
+   * @returns bool Whether any data was actually saved
+   */
+  // STILL REQUIRES CLEANUP, DOCUMENTATION, ONE NOTED CHANGE, AND A CHECK OF ALL IF AND CONDITIONALS.
+  function save () {
+    $boolSaveResult = false;
+    $errorCount = 0;
+    if ($this->changed) {
+      /* column <-> variable mapping */
+      $info = array();
+      $info['username'] = strval($this->username);
+      $info['remote'] = (strval($this->remoteUser)) ? 'Y' : 'N';
+      $info['world'] = (strval($this->world)) ? 'Y' : 'N';
+      $info['snitch'] = (strval($this->snitch)) ? 'Y' : 'N';
+      $info['snitch_views'] = $this->snitchDisplayNum;
+      $info['archive'] = strval($this->archive);
+      $info['watch_order'] = strval($this->watchOrder);
+      $info['theme_id'] = $this->theme;
+      $info['snitch_activated'] = $this->snitchEnabled;
+      $info['last_login'] = $this->lastLogin;
+      $info['last_update'] = $this->lastUpdate;
+      $info['last_ip'] = strval($this->last_ip);
+      $whereKey = '';
+      $whereValue = '';
+      $boolContinue = false;
+      if(isset($this->username)){
+        $whereKey = 'username';
+        $whereValue = $this->username;
+        $boolContinue = true;
+      }
+      else if(isset($this->userID)){
+          $whereKey = 'id';
+          $whereValue = $this->userID;
+          $boolContinue = true;
+        }
+      else{
+        $boolContinue = false;
+      }
+      if($boolContinue){
+        /* Run an update for each attribue on this user, but only if the attribute value is not empty. */
+        foreach($info as $key => $value){
+          if(!empty($value)){
+            try{
+              if(!$this->dbh){
+                throw new PDOException('Database connection not initialized.');
+              }
+              $query = $this->dbh->prepare('UPDATE users SET :key = :value WHERE :wherekey = :wherevalue');
+              $queryArray = array('wherekey' => $whereKey, 'wherevalue' => $whereValue, 'key' => $key, 'value' => $value);
+              $query->execute($queryArray);
+            }
+            catch(PDOException $badquery){
+              $errorCount++;
+            }
+          }
+          else{
+            $errorCount++;
+          }
+        }
+        /* This can be adjusted depending upon one's tolerance for errors. */
+        if($errorCount == 0){
+          $boolSaveResult = true;
+          $this->changed = false;
+        }
+        else if(($errorCount < 12) && ($errorCount > 0)){
+            $boolSaveResult = true;
+            $this->changed = true;
+          }
+        else{
+          $boolSaveResult = false;
+          $this->changed = true;
+        }
+      }
+      else{
+        $boolSaveResult = false;
+      }
+    }
+    else{
+      /* No change, but we were successful anyway. */
+      $boolSaveResult = true;
+    }
+    /* save any changed planwatch data if need be */
+    if (isset($this->planwatch)) {
+      $this->planwatch->save();
+    }
+    return $boolSaveResult;
+  }
+
+
+  /**
+   * Loads a Planwatch object containing this users planwatch.
+   * @public
+   */
+  function loadPlanwatch () {
+    if (!isset($this->planwatch)) {
+      // FIX AND ADD WHEN PLANWATCH IMPLEMENTED
+      //$this->planwatch = new Planwatch($this);
+      return false;
+    }
+    else{
+      return PLANWORLD_ERROR;
+    }
+  }
+
+
+  /**
+   * Set snitch registration status.
+   * @param val True / false registration
+   * @public
+   * @returns void
+   */
+  function setSnitch ($val) {
+    $this->changed = true;
+    if (!$val && $this->snitch) {
+      $this->clearSnitch();
+    }
+    else if ($val && $val != $this->snitch) {
+        $this->startSnitch();
+      }
+    else {
+      $this->changed = false;
+    }
+    $this->snitch = $val;
+  }
+
+
+  /**
+   * Clear this user's snitch list.
+   * @private
+   * @returns boolean
+   */
+  function clearSnitch () {
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      $this->snitch = false;
+      $this->snitchEnabled = 0;
+      $this->changed = true;
+      $query = $this->dbh->prepare('DELETE FROM snitch WHERE uid= :uid');
+      $queryArray = array('uid' => $this->userID);
+      return $query->execute($queryArray);
+    }
+    catch(PDOException $badquery){
+      return false;
+    }
+  }
+
+
+  /**
+   * Resets this user's snitch views.
+   * @public
+   * @returns boolean
+   */
+  function resetSnitchViews () {
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
       }
+      $query = $this->dbh->prepare('UPDATE snitch SET views=0 WHERE uid=:uid');
+      $queryArray = array('uid' => $this->userID);
+      return $query->execute($queryArray);
+    }
+    catch(PDOException $badquery){
+      return false;
+    }
+
+  }
 
-      $this->prefs[$name] = $val;
+  /**
+   * Is this user snitch registered?
+   * @public
+   * @returns bool
+   */
+  function getSnitch () {
+    return $this->snitch;
+  }
+
+
+  /**
+   * Returns the number of snitch views that this user has had.
+   * @public
+   */
+  function getNumSnitchViews () {
+
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      $query = $this->dbh->prepare('SELECT COUNT(*) as count FROM snitch WHERE uid=:uid');
+      $queryArray = array('uid' => $this->userID);
+      $query->execute($queryArray);
+      $result = $query->fetch();
+      return $result['count'];
+    }
+    catch(PDOException $badquery){
+      return PLANWORLD_ERROR;
     }
+  }
 
 
 
-       /**
-        * Clears a preference for this user.
-        */
-       function clearPreference ($name) {
-               $success = false;
-               if(!(in_array($name, Planworld::getArrayOfAllowedPreferences()))){
-                       $success = false;
-               }
-               else{
-                       try{
-                               if(!$this->dbh){
-                                       throw new PDOException('Database connection not initialized.');
-                               }
-                               $query = $this->dbh->prepare('DELETE FROM preferences WHERE uid= :uid AND name LIKE(:prefname)');
-                               $queryArray = array('uid' => $this->userID, 'prefname' => $name);
-                               $success = $query->execute($queryArray);
-                               /* We do this after the query but within the block so that if it blows up the catch will still give us a false return.
-                               The point is that if we get a false, we should re-investigate because preference state is likely unpredictable. */
-                               unset($this->prefs[$name]);
-                       }
-                       catch(PDOException $badquery){
-                               $success = false;
-                       }
-               }
-               return $success;
-       }
-
-
-
-
-       /**
-        * Saves user information.
-        * @public
-        * @returns bool Whether any data was actually saved
-        */
-       // STILL REQUIRES CLEANUP, DOCUMENTATION, ONE NOTED CHANGE, AND A CHECK OF ALL IF AND CONDITIONALS.
-       function save () {
-               $boolSaveResult = false;
-               $errorCount = 0;
-               if ($this->changed) {
-                       /* column <-> variable mapping */
-                       $info = array();
-                       $info['username'] = strval($this->username);
-                       $info['remote'] = (strval($this->remoteUser)) ? 'Y' : 'N';
-                       $info['world'] = (strval($this->world)) ? 'Y' : 'N';
-                       $info['snitch'] = (strval($this->snitch)) ? 'Y' : 'N';
-                       $info['snitch_views'] = $this->snitchDisplayNum;
-                       $info['archive'] = strval($this->archive);
-                       $info['watch_order'] = strval($this->watchOrder);
-                       $info['theme_id'] = $this->theme;
-                       $info['snitch_activated'] = $this->snitchEnabled;
-                       $info['last_login'] = $this->lastLogin;
-                       $info['last_update'] = $this->lastUpdate;
-                       $info['last_ip'] = strval($this->last_ip);
-                       $whereKey = '';
-                       $whereValue = '';
-                       $boolContinue = false;
-                       if(isset($this->username)){
-                               $whereKey = 'username';
-                               $whereValue = $this->username;
-                               $boolContinue = true;
-                       }
-                       else if(isset($this->userID)){
-                                       $whereKey = 'id';
-                                       $whereValue = $this->userID;
-                                       $boolContinue = true;
-                               }
-                       else{
-                               $boolContinue = false;
-                       }
-                       if($boolContinue){
-                               /* Run an update for each attribue on this user, but only if the attribute value is not empty. */
-                               foreach($info as $key => $value){
-                                       if(!empty($value)){
-                                               try{
-                                                       if(!$this->dbh){
-                                                               throw new PDOException('Database connection not initialized.');
-                                                       }
-                                                       $query = $this->dbh->prepare('UPDATE users SET :key = :value WHERE :wherekey = :wherevalue');
-                                                       $queryArray = array('wherekey' => $whereKey, 'wherevalue' => $whereValue, 'key' => $key, 'value' => $value);
-                                                       $query->execute($queryArray);
-                                               }
-                                               catch(PDOException $badquery){
-                                                       $errorCount++;
-                                               }
-                                       }
-                                       else{
-                                               $errorCount++;
-                                       }
-                               }
-                               /* This can be adjusted depending upon one's tolerance for errors. */
-                               if($errorCount == 0){
-                                       $boolSaveResult = true;
-                                       $this->changed = false;
-                               }
-                               else if(($errorCount < 12) && ($errorCount > 0)){
-                                               $boolSaveResult = true;
-                                               $this->changed = true;
-                                       }
-                               else{
-                                       $boolSaveResult = false;
-                                       $this->changed = true;
-                               }
-                       }
-                       else{
-                               $boolSaveResult = false;
-                       }
-               }
-               else{
-                       /* No change, but we were successful anyway. */
-                       $boolSaveResult = true;
-               }
-               /* save any changed planwatch data if need be */
-               if (isset($this->planwatch)) {
-                       $this->planwatch->save();
-               }
-               return $boolSaveResult;
-       }
-
-
-       /**
-        * Loads a Planwatch object containing this users planwatch.
-        * @public
-        */
-       function loadPlanwatch () {
-               if (!isset($this->planwatch)) {
-                       // FIX AND ADD WHEN PLANWATCH IMPLEMENTED
-                       //$this->planwatch = new Planwatch($this);
-                       return false;
-               }
-               else{
-                       return PLANWORLD_ERROR;
-               }
-       }
-
-
-       /**
-        * Set snitch registration status.
-        * @param val True / false registration
-        * @public
-        * @returns void
-        */
-       function setSnitch ($val) {
-               $this->changed = true;
-               if (!$val && $this->snitch) {
-                       $this->clearSnitch();
-               }
-               else if ($val && $val != $this->snitch) {
-                               $this->startSnitch();
-                       }
-               else {
-                       $this->changed = false;
-               }
-               $this->snitch = $val;
-       }
-
-
-       /**
-        * Clear this user's snitch list.
-        * @private
-        * @returns boolean
-        */
-       function clearSnitch () {
-               try{
-                       if(!$this->dbh){
-                               throw new PDOException('Database connection not initialized.');
-                       }
-                       $this->snitch = false;
-                       $this->snitchEnabled = 0;
-                       $this->changed = true;
-                       $query = $this->dbh->prepare('DELETE FROM snitch WHERE uid= :uid');
-                       $queryArray = array('uid' => $this->userID);
-                       return $query->execute($queryArray);
-               }
-               catch(PDOException $badquery){
-                       return false;
-               }
-       }
-
-
-       /**
-        * Resets this user's snitch views.
-        * @public
-        * @returns boolean
-        */
-       function resetSnitchViews () {
-               try{
-                       if(!$this->dbh){
-                               throw new PDOException('Database connection not initialized.');
-                       }
-                       $query = $this->dbh->prepare('UPDATE snitch SET views=0 WHERE uid=:uid');
-                       $queryArray = array('uid' => $this->userID);
-                       return $query->execute($queryArray);
-               }
-               catch(PDOException $badquery){
-                       return false;
-               }
-
-       }
-
-       /**
-        * Is this user snitch registered?
-        * @public
-        * @returns bool
-        */
-       function getSnitch () {
-               return $this->snitch;
-       }
-
-
-       /**
-        * Returns the number of snitch views that this user has had.
-        * @public
-        */
-       function getNumSnitchViews () {
-
-               try{
-                       if(!$this->dbh){
-                               throw new PDOException('Database connection not initialized.');
-                       }
-                       $query = $this->dbh->prepare('SELECT COUNT(*) as count FROM snitch WHERE uid=:uid');
-                       $queryArray = array('uid' => $this->userID);
-                       $query->execute($queryArray);
-                       $result = $query->fetch();
-                       return $result['count'];
-               }
-               catch(PDOException $badquery){
-                       return PLANWORLD_ERROR;
-               }
-       }
-
-
-
-
-       /* The previous version of this function allowed ordering.
+
+  /* The previous version of this function allowed ordering.
                We will assume in the future that the client will handle ordering. */
-       function getSnitchViews () {
-               $arrayDicedSnitchViews = array();
-               try{
-                       if(!$this->dbh){
-                               throw new PDOException('Database connection not initialized.');
-                       }
-                       $query = $this->dbh->prepare('SELECT snitch.s_uid, snitch.last_view, snitch.views, u2.username as s_name, u2.last_update FROM users, snitch LEFT JOIN users as u2 ON snitch.s_uid=u2.id WHERE snitch.uid=:uid AND users.id=:uid AND snitch.last_view > users.snitch_activated ORDER BY u2.last_update');
-                       $queryArray = array('uid' => $this->userID);
-                       $query->execute($queryArray);
-                       $result = $query->fetchall();
-                       $this->loadPlanwatch();
-                       foreach ($result as $row){
-                               $next = array(
-                                       'name' => $row['s_name'],
-                                       'date' => Planworld::getRFC3339DateFromTimeStamp($row['last_view']),
-                                       'views' => $row['views'],
-                                       'lastupdate' => Planworld::getRFC3339DateFromTimeStamp($row['last_update']),
-                                       //'inplanwatch' => (bool) $this->planwatch->inPlanwatch($row['s_name'])
-                                       'inplanwatch' => false // DUMMY CODE FIX WHEN PLANWATCH IMPLEMENTED
-                               );
-                               $arrayDicedSnitchViews[] = $next;
-                       }
-                       return $arrayDicedSnitchViews;
-
-               }
-               catch(PDOException $badquery){
-                       return PLANWORLD_ERROR;
-               }
-               return PLANWORLD_ERROR;
-       }
-
-
-       /**
-        * Increment the number of plan views for this user.
-        * @public
-        * @returns int
-        */
-       function addView () {
-               $this->views++;
-               try{
-                       if(!$this->dbh){
-                               throw new PDOException('Database connection not initialized.');
-                       }
-                       $query = $this->dbh->prepare('UPDATE users SET views= :views WHERE id= :uid');
-                       $queryArray = array('views' => $this->views,'uid' => $this->userID);
-                       $query->execute($queryArray);
-               }
-               catch(PDOException $badquery){
-                       return PLANWORLD_ERROR; /* We know if this returns a negative number that something went awry. */
-               }
-               return $this->views;
-       }
-
-
-
-       /**
-        * Add a view by $user to this user's snitch list.
-        * @param user Viewing user.
-        * @returns true (1) on success and -1 (Planworld error) on failure
-        */
-       function addSnitchView (&$user) {
-
-               /* First add an entry to the Snitch Tracker */
-               $intCurrentViews = 0;
-               $intSnitchRows = -1;
-               $suidForAddSnitchView = $user->getUserID();
-               if($suidForAddSnitchView){
-                       /* Check whether a snitch relationship already exists between these One users. This will determine the next query. */
-                       try{
-                               if(!$this->dbh){
-                                       throw new PDOException('Database connection not initialized.');
-                               }
-                               $queryOne = $this->dbh->prepare('SELECT views from snitch where uid=:uid AND s_uid=:s_uid');
-                               $queryOneArray = array('uid' => $this->userID, 's_uid' => $suidForAddSnitchView);
-                               $queryOne->execute($queryOneArray);
-                               $resultOne = $queryOne->fetchall();
-                               if(is_numeric(count($resultOne))){
-                                       $intNewViewCount = 1;
-                                       $intSnitchRows = count($resultOne);
-                                       if($intSnitchRows == 1){
-                                               $intNewViewCount = $resultOne[0]['views'] + 1;
-                                               $queryTwo = $this->dbh->prepare('UPDATE snitch SET last_view=:last_view, views=:views WHERE uid=:uid AND s_uid=:s_uid');
-                                               $queryTwoArray = array('uid' => $this->userID, 's_uid' => $suidForAddSnitchView, 'last_view' => time(), 'views' => $intNewViewCount);
-                                               return $queryTwo->execute($queryTwoArray);
-                                       }
-                                       else if ($intSnitchRows == 0){
-                                                       $queryThree = $this->dbh->prepare('INSERT INTO snitch (uid, s_uid, last_view, views) VALUES (:uid,:s_uid,:last_view,:views)');
-                                                       $queryThreeArray = array('uid' => $this->userID, 's_uid' => $suidForAddSnitchView, 'last_view' => time(), 'views' => $intNewViewCount);
-                                                       return $queryThree->execute($queryThreeArray);
-                                               }
-                                       else{
-                                               return PLANWORLD_ERROR;
-                                       }
-                               }
-                               else{
-                                       return PLANWORLD_ERROR;
-                               }
-                       }
-                       catch(PDOException $badquery){
-                               return PLANWORLD_ERROR;
-                       }
-               }
-               else {
-                       return PLANWORLD_ERROR;
-               }
-       }
-
-
-
-
-       /**
-        * Starts this user's snitch list.
-        * @private
-        * @returns void
-        */
-       function startSnitch () {
-               $this->snitch = true;
-               $this->snitchEnabled = time();
-               $this->changed = true;
-       }
-
-
-
-
-       /**
-        * void setLastLogin ($ts)
-        * update's users last login time to $ts (timestamp)
-        */
-       function setLastLogin ($ts) {
-               $this->changed = true;
-               $this->lastLogin = $ts;
-       }
-
-       /**
-        * void setLastUpdate ($ts)
-        * update's users last update time to $ts (timestamp)
-        */
-       function setLastUpdate ($ts) {
-               $this->changed = true;
-               $this->lastUpdate = $ts;
-       }
-
-       /**
-        * void setLastIP ($ip)
-        * update user's last known ip address
-        */
-       function setLastIP ($ip) {
-               $this->changed = true;
-               $this->last_ip = $ip;
-       }
-
-       /**
-        * Get archive settings.
-        * @public
-        * @returns string
-        */
-       function getArchive () {
-               return $this->archive;
-       }
-
-       /**
-        * Set this user's archival settings
-        * @param val (Y) Public / (P) private / (N) off archiving
-        * @public
-        * @returns bool
-        */
-       function setArchive ($val) {
-               $val = strtoupper($val);
-               if ($val == 'Y' || $val == 'P' || $val == 'N') {
-                       $this->archive = $val;
-                       $this->changed = true;
-                       return true;
-               }
-               else {
-                       return false;
-               }
-       }
-
-       /**
-        * Return the last time this user logged in.
-        * @public
-        * @returns int
-        */
-       function getLastLogin () {
-               return $this->lastLogin;
-       }
-
-       /**
-        * Return the last time this user updated his/her plan.
-        * @public
-        * @returns int
-        */
-       function getLastUpdate () {
-               return $this->lastUpdate;
-       }
-
-
-       /* FLAG FUNCTIONS */
-
-       /**
-        * Is this user an admin?
-        * @public
-        * @returns bool
-        */
-       function isAdmin () {
-               if (!isset($this->admin)) {
-                       $this->admin = $this->getPreference('admin');
-               }
-               return $this->admin;
-       }
-
-
-       /**
-        * Is this user's plan archived?
-        * @public
-        * @returns bool
-        */
-       function isArchived () {
-               return ($this->archive == 'Y' || $this->archive == 'P') ? true : false;
-       }
-
-
-       /**
-        * Is this user's plan archived publicly?
-        * @public
-        * @returns bool
-        */
-       function isArchivedPublicly () {
-               return ($this->archive == 'Y') ? true : false;
-       }
-
-
-       /**
-        * Has this user been changed?
-        * @public
-        * @returns bool
-        */
-       function isChanged () {
-               return $this->changed;
-       }
-
-       /**
-        * Is this user remote?
-        * @public
-        * @returns bool
-        */
-       function isRemoteUser () {
-               return $this->remoteUser;
-       }
-
-       /**
-        * Is this a shared plan?
-        * @public
-        * @returns bool
-        */
-       function isShared () {
-               return $this->getPreference('shared') && $this->shared;
-       }
-
-       /**
-        * Mark this as an actively shared plan (not the logged-in user).
-        */
-       function setShared () {
-               $this->shared = true;
-       }
-
-       /**
-        * Set the user who is editing this shared plan.
-        */
-       function setEditingUser ($user) {
-               $this->editor = $user;
-       }
-
-       /**
-        * Is this shared for $uid to edit?
-        */
-       function isSharedFor (&$uid) {
-               if (is_object($uid)) {
-                       $username = $uid->getUsername();
-               } else if (is_string($uid)) {
-                               $username = $uid;
-                       } else {
-                       return false;
-               }
-               return $this->getPreference('shared') && $this->getPreference('shared_' . $username);
-       }
-
-
-       /**
-        * Return a list of the users for whom this plan is shared.
-        In previous versions this returned a list with newlines. Now it returns an array.
-        It is not called by any library functions -- previously it was called from interface.
-        */
-       function getSharedUsers () {
-               try{
-                       if(!$this->dbh){
-                               throw new PDOException('Database connection not initialized.');
-                       }
-                       $query = $this->dbh->prepare('SELECT name FROM preferences WHERE name LIKE "shared_%" AND uid= :uid');
-                       $queryArray = array('uid' => $this->userID);
-                       $query->execute($queryArray);
-                       $result = $query->fetchAll();
-                       if (!$result){
-                               return PLANWORLD_ERROR;
-                       }
-                       else{
-                               $return = array();
-                               foreach($result as $row){
-                                       $return[] = $row['name'];
-                               }
-                               return $return;
-                       }
-               }
-               catch(PDOException $badquery){
-                       return PLANWORLD_ERROR;
-               }
-               return PLANWORLD_ERROR;
-       }
-
-
-
-       /**
-        * Return a list of users whose plans this user is allowed to edit.
-        */
-
-       function getPermittedPlans () {
-               try{
-                       if(!$this->dbh){
-                               throw new PDOException('Database connection not initialized.');
-                       }
-                       $query = $this->dbh->prepare("SELECT uid, username FROM preferences as p, users as u WHERE p.name= :sharedname AND u.id=p.uid");
-                       $queryArray = array('sharedname' => 'shared_' . $this->username);
-                       $query->execute($queryArray);
-                       $result = $query->fetchAll();
-                       if (!$result){
-                               return false;
-                       }
-                       else{
-                               $return = array();
-                               foreach($result as $row){
-                                       $return[] = $row['username'];
-                               }
-                               return $return;
-                       }
-               }
-               catch(PDOException $badquery){
-                       return false;
-               }
-               return false;
-       }
-
-
-
-
-
-
-       /**
-        * Does this user exist?
-        * @public
-        * @returns bool
-        */
-       function isUser () {
-               if (!isset($this->valid)) {
-                       $planworldJustForIsUser = new Planworld();
-                       $this->valid = $planworldJustForIsUser->isUser($this->username, true);
-               }
-               return $this->valid;
-       }
-
-
-       /**
-        * Is this user's plan world-accessible?
-        * @public
-        * @returns bool
-        */
-       function isWorld () {
-               return $this->getWorld();
-       }
-
-
-       /**
-        * Is this user new? (NPD: for welcome pages)
-        * @public
-        * @returns bool
-        */
-       function isNew() {
-               return !$this->lastUpdate;
-       }
-
-       /**
-        * Get number of users to display on snitch list.
-        * @public
-        * @returns int
-        */
-       function getSnitchDisplayNum () {
-               return $this->snitchDisplayNum;
-       }
-
-       /**
-        * Set number of users to display on snitch list.
-        * @param num Number of users to display
-        * @public
-        * @returns void
-        */
-       function setSnitchDisplayNum ($num) {
-               $this->snitchDisplayNum = $num;
-               $this->changed = true;
-       }
-
-
-       /**
-        * Get this user's preferred timezone.
-        * @public
-        * @returns string
-        */
-       function getTimezone () {
-               return $this->timezone;
-       }
-
-       /**
-        * Set the local timezone for this user.
-        * @param theme Timezone to use
-        * @public
-        * @returns void
-        */
-       function setTimezone ($timezone) {
-               $this->setPreference('timezone', $timezone);
-               $this->timezone = $timezone;
-       }
-
-       /**
-        * Get this user's type
-        * @public
-        * @returns string
-        */
-       function gettype() {
-               return $this->type;
-       }
-
-       /**
-        * Returns this user's userid.
-        * @public
-        * @returns int
-        */
-       function getUserID () {
-               return $this->userID;
-       }
-
-       /**
-        * Returns this user's username.
-        * @public
-        * @returns string
-        */
-       function getUsername () {
-               return addslashes($this->username);
-       }
-
-       /**
-        * Returns this user's planwatch ordering.
-        * @public
-        * @returns string
-        */
-       function getWatchOrder () {
-               return $this->watchOrder;
-       }
-
-       /**
-        * Set this user's planwatch ordering.
-        * @param type Type of ordering
-        * @public
-        * @returns void
-        */
-       function setWatchOrder ($type) {
-               $this->watchOrder = $type;
-               $this->changed = true;
-       }
-
-       /**
-        * Is this user's plan world-accessible?
-        * @public
-        * @returns bool
-        */
-       function getWorld () {
-               return $this->world;
-       }
-
-       /**
-        * Set this user's world-accessibility
-        * @param val True / false world-accessibility
-        * @public
-        * @returns void
-        */
-       function setWorld ($val) {
-               $this->world = $val;
-               $this->changed = true;
-       }
-
-
-       /* The following functions were moved here from the Online library. 20171121 JLO2 */
-
-       function isUserOnline(){
-                                       try{
-                               if(!$this->dbh){
-                                       throw new PDOException('Database connection not initialized.');
-                               }
-                               $query = $this->dbh->prepare('SELECT count(last_access) as onlinecount FROM online where uid=:uid');
-                               $queryArray = array('uid' => $this->userID);
-                               $result = $query->execute($queryArray);
-                                                               if (!$result){
-                                       return false;
-                               }
-                               else{
-                                       $intOnlineCount = (int) $result['onlinecount'];
-                                       if($intOnlineCount > 0){
-                                               return true;
-                                       }
-                                       else{
-                                               return false;
-                                       }
-                               }
-                               return false;
-                       }
-                       catch(PDOException $badquery){
-                               return false;
-                       }
-       }
-
-
-       /* Update the user's online status. If the user is not online, add them. If they are online, update them.
+  function getSnitchViews () {
+    $arrayDicedSnitchViews = array();
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      $query = $this->dbh->prepare('SELECT snitch.s_uid, snitch.last_view, snitch.views, u2.username as s_name, u2.last_update FROM users, snitch LEFT JOIN users as u2 ON snitch.s_uid=u2.id WHERE snitch.uid=:uid AND users.id=:uid AND snitch.last_view > users.snitch_activated ORDER BY u2.last_update');
+      $queryArray = array('uid' => $this->userID);
+      $query->execute($queryArray);
+      $result = $query->fetchall();
+      $this->loadPlanwatch();
+      foreach ($result as $row){
+        $next = array(
+          'name' => $row['s_name'],
+          'date' => Planworld::getRFC3339DateFromTimeStamp($row['last_view']),
+          'views' => $row['views'],
+          'lastupdate' => Planworld::getRFC3339DateFromTimeStamp($row['last_update']),
+          //'inplanwatch' => (bool) $this->planwatch->inPlanwatch($row['s_name'])
+          'inplanwatch' => false // DUMMY CODE FIX WHEN PLANWATCH IMPLEMENTED
+        );
+        $arrayDicedSnitchViews[] = $next;
+      }
+      return $arrayDicedSnitchViews;
+
+    }
+    catch(PDOException $badquery){
+      return PLANWORLD_ERROR;
+    }
+    return PLANWORLD_ERROR;
+  }
+
+
+  /**
+   * Increment the number of plan views for this user.
+   * @public
+   * @returns int
+   */
+  function addView () {
+    $this->views++;
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      $query = $this->dbh->prepare('UPDATE users SET views= :views WHERE id= :uid');
+      $queryArray = array('views' => $this->views,'uid' => $this->userID);
+      $query->execute($queryArray);
+    }
+    catch(PDOException $badquery){
+      return PLANWORLD_ERROR; /* We know if this returns a negative number that something went awry. */
+    }
+    return $this->views;
+  }
+
+
+
+  /**
+   * Add a view by $user to this user's snitch list.
+   * @param user Viewing user.
+   * @returns true (1) on success and -1 (Planworld error) on failure
+   */
+  function addSnitchView (&$user) {
+
+    /* First add an entry to the Snitch Tracker */
+    $intCurrentViews = 0;
+    $intSnitchRows = -1;
+    $suidForAddSnitchView = $user->getUserID();
+    if($suidForAddSnitchView){
+      /* Check whether a snitch relationship already exists between these One users. This will determine the next query. */
+      try{
+        if(!$this->dbh){
+          throw new PDOException('Database connection not initialized.');
+        }
+        $queryOne = $this->dbh->prepare('SELECT views from snitch where uid=:uid AND s_uid=:s_uid');
+        $queryOneArray = array('uid' => $this->userID, 's_uid' => $suidForAddSnitchView);
+        $queryOne->execute($queryOneArray);
+        $resultOne = $queryOne->fetchall();
+        if(is_numeric(count($resultOne))){
+          $intNewViewCount = 1;
+          $intSnitchRows = count($resultOne);
+          if($intSnitchRows == 1){
+            $intNewViewCount = $resultOne[0]['views'] + 1;
+            $queryTwo = $this->dbh->prepare('UPDATE snitch SET last_view=:last_view, views=:views WHERE uid=:uid AND s_uid=:s_uid');
+            $queryTwoArray = array('uid' => $this->userID, 's_uid' => $suidForAddSnitchView, 'last_view' => time(), 'views' => $intNewViewCount);
+            return $queryTwo->execute($queryTwoArray);
+          }
+          else if ($intSnitchRows == 0){
+              $queryThree = $this->dbh->prepare('INSERT INTO snitch (uid, s_uid, last_view, views) VALUES (:uid,:s_uid,:last_view,:views)');
+              $queryThreeArray = array('uid' => $this->userID, 's_uid' => $suidForAddSnitchView, 'last_view' => time(), 'views' => $intNewViewCount);
+              return $queryThree->execute($queryThreeArray);
+            }
+          else{
+            return PLANWORLD_ERROR;
+          }
+        }
+        else{
+          return PLANWORLD_ERROR;
+        }
+      }
+      catch(PDOException $badquery){
+        return PLANWORLD_ERROR;
+      }
+    }
+    else {
+      return PLANWORLD_ERROR;
+    }
+  }
+
+
+
+
+  /**
+   * Starts this user's snitch list.
+   * @private
+   * @returns void
+   */
+  function startSnitch () {
+    $this->snitch = true;
+    $this->snitchEnabled = time();
+    $this->changed = true;
+  }
+
+
+
+
+  /**
+   * void setLastLogin ($ts)
+   * update's users last login time to $ts (timestamp)
+   */
+  function setLastLogin ($ts) {
+    $this->changed = true;
+    $this->lastLogin = $ts;
+  }
+
+  /**
+   * void setLastUpdate ($ts)
+   * update's users last update time to $ts (timestamp)
+   */
+  function setLastUpdate ($ts) {
+    $this->changed = true;
+    $this->lastUpdate = $ts;
+  }
+
+  /**
+   * void setLastIP ($ip)
+   * update user's last known ip address
+   */
+  function setLastIP ($ip) {
+    $this->changed = true;
+    $this->last_ip = $ip;
+  }
+
+  /**
+   * Get archive settings.
+   * @public
+   * @returns string
+   */
+  function getArchive () {
+    return $this->archive;
+  }
+
+  /**
+   * Set this user's archival settings
+   * @param val (Y) Public / (P) private / (N) off archiving
+   * @public
+   * @returns bool
+   */
+  function setArchive ($val) {
+    $val = strtoupper($val);
+    if ($val == 'Y' || $val == 'P' || $val == 'N') {
+      $this->archive = $val;
+      $this->changed = true;
+      return true;
+    }
+    else {
+      return false;
+    }
+  }
+
+  /**
+   * Return the last time this user logged in.
+   * @public
+   * @returns int
+   */
+  function getLastLogin () {
+    return $this->lastLogin;
+  }
+
+  /**
+   * Return the last time this user updated his/her plan.
+   * @public
+   * @returns int
+   */
+  function getLastUpdate () {
+    return $this->lastUpdate;
+  }
+
+
+  /* FLAG FUNCTIONS */
+
+  /**
+   * Is this user an admin?
+   * @public
+   * @returns bool
+   */
+  function isAdmin () {
+    if (!isset($this->admin)) {
+      $this->admin = $this->getPreference('admin');
+    }
+    return $this->admin;
+  }
+
+
+  /**
+   * Is this user's plan archived?
+   * @public
+   * @returns bool
+   */
+  function isArchived () {
+    return ($this->archive == 'Y' || $this->archive == 'P') ? true : false;
+  }
+
+
+  /**
+   * Is this user's plan archived publicly?
+   * @public
+   * @returns bool
+   */
+  function isArchivedPublicly () {
+    return ($this->archive == 'Y') ? true : false;
+  }
+
+
+  /**
+   * Has this user been changed?
+   * @public
+   * @returns bool
+   */
+  function isChanged () {
+    return $this->changed;
+  }
+
+  /**
+   * Is this user remote?
+   * @public
+   * @returns bool
+   */
+  function isRemoteUser () {
+    return $this->remoteUser;
+  }
+
+  /**
+   * Is this a shared plan?
+   * @public
+   * @returns bool
+   */
+  function isShared () {
+    return $this->getPreference('shared') && $this->shared;
+  }
+
+  /**
+   * Mark this as an actively shared plan (not the logged-in user).
+   */
+  function setShared () {
+    $this->shared = true;
+  }
+
+  /**
+   * Set the user who is editing this shared plan.
+   */
+  function setEditingUser ($user) {
+    $this->editor = $user;
+  }
+
+  /**
+   * Is this shared for $uid to edit?
+   */
+  function isSharedFor (&$uid) {
+    if (is_object($uid)) {
+      $username = $uid->getUsername();
+    } else if (is_string($uid)) {
+        $username = $uid;
+      } else {
+      return false;
+    }
+    return $this->getPreference('shared') && $this->getPreference('shared_' . $username);
+  }
+
+
+  /**
+   * Return a list of the users for whom this plan is shared.
+   In previous versions this returned a list with newlines. Now it returns an array.
+   It is not called by any library functions -- previously it was called from interface.
+   */
+  function getSharedUsers () {
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      $query = $this->dbh->prepare('SELECT name FROM preferences WHERE name LIKE "shared_%" AND uid= :uid');
+      $queryArray = array('uid' => $this->userID);
+      $query->execute($queryArray);
+      $result = $query->fetchAll();
+      if (!$result){
+        return PLANWORLD_ERROR;
+      }
+      else{
+        $return = array();
+        foreach($result as $row){
+          $return[] = $row['name'];
+        }
+        return $return;
+      }
+    }
+    catch(PDOException $badquery){
+      return PLANWORLD_ERROR;
+    }
+    return PLANWORLD_ERROR;
+  }
+
+
+
+  /**
+   * Return a list of users whose plans this user is allowed to edit.
+   */
+
+  function getPermittedPlans () {
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      $query = $this->dbh->prepare("SELECT uid, username FROM preferences as p, users as u WHERE p.name= :sharedname AND u.id=p.uid");
+      $queryArray = array('sharedname' => 'shared_' . $this->username);
+      $query->execute($queryArray);
+      $result = $query->fetchAll();
+      if (!$result){
+        return false;
+      }
+      else{
+        $return = array();
+        foreach($result as $row){
+          $return[] = $row['username'];
+        }
+        return $return;
+      }
+    }
+    catch(PDOException $badquery){
+      return false;
+    }
+    return false;
+  }
+
+
+
+
+
+
+  /**
+   * Does this user exist?
+   * @public
+   * @returns bool
+   */
+  function isUser () {
+    if (!isset($this->valid)) {
+      $planworldJustForIsUser = new Planworld();
+      $this->valid = $planworldJustForIsUser->isUser($this->username, true);
+    }
+    return $this->valid;
+  }
+
+
+  /**
+   * Is this user's plan world-accessible?
+   * @public
+   * @returns bool
+   */
+  function isWorld () {
+    return $this->getWorld();
+  }
+
+
+  /**
+   * Is this user new? (NPD: for welcome pages)
+   * @public
+   * @returns bool
+   */
+  function isNew() {
+    return !$this->lastUpdate;
+  }
+
+  /**
+   * Get number of users to display on snitch list.
+   * @public
+   * @returns int
+   */
+  function getSnitchDisplayNum () {
+    return $this->snitchDisplayNum;
+  }
+
+  /**
+   * Set number of users to display on snitch list.
+   * @param num Number of users to display
+   * @public
+   * @returns void
+   */
+  function setSnitchDisplayNum ($num) {
+    $this->snitchDisplayNum = $num;
+    $this->changed = true;
+  }
+
+
+  /**
+   * Get this user's preferred timezone.
+   * @public
+   * @returns string
+   */
+  function getTimezone () {
+    return $this->timezone;
+  }
+
+  /**
+   * Set the local timezone for this user.
+   * @param theme Timezone to use
+   * @public
+   * @returns void
+   */
+  function setTimezone ($timezone) {
+    $this->setPreference('timezone', $timezone);
+    $this->timezone = $timezone;
+  }
+
+  /**
+   * Get this user's type
+   * @public
+   * @returns string
+   */
+  function gettype() {
+    return $this->type;
+  }
+
+  /**
+   * Returns this user's userid.
+   * @public
+   * @returns int
+   */
+  function getUserID () {
+    return $this->userID;
+  }
+
+  /**
+   * Returns this user's username.
+   * @public
+   * @returns string
+   */
+  function getUsername () {
+    return addslashes($this->username);
+  }
+
+  /**
+   * Returns this user's planwatch ordering.
+   * @public
+   * @returns string
+   */
+  function getWatchOrder () {
+    return $this->watchOrder;
+  }
+
+  /**
+   * Set this user's planwatch ordering.
+   * @param type Type of ordering
+   * @public
+   * @returns void
+   */
+  function setWatchOrder ($type) {
+    $this->watchOrder = $type;
+    $this->changed = true;
+  }
+
+  /**
+   * Is this user's plan world-accessible?
+   * @public
+   * @returns bool
+   */
+  function getWorld () {
+    return $this->world;
+  }
+
+  /**
+   * Set this user's world-accessibility
+   * @param val True / false world-accessibility
+   * @public
+   * @returns void
+   */
+  function setWorld ($val) {
+    $this->world = $val;
+    $this->changed = true;
+  }
+
+
+  /* The following functions were moved here from the Online library. 20171121 JLO2 */
+
+  function isUserOnline(){
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      $query = $this->dbh->prepare('SELECT count(last_access) as onlinecount FROM online where uid=:uid');
+      $queryArray = array('uid' => $this->userID);
+      $result = $query->execute($queryArray);
+      if (!$result){
+        return false;
+      }
+      else{
+        $intOnlineCount = (int) $result['onlinecount'];
+        if($intOnlineCount > 0){
+          return true;
+        }
+        else{
+          return false;
+        }
+      }
+      return false;
+    }
+    catch(PDOException $badquery){
+      return false;
+    }
+  }
+
+
+  /* Update the user's online status. If the user is not online, add them. If they are online, update them.
                Set last login based on the user's current token. This last would need to change if we stop using tokens. */
-       function userOnline($stringWhatUserIsDoing = ''){
-                       try{
-                               if(!$this->dbh){
-                                       throw new PDOException('Database connection not initialized.');
-                               }
-
-                               if($this->isUserOnline()){
-
-                               }
-                               else{
-
-                               }
-                       }
-                       catch(PDOException $badquery){
-                               return false;
-                       }
-       }
-
-
-       /* Sets the user to offline (i.e. removes them from the Online table. */
-       function userOffline(){
-                       try{
-                               if(!$this->dbh){
-                                       throw new PDOException('Database connection not initialized.');
-                               }
-                               $query = $this->dbh->prepare('DELETE FROM online WHERE uid=:uid');
-                               $queryArray = array('uid' => $this->userID);
-                               return $query->execute($queryArray);
-                       }
-                       catch(PDOException $badquery){
-                               return false;
-                       }
-       }
-
-
-       /* END CLASS */
+  function userOnline($stringWhatUserIsDoing = ''){
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+
+      if($this->isUserOnline()){
+
+      }
+      else{
+
+      }
+    }
+    catch(PDOException $badquery){
+      return false;
+    }
+  }
+
+
+  /* Sets the user to offline (i.e. removes them from the Online table. */
+  function userOffline(){
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      $query = $this->dbh->prepare('DELETE FROM online WHERE uid=:uid');
+      $queryArray = array('uid' => $this->userID);
+      return $query->execute($queryArray);
+    }
+    catch(PDOException $badquery){
+      return false;
+    }
+  }
+
+
+
+
+  /**
+   * JLO2 20191005 - A simplified form of getPlan that does not support the Archive pieces.
+   * Implemented so that we would have enough functionality to start building v3 around.
+   */
+  function getPlanSimple (&$user) {
+    if ($user->getUserID() != $this->userID) {
+      $this->addView();
+      // VERY IMPORTANT TO ADD THIS BACK IN WHEN IMPLEMENTING ARCHIVE JLO2 20191005
+      //Archive::addView($this->userID, $this->lastUpdate);
+      /* check for mutual snitch registration */
+      if ($user->getSnitch() && $this->snitch) {
+        $this->addSnitchView($user);
+      }
+    }
+    if (!isset($this->plan)) {
+      try{
+        if(!$this->dbh){
+          throw new PDOException('Database connection not initialized.');
+        }
+        $query = $this->dbh->prepare("SELECT content FROM plans WHERE uid=:uid");
+        $queryArray = array('uid' => $this->userID);
+        $query->execute($queryArray);
+        $result = $query->fetch();
+        if (!$result){
+          return '';
+        }
+        else{
+          return $result['content'];
+        }
+      }
+      catch(PDOException $badquery){
+        return '';
+      }
+    }
+  }
+
+
+   /**
+   * JLO2 20191005 - A simplified form of setPlan that does not support the Archive pieces, drafts, or journaling.
+   * Implemented so that we would have enough functionality to start building v3 around.
+   */
+  function setPlanSimple ($plan) {
+    $boolSuccess = true;
+      $timestamp = mktime();
+    $oldplan = $this->getPlanSimple($this);
+
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      $query1 = $this->dbh->prepare('DELETE FROM plans WHERE uid=:uid');
+      $queryArray1 = array('uid' => $this->userID);
+      $boolSuccess = $query1->execute($queryArray1);
+    }
+    catch(PDOException $badquery1){
+      return 'BLUEBERRY';
+    }
+
+    /* process snoop references */
+    $thisSnoop = new Snoop();
+    $boolSuccess = $boolSuccess && $thisSnoop->process($this, $plan, $oldplan);
+
+    try{
+      if(!$this->dbh){
+        throw new PDOException('Database connection not initialized.');
+      }
+      $query2 = $this->dbh->prepare('INSERT INTO plans (uid, content) VALUES (:uid, :plan)');
+      $queryArray2 = array('uid' => $this->userID, 'plan' =>$plan);
+      $boolSuccess = $boolSuccess && $query2->execute($queryArray2);
+    }
+    catch(PDOException $badquery1){
+      return false;
+    }
+    return $boolSuccess;
+  }
+
+
+
+  /* JLO2 20190830 as of today here are the functions I think are missing.
+  Not all of them need to be implemented, but certainly the Snitch and Snoop bits
+  Then we can actually, you know, display a plan.
+
+  function clearPlan () {
+function clearSnitchTracker () {
+function deleteDrafts() {
+function displayPlan (&$user, $plan=null, $ts=null) {
+function dump () {
+function getLatestDraft() {
+function getPlan (&$user, $ts=null) {
+function getSharedUsers () {
+function getSnitchTracker () {
+function getSnitchTrackerEntries () {
+function getSnitchViews () {
+function getSnitchViews ($order='d', $dir='d') {
+function getSnoopRefs () {
+function getTheme () {
+function getType () {
+function gettype() {
+function getYear() {
+function hasDraft() {
+function hasOldUsername()
+function isUserOnline(){
+function load () {
+function load(){
+function oldUsername()
+function previewPlan (&$user, $plan) {
+function repostPlan () {
+function saveDraft($text) {
+function setPlan ($plan, $archive='N', $name = '', $timestamp = null) {
+function setSnitchTracker ($val) {
+function setTheme ($theme) {
+function showSharedUsers () {
+function User ($uid) {
+function userOffline(){
+function userOnline($stringWhatUserIsDoing = ''){
+*/
+
+
+
+
+
+  /* END CLASS */
 }
 ?>
\ No newline at end of file
index 0bd7783..5160c83 100644 (file)
                <tr><td>Category<br><select name="category" />
                        <option selected value="system">system</option>
                        <option value="send">send</option>
+                       <option value="watchlist">watchlist</option>
+                       <option value="plan">plan</option>
                </select></td></tr>
                <tr><td>Planworld Noun<br><select name="planNoun" />
                        <option value="version">version (get only)</option>
+                       <option value="userslocal">userslocal (get only)</option>
+                       <option value="plan">plan (get and post)</option>
                        <option value="send">send (get and post)</option>
                        <option value="sendlist">sendlist (get only)</option>
+                       <option value="watchlist">watchlist (get only)</option>
+                       <option value="watchlistgroup">watchlistgroups (get only)</option>
+                       <option value="groupcreate">groupcreate (post only)</option>
+                       <option value="groupmoveuser">groupmoveuser (post only)</option>
+                       <option value="add">add (post only)</option>
+
                </select></td></tr>
                <tr><td>Argument 1<br><input type="text" name="arg1" /></td></tr>
                <tr><td>Argument 2<br><input type="text" name="arg2" /></td></tr>
diff --git a/description b/description
deleted file mode 100644 (file)
index 3daf02b..0000000
+++ /dev/null
@@ -1 +0,0 @@
-Public Git Repository for Work on NOTE implemenation of Planworld.
index 8c28dec..4ec6d1e 100644 (file)
@@ -7,9 +7,12 @@ _Releases in V3.00 Alpha Series_
 20170406 - "Louisbourg" - Send Only Release Without Clients
 20180409 - "Loudon" - Fixed sendlist db query. Also make a note -- PHP 5.5 or later is required. Need to eliminate old JSON file and depedency.
 MAKE ANOTHER NOTE -- The NOTE Production Database contains invalid usernames. We filter for this in PW->getallusers, but in the future we should have a cleaner process to eliminate them. ALSO getallusers is part of scaffolding and the API userslocalGet call but it doesn't return all users now, just the local ones who are properly formatted.
+20191005 - "Gordon" - Interim Release to get watchlist and basic plan-handling functionality as well as other improvements out to potential programmers before testing is finished. Necessitated by some discussion of how blocklists will be implemented. 
 
 _License_
 This release does not yet include proper attribution for authors (Seth Fitzsimmons, Baker Franke, Johnnie Odom et al) but it is licensed using the GPLv2 as the previous version was. Future releases will more properly note this.
+As of October 2019 this software uses HTML Purifier (  )
+
 
 _Introduction_
 Use these instructions to set up an independent test instance of the in-progress Planworld v3 code for testing and client development. It contains only a tiny portion of the full Planworld functionality, and the code is not as well-documented or cleaned up as it will be by release. The instructions are clear to me (jlodom00), but I deal with this sort of thing all the time so feel free to reach out ( jlodom00@alumni.amherst.edu ) if you need help.
@@ -63,7 +66,7 @@ VERSION: 0.00/
        
 CATEGORY: category/
 
-       This portion of the path is meant to make grouping planworld calls/functions/verbs easier, especially for those implementing the engine. If you have trouble making an API call, (especially using the debug client), check to make sure that this value is correct for the verb that is being called. Current values are "system" and "send".
+       This portion of the path is meant to make grouping planworld calls/functions/verbs easier, especially for those implementing the engine. If you have trouble making an API call, (especially using the debug client), check to make sure that this value is correct for the verb that is being called. Current values are "system", "send", "watchlist", and "plan".
        
 VERB: verb/
        This is the actual verb or planworld function being called. These have different properties depending upon whether information is being retrieved (GET) or sent (POST) and the same verb may perform both roles. Current values are "version" (pairing with the "system" category), "send", and "sendlist" (both pairing with the "send" category). Of the four verbs listed, all support GET but only "send" supports POST.
@@ -90,7 +93,19 @@ Category - Send (Tokens required for all)
        send : GET Returns the full send conversation between the user and another user. Takes one argument -- the username of the other user in the conversation.
        send : POST Send a new message to another user. Takes one argument -- the username of the other user in the conversation.       
        sendlist : GET Returns a list of every user with whom the current user has had a send conversation (similar to a watchlist). No arguments.
+
+Category - Plan (Tokens required for all)
+       plan : GET Returns a user's plan. Takes one argument -- the username of the plan to be read.
+               : POST Returns a boolean indicating success or failure. Deletes a user's current plan and replaces it with the data in the POST. The plan data should be in HTML format (this could encompass plain text).
        
+Category - Watchlist (Tokens required for all)
+[NOTE: These calls are not well-documented and the POST versions have not been tested.]
+       watchlist : GET Returns a user's full watchlist.
+       watchlistgroup : GET Returns the same data as watchlist but in groups
+       groupcreate : POST Creates a watchlist group. The post data should be empty. Takes one URL argument -- the name of the group to be created.
+       groupmoveuser : POST Moves a user to a specified watchlist group. The post data should be empty. Takes two URL arguments -- the name of the user and the name of the group.
+       add: POST POST Adds a user to a watchlist group. The post data should be empty. Takes one URL argument -- the username to be added.
+
 *Writing a Client*
 
 For this alpha release, you will need to create a user and a token for that user before client calls can be made because there is no way to create tokens through the client API. Clients may be written on any platform and in any programming language -- as long as they can make GET and POST HTTP calls to the API URLs. The API is a REST API and generally conforms to the conventions established by that style.