]> git.mjollnir.org Git - moodle.git/commitdiff
MDL-17099 htmlpurifier: new version from upstream
authorskodak <skodak>
Sat, 1 Nov 2008 18:58:29 +0000 (18:58 +0000)
committerskodak <skodak>
Sat, 1 Nov 2008 18:58:29 +0000 (18:58 +0000)
139 files changed:
lib/htmlpurifier/HTMLPurifier.php
lib/htmlpurifier/HTMLPurifier.safe-includes.php
lib/htmlpurifier/HTMLPurifier/AttrDef/HTML/LinkTypes.php
lib/htmlpurifier/HTMLPurifier/AttrTransform/Background.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/AttrTransform/ImgRequired.php
lib/htmlpurifier/HTMLPurifier/AttrTransform/Input.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/AttrTransform/Textarea.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/AttrTypes.php
lib/htmlpurifier/HTMLPurifier/AttrValidator.php
lib/htmlpurifier/HTMLPurifier/ChildDef.php
lib/htmlpurifier/HTMLPurifier/ChildDef/Custom.php
lib/htmlpurifier/HTMLPurifier/ChildDef/StrictBlockquote.php
lib/htmlpurifier/HTMLPurifier/Config.php
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema.ser
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormatParam.PurifierLinkifyDocURL.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormatParam.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/CSS.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Cache.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.Language.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Core.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Filter.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/FilterParam.ExtractStyleBlocksEscaping.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/FilterParam.ExtractStyleBlocksScope.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/HTML.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Test.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Base.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Host.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt
lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/URI.txt
lib/htmlpurifier/HTMLPurifier/ContentSets.php
lib/htmlpurifier/HTMLPurifier/DefinitionCache/Decorator/Template.php.in
lib/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/README [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/Encoder.php
lib/htmlpurifier/HTMLPurifier/ErrorCollector.php
lib/htmlpurifier/HTMLPurifier/ErrorStruct.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/Generator.php
lib/htmlpurifier/HTMLPurifier/HTMLModule/Forms.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/HTMLModule/Name.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/HTMLModule/Object.php
lib/htmlpurifier/HTMLPurifier/HTMLModule/Tidy/Name.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/HTMLModule/Tidy/Proprietary.php
lib/htmlpurifier/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php
lib/htmlpurifier/HTMLPurifier/HTMLModuleManager.php
lib/htmlpurifier/HTMLPurifier/Injector.php
lib/htmlpurifier/HTMLPurifier/Injector/AutoParagraph.php
lib/htmlpurifier/HTMLPurifier/Injector/DisplayLinkURI.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/Injector/RemoveEmpty.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/Injector/SafeObject.php
lib/htmlpurifier/HTMLPurifier/Language/messages/en.php
lib/htmlpurifier/HTMLPurifier/Lexer.php
lib/htmlpurifier/HTMLPurifier/Lexer/DOMLex.php
lib/htmlpurifier/HTMLPurifier/Lexer/DirectLex.php
lib/htmlpurifier/HTMLPurifier/Lexer/PH5P.php
lib/htmlpurifier/HTMLPurifier/Strategy/MakeWellFormed.php
lib/htmlpurifier/HTMLPurifier/Strategy/RemoveForeignElements.php
lib/htmlpurifier/HTMLPurifier/StringHashParser.php
lib/htmlpurifier/HTMLPurifier/Token.php
lib/htmlpurifier/HTMLPurifier/Token/Comment.php
lib/htmlpurifier/HTMLPurifier/Token/End.php
lib/htmlpurifier/HTMLPurifier/Token/Tag.php
lib/htmlpurifier/HTMLPurifier/Token/Text.php
lib/htmlpurifier/HTMLPurifier/URIFilter/DisableExternal.php
lib/htmlpurifier/HTMLPurifier/URIFilter/MakeAbsolute.php
lib/htmlpurifier/HTMLPurifier/URIFilter/Munge.php
lib/htmlpurifier/HTMLPurifier/UnitConverter.php
lib/htmlpurifier/readme_moodle.txt

index da2269dab48cfab6e6fa1a3698d9a9cbd43ac61c..629f3b269386b9c42e1aeabf51650a1cda0cc9f5 100644 (file)
@@ -19,7 +19,7 @@
  */
 
 /*
-    HTML Purifier 3.1.1 - Standards Compliant HTML Filtering
+    HTML Purifier 3.2.0 - Standards Compliant HTML Filtering
     Copyright (C) 2006-2008 Edward Z. Yang
 
     This library is free software; you can redistribute it and/or
@@ -55,10 +55,10 @@ class HTMLPurifier
 {
     
     /** Version of HTML Purifier */
-    public $version = '3.1.1';
+    public $version = '3.2.0';
     
     /** Constant with version of HTML Purifier */
-    const VERSION = '3.1.1';
+    const VERSION = '3.2.0';
     
     /** Global configuration object */
     public $config;
index 42acd76bbb31d409fd33574fa6e7cfa442cec0cc..05cc0a3c33f3ec16ece30259a6c0726d9b7caf37 100644 (file)
-<?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. This is a convenience stub that\r
- * includes all files using dirname(__FILE__) and require_once. PLEASE DO NOT\r
- * EDIT THIS FILE, changes will be overwritten the next time the script is run.\r
- * \r
- * Changes to include_path are not necessary.\r
- */\r
-\r
-$__dir = dirname(__FILE__);\r
-\r
-require_once $__dir . '/HTMLPurifier.php';\r
-require_once $__dir . '/HTMLPurifier/AttrCollections.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTypes.php';\r
-require_once $__dir . '/HTMLPurifier/AttrValidator.php';\r
-require_once $__dir . '/HTMLPurifier/Bootstrap.php';\r
-require_once $__dir . '/HTMLPurifier/Definition.php';\r
-require_once $__dir . '/HTMLPurifier/CSSDefinition.php';\r
-require_once $__dir . '/HTMLPurifier/ChildDef.php';\r
-require_once $__dir . '/HTMLPurifier/Config.php';\r
-require_once $__dir . '/HTMLPurifier/ConfigSchema.php';\r
-require_once $__dir . '/HTMLPurifier/ContentSets.php';\r
-require_once $__dir . '/HTMLPurifier/Context.php';\r
-require_once $__dir . '/HTMLPurifier/DefinitionCache.php';\r
-require_once $__dir . '/HTMLPurifier/DefinitionCacheFactory.php';\r
-require_once $__dir . '/HTMLPurifier/Doctype.php';\r
-require_once $__dir . '/HTMLPurifier/DoctypeRegistry.php';\r
-require_once $__dir . '/HTMLPurifier/ElementDef.php';\r
-require_once $__dir . '/HTMLPurifier/Encoder.php';\r
-require_once $__dir . '/HTMLPurifier/EntityLookup.php';\r
-require_once $__dir . '/HTMLPurifier/EntityParser.php';\r
-require_once $__dir . '/HTMLPurifier/ErrorCollector.php';\r
-require_once $__dir . '/HTMLPurifier/Exception.php';\r
-require_once $__dir . '/HTMLPurifier/Filter.php';\r
-require_once $__dir . '/HTMLPurifier/Generator.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLDefinition.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModuleManager.php';\r
-require_once $__dir . '/HTMLPurifier/IDAccumulator.php';\r
-require_once $__dir . '/HTMLPurifier/Injector.php';\r
-require_once $__dir . '/HTMLPurifier/Language.php';\r
-require_once $__dir . '/HTMLPurifier/LanguageFactory.php';\r
-require_once $__dir . '/HTMLPurifier/Length.php';\r
-require_once $__dir . '/HTMLPurifier/Lexer.php';\r
-require_once $__dir . '/HTMLPurifier/PercentEncoder.php';\r
-require_once $__dir . '/HTMLPurifier/Strategy.php';\r
-require_once $__dir . '/HTMLPurifier/StringHash.php';\r
-require_once $__dir . '/HTMLPurifier/StringHashParser.php';\r
-require_once $__dir . '/HTMLPurifier/TagTransform.php';\r
-require_once $__dir . '/HTMLPurifier/Token.php';\r
-require_once $__dir . '/HTMLPurifier/TokenFactory.php';\r
-require_once $__dir . '/HTMLPurifier/URI.php';\r
-require_once $__dir . '/HTMLPurifier/URIDefinition.php';\r
-require_once $__dir . '/HTMLPurifier/URIFilter.php';\r
-require_once $__dir . '/HTMLPurifier/URIParser.php';\r
-require_once $__dir . '/HTMLPurifier/URIScheme.php';\r
-require_once $__dir . '/HTMLPurifier/URISchemeRegistry.php';\r
-require_once $__dir . '/HTMLPurifier/UnitConverter.php';\r
-require_once $__dir . '/HTMLPurifier/VarParser.php';\r
-require_once $__dir . '/HTMLPurifier/VarParserException.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/Enum.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/Integer.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/Lang.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/Switch.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/Text.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/URI.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Number.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/AlphaValue.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Background.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Border.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Color.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Composite.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Filter.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Font.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/FontFamily.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Length.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/ListStyle.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Multiple.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Percentage.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/TextDecoration.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/CSS/URI.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Bool.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Color.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/HTML/FrameTarget.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/HTML/ID.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Pixels.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Length.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/HTML/LinkTypes.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/HTML/MultiLength.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Nmtokens.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/URI/Email.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/URI/Host.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/URI/IPv4.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/URI/IPv6.php';\r
-require_once $__dir . '/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/BdoDir.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/BgColor.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/BoolToCSS.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/Border.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/EnumToCSS.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/ImgRequired.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/ImgSpace.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/Lang.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/Length.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/Name.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/SafeEmbed.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/SafeObject.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/SafeParam.php';\r
-require_once $__dir . '/HTMLPurifier/AttrTransform/ScriptRequired.php';\r
-require_once $__dir . '/HTMLPurifier/ChildDef/Chameleon.php';\r
-require_once $__dir . '/HTMLPurifier/ChildDef/Custom.php';\r
-require_once $__dir . '/HTMLPurifier/ChildDef/Empty.php';\r
-require_once $__dir . '/HTMLPurifier/ChildDef/Required.php';\r
-require_once $__dir . '/HTMLPurifier/ChildDef/Optional.php';\r
-require_once $__dir . '/HTMLPurifier/ChildDef/StrictBlockquote.php';\r
-require_once $__dir . '/HTMLPurifier/ChildDef/Table.php';\r
-require_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator.php';\r
-require_once $__dir . '/HTMLPurifier/DefinitionCache/Null.php';\r
-require_once $__dir . '/HTMLPurifier/DefinitionCache/Serializer.php';\r
-require_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php';\r
-require_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator/Memory.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Bdo.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/CommonAttributes.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Edit.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Hypertext.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Image.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Legacy.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/List.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Object.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Presentation.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Proprietary.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Ruby.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/SafeEmbed.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/SafeObject.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Scripting.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/StyleAttribute.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Tables.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Target.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Text.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/XMLCommonAttributes.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Proprietary.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Strict.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Transitional.php';\r
-require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/XHTML.php';\r
-require_once $__dir . '/HTMLPurifier/Injector/AutoParagraph.php';\r
-require_once $__dir . '/HTMLPurifier/Injector/Linkify.php';\r
-require_once $__dir . '/HTMLPurifier/Injector/PurifierLinkify.php';\r
-require_once $__dir . '/HTMLPurifier/Injector/SafeObject.php';\r
-require_once $__dir . '/HTMLPurifier/Lexer/DOMLex.php';\r
-require_once $__dir . '/HTMLPurifier/Lexer/DirectLex.php';\r
-require_once $__dir . '/HTMLPurifier/Strategy/Composite.php';\r
-require_once $__dir . '/HTMLPurifier/Strategy/Core.php';\r
-require_once $__dir . '/HTMLPurifier/Strategy/FixNesting.php';\r
-require_once $__dir . '/HTMLPurifier/Strategy/MakeWellFormed.php';\r
-require_once $__dir . '/HTMLPurifier/Strategy/RemoveForeignElements.php';\r
-require_once $__dir . '/HTMLPurifier/Strategy/ValidateAttributes.php';\r
-require_once $__dir . '/HTMLPurifier/TagTransform/Font.php';\r
-require_once $__dir . '/HTMLPurifier/TagTransform/Simple.php';\r
-require_once $__dir . '/HTMLPurifier/Token/Comment.php';\r
-require_once $__dir . '/HTMLPurifier/Token/Tag.php';\r
-require_once $__dir . '/HTMLPurifier/Token/Empty.php';\r
-require_once $__dir . '/HTMLPurifier/Token/End.php';\r
-require_once $__dir . '/HTMLPurifier/Token/Start.php';\r
-require_once $__dir . '/HTMLPurifier/Token/Text.php';\r
-require_once $__dir . '/HTMLPurifier/URIFilter/DisableExternal.php';\r
-require_once $__dir . '/HTMLPurifier/URIFilter/DisableExternalResources.php';\r
-require_once $__dir . '/HTMLPurifier/URIFilter/HostBlacklist.php';\r
-require_once $__dir . '/HTMLPurifier/URIFilter/MakeAbsolute.php';\r
-require_once $__dir . '/HTMLPurifier/URIFilter/Munge.php';\r
-require_once $__dir . '/HTMLPurifier/URIScheme/ftp.php';\r
-require_once $__dir . '/HTMLPurifier/URIScheme/http.php';\r
-require_once $__dir . '/HTMLPurifier/URIScheme/https.php';\r
-require_once $__dir . '/HTMLPurifier/URIScheme/mailto.php';\r
-require_once $__dir . '/HTMLPurifier/URIScheme/news.php';\r
-require_once $__dir . '/HTMLPurifier/URIScheme/nntp.php';\r
-require_once $__dir . '/HTMLPurifier/VarParser/Flexible.php';\r
-require_once $__dir . '/HTMLPurifier/VarParser/Native.php';\r
+<?php
+
+/**
+ * @file
+ * This file was auto-generated by generate-includes.php and includes all of
+ * the core files required by HTML Purifier. This is a convenience stub that
+ * includes all files using dirname(__FILE__) and require_once. PLEASE DO NOT
+ * EDIT THIS FILE, changes will be overwritten the next time the script is run.
+ * 
+ * Changes to include_path are not necessary.
+ */
+
+$__dir = dirname(__FILE__);
+
+require_once $__dir . '/HTMLPurifier.php';
+require_once $__dir . '/HTMLPurifier/AttrCollections.php';
+require_once $__dir . '/HTMLPurifier/AttrDef.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform.php';
+require_once $__dir . '/HTMLPurifier/AttrTypes.php';
+require_once $__dir . '/HTMLPurifier/AttrValidator.php';
+require_once $__dir . '/HTMLPurifier/Bootstrap.php';
+require_once $__dir . '/HTMLPurifier/Definition.php';
+require_once $__dir . '/HTMLPurifier/CSSDefinition.php';
+require_once $__dir . '/HTMLPurifier/ChildDef.php';
+require_once $__dir . '/HTMLPurifier/Config.php';
+require_once $__dir . '/HTMLPurifier/ConfigSchema.php';
+require_once $__dir . '/HTMLPurifier/ContentSets.php';
+require_once $__dir . '/HTMLPurifier/Context.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCacheFactory.php';
+require_once $__dir . '/HTMLPurifier/Doctype.php';
+require_once $__dir . '/HTMLPurifier/DoctypeRegistry.php';
+require_once $__dir . '/HTMLPurifier/ElementDef.php';
+require_once $__dir . '/HTMLPurifier/Encoder.php';
+require_once $__dir . '/HTMLPurifier/EntityLookup.php';
+require_once $__dir . '/HTMLPurifier/EntityParser.php';
+require_once $__dir . '/HTMLPurifier/ErrorCollector.php';
+require_once $__dir . '/HTMLPurifier/ErrorStruct.php';
+require_once $__dir . '/HTMLPurifier/Exception.php';
+require_once $__dir . '/HTMLPurifier/Filter.php';
+require_once $__dir . '/HTMLPurifier/Generator.php';
+require_once $__dir . '/HTMLPurifier/HTMLDefinition.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule.php';
+require_once $__dir . '/HTMLPurifier/HTMLModuleManager.php';
+require_once $__dir . '/HTMLPurifier/IDAccumulator.php';
+require_once $__dir . '/HTMLPurifier/Injector.php';
+require_once $__dir . '/HTMLPurifier/Language.php';
+require_once $__dir . '/HTMLPurifier/LanguageFactory.php';
+require_once $__dir . '/HTMLPurifier/Length.php';
+require_once $__dir . '/HTMLPurifier/Lexer.php';
+require_once $__dir . '/HTMLPurifier/PercentEncoder.php';
+require_once $__dir . '/HTMLPurifier/Strategy.php';
+require_once $__dir . '/HTMLPurifier/StringHash.php';
+require_once $__dir . '/HTMLPurifier/StringHashParser.php';
+require_once $__dir . '/HTMLPurifier/TagTransform.php';
+require_once $__dir . '/HTMLPurifier/Token.php';
+require_once $__dir . '/HTMLPurifier/TokenFactory.php';
+require_once $__dir . '/HTMLPurifier/URI.php';
+require_once $__dir . '/HTMLPurifier/URIDefinition.php';
+require_once $__dir . '/HTMLPurifier/URIFilter.php';
+require_once $__dir . '/HTMLPurifier/URIParser.php';
+require_once $__dir . '/HTMLPurifier/URIScheme.php';
+require_once $__dir . '/HTMLPurifier/URISchemeRegistry.php';
+require_once $__dir . '/HTMLPurifier/UnitConverter.php';
+require_once $__dir . '/HTMLPurifier/VarParser.php';
+require_once $__dir . '/HTMLPurifier/VarParserException.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/Enum.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/Integer.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/Lang.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/Switch.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/Text.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Number.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/AlphaValue.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Background.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Border.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Color.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Composite.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Filter.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Font.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/FontFamily.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Length.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/ListStyle.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Multiple.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Percentage.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/TextDecoration.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/CSS/URI.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Bool.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Color.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/FrameTarget.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/ID.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Pixels.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Length.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/LinkTypes.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/MultiLength.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/HTML/Nmtokens.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI/Email.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI/Host.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI/IPv4.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI/IPv6.php';
+require_once $__dir . '/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Background.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/BdoDir.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/BgColor.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/BoolToCSS.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Border.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/EnumToCSS.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/ImgRequired.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/ImgSpace.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Input.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Lang.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Length.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Name.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/SafeEmbed.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/SafeObject.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/SafeParam.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/ScriptRequired.php';
+require_once $__dir . '/HTMLPurifier/AttrTransform/Textarea.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Chameleon.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Custom.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Empty.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Required.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Optional.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/StrictBlockquote.php';
+require_once $__dir . '/HTMLPurifier/ChildDef/Table.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache/Null.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache/Serializer.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php';
+require_once $__dir . '/HTMLPurifier/DefinitionCache/Decorator/Memory.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Bdo.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/CommonAttributes.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Edit.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Forms.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Hypertext.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Image.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Legacy.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/List.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Name.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Object.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Presentation.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Proprietary.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Ruby.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/SafeEmbed.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/SafeObject.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Scripting.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/StyleAttribute.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tables.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Target.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Text.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/XMLCommonAttributes.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Name.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Proprietary.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Strict.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/Transitional.php';
+require_once $__dir . '/HTMLPurifier/HTMLModule/Tidy/XHTML.php';
+require_once $__dir . '/HTMLPurifier/Injector/AutoParagraph.php';
+require_once $__dir . '/HTMLPurifier/Injector/DisplayLinkURI.php';
+require_once $__dir . '/HTMLPurifier/Injector/Linkify.php';
+require_once $__dir . '/HTMLPurifier/Injector/PurifierLinkify.php';
+require_once $__dir . '/HTMLPurifier/Injector/RemoveEmpty.php';
+require_once $__dir . '/HTMLPurifier/Injector/SafeObject.php';
+require_once $__dir . '/HTMLPurifier/Lexer/DOMLex.php';
+require_once $__dir . '/HTMLPurifier/Lexer/DirectLex.php';
+require_once $__dir . '/HTMLPurifier/Strategy/Composite.php';
+require_once $__dir . '/HTMLPurifier/Strategy/Core.php';
+require_once $__dir . '/HTMLPurifier/Strategy/FixNesting.php';
+require_once $__dir . '/HTMLPurifier/Strategy/MakeWellFormed.php';
+require_once $__dir . '/HTMLPurifier/Strategy/RemoveForeignElements.php';
+require_once $__dir . '/HTMLPurifier/Strategy/ValidateAttributes.php';
+require_once $__dir . '/HTMLPurifier/TagTransform/Font.php';
+require_once $__dir . '/HTMLPurifier/TagTransform/Simple.php';
+require_once $__dir . '/HTMLPurifier/Token/Comment.php';
+require_once $__dir . '/HTMLPurifier/Token/Tag.php';
+require_once $__dir . '/HTMLPurifier/Token/Empty.php';
+require_once $__dir . '/HTMLPurifier/Token/End.php';
+require_once $__dir . '/HTMLPurifier/Token/Start.php';
+require_once $__dir . '/HTMLPurifier/Token/Text.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/DisableExternal.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/DisableExternalResources.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/HostBlacklist.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/MakeAbsolute.php';
+require_once $__dir . '/HTMLPurifier/URIFilter/Munge.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/ftp.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/http.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/https.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/mailto.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/news.php';
+require_once $__dir . '/HTMLPurifier/URIScheme/nntp.php';
+require_once $__dir . '/HTMLPurifier/VarParser/Flexible.php';
+require_once $__dir . '/HTMLPurifier/VarParser/Native.php';
index a1799df541774f3408e8d3f7b1374909f7147041..dca75df3858ceedc8278a8c889b92f285fd302cc 100644 (file)
@@ -42,10 +42,7 @@ class HTMLPurifier_AttrDef_HTML_LinkTypes extends HTMLPurifier_AttrDef
         }
         
         if (empty($ret_lookup)) return false;
-        
-        $ret_array = array();
-        foreach ($ret_lookup as $part => $bool) $ret_array[] = $part;
-        $string = implode(' ', $ret_array);
+        $string = implode(' ', array_keys($ret_lookup));
         
         return $string;
         
diff --git a/lib/htmlpurifier/HTMLPurifier/AttrTransform/Background.php b/lib/htmlpurifier/HTMLPurifier/AttrTransform/Background.php
new file mode 100644 (file)
index 0000000..f7f0fed
--- /dev/null
@@ -0,0 +1,22 @@
+<?php
+
+/**
+ * Pre-transform that changes proprietary background attribute to CSS.
+ */
+class HTMLPurifier_AttrTransform_Background extends HTMLPurifier_AttrTransform {
+
+    public function transform($attr, $config, $context) {
+        
+        if (!isset($attr['background'])) return $attr;
+        
+        $background = $this->confiscateAttr($attr, 'background');
+        // some validation should happen here
+        
+        $this->prependCSS($attr, "background-image:url($background);");
+        
+        return $attr;
+        
+    }
+    
+}
+
index 52c716759a08e7d34571d8cb96258e4b11c16fd5..e938f525dc70ba2b37b36fca422bd20a3de6ac90 100644 (file)
@@ -22,7 +22,12 @@ class HTMLPurifier_AttrTransform_ImgRequired extends HTMLPurifier_AttrTransform
         
         if (!isset($attr['alt'])) {
             if ($src) {
-                $attr['alt'] = basename($attr['src']);
+                $alt = $config->get('Attr', 'DefaultImageAlt');
+                if ($alt === null) {
+                    $attr['alt'] = basename($attr['src']);
+                } else {
+                    $attr['alt'] = $alt;
+                }
             } else {
                 $attr['alt'] = $config->get('Attr', 'DefaultInvalidImageAlt');
             }
diff --git a/lib/htmlpurifier/HTMLPurifier/AttrTransform/Input.php b/lib/htmlpurifier/HTMLPurifier/AttrTransform/Input.php
new file mode 100644 (file)
index 0000000..f082c4d
--- /dev/null
@@ -0,0 +1,39 @@
+<?php
+
+/**
+ * Performs miscellaneous cross attribute validation and filtering for
+ * input elements. This is meant to be a post-transform.
+ */
+class HTMLPurifier_AttrTransform_Input extends HTMLPurifier_AttrTransform {
+    
+    protected $pixels;
+    
+    public function __construct() {
+        $this->pixels = new HTMLPurifier_AttrDef_HTML_Pixels();
+    }
+    
+    public function transform($attr, $config, $context) {
+        if (!isset($attr['type'])) $t = 'text';
+        else $t = strtolower($attr['type']);
+        if (isset($attr['checked']) && $t !== 'radio' && $t !== 'checkbox') {
+            unset($attr['checked']);
+        }
+        if (isset($attr['maxlength']) && $t !== 'text' && $t !== 'password') {
+            unset($attr['maxlength']);
+        }
+        if (isset($attr['size']) && $t !== 'text' && $t !== 'password') {
+            $result = $this->pixels->validate($attr['size'], $config, $context);
+            if ($result === false) unset($attr['size']);
+            else $attr['size'] = $result;
+        }
+        if (isset($attr['src']) && $t !== 'image') {
+            unset($attr['src']);
+        }
+        if (!isset($attr['value']) && ($t === 'radio' || $t === 'checkbox')) {
+            $attr['value'] = '';
+        }
+        return $attr;
+    }
+    
+}
+
diff --git a/lib/htmlpurifier/HTMLPurifier/AttrTransform/Textarea.php b/lib/htmlpurifier/HTMLPurifier/AttrTransform/Textarea.php
new file mode 100644 (file)
index 0000000..c7cc988
--- /dev/null
@@ -0,0 +1,16 @@
+<?php
+
+/**
+ * Sets height/width defaults for <textarea>
+ */
+class HTMLPurifier_AttrTransform_Textarea extends HTMLPurifier_AttrTransform
+{
+    
+    public function transform($attr, $config, $context) {
+        // Calculated from Firefox
+        if (!isset($attr['cols'])) $attr['cols'] = '22';
+        if (!isset($attr['rows'])) $attr['rows'] = '3';
+        return $attr;
+    }
+    
+}
\ No newline at end of file
index 9262a098c15b15f292847b607316fe29cc7f7574..c3116a162ede657c5b1941037926b2fb2698fc4d 100644 (file)
@@ -32,6 +32,9 @@ class HTMLPurifier_AttrTypes
         
         // unimplemented aliases
         $this->info['ContentType'] = new HTMLPurifier_AttrDef_Text();
+        $this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text();
+        $this->info['Charsets'] = new HTMLPurifier_AttrDef_Text();
+        $this->info['Character'] = new HTMLPurifier_AttrDef_Text();
         
         // number is really a positive integer (one or more digits)
         // FIXME: ^^ not always, see start and value of list items
index ba4510e3a4a7be21a8f3a3dd0c919a3678315b2a..fb913fc020bd71fd8e7b0a4c4d092381c827bdef 100644 (file)
@@ -35,8 +35,8 @@ class HTMLPurifier_AttrValidator
         if (!$current_token) $context->register('CurrentToken', $token);
         
         if (
-          !$token instanceof HTMLPurifier_Token_Start &&
-          !$token instanceof HTMLPurifier_Token_Empty
+            !$token instanceof HTMLPurifier_Token_Start &&
+            !$token instanceof HTMLPurifier_Token_Empty
         ) return $token;
         
         // create alias to global definition array, see also $defs
@@ -50,14 +50,18 @@ class HTMLPurifier_AttrValidator
         // nothing currently utilizes this
         foreach ($definition->info_attr_transform_pre as $transform) {
             $attr = $transform->transform($o = $attr, $config, $context);
-            if ($e && ($attr != $o)) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+            if ($e) {
+                if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+            }
         }
         
         // do local transformations only applicable to this element (pre)
         // ex. <p align="right"> to <p style="text-align:right;">
         foreach ($definition->info[$token->name]->attr_transform_pre as $transform) {
             $attr = $transform->transform($o = $attr, $config, $context);
-            if ($e && ($attr != $o)) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+            if ($e) {
+                if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+            }
         }
         
         // create alias to this element's attribute definition array, see
@@ -114,6 +118,8 @@ class HTMLPurifier_AttrValidator
                 
                 // simple substitution
                 $attr[$attr_key] = $result;
+            } else {
+                // nothing happens
             }
             
             // we'd also want slightly more complicated substitution
@@ -130,13 +136,17 @@ class HTMLPurifier_AttrValidator
         // global (error reporting untested)
         foreach ($definition->info_attr_transform_post as $transform) {
             $attr = $transform->transform($o = $attr, $config, $context);
-            if ($e && ($attr != $o)) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+            if ($e) {
+                if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+            }
         }
         
         // local (error reporting untested)
         foreach ($definition->info[$token->name]->attr_transform_post as $transform) {
             $attr = $transform->transform($o = $attr, $config, $context);
-            if ($e && ($attr != $o)) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+            if ($e) {
+                if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
+            }
         }
         
         $token->attr = $attr;
index 0cc345674d21af39a50b2a8ea0aacc36f2bdef90..38f3692f51ed83642c574fdcbeba4e3a9199a486 100644 (file)
@@ -24,6 +24,14 @@ abstract class HTMLPurifier_ChildDef
      */
     public $elements = array();
     
+    /**
+     * Get lookup of tag names that should not close this element automatically.
+     * All other elements will do so.
+     */
+    public function getNonAutoCloseElements($config) {
+        return $this->elements;
+    }
+    
     /**
      * Validates nodes according to definition and returns modification.
      * 
index 4ba07888580fef29c03c7248326e9a37c0bf35ea..f79bfcae60b512bee0ffc8872d0749f7463d2b8b 100644 (file)
@@ -5,8 +5,6 @@
  * 
  * @warning Currently this class is an all or nothing proposition, that is,
  *          it will only give a bool return value.
- * @note This class is currently not used by any code, although it is unit
- *       tested.
  */
 class HTMLPurifier_ChildDef_Custom extends HTMLPurifier_ChildDef
 {
index ecdb17ff64cc6411bb85c583acfdd28ca3054561..ec0890d91796276b886ac2f429c2658b2be16bec 100644 (file)
@@ -10,16 +10,19 @@ class HTMLPurifier_ChildDef_StrictBlockquote extends HTMLPurifier_ChildDef_Requi
     public $allow_empty = true;
     public $type = 'strictblockquote';
     protected $init = false;
+    
+    /**
+     * @note We don't want MakeWellFormed to auto-close inline elements since
+     *       they might be allowed.
+     */
+    public function getNonAutoCloseElements($config) {
+        $this->init($config);
+        return $this->fake_elements;
+    }
+    
     public function validateChildren($tokens_of_children, $config, $context) {
         
-        $def = $config->getHTMLDefinition();
-        if (!$this->init) {
-            // allow all inline elements
-            $this->real_elements = $this->elements;
-            $this->fake_elements = $def->info_content_sets['Flow'];
-            $this->fake_elements['#PCDATA'] = true;
-            $this->init = true;
-        }
+        $this->init($config);
         
         // trick the parent class into thinking it allows more
         $this->elements = $this->fake_elements;
@@ -29,6 +32,7 @@ class HTMLPurifier_ChildDef_StrictBlockquote extends HTMLPurifier_ChildDef_Requi
         if ($result === false) return array();
         if ($result === true) $result = $tokens_of_children;
         
+        $def = $config->getHTMLDefinition();
         $block_wrap_start = new HTMLPurifier_Token_Start($def->info_block_wrapper);
         $block_wrap_end   = new HTMLPurifier_Token_End(  $def->info_block_wrapper);
         $is_inline = false;
@@ -68,5 +72,16 @@ class HTMLPurifier_ChildDef_StrictBlockquote extends HTMLPurifier_ChildDef_Requi
         if ($is_inline) $ret[] = $block_wrap_end;
         return $ret;
     }
+    
+    private function init($config) {
+        if (!$this->init) {
+            $def = $config->getHTMLDefinition();
+            // allow all inline elements
+            $this->real_elements = $this->elements;
+            $this->fake_elements = $def->info_content_sets['Flow'];
+            $this->fake_elements['#PCDATA'] = true;
+            $this->init = true;
+        }
+    }
 }
 
index e2fe21b6b573446f12cf84adf160f3b08a86e668..aca84982855fd9f1ee1976077218de0a00af54a2 100644 (file)
@@ -20,7 +20,7 @@ class HTMLPurifier_Config
     /**
      * HTML Purifier's version
      */
-    public $version = '3.1.1';
+    public $version = '3.2.0';
     
     /**
      * Bool indicator whether or not to automatically finalize 
index 1af702b7df5a22925c42a39c0618b5b9f7176770..1ac5ff691eb70c078010f273ba80ef8619bb2034 100644 (file)
@@ -1 +1 @@
-O:25:"HTMLPurifier_ConfigSchema":2:{s:8:"defaults";a:12:{s:4:"Attr";a:11:{s:19:"AllowedFrameTargets";a:0:{}s:10:"AllowedRel";a:0:{}s:10:"AllowedRev";a:0:{}s:19:"DefaultInvalidImage";s:0:"";s:22:"DefaultInvalidImageAlt";s:13:"Invalid image";s:14:"DefaultTextDir";s:3:"ltr";s:8:"EnableID";b:0;s:11:"IDBlacklist";a:0:{}s:17:"IDBlacklistRegexp";N;s:8:"IDPrefix";s:0:"";s:13:"IDPrefixLocal";s:0:"";}s:10:"AutoFormat";a:4:{s:13:"AutoParagraph";b:0;s:6:"Custom";a:0:{}s:7:"Linkify";b:0;s:15:"PurifierLinkify";b:0;}s:15:"AutoFormatParam";a:1:{s:21:"PurifierLinkifyDocURL";s:3:"#%s";}s:3:"CSS";a:6:{s:14:"AllowImportant";b:0;s:11:"AllowTricky";b:0;s:17:"AllowedProperties";N;s:13:"DefinitionRev";i:1;s:12:"MaxImgLength";s:6:"1200px";s:11:"Proprietary";b:0;}s:5:"Cache";a:2:{s:14:"DefinitionImpl";s:10:"Serializer";s:14:"SerializerPath";N;}s:4:"Core";a:15:{s:17:"AggressivelyFixLt";b:0;s:13:"CollectErrors";b:0;s:13:"ColorKeywords";a:17:{s:6:"maroon";s:7:"#800000";s:3:"red";s:7:"#FF0000";s:6:"orange";s:7:"#FFA500";s:6:"yellow";s:7:"#FFFF00";s:5:"olive";s:7:"#808000";s:6:"purple";s:7:"#800080";s:7:"fuchsia";s:7:"#FF00FF";s:5:"white";s:7:"#FFFFFF";s:4:"lime";s:7:"#00FF00";s:5:"green";s:7:"#008000";s:4:"navy";s:7:"#000080";s:4:"blue";s:7:"#0000FF";s:4:"aqua";s:7:"#00FFFF";s:4:"teal";s:7:"#008080";s:5:"black";s:7:"#000000";s:6:"silver";s:7:"#C0C0C0";s:4:"gray";s:7:"#808080";}s:25:"ConvertDocumentToFragment";b:1;s:31:"DirectLexLineNumberSyncInterval";i:0;s:8:"Encoding";s:5:"utf-8";s:21:"EscapeInvalidChildren";b:0;s:17:"EscapeInvalidTags";b:0;s:24:"EscapeNonASCIICharacters";b:0;s:14:"HiddenElements";a:2:{s:6:"script";b:1;s:5:"style";b:1;}s:8:"Language";s:2:"en";s:9:"LexerImpl";N;s:19:"MaintainLineNumbers";N;s:16:"RemoveInvalidImg";b:1;s:20:"RemoveScriptContents";N;}s:6:"Filter";a:3:{s:6:"Custom";a:0:{}s:18:"ExtractStyleBlocks";b:0;s:7:"YouTube";b:0;}s:11:"FilterParam";a:3:{s:26:"ExtractStyleBlocksEscaping";b:1;s:23:"ExtractStyleBlocksScope";N;s:26:"ExtractStyleBlocksTidyImpl";N;}s:4:"HTML";a:23:{s:7:"Allowed";N;s:17:"AllowedAttributes";N;s:15:"AllowedElements";N;s:14:"AllowedModules";N;s:12:"BlockWrapper";s:1:"p";s:11:"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:13:"CustomDoctype";N;s:12:"DefinitionID";N;s:13:"DefinitionRev";i:1;s:7:"Doctype";N;s:19:"ForbiddenAttributes";a:0:{}s:17:"ForbiddenElements";a:0:{}s:12:"MaxImgLength";i:1200;s:6:"Parent";s:3:"div";s:11:"Proprietary";b:0;s:9:"SafeEmbed";b:0;s:10:"SafeObject";b:0;s:6:"Strict";b:0;s:7:"TidyAdd";a:0:{}s:9:"TidyLevel";s:6:"medium";s:10:"TidyRemove";a:0:{}s:7:"Trusted";b:0;s:5:"XHTML";b:1;}s:6:"Output";a:3:{s:21:"CommentScriptContents";b:1;s:7:"Newline";N;s:10:"TidyFormat";b:0;}s:4:"Test";a:1:{s:12:"ForceNoIconv";b:0;}s:3:"URI";a:16:{s:14:"AllowedSchemes";a:6:{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:4:"Base";N;s:13:"DefaultScheme";s:4:"http";s:12:"DefinitionID";N;s:13:"DefinitionRev";i:1;s:7:"Disable";b:0;s:15:"DisableExternal";b:0;s:24:"DisableExternalResources";b:0;s:16:"DisableResources";b:0;s:4:"Host";N;s:13:"HostBlacklist";a:0:{}s:12:"MakeAbsolute";b:0;s:5:"Munge";N;s:14:"MungeResources";b:0;s:14:"MungeSecretKey";N;s:22:"OverrideAllowedSchemes";b:1;}}s:4:"info";a:12:{s:4:"Attr";a:12:{s:19:"AllowedFrameTargets";i:8;s:10:"AllowedRel";i:8;s:10:"AllowedRev";i:8;s:19:"DefaultInvalidImage";i:1;s:22:"DefaultInvalidImageAlt";i:1;s:14:"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:8:"EnableID";i:7;s:11:"IDBlacklist";i:9;s:17:"IDBlacklistRegexp";i:-1;s:8:"IDPrefix";i:1;s:13:"IDPrefixLocal";i:1;s:10:"DisableURI";O:8:"stdClass":3:{s:9:"namespace";s:3:"URI";s:4:"name";s:7:"Disable";s:7:"isAlias";b:1;}}s:10:"AutoFormat";a:4:{s:13:"AutoParagraph";i:7;s:6:"Custom";i:9;s:7:"Linkify";i:7;s:15:"PurifierLinkify";i:7;}s:15:"AutoFormatParam";a:1:{s:21:"PurifierLinkifyDocURL";i:1;}s:3:"CSS";a:6:{s:14:"AllowImportant";i:7;s:11:"AllowTricky";i:7;s:17:"AllowedProperties";i:-8;s:13:"DefinitionRev";i:5;s:12:"MaxImgLength";i:-1;s:11:"Proprietary";i:7;}s:5:"Cache";a:2:{s:14:"DefinitionImpl";i:-1;s:14:"SerializerPath";i:-1;}s:4:"Core";a:20:{s:15:"DefinitionCache";O:8:"stdClass":3:{s:9:"namespace";s:5:"Cache";s:4:"name";s:14:"DefinitionImpl";s:7:"isAlias";b:1;}s:17:"AggressivelyFixLt";i:7;s:13:"CollectErrors";i:7;s:13:"ColorKeywords";i:10;s:25:"ConvertDocumentToFragment";i:7;s:19:"AcceptFullDocuments";O:8:"stdClass":3:{s:9:"namespace";s:4:"Core";s:4:"name";s:25:"ConvertDocumentToFragment";s:7:"isAlias";b:1;}s:31:"DirectLexLineNumberSyncInterval";i:5;s:8:"Encoding";i:2;s:21:"EscapeInvalidChildren";i:7;s:17:"EscapeInvalidTags";i:7;s:24:"EscapeNonASCIICharacters";i:7;s:14:"HiddenElements";i:8;s:8:"Language";i:1;s:9:"LexerImpl";i:-11;s:19:"MaintainLineNumbers";i:-7;s:16:"RemoveInvalidImg";i:7;s:20:"RemoveScriptContents";i:-7;s:5:"XHTML";O:8:"stdClass":3:{s:9:"namespace";s:4:"HTML";s:4:"name";s:5:"XHTML";s:7:"isAlias";b:1;}s:21:"CommentScriptContents";O:8:"stdClass":3:{s:9:"namespace";s:6:"Output";s:4:"name";s:21:"CommentScriptContents";s:7:"isAlias";b:1;}s:10:"TidyFormat";O:8:"stdClass":3:{s:9:"namespace";s:6:"Output";s:4:"name";s:10:"TidyFormat";s:7:"isAlias";b:1;}}s:6:"Filter";a:5:{s:6:"Custom";i:9;s:18:"ExtractStyleBlocks";i:7;s:7:"YouTube";i:7;s:26:"ExtractStyleBlocksEscaping";O:8:"stdClass":3:{s:9:"namespace";s:11:"FilterParam";s:4:"name";s:26:"ExtractStyleBlocksEscaping";s:7:"isAlias";b:1;}s:23:"ExtractStyleBlocksScope";O:8:"stdClass":3:{s:9:"namespace";s:11:"FilterParam";s:4:"name";s:23:"ExtractStyleBlocksScope";s:7:"isAlias";b:1;}}s:11:"FilterParam";a:3:{s:26:"ExtractStyleBlocksEscaping";i:7;s:23:"ExtractStyleBlocksScope";i:-1;s:26:"ExtractStyleBlocksTidyImpl";i:-11;}s:4:"HTML";a:24:{s:12:"EnableAttrID";O:8:"stdClass":3:{s:9:"namespace";s:4:"Attr";s:4:"name";s:8:"EnableID";s:7:"isAlias";b:1;}s:7:"Allowed";i:-4;s:17:"AllowedAttributes";i:-8;s:15:"AllowedElements";i:-8;s:14:"AllowedModules";i:-8;s:12:"BlockWrapper";i:1;s:11:"CoreModules";i:8;s:13:"CustomDoctype";i:-1;s:12:"DefinitionID";i:-1;s:13:"DefinitionRev";i:5;s:7:"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:19:"ForbiddenAttributes";i:8;s:17:"ForbiddenElements";i:8;s:12:"MaxImgLength";i:-5;s:6:"Parent";i:1;s:11:"Proprietary";i:7;s:9:"SafeEmbed";i:7;s:10:"SafeObject";i:7;s:6:"Strict";i:7;s:7:"TidyAdd";i:8;s:9:"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:10:"TidyRemove";i:8;s:7:"Trusted";i:7;s:5:"XHTML";i:7;}s:6:"Output";a:3:{s:21:"CommentScriptContents";i:7;s:7:"Newline";i:-1;s:10:"TidyFormat";i:7;}s:4:"Test";a:1:{s:12:"ForceNoIconv";i:7;}s:3:"URI";a:16:{s:14:"AllowedSchemes";i:8;s:4:"Base";i:-1;s:13:"DefaultScheme";i:1;s:12:"DefinitionID";i:-1;s:13:"DefinitionRev";i:5;s:7:"Disable";i:7;s:15:"DisableExternal";i:7;s:24:"DisableExternalResources";i:7;s:16:"DisableResources";i:7;s:4:"Host";i:-1;s:13:"HostBlacklist";i:9;s:12:"MakeAbsolute";i:7;s:5:"Munge";i:-1;s:14:"MungeResources";i:7;s:14:"MungeSecretKey";i:-1;s:22:"OverrideAllowedSchemes";i:7;}}}
\ No newline at end of file
+O:25:"HTMLPurifier_ConfigSchema":2:{s:8:"defaults";a:12:{s:4:"Attr";a:12:{s:19:"AllowedFrameTargets";a:0:{}s:10:"AllowedRel";a:0:{}s:10:"AllowedRev";a:0:{}s:15:"DefaultImageAlt";N;s:19:"DefaultInvalidImage";s:0:"";s:22:"DefaultInvalidImageAlt";s:13:"Invalid image";s:14:"DefaultTextDir";s:3:"ltr";s:8:"EnableID";b:0;s:11:"IDBlacklist";a:0:{}s:17:"IDBlacklistRegexp";N;s:8:"IDPrefix";s:0:"";s:13:"IDPrefixLocal";s:0:"";}s:10:"AutoFormat";a:6:{s:13:"AutoParagraph";b:0;s:6:"Custom";a:0:{}s:14:"DisplayLinkURI";b:0;s:7:"Linkify";b:0;s:15:"PurifierLinkify";b:0;s:11:"RemoveEmpty";b:0;}s:15:"AutoFormatParam";a:1:{s:21:"PurifierLinkifyDocURL";s:3:"#%s";}s:3:"CSS";a:6:{s:14:"AllowImportant";b:0;s:11:"AllowTricky";b:0;s:17:"AllowedProperties";N;s:13:"DefinitionRev";i:1;s:12:"MaxImgLength";s:6:"1200px";s:11:"Proprietary";b:0;}s:5:"Cache";a:2:{s:14:"DefinitionImpl";s:10:"Serializer";s:14:"SerializerPath";N;}s:4:"Core";a:15:{s:17:"AggressivelyFixLt";b:1;s:13:"CollectErrors";b:0;s:13:"ColorKeywords";a:17:{s:6:"maroon";s:7:"#800000";s:3:"red";s:7:"#FF0000";s:6:"orange";s:7:"#FFA500";s:6:"yellow";s:7:"#FFFF00";s:5:"olive";s:7:"#808000";s:6:"purple";s:7:"#800080";s:7:"fuchsia";s:7:"#FF00FF";s:5:"white";s:7:"#FFFFFF";s:4:"lime";s:7:"#00FF00";s:5:"green";s:7:"#008000";s:4:"navy";s:7:"#000080";s:4:"blue";s:7:"#0000FF";s:4:"aqua";s:7:"#00FFFF";s:4:"teal";s:7:"#008080";s:5:"black";s:7:"#000000";s:6:"silver";s:7:"#C0C0C0";s:4:"gray";s:7:"#808080";}s:25:"ConvertDocumentToFragment";b:1;s:31:"DirectLexLineNumberSyncInterval";i:0;s:8:"Encoding";s:5:"utf-8";s:21:"EscapeInvalidChildren";b:0;s:17:"EscapeInvalidTags";b:0;s:24:"EscapeNonASCIICharacters";b:0;s:14:"HiddenElements";a:2:{s:6:"script";b:1;s:5:"style";b:1;}s:8:"Language";s:2:"en";s:9:"LexerImpl";N;s:19:"MaintainLineNumbers";N;s:16:"RemoveInvalidImg";b:1;s:20:"RemoveScriptContents";N;}s:6:"Filter";a:3:{s:6:"Custom";a:0:{}s:18:"ExtractStyleBlocks";b:0;s:7:"YouTube";b:0;}s:11:"FilterParam";a:3:{s:26:"ExtractStyleBlocksEscaping";b:1;s:23:"ExtractStyleBlocksScope";N;s:26:"ExtractStyleBlocksTidyImpl";N;}s:4:"HTML";a:23:{s:7:"Allowed";N;s:17:"AllowedAttributes";N;s:15:"AllowedElements";N;s:14:"AllowedModules";N;s:12:"BlockWrapper";s:1:"p";s:11:"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:13:"CustomDoctype";N;s:12:"DefinitionID";N;s:13:"DefinitionRev";i:1;s:7:"Doctype";N;s:19:"ForbiddenAttributes";a:0:{}s:17:"ForbiddenElements";a:0:{}s:12:"MaxImgLength";i:1200;s:6:"Parent";s:3:"div";s:11:"Proprietary";b:0;s:9:"SafeEmbed";b:0;s:10:"SafeObject";b:0;s:6:"Strict";b:0;s:7:"TidyAdd";a:0:{}s:9:"TidyLevel";s:6:"medium";s:10:"TidyRemove";a:0:{}s:7:"Trusted";b:0;s:5:"XHTML";b:1;}s:6:"Output";a:4:{s:21:"CommentScriptContents";b:1;s:7:"Newline";N;s:8:"SortAttr";b:0;s:10:"TidyFormat";b:0;}s:4:"Test";a:1:{s:12:"ForceNoIconv";b:0;}s:3:"URI";a:16:{s:14:"AllowedSchemes";a:6:{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:4:"Base";N;s:13:"DefaultScheme";s:4:"http";s:12:"DefinitionID";N;s:13:"DefinitionRev";i:1;s:7:"Disable";b:0;s:15:"DisableExternal";b:0;s:24:"DisableExternalResources";b:0;s:16:"DisableResources";b:0;s:4:"Host";N;s:13:"HostBlacklist";a:0:{}s:12:"MakeAbsolute";b:0;s:5:"Munge";N;s:14:"MungeResources";b:0;s:14:"MungeSecretKey";N;s:22:"OverrideAllowedSchemes";b:1;}}s:4:"info";a:12:{s:4:"Attr";a:13:{s:19:"AllowedFrameTargets";i:8;s:10:"AllowedRel";i:8;s:10:"AllowedRev";i:8;s:15:"DefaultImageAlt";i:-1;s:19:"DefaultInvalidImage";i:1;s:22:"DefaultInvalidImageAlt";i:1;s:14:"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:8:"EnableID";i:7;s:11:"IDBlacklist";i:9;s:17:"IDBlacklistRegexp";i:-1;s:8:"IDPrefix";i:1;s:13:"IDPrefixLocal";i:1;s:10:"DisableURI";O:8:"stdClass":3:{s:9:"namespace";s:3:"URI";s:4:"name";s:7:"Disable";s:7:"isAlias";b:1;}}s:10:"AutoFormat";a:6:{s:13:"AutoParagraph";i:7;s:6:"Custom";i:9;s:14:"DisplayLinkURI";i:7;s:7:"Linkify";i:7;s:15:"PurifierLinkify";i:7;s:11:"RemoveEmpty";i:7;}s:15:"AutoFormatParam";a:1:{s:21:"PurifierLinkifyDocURL";i:1;}s:3:"CSS";a:6:{s:14:"AllowImportant";i:7;s:11:"AllowTricky";i:7;s:17:"AllowedProperties";i:-8;s:13:"DefinitionRev";i:5;s:12:"MaxImgLength";i:-1;s:11:"Proprietary";i:7;}s:5:"Cache";a:2:{s:14:"DefinitionImpl";i:-1;s:14:"SerializerPath";i:-1;}s:4:"Core";a:20:{s:15:"DefinitionCache";O:8:"stdClass":3:{s:9:"namespace";s:5:"Cache";s:4:"name";s:14:"DefinitionImpl";s:7:"isAlias";b:1;}s:17:"AggressivelyFixLt";i:7;s:13:"CollectErrors";i:7;s:13:"ColorKeywords";i:10;s:25:"ConvertDocumentToFragment";i:7;s:19:"AcceptFullDocuments";O:8:"stdClass":3:{s:9:"namespace";s:4:"Core";s:4:"name";s:25:"ConvertDocumentToFragment";s:7:"isAlias";b:1;}s:31:"DirectLexLineNumberSyncInterval";i:5;s:8:"Encoding";i:2;s:21:"EscapeInvalidChildren";i:7;s:17:"EscapeInvalidTags";i:7;s:24:"EscapeNonASCIICharacters";i:7;s:14:"HiddenElements";i:8;s:8:"Language";i:1;s:9:"LexerImpl";i:-11;s:19:"MaintainLineNumbers";i:-7;s:16:"RemoveInvalidImg";i:7;s:20:"RemoveScriptContents";i:-7;s:5:"XHTML";O:8:"stdClass":3:{s:9:"namespace";s:4:"HTML";s:4:"name";s:5:"XHTML";s:7:"isAlias";b:1;}s:21:"CommentScriptContents";O:8:"stdClass":3:{s:9:"namespace";s:6:"Output";s:4:"name";s:21:"CommentScriptContents";s:7:"isAlias";b:1;}s:10:"TidyFormat";O:8:"stdClass":3:{s:9:"namespace";s:6:"Output";s:4:"name";s:10:"TidyFormat";s:7:"isAlias";b:1;}}s:6:"Filter";a:5:{s:6:"Custom";i:9;s:18:"ExtractStyleBlocks";i:7;s:7:"YouTube";i:7;s:26:"ExtractStyleBlocksEscaping";O:8:"stdClass":3:{s:9:"namespace";s:11:"FilterParam";s:4:"name";s:26:"ExtractStyleBlocksEscaping";s:7:"isAlias";b:1;}s:23:"ExtractStyleBlocksScope";O:8:"stdClass":3:{s:9:"namespace";s:11:"FilterParam";s:4:"name";s:23:"ExtractStyleBlocksScope";s:7:"isAlias";b:1;}}s:11:"FilterParam";a:3:{s:26:"ExtractStyleBlocksEscaping";i:7;s:23:"ExtractStyleBlocksScope";i:-1;s:26:"ExtractStyleBlocksTidyImpl";i:-11;}s:4:"HTML";a:24:{s:12:"EnableAttrID";O:8:"stdClass":3:{s:9:"namespace";s:4:"Attr";s:4:"name";s:8:"EnableID";s:7:"isAlias";b:1;}s:7:"Allowed";i:-4;s:17:"AllowedAttributes";i:-8;s:15:"AllowedElements";i:-8;s:14:"AllowedModules";i:-8;s:12:"BlockWrapper";i:1;s:11:"CoreModules";i:8;s:13:"CustomDoctype";i:-1;s:12:"DefinitionID";i:-1;s:13:"DefinitionRev";i:5;s:7:"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:19:"ForbiddenAttributes";i:8;s:17:"ForbiddenElements";i:8;s:12:"MaxImgLength";i:-5;s:6:"Parent";i:1;s:11:"Proprietary";i:7;s:9:"SafeEmbed";i:7;s:10:"SafeObject";i:7;s:6:"Strict";i:7;s:7:"TidyAdd";i:8;s:9:"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:10:"TidyRemove";i:8;s:7:"Trusted";i:7;s:5:"XHTML";i:7;}s:6:"Output";a:4:{s:21:"CommentScriptContents";i:7;s:7:"Newline";i:-1;s:8:"SortAttr";i:7;s:10:"TidyFormat";i:7;}s:4:"Test";a:1:{s:12:"ForceNoIconv";i:7;}s:3:"URI";a:16:{s:14:"AllowedSchemes";i:8;s:4:"Base";i:-1;s:13:"DefaultScheme";i:1;s:12:"DefinitionID";i:-1;s:13:"DefinitionRev";i:5;s:7:"Disable";i:7;s:15:"DisableExternal";i:7;s:24:"DisableExternalResources";i:7;s:16:"DisableResources";i:7;s:4:"Host";i:-1;s:13:"HostBlacklist";i:9;s:12:"MakeAbsolute";i:7;s:5:"Munge";i:-1;s:14:"MungeResources";i:7;s:14:"MungeSecretKey";i:-1;s:22:"OverrideAllowedSchemes";i:7;}}}
\ No newline at end of file
index 6cecfa2f00220fa926780896e77006e11b43601e..e1d82cf9005d141935081cfa23ae268b3e0ad2b9 100644 (file)
@@ -1,11 +1,11 @@
-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
+Attr.AllowedFrameTargets
+TYPE: lookup
+DEFAULT: array()
+--DESCRIPTION--
+Lookup table of all allowed link frame targets.  Some commonly used link
+targets include _blank, _self, _parent and _top. Values should be
+lowercase, as validation will be done in a case-sensitive manner despite
+W3C's recommendation. XHTML 1.0 Strict does not permit the target attribute
+so this directive will have no effect in that doctype. XHTML 1.1 does not
+enable the Target module by default, you will have to manually enable it
+(see the module documentation for more details.)
index 26bbc371306cf8e5bc4a3b2e99b93cb559508f56..e9f3febe689424d3de3bf3524f53438ffb4c945e 100644 (file)
@@ -1,8 +1,8 @@
-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
+Attr.AllowedRel
+TYPE: lookup
+VERSION: 1.6.0
+DEFAULT: array()
+--DESCRIPTION--
+List of allowed forward document relationships in the rel attribute. Common
+values may be nofollow or print. By default, this is empty, meaning that no
+document relationships are allowed. 
index b007bc58ac4849634dceedf479de07c0fb487b71..95cc372e1b78d47431e7574865f1d936bf6f7345 100644 (file)
@@ -1,8 +1,8 @@
-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
+Attr.AllowedRev
+TYPE: lookup
+VERSION: 1.6.0
+DEFAULT: array()
+--DESCRIPTION--
+List of allowed reverse document relationships in the rev attribute. This
+attribute is a bit of an edge-case; if you don't know what it is for, stay
+away. 
diff --git a/lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt b/lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt
new file mode 100644 (file)
index 0000000..e0be51b
--- /dev/null
@@ -0,0 +1,9 @@
+Attr.DefaultImageAlt
+TYPE: string/null
+DEFAULT: null
+--DESCRIPTION--
+This is the content of the alt tag of an image if the user had not
+previously specified an alt attribute.  This applies to all images without
+a valid alt attribute, as opposed to %Attr.DefaultInvalidImageAlt, which
+only applies to invalid images, and overrides in the case of an invalid image.
+Default behavior with null is to use the basename of the src tag for the alt.
index 3d5c45d4ffafb8b2f5ed075324ccc2ec60926707..ebd15275efbe22b23d8a0ac8d683a115fb08cdd3 100644 (file)
@@ -1,8 +1,8 @@
-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
+Attr.DefaultInvalidImage
+TYPE: string
+DEFAULT: ''
+--DESCRIPTION--
+This is the default image an img tag will be pointed to if it does not have
+a valid src attribute.  In future versions, we may allow the image tag to
+be removed completely, but due to design issues, this is not possible right
+now.
index cfc9f904be401eafa62c4dfc2d7a392c6744954a..883e12e4142c672aa7b6da34fcc0f52aed320e93 100644 (file)
@@ -1,7 +1,7 @@
-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
+Attr.DefaultInvalidImageAlt
+TYPE: string
+DEFAULT: 'Invalid image'
+--DESCRIPTION--
+This is the content of the alt tag of an invalid image if the user had not
+previously specified an alt attribute.  It has no effect when the image is
+valid but there was no alt attribute present.
index 80296fccf4cc8b129c687f29db5e9a95f32f6d08..f138c991b9bd63a4c9a665ee27b43a465d29e1f8 100644 (file)
@@ -1,9 +1,9 @@
-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
+Attr.DefaultTextDir
+TYPE: string
+DEFAULT: 'ltr'
+--DESCRIPTION--
+Defines the default text direction (ltr or rtl) of the document being
+parsed.  This generally is the same as the value of the dir attribute in
+HTML, or ltr if that is not specified.
+--ALLOWED--
+'ltr', 'rtl'
index 358d6d07a6a672aabf0280268204d19258370f1e..8803e01f98d8265a91b434f950d71d2d80145109 100644 (file)
@@ -1,15 +1,15 @@
-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
+Attr.EnableID
+TYPE: bool
+DEFAULT: false
+VERSION: 1.2.0
+--DESCRIPTION--
+Allows the ID attribute in HTML.  This is disabled by default due to the
+fact that without proper configuration user input can easily break the
+validation of a webpage by specifying an ID that is already on the
+surrounding HTML.  If you don't mind throwing caution to the wind, enable
+this directive, but I strongly recommend you also consider blacklisting IDs
+you use (%Attr.IDBlacklist) or prefixing all user supplied IDs
+(%Attr.IDPrefix).  When set to true HTML Purifier reverts to the behavior of
+pre-1.2.0 versions.
+--ALIASES--
+HTML.EnableAttrID
index 16fc46e16b826b968cc9a1854ace12f17add49d4..7ab584440b90ce882996ec71aa250e4674bc0839 100644 (file)
@@ -1,4 +1,4 @@
-Attr.IDBlacklist\r
-TYPE: list\r
-DEFAULT: array()\r
-DESCRIPTION: Array of IDs not allowed in the document.\r
+Attr.IDBlacklist
+TYPE: list
+DEFAULT: array()
+DESCRIPTION: Array of IDs not allowed in the document.
index 98f7c5a632325a46e14e2b1e2d3c5eee3ea4a20b..08a74a0a46e2cdee103c3c31ca76eecf131d6b09 100644 (file)
@@ -1,8 +1,8 @@
-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
+Attr.IDBlacklistRegexp
+TYPE: string/null
+VERSION: 1.6.0
+DEFAULT: NULL
+--DESCRIPTION--
+PCRE regular expression to be matched against all IDs. If the expression is
+matches, the ID is rejected. Use this with care: may cause significant
+degradation. ID matching is done after all other validation. 
index f996c08436cb9779441c1fd2c1d7a4a209a1feec..362aa2424cb626cab63b110180a3bd85df2a0ff3 100644 (file)
@@ -1,11 +1,11 @@
-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
+Attr.IDPrefix
+TYPE: string
+VERSION: 1.2.0
+DEFAULT: ''
+--DESCRIPTION--
+String to prefix to IDs.  If you have no idea what IDs your pages may use,
+you may opt to simply add a prefix to all user-submitted ID attributes so
+that they are still usable, but will not conflict with core page IDs.
+Example: setting the directive to 'user_' will result in a user submitted
+'foo' to become 'user_foo'  Be sure to set %HTML.EnableAttrID to true
+before using this.  
index b403fa9cd2a851b206812d9544e30b631c9b0bbb..b4f6b315b2d00fb61873f9a86b19fd8861d93ccd 100644 (file)
@@ -1,13 +1,13 @@
-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
+Attr.IDPrefixLocal
+TYPE: string
+VERSION: 1.2.0
+DEFAULT: ''
+--DESCRIPTION--
+Temporary prefix for IDs used in conjunction with %Attr.IDPrefix.  If you
+need to allow multiple sets of user content on web page, you may need to
+have a seperate prefix that changes with each iteration.  This way,
+seperately submitted user content displayed on the same page doesn't
+clobber each other. Ideal values are unique identifiers for the content it
+represents (i.e. the id of the row in the database). Be sure to add a
+seperator (like an underscore) at the end.  Warning: this directive will
+not work unless %Attr.IDPrefix is set to a non-empty value! 
index fb18894fe93910c9753ce6ab132666f85ed1b48e..de0591d37d67d7fa84cc51e6c55f996285d7e155 100644 (file)
@@ -1,2 +1,2 @@
-Attr\r
-DESCRIPTION: Features regarding attribute validation.\r
+Attr
+DESCRIPTION: Features regarding attribute validation.
index e1f7a475ecb8d202df51d68c22498a861801580b..1548c1f22db39c31001d6d7b0f0685573b34c009 100644 (file)
@@ -1,30 +1,30 @@
-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
+AutoFormat.AutoParagraph
+TYPE: bool
+VERSION: 2.0.1
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+  This directive turns on auto-paragraphing, where double newlines are
+  converted in to paragraphs whenever possible. Auto-paragraphing:
+</p>
+<ul>
+  <li>Always applies to inline elements or text in the root node,</li>
+  <li>Applies to inline elements or text with double newlines in nodes
+      that allow paragraph tags,</li>
+  <li>Applies to double newlines in paragraph tags</li>
+</ul>
+<p>
+  <code>p</code> tags must be allowed for this directive to take effect.
+  We do not use <code>br</code> tags for paragraphing, as that is
+  semantically incorrect.
+</p>
+<p>
+  To prevent auto-paragraphing as a content-producer, refrain from using
+  double-newlines except to specify a new paragraph or in contexts where
+  it has special meaning (whitespace usually has no meaning except in
+  tags like <code>pre</code>, so this should not be difficult.) To prevent
+  the paragraphing of inline text adjacent to block elements, wrap them
+  in <code>div</code> tags (the behavior is slightly different outside of
+  the root node.)
+</p>
index c5a363b3992a384e1bb5eaac1b2ecfcf81803d06..a8bd4eb116c8ed54542101dcd9a941af0c240ec5 100644 (file)
@@ -1,12 +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
-\r
+AutoFormat.Custom
+TYPE: list
+VERSION: 2.0.1
+DEFAULT: array()
+--DESCRIPTION--
+
+<p>
+  This directive can be used to add custom auto-format injectors.
+  Specify an array of injector names (class name minus the prefix)
+  or concrete implementations. Injector class must exist. 
+</p>
+
diff --git a/lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt b/lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt
new file mode 100644 (file)
index 0000000..28a157e
--- /dev/null
@@ -0,0 +1,10 @@
+AutoFormat.DisplayLinkURI
+TYPE: bool
+VERSION: 3.2.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+  This directive turns on the in-text display of URIs in &lt;a&gt; tags, and disables
+  those links. For example, <a href="http://example.com">example</a> becomes
+  example (<a>http://example.com</a>).
+</p>
index 554086f3594549824410ac4c8b6005134f2f3359..6c1cd7b671352be3a2c6bcc235f74dd53d31f3d2 100644 (file)
@@ -1,12 +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
-\r
+AutoFormat.Linkify
+TYPE: bool
+VERSION: 2.0.1
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+  This directive turns on linkification, auto-linking http, ftp and
+  https URLs. <code>a</code> tags with the <code>href</code> attribute
+  must be allowed. 
+</p>
+
index c7bcaf283e457d43f0319eb297abda20477b729b..cd7f0b8eb4a4edb35b2069658e4d05e271fcfdb0 100644 (file)
@@ -1,12 +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
-\r
+AutoFormat.PurifierLinkify
+TYPE: bool
+VERSION: 2.0.1
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+  Internal auto-formatter that converts configuration directives in
+  syntax <a>%Namespace.Directive</a> to links. <code>a</code> tags
+  with the <code>href</code> attribute must be allowed.
+</p>
+
diff --git a/lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt b/lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt
new file mode 100644 (file)
index 0000000..9edf0d6
--- /dev/null
@@ -0,0 +1,44 @@
+AutoFormat.RemoveEmpty
+TYPE: bool
+VERSION: 3.2.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+  When enabled, HTML Purifier will attempt to remove empty elements that
+  contribute no semantic information to the document. The following types
+  of nodes will be removed:
+</p>
+<ul><li>
+    Tags with no attributes and no content, and that are not empty
+    elements (remove <code>&lt;a&gt;&lt;/a&gt;</code> but not
+    <code>&lt;br /&gt;</code>), and
+  </li>
+  <li>
+    Tags with no content, except for:<ul>
+      <li>The <code>colgroup</code> element, or</li>
+      <li>
+        Elements with the <code>id</code> or <code>name</code> attribute,
+        when those attributes are permitted on those elements.
+      </li>
+    </ul></li>
+</ul>
+<p>
+  Please be very careful when using this functionality; while it may not
+  seem that empty elements contain useful information, they can alter the
+  layout of a document given appropriate styling. This directive is most
+  useful when you are processing machine-generated HTML, please avoid using
+  it on regular user HTML.
+</p>
+<p>
+  Elements that contain only whitespace will be treated as empty. Non-breaking
+  spaces, however, do not count as whitespace.
+</p>
+<p>
+  This algorithm is not perfect; you may still notice some empty tags,
+  particularly if a node had elements, but those elements were later removed
+  because they were not permitted in that context, or tags that, after
+  being auto-closed by another tag, where empty. This is for safety reasons
+  to prevent clever code from breaking validation. The general rule of thumb:
+  if a tag looked empty on the way end, it will get removed; if HTML Purifier
+  made it empty, it will stay.
+</p>
index 4a7b5521f79d743b64b136fdc79190b69c24f49f..c63fb699858e024e30177eb2362e1cb9fa9b1b02 100644 (file)
@@ -1,2 +1,2 @@
-AutoFormat\r
-DESCRIPTION: Configuration for activating auto-formatting functionality (also known as <code>Injector</code>s)\r
+AutoFormat
+DESCRIPTION: Configuration for activating auto-formatting functionality (also known as <code>Injector</code>s)
index 79d3358061f09e671d3e790d309474baff8e1d91..11d3b4e132f89d63861bd41181531418dda91f1d 100644 (file)
@@ -1,12 +1,12 @@
-AutoFormatParam.PurifierLinkifyDocURL\r
-TYPE: string\r
-VERSION: 2.0.1\r
-DEFAULT: '#%s'\r
---DESCRIPTION--\r
-\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
-\r
+AutoFormatParam.PurifierLinkifyDocURL
+TYPE: string
+VERSION: 2.0.1
+DEFAULT: '#%s'
+--DESCRIPTION--
+
+<p>
+  Location of configuration documentation to link to, let %s substitute
+  into the configuration's namespace and directive names sans the percent
+  sign. 
+</p>
+
index 0ed78846ed9a0f0fd2ef51ddcde1bb1ac03136e9..95bffcd88faeae68599e992fd19b488a8c84ead4 100644 (file)
@@ -1,2 +1,2 @@
-AutoFormatParam\r
-DESCRIPTION: Configuration for customizing auto-formatting functionality\r
+AutoFormatParam
+DESCRIPTION: Configuration for customizing auto-formatting functionality
index e1e5992680a4560ada35743eb8eaa6ff586455d8..5b40de2a054650a86048d8641c9784001a76f4d1 100644 (file)
@@ -1,11 +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
-\r
+CSS.DefinitionRev
+TYPE: int
+VERSION: 2.0.0
+DEFAULT: 1
+--DESCRIPTION--
+
+<p>
+    Revision identifier for your custom definition. See
+    %HTML.DefinitionRev for details. 
+</p>
+
index c9c068fc39603f2ae2fd56c0b3941e0c76277542..cc883dc57896f3780002cd94f9d040c1f6c71a9f 100644 (file)
@@ -1,10 +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
-\r
+CSS.Proprietary
+TYPE: bool
+VERSION: 3.0.0
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+    Whether or not to allow safe, proprietary CSS values. 
+</p>
+
index 060f5d3715152eec162b9ce5583403fab246bfc5..8bafc4b3c8674fa29f2a3243e1a7fefbe6671be8 100644 (file)
@@ -1,2 +1,2 @@
-CSS\r
-DESCRIPTION: Configuration regarding allowed CSS.\r
+CSS
+DESCRIPTION: Configuration regarding allowed CSS.
index e9fa699ae81270af96013329876bd429e3e845ab..192db1f9e69fa1cff09902c4cd964b14b89fec66 100644 (file)
@@ -1,13 +1,13 @@
-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
+Cache.DefinitionImpl
+TYPE: string/null
+VERSION: 2.0.0
+DEFAULT: 'Serializer'
+--DESCRIPTION--
+
+This directive defines which method to use when caching definitions,
+the complex data-type that makes HTML Purifier tick. Set to null
+to disable caching (not recommended, as you will see a definite
+performance degradation). 
+
+--ALIASES--
+Core.DefinitionCache
index 3682cbb37e4aef963eb8389e6dba1d759fcb7ec9..600c567ecfb8a0b900b142fcca1748ced4aeb3c6 100644 (file)
@@ -1,13 +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
-\r
+Cache.SerializerPath
+TYPE: string/null
+VERSION: 2.0.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+    Absolute path with no trailing slash to store serialized definitions in.
+    Default is within the
+    HTML Purifier library inside DefinitionCache/Serializer. This
+    path must be writable by the webserver. 
+</p>
+
index 2f7aaa268e643c9e62552bdcb8d80098e55588c0..6edaae0c4788337ff279289e708f232b331cd877 100644 (file)
@@ -1,2 +1,2 @@
-Cache\r
-DESCRIPTION: Configuration for DefinitionCache and related subclasses.\r
+Cache
+DESCRIPTION: Configuration for DefinitionCache and related subclasses.
index 0d60b89f6bd653d605eba34a85689d5952235227..7fdca4924a0ed73de66f42cb08aac373649db137 100644 (file)
@@ -1,13 +1,17 @@
-Core.AggressivelyFixLt\r
-TYPE: bool\r
-VERSION: 2.1.0\r
-DEFAULT: false\r
---DESCRIPTION--\r
-\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 one preg_replace call for every bit of HTML passed through here.\r
-It is not necessary and will have no effect for PHP 4.\r
-\r
-\r
+Core.AggressivelyFixLt
+TYPE: bool
+VERSION: 2.1.0
+DEFAULT: true
+--DESCRIPTION--
+<p>
+    This directive enables aggressive pre-filter fixes HTML Purifier can
+    perform in order to ensure that open angled-brackets do not get killed
+    during parsing stage. Enabling this will result in two preg_replace_callback
+    calls and at least two preg_replace calls for every HTML document parsed;
+    if your users make very well-formed HTML, you can set this directive false.
+    This has no effect when DirectLex is used.
+</p>
+<p>
+    <strong>Notice:</strong> This directive's default turned from false to true
+    in HTML Purifier 3.2.0.
+</p>
\ No newline at end of file
index dcf20563d2350c5c47544c522e678ea18e158e35..ccaf2ae3d9d67eb03166c43c774ea0f284722a6f 100644 (file)
@@ -1,11 +1,11 @@
-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
+Core.CollectErrors
+TYPE: bool
+VERSION: 2.0.0
+DEFAULT: false
+--DESCRIPTION--
+
+Whether or not to collect errors found while filtering the document. This
+is a useful way to give feedback to your users. <strong>Warning:</strong>
+Currently this feature is very patchy and experimental, with lots of
+possible error messages not yet implemented. It will not cause any
+problems, but it may not help your users either. 
index 28c96821071223ac8fa59dc0b9b6143840db676d..6ec36dbbcd298a2207829129145670088e9ab30a 100644 (file)
@@ -1,29 +1,29 @@
-Core.ColorKeywords\r
-TYPE: hash\r
-VERSION: 2.0.0\r
---DEFAULT--\r
-array (\r
-  'maroon' => '#800000',\r
-  'red' => '#FF0000',\r
-  'orange' => '#FFA500',\r
-  'yellow' => '#FFFF00',\r
-  'olive' => '#808000',\r
-  'purple' => '#800080',\r
-  'fuchsia' => '#FF00FF',\r
-  'white' => '#FFFFFF',\r
-  'lime' => '#00FF00',\r
-  'green' => '#008000',\r
-  'navy' => '#000080',\r
-  'blue' => '#0000FF',\r
-  'aqua' => '#00FFFF',\r
-  'teal' => '#008080',\r
-  'black' => '#000000',\r
-  'silver' => '#C0C0C0',\r
-  'gray' => '#808080',\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.\r
-\r
-\r
+Core.ColorKeywords
+TYPE: hash
+VERSION: 2.0.0
+--DEFAULT--
+array (
+  'maroon' => '#800000',
+  'red' => '#FF0000',
+  'orange' => '#FFA500',
+  'yellow' => '#FFFF00',
+  'olive' => '#808000',
+  'purple' => '#800080',
+  'fuchsia' => '#FF00FF',
+  'white' => '#FFFFFF',
+  'lime' => '#00FF00',
+  'green' => '#008000',
+  'navy' => '#000080',
+  'blue' => '#0000FF',
+  'aqua' => '#00FFFF',
+  'teal' => '#008080',
+  'black' => '#000000',
+  'silver' => '#C0C0C0',
+  'gray' => '#808080',
+)
+--DESCRIPTION--
+
+Lookup array of color names to six digit hexadecimal number corresponding
+to color, with preceding hash mark. Used when parsing colors.
+
+
index 0f03d3aada92b895d04e62ccacaa9a4f805d800d..3f832c104679c076995a60ccc1cbd327e1494df1 100644 (file)
@@ -1,13 +1,13 @@
-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
+Core.ConvertDocumentToFragment
+TYPE: bool
+DEFAULT: true
+--DESCRIPTION--
+
+This parameter determines whether or not the filter should convert
+input that is a full document with html and body tags to a fragment
+of just the contents of a body tag. This parameter is simply something
+HTML Purifier can do during an edge-case: for most inputs, this
+processing is not necessary.
+
+--ALIASES--
+Core.AcceptFullDocuments
index 392adb5a186f3d0a2e4731a5c2986776a14cbbb1..1ecc663787a1d9ca4e74fbafae33cecef58bfb62 100644 (file)
@@ -1,17 +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
-\r
+Core.DirectLexLineNumberSyncInterval
+TYPE: int
+VERSION: 2.0.0
+DEFAULT: 0
+--DESCRIPTION--
+
+<p>
+  Specifies the number of tokens the DirectLex line number tracking
+  implementations should process before attempting to resyncronize the
+  current line count by manually counting all previous new-lines. When
+  at 0, this functionality is disabled. Lower values will decrease
+  performance, and this is only strictly necessary if the counting
+  algorithm is buggy (in which case you should report it as a bug).
+  This has no effect when %Core.MaintainLineNumbers is disabled or DirectLex is
+  not being used. 
+</p>
+
index 9bca95c7c7f2db2544b3ecad21b33ee9862175ac..ab75dbd99565bf3cae4b323ec61d8d28c44df792 100644 (file)
@@ -1,14 +1,14 @@
-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
+Core.Encoding
+TYPE: istring
+DEFAULT: 'utf-8'
+--DESCRIPTION--
+If for some reason you are unable to convert all webpages to UTF-8, you can
+use this directive as a stop-gap compatibility change to let HTML Purifier
+deal with non UTF-8 input.  This technique has notable deficiencies:
+absolutely no characters outside of the selected character encoding will be
+preserved, not even the ones that have been ampersand escaped (this is due
+to a UTF-8 specific <em>feature</em> that automatically resolves all
+entities), making it pretty useless for anything except the most I18N-blind
+applications, although %Core.EscapeNonASCIICharacters offers fixes this
+trouble with another tradeoff. This directive only accepts ISO-8859-1 if
+iconv is not enabled.
index cca96c601889573bb035e76271260c54eb90b89c..554d6a249b4da739e06b11294cf8608357ca5c36 100644 (file)
@@ -1,9 +1,9 @@
-Core.EscapeInvalidChildren\r
-TYPE: bool\r
-DEFAULT: false\r
---DESCRIPTION--\r
-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.\r
+Core.EscapeInvalidChildren
+TYPE: bool
+DEFAULT: false
+--DESCRIPTION--
+When true, a child is found that is not allowed in the context of the
+parent element will be transformed into text as if it were ASCII. When
+false, that element and all internal tags will be dropped, though text will
+be preserved.  There is no option for dropping the element but preserving
+child nodes.
index 6e02a19bb4324cd98f30fbd5a485a075800af991..779a573ecef2e41289b6f619deadddb4abb860fc 100644 (file)
@@ -1,6 +1,6 @@
-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
+Core.EscapeInvalidTags
+TYPE: bool
+DEFAULT: false
+--DESCRIPTION--
+When true, invalid tags will be written back to the document as plain text.
+Otherwise, they are silently dropped.
index f8b7d38bfb02cb967f9e4f834dbc8c8a7128af8e..93b8a4b203799c27876b6e7f72d315e68646346b 100644 (file)
@@ -1,12 +1,12 @@
-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
+Core.EscapeNonASCIICharacters
+TYPE: bool
+VERSION: 1.4.0
+DEFAULT: false
+--DESCRIPTION--
+This directive overcomes a deficiency in %Core.Encoding by blindly
+converting all non-ASCII characters into decimal numeric entities before
+converting it to its native encoding. This means that even characters that
+can be expressed in the non-UTF-8 encoding will be entity-ized, which can
+be a real downer for encodings like Big5. It also assumes that the ASCII
+repetoire is available, although this is the case for almost all encodings.
+Anyway, use UTF-8! 
index 0a86d96a02b0d51700ffa29ea848a436e856bac4..f317221c8bf55f50e9a19ba5cc4ba3a5abebb447 100644 (file)
@@ -1,19 +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
-\r
+Core.HiddenElements
+TYPE: lookup
+--DEFAULT--
+array (
+  'script' => true,
+  'style' => true,
+)
+--DESCRIPTION--
+
+<p>
+  This directive is a lookup array of elements which should have their
+  contents removed when they are not allowed by the HTML definition.
+  For example, the contents of a <code>script</code> tag are not 
+  normally shown in a document, so if script tags are to be removed,
+  their contents should be removed to. This is opposed to a <code>b</code>
+  tag, which defines some presentational changes but does not hide its
+  contents.
+</p>
+
index 1be60037fc0d16972ad6fc2b9a5866335c75f8b7..38d7e661de42b6cc95277347df299daf1eb4329f 100644 (file)
@@ -1,11 +1,11 @@
-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
-\r
-\r
+Core.Language
+TYPE: string
+VERSION: 2.0.0
+DEFAULT: 'en'
+--DESCRIPTION--
+
+ISO 639 language code for localizable things in HTML Purifier to use,
+which is mainly error reporting. There is currently only an English (en)
+translation, so this directive is currently useless.
+
+
index 62125a4710c780d55fee2e1c4395b6d7c33c3d16..c32a6f6517c991ddaa1ec4c6136118237e1b1d4c 100644 (file)
@@ -1,33 +1,33 @@
-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
+Core.LexerImpl
+TYPE: mixed/null
+VERSION: 2.0.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+  This parameter determines what lexer implementation can be used. The
+  valid values are:
+</p>
+<dl>
+  <dt><em>null</em></dt>
+  <dd>
+    Recommended, the lexer implementation will be auto-detected based on
+    your PHP-version and configuration.
+  </dd>
+  <dt><em>string</em> lexer identifier</dt>
+  <dd>
+    This is a slim way of manually overridding the implementation.
+    Currently recognized values are: DOMLex (the default PHP5
+implementation)
+    and DirectLex (the default PHP4 implementation). Only use this if
+    you know what you are doing: usually, the auto-detection will
+    manage things for cases you aren't even aware of.
+  </dd>
+  <dt><em>object</em> lexer instance</dt>
+  <dd>
+    Super-advanced: you can specify your own, custom, implementation that
+    implements the interface defined by <code>HTMLPurifier_Lexer</code>.
+    I may remove this option simply because I don't expect anyone
+    to use it.
+  </dd>
+</dl>
index de10208f85b8be74a2a628f389f2f3d591f6e39b..00fa755020f439ee1f46bb3c2719aaa124316e6c 100644 (file)
@@ -1,16 +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
-\r
+Core.MaintainLineNumbers
+TYPE: bool/null
+VERSION: 2.0.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+  If true, HTML Purifier will add line number information to all tokens.
+  This is useful when error reporting is turned on, but can result in
+  significant performance degradation and should not be used when
+  unnecessary. This directive must be used with the DirectLex lexer,
+  as the DOMLex lexer does not (yet) support this functionality. 
+  If the value is null, an appropriate value will be selected based
+  on other configuration. 
+</p>
+
index 7ac86b3169aa22887853d44e24b449b397d49183..3b5c8fd0cd55717c49b929e0ccf53f9c96b2a931 100644 (file)
@@ -1,12 +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
-\r
+Core.RemoveInvalidImg
+TYPE: bool
+DEFAULT: true
+VERSION: 1.3.0
+--DESCRIPTION--
+
+<p>
+  This directive enables pre-emptive URI checking in <code>img</code> 
+  tags, as the attribute validation strategy is not authorized to 
+  remove elements from the document. Revert to pre-1.3.0 behavior by setting to false.
+</p>
+
index 531718ba7b425fd683c063f3dd1e2b81305067f7..1d0e9779efa8d1ce032abf4e8449c635c5f7ceb1 100644 (file)
@@ -1,11 +1,11 @@
-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
+Core.RemoveScriptContents
+TYPE: bool/null
+DEFAULT: NULL
+VERSION: 2.0.0
+DEPRECATED-VERSION: 2.1.0
+DEPRECATED-USE: Core.HiddenElements
+--DESCRIPTION--
+<p>
+  This directive enables HTML Purifier to remove not only script tags
+  but all of their contents.
+</p>
index 3240014d199af1d8dfb29a9f6e892be471ebb685..296982a5df1536506d78af6c63ae582348b2b47f 100644 (file)
@@ -1,2 +1,2 @@
-Core\r
-DESCRIPTION: Core features that are always available.\r
+Core
+DESCRIPTION: Core features that are always available.
index 36d11e959467c90673ece5fa9ab8c0b44a9ed066..aaa741635169e1cf8356a7983e54649efba2df02 100644 (file)
@@ -14,13 +14,49 @@ EXTERNAL: CSSTidy
 <p>
   Sample usage:
 </p>
-<pre><![CDATA[$config = HTMLPurifier_Config::createDefault();
-$config->set('Filter', 'ExtractStyleBlocks', true);
-$purifier = new HTMLPurifier($config);
-$styles = $purifier->context->get('StyleBlocks');
-foreach ($styles as $style) {
-    echo '<style type="text/css">' . $style . "</style>\n";
-}]]></pre>
+<pre><![CDATA[
+<?php
+    header('Content-type: text/html; charset=utf-8');
+    echo '<?xml version="1.0" encoding="UTF-8"?>';
+?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+<head>
+  <title>Filter.ExtractStyleBlocks</title>
+<?php
+    require_once '/path/to/library/HTMLPurifier.auto.php';
+    require_once '/path/to/csstidy.class.php';
+    
+    $dirty = '<style>body {color:#F00;}</style> Some text';
+
+    $config = HTMLPurifier_Config::createDefault();
+    $config->set('Filter', 'ExtractStyleBlocks', true);
+    $purifier = new HTMLPurifier($config);
+    
+    $html = $purifier->purify($dirty);
+    
+    // This implementation writes the stylesheets to the styles/ directory.
+    // You can also echo the styles inside the document, but it's a bit
+    // more difficult to make sure they get interpreted properly by
+    // browsers; try the usual CSS armoring techniques.
+    $styles = $purifier->context->get('StyleBlocks');
+    $dir = 'styles/';
+    if (!is_dir($dir)) mkdir($dir);
+    $hash = sha1($_GET['html']);
+    foreach ($styles as $i => $style) {
+        file_put_contents($name = $dir . $hash . "_$i");
+        echo '<link rel="stylesheet" type="text/css" href="'.$name.'" />';
+    }
+?>
+</head>
+<body>
+  <div>
+    <?php echo $html; ?>
+  </div>
+</b]]><![CDATA[ody>
+</html>
+]]></pre>
 <p>
   <strong>Warning:</strong> It is possible for a user to mount an
   imagecrash attack using this CSS. Counter-measures are difficult;
index 9fad43a8fa24f5bcf7fa954afa9f9ff63e91feb5..cf5f89cdc0e34ac52cee1fbaa1d4b903c4cdf045 100644 (file)
@@ -1,2 +1,2 @@
-Filter\r
-DESCRIPTION: Directives for turning filters on and off, or specifying custom filters.\r
+Filter
+DESCRIPTION: Directives for turning filters on and off, or specifying custom filters.
index d20010c7a6dafc1e9c8cd5f970f7a877f0e90789..96ac5e5d1c4446eff9eb0ec5c0a32870e88533e6 100644 (file)
@@ -1,14 +1,14 @@
-FilterParam.ExtractStyleBlocksEscaping\r
-TYPE: bool\r
-VERSION: 3.0.0\r
-DEFAULT: true\r
-ALIASES: Filter.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
-\r
+FilterParam.ExtractStyleBlocksEscaping
+TYPE: bool
+VERSION: 3.0.0
+DEFAULT: true
+ALIASES: Filter.ExtractStyleBlocksEscaping
+--DESCRIPTION--
+
+<p>
+  Whether or not to escape the dangerous characters &lt;, &gt; and &amp;
+  as \3C, \3E and \26, respectively. This is can be safely set to false
+  if the contents of StyleBlocks will be placed in an external stylesheet,
+  where there is no risk of it being interpreted as HTML. 
+</p>
+
index ec29078d857c9a45986f9bf1fa52322ffb58bced..366df44563460c384308cd090395d73e94e40f33 100644 (file)
@@ -1,28 +1,28 @@
-FilterParam.ExtractStyleBlocksScope\r
-TYPE: string/null\r
-VERSION: 3.0.0\r
-DEFAULT: NULL\r
-ALIASES: Filter.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
+FilterParam.ExtractStyleBlocksScope
+TYPE: string/null
+VERSION: 3.0.0
+DEFAULT: NULL
+ALIASES: Filter.ExtractStyleBlocksScope
+--DESCRIPTION--
+
+<p>
+  If you would like users to be able to define external stylesheets, but
+  only allow them to specify CSS declarations for a specific node and
+  prevent them from fiddling with other elements, use this directive.
+  It accepts any valid CSS selector, and will prepend this to any
+  CSS declaration extracted from the document. For example, if this
+  directive is set to <code>#user-content</code> and a user uses the
+  selector <code>a:hover</code>, the final selector will be
+  <code>#user-content a:hover</code>.
+</p>
+<p>
+  The comma shorthand may be used; consider the above example, with
+  <code>#user-content, #user-content2</code>, the final selector will
+  be <code>#user-content a:hover, #user-content2 a:hover</code>.
+</p>
+<p>
+  <strong>Warning:</strong> It is possible for users to bypass this measure
+  using a naughty + selector. This is a bug in CSS Tidy 1.3, not HTML
+  Purifier, and I am working to get it fixed. Until then, HTML Purifier
+  performs a basic check to prevent this.
+</p>
index 9329eb154487ec8672d4f18966a6256994865a6e..5fcd12441c52649e1d577ebbe07511df36b7c755 100644 (file)
@@ -1,22 +1,22 @@
-HTML.Allowed\r
-TYPE: itext/null\r
-VERSION: 2.0.0\r
-DEFAULT: NULL\r
---DESCRIPTION--\r
-\r
-<p>\r
-    This is a convenience directive that rolls the functionality of\r
-    %HTML.AllowedElements and %HTML.AllowedAttributes into one directive.\r
-    Specify elements and attributes that are allowed using:\r
-    <code>element1[attr1|attr2],element2...</code>. You can also use\r
-    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
-\r
+HTML.Allowed
+TYPE: itext/null
+VERSION: 2.0.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+    This is a convenience directive that rolls the functionality of
+    %HTML.AllowedElements and %HTML.AllowedAttributes into one directive.
+    Specify elements and attributes that are allowed using:
+    <code>element1[attr1|attr2],element2...</code>. You can also use
+    newlines instead of commas to separate elements.
+</p>
+<p>
+    <strong>Warning</strong>:
+    All of the constraints on the component directives are still enforced.
+    The syntax is a <em>subset</em> of TinyMCE's <code>valid_elements</code>
+    whitelist: directly copy-pasting it here will probably result in
+    broken whitelists. If %HTML.AllowedElements or %HTML.AllowedAttributes
+    are set, this directive has no effect.
+</p>
+
index 6ff12fc5fa08fde27c6dcc8bbd9a0c8ec3a11d84..88e696e8121b711f929f12c86739879116cc36c3 100644 (file)
@@ -1,19 +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
-\r
+HTML.AllowedAttributes
+TYPE: lookup/null
+VERSION: 1.3.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+    If HTML Purifier's attribute set is unsatisfactory, overload it! 
+    The syntax is "tag.attr" or "*.attr" for the global attributes 
+    (style, id, class, dir, lang, xml:lang).
+</p>
+<p>
+    <strong>Warning:</strong> If another directive conflicts with the 
+    elements here, <em>that</em> directive will win and override. For 
+    example, %HTML.EnableAttrID will take precedence over *.id in this 
+    directive.  You must set that directive to true before you can use 
+    IDs at all. 
+</p>
+
index 031a300678dbb2bc7054646d3da21200697cfec9..b667b3da8b05688d7c6fdfb7d612fd5e3db68a50 100644 (file)
@@ -1,18 +1,18 @@
-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 \r
-    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 a tag that HTML Purifier never \r
-    supported in the first place (like embed, form or head).  If you \r
-    change this, you probably also want to change %HTML.AllowedAttributes.\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
-\r
+HTML.AllowedElements
+TYPE: lookup/null
+VERSION: 1.3.0
+DEFAULT: NULL
+--DESCRIPTION--
+<p>
+    If HTML Purifier's tag set is unsatisfactory for your needs, you 
+    can overload it with your own list of tags to allow.  Note that this 
+    method is subtractive: it does its job by taking away from HTML Purifier 
+    usual feature set, so you cannot add a tag that HTML Purifier never 
+    supported in the first place (like embed, form or head).  If you 
+    change this, you probably also want to change %HTML.AllowedAttributes.
+</p>
+<p>
+    <strong>Warning:</strong> If another directive conflicts with the 
+    elements here, <em>that</em> directive will win and override. 
+</p>
+
index 7b8367e1b89fa15dc51178195fed61b9d991eb23..85e39f7647b2e2fadc2fd9cf3697bd28ba0665ba 100644 (file)
@@ -1,20 +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
-\r
+HTML.AllowedModules
+TYPE: lookup/null
+VERSION: 2.0.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+    A doctype comes with a set of usual modules to use. Without having
+    to mucking about with the doctypes, you can quickly activate or
+    disable these modules by specifying which modules you wish to allow
+    with this directive. This is most useful for unit testing specific
+    modules, although end users may find it useful for their own ends.
+</p>
+<p>
+    If you specify a module that does not exist, the manager will silently
+    fail to use it, so be careful! User-defined modules are not affected
+    by this directive. Modules defined in %HTML.CoreModules are not
+    affected by this directive. 
+</p>
+
index 47fe1433f450a8bfb0af87dcae76fa52d40ed792..e12edb6414f91614a0c069151d78124f4295db34 100644 (file)
@@ -1,18 +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
-\r
+HTML.BlockWrapper
+TYPE: string
+VERSION: 1.3.0
+DEFAULT: 'p'
+--DESCRIPTION--
+
+<p>
+    String name of element to wrap inline elements that are inside a block
+    context.  This only occurs in the children of blockquote in strict mode.
+</p>
+<p>
+    Example: by default value,
+    <code>&lt;blockquote&gt;Foo&lt;/blockquote&gt;</code> would become
+    <code>&lt;blockquote&gt;&lt;p&gt;Foo&lt;/p&gt;&lt;/blockquote&gt;</code>.
+    The <code>&lt;p&gt;</code> tags can be replaced with whatever you desire,
+    as long as it is a block level element. 
+</p>
+
index 78bffdbe082ad61aae78bb0597f3dbc08e8f2ddb..c629f66b45c530958d3da30ef9a4d4c88e49b0a8 100644 (file)
@@ -1,23 +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
-\r
+HTML.CoreModules
+TYPE: lookup
+VERSION: 2.0.0
+--DEFAULT--
+array (
+  'Structure' => true,
+  'Text' => true,
+  'Hypertext' => true,
+  'List' => true,
+  'NonXMLCommonAttributes' => true,
+  'XMLCommonAttributes' => true,
+  'CommonAttributes' => true,
+)
+--DESCRIPTION--
+
+<p>
+    Certain modularized doctypes (XHTML, namely), have certain modules
+    that must be included for the doctype to be an conforming document
+    type: put those modules here. By default, XHTML's core modules
+    are used. You can set this to a blank array to disable core module
+    protection, but this is not recommended. 
+</p>
+
index 4b6d39cfbfd857e882e68c6bf38faf5a109646f7..ee410ff07c0fcd505ce9bbaa999f4c317c353222 100644 (file)
@@ -1,10 +1,10 @@
-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 there own document\r
-type. This directive only applies when %HTML.Doctype is blank.\r
-\r
-\r
+HTML.CustomDoctype
+TYPE: string/null
+VERSION: 2.0.1
+DEFAULT: NULL
+--DESCRIPTION--
+
+A custom doctype for power-users who defined there own document
+type. This directive only applies when %HTML.Doctype is blank.
+
+
index 07f6b67cf9152162cdf99d86ed5c735ed7be7018..36a3e9dab4d3a45a594f63d2c34e2efca34d6419 100644 (file)
@@ -1,33 +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
-\r
+HTML.DefinitionID
+TYPE: string/null
+DEFAULT: NULL
+VERSION: 2.0.0
+--DESCRIPTION--
+
+<p>
+    Unique identifier for a custom-built HTML definition. If you edit
+    the raw version of the HTMLDefinition, introducing changes that the
+    configuration object does not reflect, you must specify this variable.
+    If you change your custom edits, you should change this directive, or
+    clear your cache. Example:
+</p>
+<pre>
+$config = HTMLPurifier_Config::createDefault();
+$config->set('HTML', 'DefinitionID', '1');
+$def = $config->getHTMLDefinition();
+$def->addAttribute('a', 'tabindex', 'Number');
+</pre>
+<p>
+    In the above example, the configuration is still at the defaults, but
+    using the advanced API, an extra attribute has been added. The
+    configuration object normally has no way of knowing that this change
+    has taken place, so it needs an extra directive: %HTML.DefinitionID.
+    If someone else attempts to use the default configuration, these two
+    pieces of code will not clobber each other in the cache, since one has
+    an extra directive attached to it.
+</p>
+<p>
+    You <em>must</em> specify a value to this directive to use the
+    advanced API features.
+</p>
+
index dfee8e7741fbf4e505f4715ae0e91fb39c4b78a6..bc084fa37febf35a237d190decb433639560a27b 100644 (file)
@@ -1,16 +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
-\r
+HTML.DefinitionRev
+TYPE: int
+VERSION: 2.0.0
+DEFAULT: 1
+--DESCRIPTION--
+
+<p>
+    Revision identifier for your custom definition specified in
+    %HTML.DefinitionID.  This serves the same purpose: uniquely identifying
+    your custom definition, but this one does so in a chronological
+    context: revision 3 is more up-to-date then revision 2.  Thus, when
+    this gets incremented, the cache handling is smart enough to clean
+    up any older revisions of your definition as well as flush the
+    cache.  
+</p>
+
index 1c58e2a371a35e1aed8480d40a3506fe3818dc17..051cf20a6221942171611e6bdfabbeb138feb3a9 100644 (file)
@@ -1,10 +1,10 @@
-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
+HTML.Doctype
+TYPE: string/null
+DEFAULT: NULL
+--DESCRIPTION--
+Doctype to use during filtering. Technically speaking this is not actually
+a doctype (as it does not identify a corresponding DTD), but we are using
+this name for sake of simplicity. When non-blank, this will override any
+older directives like %HTML.XHTML or %HTML.Strict.
+--ALLOWED--
+'HTML 4.01 Transitional', 'HTML 4.01 Strict', 'XHTML 1.0 Transitional', 'XHTML 1.0 Strict', 'XHTML 1.1'
index 0e680f62e9223025cc58af578cf569c135b726b3..ecc2f77b606419f464994b5223370e13a12d8e76 100644 (file)
@@ -1,12 +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
-\r
+HTML.Parent
+TYPE: string
+VERSION: 1.3.0
+DEFAULT: 'div'
+--DESCRIPTION--
+
+<p>
+    String name of element that HTML fragment passed to library will be 
+    inserted in.  An interesting variation would be using span as the 
+    parent element, meaning that only inline tags would be allowed. 
+</p>
+
index 39f81796349c400500369a44e10cc2e6a31213b3..c9697bde82cc6bc415845d8ed2e353a17ea1d16e 100644 (file)
@@ -1,8 +1,8 @@
-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
+HTML.Strict
+TYPE: bool
+VERSION: 1.3.0
+DEFAULT: false
+DEPRECATED-VERSION: 1.7.0
+DEPRECATED-USE: HTML.Doctype
+--DESCRIPTION--
+Determines whether or not to use Transitional (loose) or Strict rulesets.
index 7bf3c6d409160ce9e3bef90365f2d534b2a66bda..7fadf06c7388dc561dc9baf9c685383acb9ce177 100644 (file)
@@ -1,8 +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
-\r
+HTML.TidyAdd
+TYPE: lookup
+VERSION: 2.0.0
+DEFAULT: array()
+--DESCRIPTION--
+
+Fixes to add to the default set of Tidy fixes as per your level. 
+
index 7b98bc7e9357aec256e0f63f830baeec67c5c653..9383bbaaed7c60ad64e68e1d201e4e0d468d010a 100644 (file)
@@ -1,23 +1,23 @@
-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
+HTML.TidyLevel
+TYPE: string
+VERSION: 2.0.0
+DEFAULT: 'medium'
+--DESCRIPTION--
+
+<p>General level of cleanliness the Tidy module should enforce.
+There are four allowed values:</p>
+<dl>
+    <dt>none</dt>
+    <dd>No extra tidying should be done</dd>
+    <dt>light</dt>
+    <dd>Only fix elements that would be discarded otherwise due to
+    lack of support in doctype</dd>
+    <dt>medium</dt>
+    <dd>Enforce best practices</dd>
+    <dt>heavy</dt>
+    <dd>Transform all deprecated elements and attributes to standards
+    compliant equivalents</dd>
+</dl>
+
+--ALLOWED--
+'none', 'light', 'medium', 'heavy'
index 1e220695e00906f463dff684cdfb9870125ee8e5..4717f39fdb7e8dd09901e90def903c0c27135d03 100644 (file)
@@ -1,8 +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
-\r
+HTML.TidyRemove
+TYPE: lookup
+VERSION: 2.0.0
+DEFAULT: array()
+--DESCRIPTION--
+
+Fixes to remove from the default set of Tidy fixes as per your level. 
+
index 9785137dc9cf110a174ab7a37369d54bb796a8bf..6a4015e7bfea363474059d9df7f5a0d66760fa84 100644 (file)
@@ -1,7 +1,7 @@
-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
+HTML.Trusted
+TYPE: bool
+VERSION: 2.0.0
+DEFAULT: false
+--DESCRIPTION--
+Indicates whether or not the user input is trusted or not. If the input is
+trusted, a more expansive set of allowed tags and attributes will be used. 
index 7909203ef5790c7cdca6de435171a40b4fc561a3..8cca4b052a62006ee781e6532d4e30a6e9614628 100644 (file)
@@ -1,10 +1,10 @@
-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
+HTML.XHTML
+TYPE: bool
+DEFAULT: true
+VERSION: 1.1.0
+DEPRECATED-VERSION: 1.7.0
+DEPRECATED-USE: HTML.Doctype
+--DESCRIPTION--
+Determines whether or not output is XHTML 1.0 or HTML 4.01 flavor.
+--ALIASES--
+Core.XHTML
index 9b8b3a74a4d2472c9613a4452e7369d4c2c0f63f..935000863930bc37cd2f7b879ad92e6b9780bac8 100644 (file)
@@ -1,2 +1,2 @@
-HTML\r
-DESCRIPTION: Configuration regarding allowed HTML.\r
+HTML
+DESCRIPTION: Configuration regarding allowed HTML.
index 171b0fff6c46cd2eb47bc0a97b1d4cbba53bf28c..5a77edb4d229b632474a10c79d6c02db8d5357c6 100644 (file)
@@ -1,9 +1,9 @@
-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
+Output.CommentScriptContents
+TYPE: bool
+VERSION: 2.0.0
+DEFAULT: true
+--DESCRIPTION--
+Determines whether or not HTML Purifier should attempt to fix up the
+contents of script tags for legacy browsers with comments. 
+--ALIASES--
+Core.CommentScriptContents
index 2021572516dd57fa2189c2652ac655a9b2dbf95e..2dd17999df4fbfd5a943e1b90f721dbd0010b278 100644 (file)
@@ -1,13 +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
-\r
+Output.Newline
+TYPE: string/null
+VERSION: 2.0.1
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+    Newline string to format final output with. If left null, HTML Purifier
+    will auto-detect the default newline type of the system and use that;
+    you can manually override it here. Remember, \r\n is Windows, \r
+    is Mac, and \n is Unix. 
+</p>
+
diff --git a/lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt b/lib/htmlpurifier/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt
new file mode 100644 (file)
index 0000000..5392b3b
--- /dev/null
@@ -0,0 +1,13 @@
+Output.SortAttr
+TYPE: bool
+VERSION: 3.2.0
+DEFAULT: false
+--DESCRIPTION--
+<p>
+  If true, HTML Purifier will sort attributes by name before writing them back
+  to the document, converting a tag like: <code>&lt;el b="" a="" c="" /&gt;</code>
+  to <code>&lt;el a="" b="" c="" /&gt;</code>. This is a workaround for
+  a bug in FCKeditor which causes it to swap attributes order, adding noise
+  to text diffs. If you're not seeing this bug, chances are, you don't need
+  this directive.
+</p>
index 5d7f29d3f8a3062be892c5a66b5030935347d669..6d26c4ded9e14694d6f39cf398ea7a9ceef7efb2 100644 (file)
@@ -1,24 +1,24 @@
-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
+Output.TidyFormat
+TYPE: bool
+VERSION: 1.1.1
+DEFAULT: false
+--DESCRIPTION--
+<p>
+    Determines whether or not to run Tidy on the final output for pretty 
+    formatting reasons, such as indentation and wrap.
+</p>
+<p>
+    This can greatly improve readability for editors who are hand-editing
+    the HTML, but is by no means necessary as HTML Purifier has already
+    fixed all major errors the HTML may have had. Tidy is a non-default
+    extension, and this directive will silently fail if Tidy is not
+    available.
+</p>
+<p>
+    If you are looking to make the overall look of your page's source
+    better, I recommend running Tidy on the entire page rather than just
+    user-content (after all, the indentation relative to the containing
+    blocks will be incorrect).
+</p>
+--ALIASES--
+Core.TidyFormat
index 134e141f098a753941052948753a4f6ca8814b93..abd4b1b39e4290fce517c71c3bd79372da1fe95a 100644 (file)
@@ -1,2 +1,2 @@
-Output\r
-DESCRIPTION: Configuration relating to the generation of (X)HTML.\r
+Output
+DESCRIPTION: Configuration relating to the generation of (X)HTML.
index 99337628db613f2f8fe97a4f028684a6fbeacef2..2cd7067ddcec023aa1cb3df95940048d8e61f5a2 100644 (file)
@@ -1,6 +1,6 @@
-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
+Test.ForceNoIconv
+TYPE: bool
+DEFAULT: false
+--DESCRIPTION--
+When set to true, HTMLPurifier_Encoder will act as if iconv does not exist
+and use only pure PHP implementations.
index fec6f8d8f8376d76ff29f926cdb2b5bb8a3ae45f..a9928fec202a3ce59e012fdbf4d31648bf065312 100644 (file)
@@ -1,2 +1,2 @@
-Test\r
-DESCRIPTION: Developer testing configuration for our unit tests.\r
+Test
+DESCRIPTION: Developer testing configuration for our unit tests.
index 2686bac420f7dbbb1ed7e94b71fa7319f417af96..cf1271c0eba652d2b7cbe9c4d049682ed69a7c7b 100644 (file)
@@ -1,14 +1,14 @@
-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
-)\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
+URI.AllowedSchemes
+TYPE: lookup
+--DEFAULT--
+array (
+  'http' => true,
+  'https' => true,
+  'mailto' => true,
+  'ftp' => true,
+  'nntp' => true,
+  'news' => true,
+)
+--DESCRIPTION--
+Whitelist that defines the schemes that a URI is allowed to have.  This
+prevents XSS attacks from using pseudo-schemes like javascript or mocha.
index a0f8d97b05c87fee69bc6c5c85c48ee7025545cb..f68b82596eafafee57c28a91321e43d840507cb0 100644 (file)
@@ -1,17 +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
-\r
+URI.Base
+TYPE: string/null
+VERSION: 2.1.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+    The base URI is the URI of the document this purified HTML will be
+    inserted into.  This information is important if HTML Purifier needs
+    to calculate absolute URIs from relative URIs, such as when %URI.MakeAbsolute
+    is on.  You may use a non-absolute URI for this value, but behavior
+    may vary (%URI.MakeAbsolute deals nicely with both absolute and 
+    relative paths, but forwards-compatibility is not guaranteed).
+    <strong>Warning:</strong> If set, the scheme on this URI
+    overrides the one specified by %URI.DefaultScheme. 
+</p>
+
index 2f39c2fad3e0e6fd13ff45c9227ff149c3b9931a..ba472edadcd6fdb6940db3c7c38ae04c45bc4ac4 100644 (file)
@@ -1,10 +1,10 @@
-URI.DefaultScheme\r
-TYPE: string\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
+URI.DefaultScheme
+TYPE: string
+DEFAULT: 'http'
+--DESCRIPTION--
+
+<p>
+    Defines through what scheme the output will be served, in order to 
+    select the proper object validator when no scheme information is present.
+</p>
+
index 20bfc1db77bf8687bfaed39af70cd58adc3469e5..dd324a5923f56a8525b37c334fe1e1a5d0e69b87 100644 (file)
@@ -1,11 +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
-\r
+URI.DefinitionID
+TYPE: string/null
+VERSION: 2.1.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+    Unique identifier for a custom-built URI definition. If you  want
+    to add custom URIFilters, you must specify this value.
+</p>
+
index 7dabdc6d7f6cd290d92a851c4a204b51666655f8..9049897b66a726c51164e75f09cc1873c57857a5 100644 (file)
@@ -1,11 +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
-\r
+URI.DefinitionRev
+TYPE: int
+VERSION: 2.1.0
+DEFAULT: 1
+--DESCRIPTION--
+
+<p>
+    Revision identifier for your custom definition. See
+    %HTML.DefinitionRev for details. 
+</p>
+
index a97b2e29e298f4e0a57fc077be29eefe99b78c04..85fe3df10ab35ae459dd70943441c1719b454921 100644 (file)
@@ -1,13 +1,13 @@
-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
+URI.Disable
+TYPE: bool
+VERSION: 1.3.0
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+    Disables all URIs in all forms. Not sure why you'd want to do that 
+    (after all, the Internet's founded on the notion of a hyperlink). 
+</p>
+
+--ALIASES--
+Attr.DisableURI
index 6d3ceba86f64bec716b1b47b4e8f1a85eafb0ad7..5f9dc31f9f813ed81abc69fddcafc2545e77fe13 100644 (file)
@@ -1,10 +1,10 @@
-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
+URI.DisableExternal
+TYPE: bool
+VERSION: 1.2.0
+DEFAULT: false
+--DESCRIPTION--
+Disables links to external websites.  This is a highly effective anti-spam
+and anti-pagerank-leech measure, but comes at a hefty price: nolinks or
+images outside of your domain will be allowed.  Non-linkified URIs will
+still be preserved.  If you want to be able to link to subdomains or use
+absolute URIs, specify %URI.Host for your website. 
index 37f5d13f8ac268a37c8ea2934a048e33a5db78b9..af43b614022b47a5d0585a3814abc577213289c9 100644 (file)
@@ -1,12 +1,12 @@
-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
+URI.DisableExternalResources
+TYPE: bool
+VERSION: 1.3.0
+DEFAULT: false
+--DESCRIPTION--
+Disables the embedding of external resources, preventing users from
+embedding things like images from other hosts. This prevents access
+tracking (good for email viewers), bandwidth leeching, cross-site request
+forging, goatse.cx posting, and other nasties, but also results in a loss
+of end-user functionality (they can't directly post a pic they posted from
+Flickr anymore). Use it if you don't have a robust user-content moderation
+team. 
index a456051451bad005bb00a2cbaad97daca29b3542..2f4e57417abe0f5f2a6c26911e550190ac9cdbbb 100644 (file)
@@ -1,12 +1,12 @@
-URI.DisableResources\r
-TYPE: bool\r
-VERSION: 1.3.0\r
-DEFAULT: false\r
---DESCRIPTION--\r
-\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
-\r
+URI.DisableResources
+TYPE: bool
+VERSION: 1.3.0
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+    Disables embedding resources, essentially meaning no pictures. You can
+    still link to them though. See %URI.DisableExternalResources for why 
+    this might be a good idea. 
+</p>
+
index 15356ac2069d7215f94214b3a1896e1557376ab0..4815940753bccae0468025adb6bf12ca1f9d7b35 100644 (file)
@@ -1,19 +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
-\r
+URI.Host
+TYPE: string/null
+VERSION: 1.2.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+    Defines the domain name of the server, so we can determine whether or 
+    an absolute URI is from your website or not.  Not strictly necessary, 
+    as users should be using relative URIs to reference resources on your 
+    website.  It will, however, let you use absolute URIs to link to 
+    subdomains of the domain you post here: i.e. example.com will allow 
+    sub.example.com.  However, higher up domains will still be excluded: 
+    if you set %URI.Host to sub.example.com, example.com will be blocked. 
+    <strong>Note:</strong> This directive overrides %URI.Base because
+    a given page may be on a sub-domain, but you wish HTML Purifier to be
+    more relaxed and allow some of the parent domains too.
+</p>
+
index 5f5cbc5693bf89eec437640081d898ef0b50b932..a62a354374d4976245c9be291e615fcd02e4a956 100644 (file)
@@ -1,8 +1,8 @@
-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
+URI.HostBlacklist
+TYPE: list
+VERSION: 1.3.0
+DEFAULT: array()
+--DESCRIPTION--
+List of strings that are forbidden in the host of any URI. Use it to kill
+domain names of spam, etc. Note that it will catch anything in the domain,
+so <tt>moo.com</tt> will catch <tt>moo.com.example.com</tt>. 
index 2d2b40a5e436ba8a9dc231ea8d6863f036a79d52..0832b2cc6781454759897987764ade9cf69f5971 100644 (file)
@@ -1,12 +1,12 @@
-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
+URI.MakeAbsolute
+TYPE: bool
+VERSION: 2.1.0
+DEFAULT: false
+--DESCRIPTION--
+
+<p>
+    Converts all URIs into absolute forms. This is useful when the HTML
+    being filtered assumes a specific base path, but will actually be
+    viewed in a different context (and setting an alternate base URI is
+    not possible). %URI.Base must be set for this directive to work.
+</p>
index 7743ac2923917097783555f17f55c35da9a1e048..ed9e142d8b72ce7e35dc1d8e1f3fe896d7662d84 100644 (file)
@@ -1,82 +1,82 @@
-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
+URI.Munge
+TYPE: string/null
+VERSION: 1.3.0
+DEFAULT: NULL
+--DESCRIPTION--
+
+<p>
+    Munges all browsable (usually http, https and ftp)
+    absolute URIs into another URI, usually a URI redirection service.
+    This directive accepts a URI, formatted with a <code>%s</code> where 
+    the url-encoded original URI should be inserted (sample: 
+    <code>http://www.google.com/url?q=%s</code>).
+</p>
+<p>
+    Uses for this directive:
+</p>
+<ul>
+    <li>
+        Prevent PageRank leaks, while being fairly transparent 
+        to users (you may also want to add some client side JavaScript to 
+        override the text in the statusbar). <strong>Notice</strong>:
+        Many security experts believe that this form of protection does not deter spam-bots. 
+    </li>
+    <li>
+        Redirect users to a splash page telling them they are leaving your
+        website. While this is poor usability practice, it is often mandated
+        in corporate environments.
+    </li>
+</ul>
+<p>
+    Prior to HTML Purifier 3.1.1, this directive also enabled the munging
+    of browsable external resources, which could break things if your redirection
+    script was a splash page or used <code>meta</code> tags. To revert to
+    previous behavior, please use %URI.MungeResources.
+</p>
+<p>
+    You may want to also use %URI.MungeSecretKey along with this directive
+    in order to enforce what URIs your redirector script allows. Open
+    redirector scripts can be a security risk and negatively affect the
+    reputation of your domain name.
+</p>
+<p>
+    Starting with HTML Purifier 3.1.1, there is also these substitutions:
+</p>
+<table>
+    <thead>
+        <tr>
+            <th>Key</th>
+            <th>Description</th>
+            <th>Example <code>&lt;a href=""&gt;</code></th>
+        </tr>
+    </thead>
+    <tbody>
+        <tr>
+            <td>%r</td>
+            <td>1 - The URI embeds a resource<br />(blank) - The URI is merely a link</td>
+            <td></td>
+        </tr>
+        <tr>
+            <td>%n</td>
+            <td>The name of the tag this URI came from</td>
+            <td>a</td>
+        </tr>
+        <tr>
+            <td>%m</td>
+            <td>The name of the attribute this URI came from</td>
+            <td>href</td>
+        </tr>
+        <tr>
+            <td>%p</td>
+            <td>The name of the CSS property this URI came from, or blank if irrelevant</td>
+            <td></td>
+        </tr>
+    </tbody>
+</table>
+<p>
+    Admittedly, these letters are somewhat arbitrary; the only stipulation
+    was that they couldn't be a through f. r is for resource (I would have preferred
+    e, but you take what you can get), n is for name, m
+    was picked because it came after n (and I couldn't use a), p is for
+    property.
+</p>
index c75b13314223d500a85cb29d533ff18358ecc646..e910ee54035bbdf1ecaeae5400ed16b598422dce 100644 (file)
@@ -1,8 +1,8 @@
-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
+URI.OverrideAllowedSchemes
+TYPE: bool
+DEFAULT: true
+--DESCRIPTION--
+If this is set to true (which it is by default), you can override
+%URI.AllowedSchemes by simply registering a HTMLPurifier_URIScheme to the
+registry.  If false, you will also have to update that directive in order
+to add more schemes.
index 114ecb17f39e1337ad6d76092e9bcc1d7353705a..4bcdb95b1fd4a97f0addcf09cd688e9c7775571c 100644 (file)
@@ -1,2 +1,2 @@
-URI\r
-DESCRIPTION: Features regarding Uniform Resource Identifiers.\r
+URI
+DESCRIPTION: Features regarding Uniform Resource Identifiers.
index 16438fda448b4733ae07d27166c2dce22f168c0f..15c8d97fee260fcc80f65c2b6a045ed7a2a33db1 100644 (file)
@@ -37,33 +37,35 @@ class HTMLPurifier_ContentSets
         // sorry, no way of overloading
         foreach ($modules as $module_i => $module) {
             foreach ($module->content_sets as $key => $value) {
-                if (isset($this->info[$key])) {
+                $temp = $this->convertToLookup($value);
+                if (isset($this->lookup[$key])) {
                     // add it into the existing content set
-                    $this->info[$key] = $this->info[$key] . ' | ' . $value;
+                    $this->lookup[$key] = array_merge($this->lookup[$key], $temp);
                 } else {
-                    $this->info[$key] = $value;
+                    $this->lookup[$key] = $temp;
                 }
             }
         }
-        // perform content_set expansions
-        $this->keys = array_keys($this->info);
-        foreach ($this->info as $i => $set) {
-            // only performed once, so infinite recursion is not
-            // a problem
-            $this->info[$i] =
-                str_replace(
-                    $this->keys,
-                    // must be recalculated each time due to
-                    // changing substitutions
-                    array_values($this->info),
-                $set);
+        $old_lookup = false;
+        while ($old_lookup !== $this->lookup) {
+            $old_lookup = $this->lookup;
+            foreach ($this->lookup as $i => $set) {
+                $add = array();
+                foreach ($set as $element => $x) {
+                    if (isset($this->lookup[$element])) {
+                        $add += $this->lookup[$element];
+                        unset($this->lookup[$i][$element]);
+                    }
+                }
+                $this->lookup[$i] += $add;
+            }
         }
-        $this->values = array_values($this->info);
         
-        // generate lookup tables
-        foreach ($this->info as $name => $set) {
-            $this->lookup[$name] = $this->convertToLookup($set);
+        foreach ($this->lookup as $key => $lookup) {
+            $this->info[$key] = implode(' | ', array_keys($lookup));
         }
+        $this->keys   = array_keys($this->info);
+        $this->values = array_values($this->info);
     }
     
     /**
@@ -75,12 +77,22 @@ class HTMLPurifier_ContentSets
         if (!empty($def->child)) return; // already done!
         $content_model = $def->content_model;
         if (is_string($content_model)) {
-            $def->content_model = str_replace(
-                $this->keys, $this->values, $content_model);
+            // Assume that $this->keys is alphanumeric
+            $def->content_model = preg_replace_callback(
+                '/\b(' . implode('|', $this->keys) . ')\b/',
+                array($this, 'generateChildDefCallback'),
+                $content_model
+            );
+            //$def->content_model = str_replace(
+            //    $this->keys, $this->values, $content_model);
         }
         $def->child = $this->getChildDef($def, $module);
     }
     
+    public function generateChildDefCallback($matches) {
+        return $this->info[$matches[0]];
+    }
+    
     /**
      * Instantiates a ChildDef based on content_model and content_model_type
      * member variables in HTMLPurifier_ElementDef
index 62235e225dbb7d44c26ed024faa1b05c3e9584e7..d741764c860feca646ebb0adcbb59163a73bc544 100644 (file)
@@ -1,46 +1,46 @@
-<?php\r
-\r
-require_once 'HTMLPurifier/DefinitionCache/Decorator.php';\r
-\r
-/**\r
- * Definition cache decorator template.\r
- */\r
-class HTMLPurifier_DefinitionCache_Decorator_Template extends\r
-      HTMLPurifier_DefinitionCache_Decorator\r
-{\r
-    \r
-    var $name = 'Template'; // replace this\r
-    \r
-    function copy() {\r
-        // replace class name with yours\r
-        return new HTMLPurifier_DefinitionCache_Decorator_Template();\r
-    }\r
-    \r
-    // remove methods you don't need\r
-    \r
-    function add($def, $config) {\r
-        return parent::add($def, $config);\r
-    }\r
-    \r
-    function set($def, $config) {\r
-        return parent::set($def, $config);\r
-    }\r
-    \r
-    function replace($def, $config) {\r
-        return parent::replace($def, $config);\r
-    }\r
-    \r
-    function get($config) {\r
-        return parent::get($config);\r
-    }\r
-    \r
-    function flush() {\r
-        return parent::flush();\r
-    }\r
-    \r
-    function cleanup($config) {\r
-        return parent::cleanup($config);\r
-    }\r
-    \r
-}\r
-\r
+<?php
+
+require_once 'HTMLPurifier/DefinitionCache/Decorator.php';
+
+/**
+ * Definition cache decorator template.
+ */
+class HTMLPurifier_DefinitionCache_Decorator_Template extends
+      HTMLPurifier_DefinitionCache_Decorator
+{
+    
+    var $name = 'Template'; // replace this
+    
+    function copy() {
+        // replace class name with yours
+        return new HTMLPurifier_DefinitionCache_Decorator_Template();
+    }
+    
+    // remove methods you don't need
+    
+    function add($def, $config) {
+        return parent::add($def, $config);
+    }
+    
+    function set($def, $config) {
+        return parent::set($def, $config);
+    }
+    
+    function replace($def, $config) {
+        return parent::replace($def, $config);
+    }
+    
+    function get($config) {
+        return parent::get($config);
+    }
+    
+    function flush() {
+        return parent::flush();
+    }
+    
+    function cleanup($config) {
+        return parent::cleanup($config);
+    }
+    
+}
+
diff --git a/lib/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/README b/lib/htmlpurifier/HTMLPurifier/DefinitionCache/Serializer/README
new file mode 100644 (file)
index 0000000..962b80a
--- /dev/null
@@ -0,0 +1 @@
+This is a dummy file to prevent Git from ignoring this empty directory.
index 0518814ec3632aab6128c9d8886ffd3be24f9bc2..c2df31325433d37f4e8f9ae91185cef08f1a2ff2 100644 (file)
@@ -271,6 +271,12 @@ class HTMLPurifier_Encoder
         set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
         if ($iconv && !$config->get('Test', 'ForceNoIconv')) {
             $str = iconv($encoding, 'utf-8//IGNORE', $str);
+            if ($str === false) {
+                // $encoding is not a valid encoding
+                restore_error_handler();
+                trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR);
+                return '';
+            }
             // If the string is bjorked by Shift_JIS or a similar encoding
             // that doesn't support all of ASCII, convert the naughty
             // characters to their true byte-wise ASCII/UTF-8 equivalents.
@@ -282,7 +288,7 @@ class HTMLPurifier_Encoder
             restore_error_handler();
             return $str;
         }
-        trigger_error('Encoding not supported', E_USER_ERROR);
+        trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);
     }
     
     /**
index 34354844c841b0d8f20bc1a43b23ec6269d53a63..16cc89c67e09b8f30b31b1ce7e60ea581d74d419 100644 (file)
@@ -7,22 +7,37 @@
 class HTMLPurifier_ErrorCollector
 {
     
-    protected $errors = array();
+    /**
+     * Identifiers for the returned error array. These are purposely numeric
+     * so list() can be used.
+     */
+    const LINENO   = 0;
+    const SEVERITY = 1;
+    const MESSAGE  = 2;
+    const CHILDREN = 3;
+    
+    protected $errors;
+    protected $_current;
+    protected $_stacks = array(array());
     protected $locale;
     protected $generator;
     protected $context;
     
+    protected $lines = array();
+    
     public function __construct($context) {
         $this->locale    =& $context->get('Locale');
-        $this->generator =& $context->get('Generator');
         $this->context   = $context;
+        $this->_current  =& $this->_stacks[0];
+        $this->errors    =& $this->_stacks[0];
     }
     
     /**
      * Sends an error message to the collector for later use
-     * @param $line Integer line number, or HTMLPurifier_Token that caused error
      * @param $severity int Error severity, PHP error style (don't use E_USER_)
      * @param $msg string Error message text
+     * @param $subst1 string First substitution for $msg
+     * @param $subst2 string ...
      */
     public function send($severity, $msg) {
         
@@ -35,6 +50,7 @@ class HTMLPurifier_ErrorCollector
         
         $token = $this->context->get('CurrentToken', true);
         $line  = $token ? $token->line : $this->context->get('CurrentLine', true);
+        $col   = $token ? $token->col  : $this->context->get('CurrentCol',  true);
         $attr  = $this->context->get('CurrentAttr', true);
         
         // perform special substitutions, also add custom parameters
@@ -55,13 +71,66 @@ class HTMLPurifier_ErrorCollector
         
         if (!empty($subst)) $msg = strtr($msg, $subst);
         
-        $this->errors[] = array($line, $severity, $msg);
+        // (numerically indexed)
+        $error = array(
+            self::LINENO   => $line,
+            self::SEVERITY => $severity,
+            self::MESSAGE  => $msg,
+            self::CHILDREN => array()
+        );
+        $this->_current[] = $error;
+        
+        
+        // NEW CODE BELOW ...
+        
+        $struct = null;
+        // Top-level errors are either:
+        //  TOKEN type, if $value is set appropriately, or
+        //  "syntax" type, if $value is null
+        $new_struct = new HTMLPurifier_ErrorStruct();
+        $new_struct->type = HTMLPurifier_ErrorStruct::TOKEN;
+        if ($token) $new_struct->value = clone $token;
+        if (is_int($line) && is_int($col)) {
+            if (isset($this->lines[$line][$col])) {
+                $struct = $this->lines[$line][$col];
+            } else {
+                $struct = $this->lines[$line][$col] = $new_struct;
+            }
+            // These ksorts may present a performance problem
+            ksort($this->lines[$line], SORT_NUMERIC);
+        } else {
+            if (isset($this->lines[-1])) {
+                $struct = $this->lines[-1];
+            } else {
+                $struct = $this->lines[-1] = $new_struct;
+            }
+        }
+        ksort($this->lines, SORT_NUMERIC);
+        
+        // Now, check if we need to operate on a lower structure
+        if (!empty($attr)) {
+            $struct = $struct->getChild(HTMLPurifier_ErrorStruct::ATTR, $attr);
+            if (!$struct->value) {
+                $struct->value = array($attr, 'PUT VALUE HERE');
+            }
+        }
+        if (!empty($cssprop)) {
+            $struct = $struct->getChild(HTMLPurifier_ErrorStruct::CSSPROP, $cssprop);
+            if (!$struct->value) {
+                // if we tokenize CSS this might be a little more difficult to do
+                $struct->value = array($cssprop, 'PUT VALUE HERE');
+            }
+        }
+        
+        // Ok, structs are all setup, now time to register the error
+        $struct->addError($severity, $msg);
     }
     
     /**
      * Retrieves raw error data for custom formatter to use
-     * @param List of arrays in format of array(Error message text,
-     *        token that caused error, tokens surrounding token)
+     * @param List of arrays in format of array(line of error,
+     *        error severity, error message,
+     *        recursive sub-errors array)
      */
     public function getRaw() {
         return $this->errors;
@@ -70,38 +139,25 @@ class HTMLPurifier_ErrorCollector
     /**
      * Default HTML formatting implementation for error messages
      * @param $config Configuration array, vital for HTML output nature
+     * @param $errors Errors array to display; used for recursion.
      */
-    public function getHTMLFormatted($config) {
+    public function getHTMLFormatted($config, $errors = null) {
         $ret = array();
         
-        $errors = $this->errors;
-        
-        // sort error array by line
-        // line numbers are enabled if they aren't explicitly disabled
-        if ($config->get('Core', 'MaintainLineNumbers') !== false) {
-            $has_line       = array();
-            $lines          = array();
-            $original_order = array();
-            foreach ($errors as $i => $error) {
-                $has_line[] = (int) (bool) $error[0];
-                $lines[] = $error[0];
-                $original_order[] = $i;
-            }
-            array_multisort($has_line, SORT_DESC, $lines, SORT_ASC, $original_order, SORT_ASC, $errors);
-        }
+        $this->generator = new HTMLPurifier_Generator($config, $this->context);
+        if ($errors === null) $errors = $this->errors;
+        
+        // 'At line' message needs to be removed
         
-        foreach ($errors as $error) {
-            list($line, $severity, $msg) = $error;
-            $string = '';
-            $string .= '<strong>' . $this->locale->getErrorName($severity) . '</strong>: ';
-            $string .= $this->generator->escape($msg); 
-            if ($line) {
-                // have javascript link generation that causes 
-                // textarea to skip to the specified line
-                $string .= $this->locale->formatMessage(
-                    'ErrorCollector: At line', array('line' => $line));
+        // generation code for new structure goes here. It needs to be recursive.
+        foreach ($this->lines as $line => $col_array) {
+            if ($line == -1) continue;
+            foreach ($col_array as $col => $struct) {
+                $this->_renderStruct($ret, $struct, $line, $col);
             }
-            $ret[] = $string;
+        }
+        if (isset($this->lines[-1])) {
+            $this->_renderStruct($ret, $this->lines[-1]);
         }
         
         if (empty($errors)) {
@@ -112,5 +168,41 @@ class HTMLPurifier_ErrorCollector
         
     }
     
+    private function _renderStruct(&$ret, $struct, $line = null, $col = null) {
+        $stack = array($struct);
+        $context_stack = array(array());
+        while ($current = array_pop($stack)) {
+            $context = array_pop($context_stack);
+            foreach ($current->errors as $error) {
+                list($severity, $msg) = $error;
+                $string = '';
+                $string .= '<div>';
+                // W3C uses an icon to indicate the severity of the error.
+                $error = $this->locale->getErrorName($severity);
+                $string .= "<span class=\"error e$severity\"><strong>$error</strong></span> ";
+                if (!is_null($line) && !is_null($col)) {
+                    $string .= "<em class=\"location\">Line $line, Column $col: </em> ";
+                } else {
+                    $string .= '<em class="location">End of Document: </em> ';
+                }
+                $string .= '<strong class="description">' . $this->generator->escape($msg) . '</strong> ';
+                $string .= '</div>';
+                // Here, have a marker for the character on the column appropriate.
+                // Be sure to clip extremely long lines.
+                //$string .= '<pre>';
+                //$string .= '';
+                //$string .= '</pre>';
+                $ret[] = $string;
+            }
+            foreach ($current->children as $type => $array) {
+                $context[] = $current;
+                $stack = array_merge($stack, array_reverse($array, true));
+                for ($i = count($array); $i > 0; $i--) {
+                    $context_stack[] = $context;
+                }
+            }
+        }
+    }
+    
 }
 
diff --git a/lib/htmlpurifier/HTMLPurifier/ErrorStruct.php b/lib/htmlpurifier/HTMLPurifier/ErrorStruct.php
new file mode 100644 (file)
index 0000000..9da712b
--- /dev/null
@@ -0,0 +1,58 @@
+<?php
+
+/**
+ * Records errors for particular segments of an HTML document such as tokens,
+ * attributes or CSS properties. They can contain error structs (which apply
+ * to components of what they represent), but their main purpose is to hold
+ * errors applying to whatever struct is being used.
+ */
+class HTMLPurifier_ErrorStruct
+{
+    
+    /**
+     * Possible values for $children first-key. Note that top-level structures
+     * are automatically token-level.
+     */
+    const TOKEN     = 0;
+    const ATTR      = 1;
+    const CSSPROP   = 2;
+    
+    /**
+     * Type of this struct.
+     */
+    public $type;
+    
+    /**
+     * Value of the struct we are recording errors for. There are various
+     * values for this:
+     *  - TOKEN: Instance of HTMLPurifier_Token
+     *  - ATTR: array('attr-name', 'value')
+     *  - CSSPROP: array('prop-name', 'value')
+     */
+    public $value;
+    
+    /**
+     * Errors registered for this structure.
+     */
+    public $errors = array();
+    
+    /**
+     * Child ErrorStructs that are from this structure. For example, a TOKEN
+     * ErrorStruct would contain ATTR ErrorStructs. This is a multi-dimensional
+     * array in structure: [TYPE]['identifier']
+     */
+    public $children = array();
+    
+    public function getChild($type, $id) {
+        if (!isset($this->children[$type][$id])) {
+            $this->children[$type][$id] = new HTMLPurifier_ErrorStruct();
+            $this->children[$type][$id]->type = $type;
+        }
+        return $this->children[$type][$id];
+    }
+    
+    public function addError($severity, $message) {
+        $this->errors[] = array($severity, $message);
+    }
+    
+}
index 42ea17fe6bc994ec9f6753bda2ffb7ee0c599ff0..d4c42fbff9d1556006234cf5c6e0e922947b9faa 100644 (file)
@@ -26,6 +26,11 @@ class HTMLPurifier_Generator
      */
     private $_def;
     
+    /**
+     * Cache of %Output.SortAttr
+     */
+    private $_sortAttr;
+    
     /**
      * Configuration for the generator
      */
@@ -38,6 +43,7 @@ class HTMLPurifier_Generator
     public function __construct($config, $context) {
         $this->config = $config;
         $this->_scriptFix = $config->get('Output', 'CommentScriptContents');
+        $this->_sortAttr = $config->get('Output', 'SortAttr');
         $this->_def = $config->getHTMLDefinition();
         $this->_xhtml = $this->_def->doctype->xml;
     }
@@ -142,6 +148,7 @@ class HTMLPurifier_Generator
      */
     public function generateAttributes($assoc_array_of_attributes, $element = false) {
         $html = '';
+        if ($this->_sortAttr) ksort($assoc_array_of_attributes);
         foreach ($assoc_array_of_attributes as $key => $value) {
             if (!$this->_xhtml) {
                 // Remove namespaced attributes
diff --git a/lib/htmlpurifier/HTMLPurifier/HTMLModule/Forms.php b/lib/htmlpurifier/HTMLPurifier/HTMLModule/Forms.php
new file mode 100644 (file)
index 0000000..6a2dc69
--- /dev/null
@@ -0,0 +1,117 @@
+<?php
+
+/**
+ * XHTML 1.1 Forms module, defines all form-related elements found in HTML 4.
+ */
+class HTMLPurifier_HTMLModule_Forms extends HTMLPurifier_HTMLModule
+{
+    public $name = 'Forms';
+    public $safe = false;
+    
+    public $content_sets = array(
+        'Block' => 'Form',
+        'Inline' => 'Formctrl',
+    );
+    
+    public function setup($config) {
+        $form = $this->addElement('form', 'Form',
+          'Required: Heading | List | Block | fieldset', 'Common', array(
+            'accept' => 'ContentTypes',
+            'accept-charset' => 'Charsets',
+            'action*' => 'URI',
+            'method' => 'Enum#get,post',
+            // really ContentType, but these two are the only ones used today
+            'enctype' => 'Enum#application/x-www-form-urlencoded,multipart/form-data',
+        ));
+        $form->excludes = array('form' => true);
+        
+        $input = $this->addElement('input', 'Formctrl', 'Empty', 'Common', array(
+            'accept' => 'ContentTypes',
+            'accesskey' => 'Character',
+            'alt' => 'Text',
+            'checked' => 'Bool#checked',
+            'disabled' => 'Bool#disabled',
+            'maxlength' => 'Number',
+            'name' => 'CDATA',
+            'readonly' => 'Bool#readonly',
+            'size' => 'Number',
+            'src' => 'URI#embeds',
+            'tabindex' => 'Number',
+            'type' => 'Enum#text,password,checkbox,button,radio,submit,reset,file,hidden,image',
+            'value' => 'CDATA',
+        ));
+        $input->attr_transform_post[] = new HTMLPurifier_AttrTransform_Input();
+        
+        $this->addElement('select', 'Formctrl', 'Required: optgroup | option', 'Common', array(
+            'disabled' => 'Bool#disabled',
+            'multiple' => 'Bool#multiple',
+            'name' => 'CDATA',
+            'size' => 'Number',
+            'tabindex' => 'Number',
+        ));
+        
+        $this->addElement('option', false, 'Optional: #PCDATA', 'Common', array(
+            'disabled' => 'Bool#disabled',
+            'label' => 'Text',
+            'selected' => 'Bool#selected',
+            'value' => 'CDATA',
+        ));
+        // It's illegal for there to be more than one selected, but not
+        // be multiple. Also, no selected means undefined behavior. This might
+        // be difficult to implement; perhaps an injector, or a context variable.
+        
+        $textarea = $this->addElement('textarea', 'Formctrl', 'Optional: #PCDATA', 'Common', array(
+            'accesskey' => 'Character',
+            'cols*' => 'Number',
+            'disabled' => 'Bool#disabled',
+            'name' => 'CDATA',
+            'readonly' => 'Bool#readonly',
+            'rows*' => 'Number',
+            'tabindex' => 'Number',
+        ));
+        $textarea->attr_transform_pre[] = new HTMLPurifier_AttrTransform_Textarea();
+        
+        $button = $this->addElement('button', 'Formctrl', 'Optional: #PCDATA | Heading | List | Block | Inline', 'Common', array(
+            'accesskey' => 'Character',
+            'disabled' => 'Bool#disabled',
+            'name' => 'CDATA',
+            'tabindex' => 'Number',
+            'type' => 'Enum#button,submit,reset',
+            'value' => 'CDATA',
+        ));
+        
+        // For exclusions, ideally we'd specify content sets, not literal elements
+        $button->excludes = $this->makeLookup(
+            'form', 'fieldset', // Form
+            'input', 'select', 'textarea', 'label', 'button', // Formctrl
+            'a' // as per HTML 4.01 spec, this is omitted by modularization
+        );
+        
+        // Extra exclusion: img usemap="" is not permitted within this element.
+        // We'll omit this for now, since we don't have any good way of
+        // indicating it yet.
+        
+        // This is HIGHLY user-unfriendly; we need a custom child-def for this
+        $this->addElement('fieldset', 'Form', 'Custom: (#WS?,legend,(Flow|#PCDATA)*)', 'Common');
+        
+        $label = $this->addElement('label', 'Formctrl', 'Optional: #PCDATA | Inline', 'Common', array(
+            'accesskey' => 'Character',
+            // 'for' => 'IDREF', // IDREF not implemented, cannot allow
+        ));
+        $label->excludes = array('label' => true);
+        
+        $this->addElement('legend', false, 'Optional: #PCDATA | Inline', 'Common', array(
+            'accesskey' => 'Character',
+        ));
+        
+        $this->addElement('optgroup', false, 'Required: option', 'Common', array(
+            'disabled' => 'Bool#disabled',
+            'label*' => 'Text',
+        ));
+        
+        // Don't forget an injector for <isindex>. This one's a little complex
+        // because it maps to multiple elements.
+        
+    }
+}
+
diff --git a/lib/htmlpurifier/HTMLPurifier/HTMLModule/Name.php b/lib/htmlpurifier/HTMLPurifier/HTMLModule/Name.php
new file mode 100644 (file)
index 0000000..db2ab4f
--- /dev/null
@@ -0,0 +1,16 @@
+<?php
+
+class HTMLPurifier_HTMLModule_Name extends HTMLPurifier_HTMLModule
+{
+    
+    public $name = 'Name';
+    
+    public function setup($config) {
+        $elements = array('a', 'applet', 'form', 'frame', 'iframe', 'img', 'map');
+        foreach ($elements as $name) {
+            $element = $this->addBlankElement($name);
+            $element->attr['name'] = 'ID';
+        }
+    }
+    
+}
index 7dfd6b3134193dad68e37c9937a08e01956e902d..cd4ce2648ad9173d03e776aaf0470f73da408c9d 100644 (file)
@@ -1,46 +1,46 @@
-<?php\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
-    public $name = 'Object';\r
-    public $safe = false;\r
-    \r
-    public function setup($config) {\r
-        \r
-        $this->addElement('object', 'Inline', 'Optional: #PCDATA | Flow | param', '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('param', false, 'Empty', false,\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
+<?php
+
+/**
+ * XHTML 1.1 Object Module, defines elements for generic object inclusion
+ * @warning Users will commonly use <embed> to cater to legacy browsers: this
+ *      module does not allow this sort of behavior
+ */
+class HTMLPurifier_HTMLModule_Object extends HTMLPurifier_HTMLModule
+{
+    
+    public $name = 'Object';
+    public $safe = false;
+    
+    public function setup($config) {
+        
+        $this->addElement('object', 'Inline', 'Optional: #PCDATA | Flow | param', 'Common', 
+            array(
+                'archive' => 'URI',
+                'classid' => 'URI',
+                'codebase' => 'URI',
+                'codetype' => 'Text',
+                'data' => 'URI',
+                'declare' => 'Bool#declare',
+                'height' => 'Length',
+                'name' => 'CDATA',
+                'standby' => 'Text',
+                'tabindex' => 'Number',
+                'type' => 'ContentType',
+                'width' => 'Length'
+            )
+        );
+
+        $this->addElement('param', false, 'Empty', false,
+            array(
+                'id' => 'ID',
+                'name*' => 'Text',
+                'type' => 'Text',
+                'value' => 'Text',
+                'valuetype' => 'Enum#data,ref,object'
+           )
+        );
+    
+    }
+    
+}
+
diff --git a/lib/htmlpurifier/HTMLPurifier/HTMLModule/Tidy/Name.php b/lib/htmlpurifier/HTMLPurifier/HTMLModule/Tidy/Name.php
new file mode 100644 (file)
index 0000000..9056e5f
--- /dev/null
@@ -0,0 +1,23 @@
+<?php
+
+/**
+ * Name is deprecated, but allowed in strict doctypes, so onl
+ */
+class HTMLPurifier_HTMLModule_Tidy_Name extends HTMLPurifier_HTMLModule_Tidy
+{
+    public $name = 'Tidy_Name';
+    public $defaultLevel = 'heavy';
+    public function makeFixes() {
+        
+        $r = array();
+        
+        // @name for img, a -----------------------------------------------
+        // Technically, it's allowed even on strict, so we allow authors to use
+        // it. However, it's deprecated in future versions of XHTML.
+        $r['img@name'] = 
+        $r['a@name'] = new HTMLPurifier_AttrTransform_Name();
+        
+        return $r;
+    }
+}
+
index babbb1903f422c03cee205e161710c338f90fbe4..41c1f78eacc717067548830f1abf9ed3b8ab45bb 100644 (file)
@@ -7,7 +7,15 @@ class HTMLPurifier_HTMLModule_Tidy_Proprietary extends HTMLPurifier_HTMLModule_T
     public $defaultLevel = 'light';
     
     public function makeFixes() {
-        return array();
+        $r = array();
+        $r['table@background'] = new HTMLPurifier_AttrTransform_Background();
+        $r['td@background']    = new HTMLPurifier_AttrTransform_Background();
+        $r['th@background']    = new HTMLPurifier_AttrTransform_Background();
+        $r['tr@background']    = new HTMLPurifier_AttrTransform_Background();
+        $r['thead@background'] = new HTMLPurifier_AttrTransform_Background();
+        $r['tfoot@background'] = new HTMLPurifier_AttrTransform_Background();
+        $r['tbody@background'] = new HTMLPurifier_AttrTransform_Background();
+        return $r;
     }
     
 }
index 2c6407c7014dd0a315a67394a0a4118870935ee3..9e1292500c83a8d92b6e52f4eeea088727784b29 100644 (file)
@@ -103,10 +103,6 @@ class HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4 extends HTMLPurifier_HTMLModule
         // @hspace for img ------------------------------------------------
         $r['img@hspace'] = new HTMLPurifier_AttrTransform_ImgSpace('hspace');
         
-        // @name for img, a -----------------------------------------------
-        $r['img@name'] = 
-        $r['a@name'] = new HTMLPurifier_AttrTransform_Name();
-        
         // @noshade for hr ------------------------------------------------
         // this transformation is not precise but often good enough.
         // different browsers use different styles to designate noshade
index 3664e88fcadd2888bd9538d8112fbf7ce2bf8fe4..63e0ebf8983b205573fa050deeda0302850323a0 100644 (file)
@@ -63,7 +63,11 @@ class HTMLPurifier_HTMLModuleManager
         $common = array(
             'CommonAttributes', 'Text', 'Hypertext', 'List',
             'Presentation', 'Edit', 'Bdo', 'Tables', 'Image',
-            'StyleAttribute', 'Scripting', 'Object'
+            'StyleAttribute',
+            // Unsafe:
+            'Scripting', 'Object',  'Forms',
+            // Sorta legacy, but present in strict:
+            'Name', 
         );
         $transitional = array('Legacy', 'Target');
         $xml = array('XMLCommonAttributes');
@@ -82,7 +86,7 @@ class HTMLPurifier_HTMLModuleManager
         $this->doctypes->register(
             'HTML 4.01 Strict', false,
             array_merge($common, $non_xml),
-            array('Tidy_Strict', 'Tidy_Proprietary'),
+            array('Tidy_Strict', 'Tidy_Proprietary', 'Tidy_Name'),
             array(),
             '-//W3C//DTD HTML 4.01//EN',
             'http://www.w3.org/TR/html4/strict.dtd'
@@ -91,7 +95,7 @@ class HTMLPurifier_HTMLModuleManager
         $this->doctypes->register(
             'XHTML 1.0 Transitional', true,
             array_merge($common, $transitional, $xml, $non_xml),
-            array('Tidy_Transitional', 'Tidy_XHTML', 'Tidy_Proprietary'),
+            array('Tidy_Transitional', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Name'),
             array(),
             '-//W3C//DTD XHTML 1.0 Transitional//EN',
             'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
@@ -100,7 +104,7 @@ class HTMLPurifier_HTMLModuleManager
         $this->doctypes->register(
             'XHTML 1.0 Strict', true,
             array_merge($common, $xml, $non_xml),
-            array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Strict', 'Tidy_Proprietary'),
+            array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Strict', 'Tidy_Proprietary', 'Tidy_Name'),
             array(),
             '-//W3C//DTD XHTML 1.0 Strict//EN',
             'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
@@ -109,7 +113,7 @@ class HTMLPurifier_HTMLModuleManager
         $this->doctypes->register(
             'XHTML 1.1', true,
             array_merge($common, $xml, array('Ruby')),
-            array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Strict'), // Tidy_XHTML1_1
+            array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Strict', 'Tidy_Name'), // Tidy_XHTML1_1
             array(),
             '-//W3C//DTD XHTML 1.1//EN',
             'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'
@@ -212,9 +216,6 @@ class HTMLPurifier_HTMLModuleManager
             }
         }
         
-        // merge in custom modules
-        $modules = array_merge($modules, $this->userModules);
-        
         // add proprietary module (this gets special treatment because
         // it is completely removed from doctypes, etc.)
         if ($config->get('HTML', 'Proprietary')) {
@@ -229,6 +230,9 @@ class HTMLPurifier_HTMLModuleManager
             $modules[] = 'SafeEmbed';
         }
         
+        // merge in custom modules
+        $modules = array_merge($modules, $this->userModules);
+        
         foreach ($modules as $module) {
             $this->processModule($module);
             $this->modules[$module]->setup($config);
@@ -378,7 +382,11 @@ class HTMLPurifier_HTMLModuleManager
             
             $this->contentSets->generateChildDef($def, $module);
         }
-            
+        
+        // This can occur if there is a blank definition, but no base to
+        // mix it in with
+        if (!$def) return false;
+        
         // add information on required attributes
         foreach ($def->attr as $attr_name => $attr_def) {
             if ($attr_def->required) {
index 1947c340fe80a89bfabc8d2a0077add28e190694..2d6a861cc0cf92c1c436645a400ec9d35cb27ea7 100644 (file)
@@ -5,6 +5,11 @@
  * This enables "formatter-like" functionality such as auto-paragraphing,
  * smiley-ification and linkification to take place.
  * 
+ * A note on how handlers create changes; this is done by assigning a new
+ * value to the $token reference. These values can take a variety of forms and
+ * are best described HTMLPurifier_Strategy_MakeWellFormed->processToken()
+ * documentation.
+ * 
  * @todo Allow injectors to request a re-run on their output. This 
  *       would help if an operation is recursive.
  */
@@ -16,13 +21,6 @@ abstract class HTMLPurifier_Injector
      */
     public $name;
     
-    /**
-     * Amount of tokens the injector needs to skip + 1. Because
-     * the decrement is the first thing that happens, this needs to
-     * be one greater than the "real" skip count.
-     */
-    public $skip = 1;
-    
     /**
      * Instance of HTMLPurifier_HTMLDefinition
      */
@@ -54,6 +52,32 @@ abstract class HTMLPurifier_Injector
      */
     public $needed = array();
     
+    /**
+     * Index of inputTokens to rewind to.
+     */
+    protected $rewind = false;
+    
+    /**
+     * Rewind to a spot to re-perform processing. This is useful if you
+     * deleted a node, and now need to see if this change affected any
+     * earlier nodes. Rewinding does not affect other injectors, and can
+     * result in infinite loops if not used carefully.
+     * @warning HTML Purifier will prevent you from fast-forwarding with this
+     *          function.
+     */
+    public function rewind($index) {
+        $this->rewind = $index;
+    }
+    
+    /**
+     * Retrieves rewind, and then unsets it.
+     */
+    public function getRewind() {
+        $r = $this->rewind;
+        $this->rewind = false;
+        return $r;
+    }
+    
     /**
      * Prepares the injector by giving it the config and context objects:
      * this allows references to important variables to be made within
@@ -116,6 +140,69 @@ abstract class HTMLPurifier_Injector
         return true;
     }
     
+    /**
+     * Iterator function, which starts with the next token and continues until
+     * you reach the end of the input tokens.
+     * @warning Please prevent previous references from interfering with this
+     *          functions by setting $i = null beforehand!
+     * @param &$i Current integer index variable for inputTokens
+     * @param &$current Current token variable. Do NOT use $token, as that variable is also a reference
+     */
+    protected function forward(&$i, &$current) {
+        if ($i === null) $i = $this->inputIndex + 1;
+        else $i++;
+        if (!isset($this->inputTokens[$i])) return false;
+        $current = $this->inputTokens[$i];
+        return true;
+    }
+    
+    /**
+     * Similar to _forward, but accepts a third parameter $nesting (which
+     * should be initialized at 0) and stops when we hit the end tag
+     * for the node $this->inputIndex starts in.
+     */
+    protected function forwardUntilEndToken(&$i, &$current, &$nesting) {
+        $result = $this->forward($i, $current);
+        if (!$result) return false;
+        if ($nesting === null) $nesting = 0;
+        if     ($current instanceof HTMLPurifier_Token_Start) $nesting++;
+        elseif ($current instanceof HTMLPurifier_Token_End) {
+            if ($nesting <= 0) return false;
+            $nesting--;
+        }
+        return true;
+    }
+    
+    /**
+     * Iterator function, starts with the previous token and continues until
+     * you reach the beginning of input tokens.
+     * @warning Please prevent previous references from interfering with this
+     *          functions by setting $i = null beforehand!
+     * @param &$i Current integer index variable for inputTokens
+     * @param &$current Current token variable. Do NOT use $token, as that variable is also a reference
+     */
+    protected function backward(&$i, &$current) {
+        if ($i === null) $i = $this->inputIndex - 1;
+        else $i--;
+        if ($i < 0) return false;
+        $current = $this->inputTokens[$i];
+        return true;
+    }
+    
+    /**
+     * Initializes the iterator at the current position. Use in a do {} while;
+     * loop to force the _forward and _backward functions to start at the
+     * current location.
+     * @warning Please prevent previous references from interfering with this
+     *          functions by setting $i = null beforehand!
+     * @param &$i Current integer index variable for inputTokens
+     * @param &$current Current token variable. Do NOT use $token, as that variable is also a reference
+     */
+    protected function current(&$i, &$current) {
+        if ($i === null) $i = $this->inputIndex;
+        $current = $this->inputTokens[$i];
+    }
+    
     /**
      * Handler that is called when a text token is processed
      */
@@ -126,9 +213,17 @@ abstract class HTMLPurifier_Injector
      */
     public function handleElement(&$token) {}
     
+    /**
+     * Handler that is called when an end token is processed
+     */
+    public function handleEnd(&$token) {
+        $this->notifyEnd($token);
+    }
+    
     /**
      * Notifier that is called when an end token is processed
      * @note This differs from handlers in that the token is read-only
+     * @deprecated
      */
     public function notifyEnd($token) {}
     
index e51f4ece224ee0927e16cfd2584e376a8a2ecfae..3a7666242fe7cc28b9b756362e1c97afe70fa627 100644 (file)
@@ -3,6 +3,8 @@
 /**
  * Injector that auto paragraphs text in the root node based on
  * double-spacing.
+ * @todo Ensure all states are unit tested, including variations as well.
+ * @todo Make a graph of the flow control for this Injector.
  */
 class HTMLPurifier_Injector_AutoParagraph extends HTMLPurifier_Injector
 {
@@ -18,116 +20,177 @@ class HTMLPurifier_Injector_AutoParagraph extends HTMLPurifier_Injector
     
     public function handleText(&$token) {
         $text = $token->data;
-        if (empty($this->currentNesting)) {
-            if (!$this->allowsElement('p')) return;
-            // case 1: we're in root node (and it allows paragraphs)
-            $token = array($this->_pStart());
-            $this->_splitText($text, $token);
-        } elseif ($this->currentNesting[count($this->currentNesting)-1]->name == 'p') {
-            // case 2: we're in a paragraph
-            $token = array();
-            $this->_splitText($text, $token);
-        } elseif ($this->allowsElement('p')) {
-            // case 3: we're in an element that allows paragraphs
-            if (strpos($text, "\n\n") !== false) {
-                // case 3.1: this text node has a double-newline
-                $token = array($this->_pStart());
-                $this->_splitText($text, $token);
-            } else {
-                $ok = false;
-                // test if up-coming tokens are either block or have
-                // a double newline in them
-                $nesting = 0;
-                for ($i = $this->inputIndex + 1; isset($this->inputTokens[$i]); $i++) {
-                    if ($this->inputTokens[$i] instanceof HTMLPurifier_Token_Start){
-                        if (!$this->_isInline($this->inputTokens[$i])) {
-                            // we haven't found a double-newline, and
-                            // we've hit a block element, so don't paragraph
-                            $ok = false;
-                            break;
-                        }
-                        $nesting++;
-                    }
-                    if ($this->inputTokens[$i] instanceof HTMLPurifier_Token_End) {
-                        if ($nesting <= 0) break;
-                        $nesting--;
-                    }
-                    if ($this->inputTokens[$i] instanceof HTMLPurifier_Token_Text) {
-                        // found it!
-                        if (strpos($this->inputTokens[$i]->data, "\n\n") !== false) {
-                            $ok = true;
-                            break;
-                        }
-                    }
+        // Does the current parent allow <p> tags?
+        if ($this->allowsElement('p')) {
+            if (empty($this->currentNesting) || strpos($text, "\n\n") !== false) {
+                // Note that we have differing behavior when dealing with text
+                // in the anonymous root node, or a node inside the document.
+                // If the text as a double-newline, the treatment is the same;
+                // if it doesn't, see the next if-block if you're in the document.
+                
+                $i = $nesting = null;
+                if (!$this->forwardUntilEndToken($i, $current, $nesting) && $token->is_whitespace) {
+                    // State 1.1: ...    ^ (whitespace, then document end)
+                    //               ----
+                    // This is a degenerate case
+                } else {
+                    // State 1.2: PAR1
+                    //            ----
+                    
+                    // State 1.3: PAR1\n\nPAR2
+                    //            ------------
+                    
+                    // State 1.4: <div>PAR1\n\nPAR2 (see State 2)
+                    //                 ------------
+                    $token = array($this->_pStart());
+                    $this->_splitText($text, $token);
                 }
-                if ($ok) {
-                    // case 3.2: this text node is next to another node
-                    // that will start a paragraph
+            } else {
+                // State 2:   <div>PAR1... (similar to 1.4)
+                //                 ----
+                
+                // We're in an element that allows paragraph tags, but we're not
+                // sure if we're going to need them.
+                if ($this->_pLookAhead()) {
+                    // State 2.1: <div>PAR1<b>PAR1\n\nPAR2
+                    //                 ----
+                    // Note: This will always be the first child, since any
+                    // previous inline element would have triggered this very
+                    // same routine, and found the double newline. One possible
+                    // exception would be a comment.
                     $token = array($this->_pStart(), $token);
+                } else {
+                    // State 2.2.1: <div>PAR1<div>
+                    //                   ----
+                    
+                    // State 2.2.2: <div>PAR1<b>PAR1</b></div>
+                    //                   ----
                 }
             }
+        // Is the current parent a <p> tag?
+        } elseif (
+            !empty($this->currentNesting) &&
+            $this->currentNesting[count($this->currentNesting)-1]->name == 'p'
+        ) {
+            // State 3.1: ...<p>PAR1
+            //                  ----
+            
+            // State 3.2: ...<p>PAR1\n\nPAR2
+            //                  ------------
+            $token = array();
+            $this->_splitText($text, $token);
+        // Abort!
+        } else {
+            // State 4.1: ...<b>PAR1
+            //                  ----
+            
+            // State 4.2: ...<b>PAR1\n\nPAR2
+            //                  ------------
         }
-        
     }
     
     public function handleElement(&$token) {
-        // check if we're inside a tag already
-        if (!empty($this->currentNesting)) {
-            if ($this->allowsElement('p')) {
-                // special case: we're in an element that allows paragraphs
-                
-                // this token is already paragraph, abort
-                if ($token->name == 'p') return;
-                
-                // this token is a block level, abort
-                if (!$this->_isInline($token)) return;
-                
-                // check if this token is adjacent to the parent token
-                $prev = $this->inputTokens[$this->inputIndex - 1];
-                if (!$prev instanceof HTMLPurifier_Token_Start) {
-                    // not adjacent, we can abort early
-                    // add lead paragraph tag if our token is inline
-                    // and the previous tag was an end paragraph
-                    if (
-                        $prev->name == 'p' && $prev instanceof HTMLPurifier_Token_End &&
-                        $this->_isInline($token)
-                    ) {
-                        $token = array($this->_pStart(), $token);
-                    }
-                    return;
-                }
-                
-                // this token is the first child of the element that allows
-                // paragraph. We have to peek ahead and see whether or not
-                // there is anything inside that suggests that a paragraph
-                // will be needed
-                $ok = false;
-                // maintain a mini-nesting counter, this lets us bail out
-                // early if possible
-                $j = 1; // current nesting, one is due to parent (we recalculate current token)
-                for ($i = $this->inputIndex; isset($this->inputTokens[$i]); $i++) {
-                    if ($this->inputTokens[$i] instanceof HTMLPurifier_Token_Start) $j++;
-                    if ($this->inputTokens[$i] instanceof HTMLPurifier_Token_End) $j--;
-                    if ($this->inputTokens[$i] instanceof HTMLPurifier_Token_Text) {
-                        if (strpos($this->inputTokens[$i]->data, "\n\n") !== false) {
-                            $ok = true;
-                            break;
+        // We don't have to check if we're already in a <p> tag for block
+        // tokens, because the tag would have been autoclosed by MakeWellFormed.
+        if ($this->allowsElement('p')) {
+            if (!empty($this->currentNesting)) {
+                if ($this->_isInline($token)) {
+                    // State 1: <div>...<b>
+                    //                  ---
+                    
+                    // Check if this token is adjacent to the parent token
+                    // (seek backwards until token isn't whitespace)
+                    $i = null;
+                    $this->backward($i, $prev);
+                    
+                    if (!$prev instanceof HTMLPurifier_Token_Start) {
+                        // Token wasn't adjacent
+                        
+                        if (
+                            $prev instanceof HTMLPurifier_Token_Text &&
+                            substr($prev->data, -2) === "\n\n"
+                        ) {
+                            // State 1.1.4: <div><p>PAR1</p>\n\n<b>
+                            //                                  ---
+                            
+                            // Quite frankly, this should be handled by splitText
+                            $token = array($this->_pStart(), $token);
+                        } else {
+                            // State 1.1.1: <div><p>PAR1</p><b>
+                            //                              ---
+                            
+                            // State 1.1.2: <div><br /><b>
+                            //                         ---
+                            
+                            // State 1.1.3: <div>PAR<b>
+                            //                      ---
+                        }
+                        
+                    } else {
+                        // State 1.2.1: <div><b>
+                        //                   ---
+                        
+                        // Lookahead to see if <p> is needed.
+                        if ($this->_pLookAhead()) {
+                            // State 1.3.1: <div><b>PAR1\n\nPAR2
+                            //                   ---
+                            $token = array($this->_pStart(), $token);
+                        } else {
+                            // State 1.3.2: <div><b>PAR1</b></div>
+                            //                   ---
+                            
+                            // State 1.3.3: <div><b>PAR1</b><div></div>\n\n</div>
+                            //                   ---
                         }
                     }
-                    if ($j <= 0) break;
+                } else {
+                    // State 2.3: ...<div>
+                    //               -----
                 }
-                if ($ok) {
+            } else {
+                if ($this->_isInline($token)) {
+                    // State 3.1: <b>
+                    //            ---
+                    // This is where the {p} tag is inserted, not reflected in
+                    // inputTokens yet, however.
                     $token = array($this->_pStart(), $token);
+                } else {
+                    // State 3.2: <div>
+                    //            -----
+                }
+                
+                $i = null;
+                if ($this->backward($i, $prev)) {
+                    if (
+                        !$prev instanceof HTMLPurifier_Token_Text
+                    ) {
+                        // State 3.1.1: ...</p>{p}<b>
+                        //                        ---
+                        
+                        // State 3.2.1: ...</p><div>
+                        //                     -----
+                        
+                        if (!is_array($token)) $token = array($token);
+                        array_unshift($token, new HTMLPurifier_Token_Text("\n\n"));
+                    } else {
+                        // State 3.1.2: ...</p>\n\n{p}<b>
+                        //                            ---
+                        
+                        // State 3.2.2: ...</p>\n\n<div>
+                        //                         -----
+                        
+                        // Note: PAR<ELEM> cannot occur because PAR would have been
+                        // wrapped in <p> tags.
+                    }
                 }
             }
-            return;
+        } else {
+            // State 2.2: <ul><li>
+            //                ----
+            
+            // State 2.4: <p><b>
+            //               ---
         }
-        
-        // check if the start tag counts as a "block" element
-        if (!$this->_isInline($token)) return;
-        
-        // append a paragraph tag before the token
-        $token = array($this->_pStart(), $token);
     }
     
     /**
@@ -142,96 +205,80 @@ class HTMLPurifier_Injector_AutoParagraph extends HTMLPurifier_Injector
      */
     private function _splitText($data, &$result) {
         $raw_paragraphs = explode("\n\n", $data);
-        
-        // remove empty paragraphs
-        $paragraphs = array();
+        $paragraphs  = array(); // without empty paragraphs
         $needs_start = false;
         $needs_end   = false;
         
         $c = count($raw_paragraphs);
         if ($c == 1) {
-            // there were no double-newlines, abort quickly
+            // There were no double-newlines, abort quickly. In theory this
+            // should never happen.
             $result[] = new HTMLPurifier_Token_Text($data);
             return;
         }
-        
         for ($i = 0; $i < $c; $i++) {
             $par = $raw_paragraphs[$i];
             if (trim($par) !== '') {
                 $paragraphs[] = $par;
-                continue;
-            }
-            if ($i == 0 && empty($result)) {
-                // The empty result indicates that the AutoParagraph
-                // injector did not add any start paragraph tokens.
-                // The fact that the first paragraph is empty indicates
-                // that there was a double-newline at the start of the
-                // data.
-                // Combined together, this means that we are in a paragraph,
-                // and the newline means we should start a new one.
-                $result[] = new HTMLPurifier_Token_End('p');
-                // However, the start token should only be added if 
-                // there is more processing to be done (i.e. there are
-                // real paragraphs in here). If there are none, the
-                // next start paragraph tag will be handled by the
-                // next run-around the injector
-                $needs_start = true;
-            } elseif ($i + 1 == $c) {
-                // a double-paragraph at the end indicates that
-                // there is an overriding need to start a new paragraph
-                // for the next section. This has no effect until
-                // we've processed all of the other paragraphs though
-                $needs_end = true;
+            } else {
+                if ($i == 0) {
+                    // Double newline at the front
+                    if (empty($result)) {
+                        // The empty result indicates that the AutoParagraph
+                        // injector did not add any start paragraph tokens.
+                        // This means that we have been in a paragraph for
+                        // a while, and the newline means we should start a new one.
+                        $result[] = new HTMLPurifier_Token_End('p');
+                        $result[] = new HTMLPurifier_Token_Text("\n\n");
+                        // However, the start token should only be added if 
+                        // there is more processing to be done (i.e. there are
+                        // real paragraphs in here). If there are none, the
+                        // next start paragraph tag will be handled by the
+                        // next call to the injector
+                        $needs_start = true;
+                    } else {
+                        // We just started a new paragraph!
+                        // Reinstate a double-newline for presentation's sake, since
+                        // it was in the source code.
+                        array_unshift($result, new HTMLPurifier_Token_Text("\n\n"));
+                    }
+                } elseif ($i + 1 == $c) {
+                    // Double newline at the end
+                    // There should be a trailing </p> when we're finally done.
+                    $needs_end = true;
+                }
             }
         }
         
-        // check if there are no "real" paragraphs to be processed
+        // Check if this was just a giant blob of whitespace. Move this earlier,
+        // perhaps?
         if (empty($paragraphs)) {
             return;
         }
         
-        // add a start tag if an end tag was added while processing
-        // the raw paragraphs (that happens if there's a leading double
-        // newline)
-        if ($needs_start) $result[] = $this->_pStart();
+        // Add the start tag indicated by \n\n at the beginning of $data
+        if ($needs_start) {
+            $result[] = $this->_pStart();
+        }
         
-        // append the paragraphs onto the result
+        // Append the paragraphs onto the result
         foreach ($paragraphs as $par) {
             $result[] = new HTMLPurifier_Token_Text($par);
             $result[] = new HTMLPurifier_Token_End('p');
+            $result[] = new HTMLPurifier_Token_Text("\n\n");
             $result[] = $this->_pStart();
         }
         
-        // remove trailing start token, if one is needed, it will
-        // be handled the next time this injector is called
+        // Remove trailing start token; Injector will handle this later if
+        // it was indeed needed. This prevents from needing to do a lookahead,
+        // at the cost of a lookbehind later.
         array_pop($result);
         
-        // check the outside to determine whether or not the
-        // end paragraph tag should be removed. It should be removed
-        // unless the next non-whitespace token is a paragraph
-        // or a block element.
-        $remove_paragraph_end = true;
-        
+        // If there is no need for an end tag, remove all of it and let 
+        // MakeWellFormed close it later.
         if (!$needs_end) {
-            // Start of the checks one after the current token's index
-            for ($i = $this->inputIndex + 1; isset($this->inputTokens[$i]); $i++) {
-                if ($this->inputTokens[$i] instanceof HTMLPurifier_Token_Start || $this->inputTokens[$i] instanceof HTMLPurifier_Token_Empty) {
-                    $remove_paragraph_end = $this->_isInline($this->inputTokens[$i]);
-                }
-                // check if we can abort early (whitespace means we carry-on!)
-                if ($this->inputTokens[$i] instanceof HTMLPurifier_Token_Text && !$this->inputTokens[$i]->is_whitespace) break;
-                // end tags will automatically be handled by MakeWellFormed,
-                // so we don't have to worry about them
-                if ($this->inputTokens[$i] instanceof HTMLPurifier_Token_End) break;
-            }
-        } else {
-            $remove_paragraph_end = false;
-        }
-        
-        // check the outside to determine whether or not the
-        // end paragraph tag should be removed
-        if ($remove_paragraph_end) {
-            array_pop($result);
+            array_pop($result); // removes \n\n
+            array_pop($result); // removes </p>
         }
         
     }
@@ -244,5 +291,49 @@ class HTMLPurifier_Injector_AutoParagraph extends HTMLPurifier_Injector
         return isset($this->htmlDefinition->info['p']->child->elements[$token->name]);
     }
     
+    /**
+     * Looks ahead in the token list and determines whether or not we need
+     * to insert a <p> tag.
+     */
+    private function _pLookAhead() {
+        $this->current($i, $current);
+        if ($current instanceof HTMLPurifier_Token_Start) $nesting = 1;
+        else $nesting = 0;
+        $ok = false;
+        while ($this->forwardUntilEndToken($i, $current, $nesting)) {
+            $result = $this->_checkNeedsP($current);
+            if ($result !== null) {
+                $ok = $result;
+                break;
+            }
+        }
+        return $ok;
+    }
+    
+    /**
+     * Determines if a particular token requires an earlier inline token
+     * to get a paragraph. This should be used with _forwardUntilEndToken
+     */
+    private function _checkNeedsP($current) {
+        if ($current instanceof HTMLPurifier_Token_Start){
+            if (!$this->_isInline($current)) {
+                // <div>PAR1<div>
+                //      ----
+                // Terminate early, since we hit a block element
+                return false;
+            }
+        } elseif ($current instanceof HTMLPurifier_Token_Text) {
+            if (strpos($current->data, "\n\n") !== false) {
+                // <div>PAR1<b>PAR1\n\nPAR2
+                //      ----
+                return true;
+            } else {
+                // <div>PAR1<b>PAR1...
+                //      ----
+            }
+        }
+        return null;
+    }
+    
 }
 
diff --git a/lib/htmlpurifier/HTMLPurifier/Injector/DisplayLinkURI.php b/lib/htmlpurifier/HTMLPurifier/Injector/DisplayLinkURI.php
new file mode 100644 (file)
index 0000000..6fc566d
--- /dev/null
@@ -0,0 +1,24 @@
+<?php
+
+/**
+ * Injector that displays the URL of an anchor instead of linking to it, in addition to showing the text of the link.
+ */
+class HTMLPurifier_Injector_DisplayLinkURI extends HTMLPurifier_Injector
+{
+    
+    public $name = 'DisplayLinkURI';
+    public $needed = array('a');
+    
+    public function handleElement(&$token) {
+    }
+    
+    public function handleEnd(&$token) {
+        if (isset($token->start->attr['href'])){
+            $url = $token->start->attr['href'];
+            unset($token->start->attr['href']);
+            $token = array($token, new HTMLPurifier_Token_Text(" ($url)"));
+        } else {
+            // nothing to display
+        }
+    }
+}
\ No newline at end of file
diff --git a/lib/htmlpurifier/HTMLPurifier/Injector/RemoveEmpty.php b/lib/htmlpurifier/HTMLPurifier/Injector/RemoveEmpty.php
new file mode 100644 (file)
index 0000000..53bb0f0
--- /dev/null
@@ -0,0 +1,40 @@
+<?php
+
+class HTMLPurifier_Injector_RemoveEmpty extends HTMLPurifier_Injector
+{
+    
+    private $context, $config;
+    
+    public function prepare($config, $context) {
+        parent::prepare($config, $context);
+        $this->config = $config;
+        $this->context = $context;
+        $this->attrValidator = new HTMLPurifier_AttrValidator();
+    }
+    
+    public function handleElement(&$token) {
+        if (!$token instanceof HTMLPurifier_Token_Start) return;
+        $next = false;
+        for ($i = $this->inputIndex + 1, $c = count($this->inputTokens); $i < $c; $i++) {
+            $next = $this->inputTokens[$i];
+            if ($next instanceof HTMLPurifier_Token_Text && $next->is_whitespace) continue;
+            break;
+        }
+        if (!$next || ($next instanceof HTMLPurifier_Token_End && $next->name == $token->name)) {
+            if ($token->name == 'colgroup') return;
+            $this->attrValidator->validateToken($token, $this->config, $this->context);
+            $token->armor['ValidateAttributes'] = true;
+            if (isset($token->attr['id']) || isset($token->attr['name'])) return;
+            $token = $i - $this->inputIndex + 1;
+            for ($b = $this->inputIndex - 1; $b > 0; $b--) {
+                $prev = $this->inputTokens[$b];
+                if ($prev instanceof HTMLPurifier_Token_Text && $prev->is_whitespace) continue;
+                break;
+            }
+            // This is safe because we removed the token that triggered this.
+            $this->rewind($b - 1);
+            return;
+        }
+    }
+    
+}
index f379406866bb49c2847f69d1aca3d92018f440ce..1ac6c359368423526cead896a0b589cc6e697e7e 100644 (file)
@@ -72,7 +72,10 @@ class HTMLPurifier_Injector_SafeObject extends HTMLPurifier_Injector
         }
     }
     
-    public function notifyEnd($token) {
+    public function handleEnd(&$token) {
+        // This is the WRONG way of handling the object and param stacks;
+        // we should be inserting them directly on the relevant object tokens
+        // so that the global stack handling handles it.
         if ($token->name == 'object') {
             array_pop($this->objectStack);
             array_pop($this->paramStack);
index b16c3ff38561bacb3ec7f1969b37cd47121c4444..212acd822b432413db0b6a58e5db0baef4e27bdd 100644 (file)
@@ -15,7 +15,8 @@ $messages = array(
 'Item separator last' => ' and ', // non-Harvard style
 
 '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.',
-'ErrorCollector: At line' => ' at line $line',
+'ErrorCollector: At line'   => ' at line $line',
+'ErrorCollector: Incidental errors'  => 'Incidental errors',
 
 'Lexer: Unclosed comment'      => 'Unclosed comment',
 'Lexer: Unescaped lt'          => 'Unescaped less-than sign (<) should be &lt;',
@@ -30,6 +31,8 @@ $messages = array(
 'Strategy_RemoveForeignElements: Comment removed'            => 'Comment containing "$CurrentToken.Data" removed',
 'Strategy_RemoveForeignElements: Foreign meta element removed' => 'Unrecognized $CurrentToken.Serialized meta tag and all descendants removed',
 'Strategy_RemoveForeignElements: Token removed to end'       => 'Tags and text starting from $1 element where removed to end',
+'Strategy_RemoveForeignElements: Trailing hyphen in comment removed' => 'Trailing hyphen(s) in comment removed',
+'Strategy_RemoveForeignElements: Hyphens in comment collapsed' => 'Double hyphens in comments are not allowed, and were collapsed into single hyphens',
 
 'Strategy_MakeWellFormed: Unnecessary end tag removed' => 'Unnecessary $CurrentToken.Serialized tag removed',
 'Strategy_MakeWellFormed: Unnecessary end tag to text' => 'Unnecessary $CurrentToken.Serialized tag converted to text',
@@ -50,8 +53,8 @@ $messages = array(
 );
 
 $errorNames = array(
-    E_ERROR => 'Error',
+    E_ERROR   => 'Error',
     E_WARNING => 'Warning',
-    E_NOTICE => 'Notice'
+    E_NOTICE  => 'Notice'
 );
 
index 01364f65b9262094c980ea542b82d90249725019..043c0ea0db88b8cc911596147c6b3d6f89d9a03c 100644 (file)
 class HTMLPurifier_Lexer
 {
     
+    /**
+     * Whether or not this lexer implements line-number/column-number tracking.
+     * If it does, set to true.
+     */
+    public $tracksLineNumbers = false;
+    
     // -- STATIC ----------------------------------------------------------
     
     /**
@@ -70,46 +76,65 @@ class HTMLPurifier_Lexer
             $lexer = $config->get('Core', 'LexerImpl');
         }
         
-        if (is_object($lexer)) {
-            return $lexer;
-        }
+        $needs_tracking =
+            $config->get('Core', 'MaintainLineNumbers') ||
+            $config->get('Core', 'CollectErrors');
         
-        if (is_null($lexer)) { do {
-            // auto-detection algorithm
+        $inst = null;
+        if (is_object($lexer)) {
+            $inst = $lexer;
+        } else {
             
-            // once PHP DOM implements native line numbers, or we
-            // hack out something using XSLT, remove this stipulation
-            $line_numbers = $config->get('Core', 'MaintainLineNumbers');
-            if (
-                $line_numbers === true ||
-                ($line_numbers === null && $config->get('Core', 'CollectErrors'))
-            ) {
-                $lexer = 'DirectLex';
-                break;
-            }
+            if (is_null($lexer)) { do {
+                // auto-detection algorithm
+                
+                if ($needs_tracking) {
+                    $lexer = 'DirectLex';
+                    break;
+                }
+                
+                if (
+                    class_exists('DOMDocument') &&
+                    method_exists('DOMDocument', 'loadHTML') &&
+                    !extension_loaded('domxml')
+                ) {
+                    // check for DOM support, because while it's part of the
+                    // core, it can be disabled compile time. Also, the PECL
+                    // domxml extension overrides the default DOM, and is evil
+                    // and nasty and we shan't bother to support it
+                    $lexer = 'DOMLex';
+                } else {
+                    $lexer = 'DirectLex';
+                }
+                
+            } while(0); } // do..while so we can break
             
-            if (class_exists('DOMDocument')) {
-                // check for DOM support, because, surprisingly enough,
-                // it's *not* part of the core!
-                $lexer = 'DOMLex';
-            } else {
-                $lexer = 'DirectLex';
+            // instantiate recognized string names
+            switch ($lexer) {
+                case 'DOMLex':
+                    $inst = new HTMLPurifier_Lexer_DOMLex();
+                    break;
+                case 'DirectLex':
+                    $inst = new HTMLPurifier_Lexer_DirectLex();
+                    break;
+                case 'PH5P':
+                    $inst = new HTMLPurifier_Lexer_PH5P();
+                    break;
+                default:
+                    throw new HTMLPurifier_Exception("Cannot instantiate unrecognized Lexer type " . htmlspecialchars($lexer));
             }
-            
-        } while(0); } // do..while so we can break
+        }
+        
+        if (!$inst) throw new HTMLPurifier_Exception('No lexer was instantiated');
         
-        // instantiate recognized string names
-        switch ($lexer) {
-            case 'DOMLex':
-                return new HTMLPurifier_Lexer_DOMLex();
-            case 'DirectLex':
-                return new HTMLPurifier_Lexer_DirectLex();
-            case 'PH5P':
-                return new HTMLPurifier_Lexer_PH5P();
-            default:
-                trigger_error("Cannot instantiate unrecognized Lexer type " . htmlspecialchars($lexer), E_USER_ERROR);
+        // once PHP DOM implements native line numbers, or we
+        // hack out something using XSLT, remove this stipulation
+        if ($needs_tracking && !$inst->tracksLineNumbers) {
+            throw new HTMLPurifier_Exception('Cannot use lexer that does not support line numbers with Core.MaintainLineNumbers or Core.CollectErrors (use DirectLex instead)');
         }
         
+        return $inst;
+        
     }
     
     // -- CONVENIENCE MEMBERS ---------------------------------------------
@@ -226,11 +251,6 @@ class HTMLPurifier_Lexer
      */
     public function normalize($html, $config, $context) {
         
-        // extract body from document if applicable
-        if ($config->get('Core', 'ConvertDocumentToFragment')) {
-            $html = $this->extractBody($html);
-        }
-        
         // normalize newlines to \n
         $html = str_replace("\r\n", "\n", $html);
         $html = str_replace("\r", "\n", $html);
@@ -243,6 +263,11 @@ class HTMLPurifier_Lexer
         // escape CDATA
         $html = $this->escapeCDATA($html);
         
+        // extract body from document if applicable
+        if ($config->get('Core', 'ConvertDocumentToFragment')) {
+            $html = $this->extractBody($html);
+        }
+        
         // expand entities that aren't the big five
         $html = $this->_entity_parser->substituteNonSpecialEntities($html);
         
index dc0adff27540666ca43e1e69457d16a3bcb86123..3ffe7dbdf5a2f8b345fa7dddbee38f7c7299431a 100644 (file)
@@ -45,7 +45,10 @@ class HTMLPurifier_Lexer_DOMLex extends HTMLPurifier_Lexer
             $char = '[^a-z!\/]';
             $comment = "/<!--(.*?)(-->|\z)/is";
             $html = preg_replace_callback($comment, array($this, 'callbackArmorCommentEntities'), $html);
-            $html = preg_replace("/<($char)/i", '&lt;\\1', $html);
+            do {
+                $old = $html;
+                $html = preg_replace("/<($char)/i", '&lt;\\1', $html);
+            } while ($html !== $old);
             $html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments
         }
         
index 985ad68084c604af81ea29b0a8fc4f5ea26cd30e..45ddc876e42b5fc0b936a2ec768ea5daa99c6b8a 100644 (file)
@@ -13,6 +13,8 @@
 class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
 {
     
+    public $tracksLineNumbers = true;
+    
     /**
      * Whitespace characters for str(c)spn.
      */
@@ -42,6 +44,7 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
         $inside_tag = false; // whether or not we're parsing the inside of a tag
         $array = array(); // result array
         
+        // This is also treated to mean maintain *column* numbers too
         $maintain_line_numbers = $config->get('Core', 'MaintainLineNumbers');
         
         if ($maintain_line_numbers === null) {
@@ -50,9 +53,17 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
             $maintain_line_numbers = $config->get('Core', 'CollectErrors');
         }
         
-        if ($maintain_line_numbers) $current_line = 1;
-        else $current_line = false;
+        if ($maintain_line_numbers) {
+            $current_line = 1;
+            $current_col  = 0; 
+            $length = strlen($html);
+        } else {
+            $current_line = false;
+            $current_col  = false;
+            $length = false;
+        }
         $context->register('CurrentLine', $current_line);
+        $context->register('CurrentCol',  $current_col);
         $nl = "\n";
         // how often to manually recalculate. This will ALWAYS be right,
         // but it's pretty wasteful. Set to 0 to turn off
@@ -68,14 +79,31 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
         
         while(++$loops) {
             
-            // recalculate lines
-            if (
-                $maintain_line_numbers && // line number tracking is on
-                $synchronize_interval &&  // synchronization is on
-                $cursor > 0 &&            // cursor is further than zero
-                $loops % $synchronize_interval === 0 // time to synchronize!
-            ) {
-                $current_line = 1 + $this->substrCount($html, $nl, 0, $cursor);
+            // $cursor is either at the start of a token, or inside of
+            // a tag (i.e. there was a < immediately before it), as indicated
+            // by $inside_tag
+            
+            if ($maintain_line_numbers) {
+                
+                // $rcursor, however, is always at the start of a token.
+                $rcursor = $cursor - (int) $inside_tag;
+                
+                // Column number is cheap, so we calculate it every round.
+                // We're interested at the *end* of the newline string, so 
+                // we need to add strlen($nl) == 1 to $nl_pos before subtracting it
+                // from our "rcursor" position.
+                $nl_pos = strrpos($html, $nl, $rcursor - $length);
+                $current_col = $rcursor - (is_bool($nl_pos) ? 0 : $nl_pos + 1);
+                
+                // recalculate lines
+                if (
+                    $synchronize_interval &&  // synchronization is on
+                    $cursor > 0 &&            // cursor is further than zero
+                    $loops % $synchronize_interval === 0 // time to synchronize!
+                ) {
+                    $current_line = 1 + $this->substrCount($html, $nl, 0, $cursor);
+                }
+                
             }
             
             $position_next_lt = strpos($html, '<', $cursor);
@@ -99,7 +127,7 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
                         )
                     );
                 if ($maintain_line_numbers) {
-                    $token->line = $current_line;
+                    $token->rawPosition($current_line, $current_col);
                     $current_line += $this->substrCount($html, $nl, $cursor, $position_next_lt - $cursor);
                 }
                 $array[] = $token;
@@ -119,7 +147,7 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
                             )
                         )
                     );
-                if ($maintain_line_numbers) $token->line = $current_line;
+                if ($maintain_line_numbers) $token->rawPosition($current_line, $current_col);
                 $array[] = $token;
                 break;
             } elseif ($inside_tag && $position_next_gt !== false) {
@@ -167,7 +195,7 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
                             )
                         );
                     if ($maintain_line_numbers) {
-                        $token->line = $current_line;
+                        $token->rawPosition($current_line, $current_col);
                         $current_line += $this->substrCount($html, $nl, $cursor, $strlen_segment);
                     }
                     $array[] = $token;
@@ -182,7 +210,7 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
                     $type = substr($segment, 1);
                     $token = new HTMLPurifier_Token_End($type);
                     if ($maintain_line_numbers) {
-                        $token->line = $current_line;
+                        $token->rawPosition($current_line, $current_col);
                         $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
                     }
                     $array[] = $token;
@@ -197,20 +225,12 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
                 if (!ctype_alpha($segment[0])) {
                     // XML:  $segment[0] !== '_' && $segment[0] !== ':'
                     if ($e) $e->send(E_NOTICE, 'Lexer: Unescaped lt');
-                    $token = new
-                        HTMLPurifier_Token_Text(
-                            '<' .
-                            $this->parseData(
-                                $segment
-                            ) . 
-                            '>'
-                        );
+                    $token = new HTMLPurifier_Token_Text('<');
                     if ($maintain_line_numbers) {
-                        $token->line = $current_line;
+                        $token->rawPosition($current_line, $current_col);
                         $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
                     }
                     $array[] = $token;
-                    $cursor = $position_next_gt + 1;
                     $inside_tag = false;
                     continue;
                 }
@@ -235,7 +255,7 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
                         $token = new HTMLPurifier_Token_Start($segment);
                     }
                     if ($maintain_line_numbers) {
-                        $token->line = $current_line;
+                        $token->rawPosition($current_line, $current_col);
                         $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
                     }
                     $array[] = $token;
@@ -267,7 +287,7 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
                     $token = new HTMLPurifier_Token_Start($type, $attr);
                 }
                 if ($maintain_line_numbers) {
-                    $token->line = $current_line;
+                    $token->rawPosition($current_line, $current_col);
                     $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
                 }
                 $array[] = $token;
@@ -284,7 +304,7 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
                             substr($html, $cursor)
                         )
                     );
-                if ($maintain_line_numbers) $token->line = $current_line;
+                if ($maintain_line_numbers) $token->rawPosition($current_line, $current_col);
                 // no cursor scroll? Hmm...
                 $array[] = $token;
                 break;
@@ -293,6 +313,7 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
         }
         
         $context->destroy('CurrentLine');
+        $context->destroy('CurrentCol');
         return $array;
     }
     
index 81659e5051fe3b3307ddcb179c43d8845e00c518..fa1bf973e0b8bac95c00d40789148d90c2f52f51 100644 (file)
-<?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 throughs an exception.\r
- */\r
-\r
-class HTMLPurifier_Lexer_PH5P extends HTMLPurifier_Lexer_DOMLex {\r
-    \r
-    public function tokenizeHTML($html, $config, $context) {\r
-        $new_html = $this->normalize($html, $config, $context);\r
-        $new_html = $this->wrapHTML($new_html, $config, $context);\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
-                  getElementsByTagName('div')->item(0)    //     <div>\r
-            , $tokens);\r
-        return $tokens;\r
-    }\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
-    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('AElig;','AElig','AMP;','AMP','Aacute;','Aacute',\r
-    'Acirc;','Acirc','Agrave;','Agrave','Alpha;','Aring;','Aring','Atilde;',\r
-    'Atilde','Auml;','Auml','Beta;','COPY;','COPY','Ccedil;','Ccedil','Chi;',\r
-    'Dagger;','Delta;','ETH;','ETH','Eacute;','Eacute','Ecirc;','Ecirc','Egrave;',\r
-    'Egrave','Epsilon;','Eta;','Euml;','Euml','GT;','GT','Gamma;','Iacute;',\r
-    'Iacute','Icirc;','Icirc','Igrave;','Igrave','Iota;','Iuml;','Iuml','Kappa;',\r
-    'LT;','LT','Lambda;','Mu;','Ntilde;','Ntilde','Nu;','OElig;','Oacute;',\r
-    'Oacute','Ocirc;','Ocirc','Ograve;','Ograve','Omega;','Omicron;','Oslash;',\r
-    'Oslash','Otilde;','Otilde','Ouml;','Ouml','Phi;','Pi;','Prime;','Psi;',\r
-    'QUOT;','QUOT','REG;','REG','Rho;','Scaron;','Sigma;','THORN;','THORN',\r
-    'TRADE;','Tau;','Theta;','Uacute;','Uacute','Ucirc;','Ucirc','Ugrave;',\r
-    'Ugrave','Upsilon;','Uuml;','Uuml','Xi;','Yacute;','Yacute','Yuml;','Zeta;',\r
-    'aacute;','aacute','acirc;','acirc','acute;','acute','aelig;','aelig',\r
-    'agrave;','agrave','alefsym;','alpha;','amp;','amp','and;','ang;','apos;',\r
-    'aring;','aring','asymp;','atilde;','atilde','auml;','auml','bdquo;','beta;',\r
-    'brvbar;','brvbar','bull;','cap;','ccedil;','ccedil','cedil;','cedil',\r
-    'cent;','cent','chi;','circ;','clubs;','cong;','copy;','copy','crarr;',\r
-    'cup;','curren;','curren','dArr;','dagger;','darr;','deg;','deg','delta;',\r
-    'diams;','divide;','divide','eacute;','eacute','ecirc;','ecirc','egrave;',\r
-    'egrave','empty;','emsp;','ensp;','epsilon;','equiv;','eta;','eth;','eth',\r
-    'euml;','euml','euro;','exist;','fnof;','forall;','frac12;','frac12',\r
-    'frac14;','frac14','frac34;','frac34','frasl;','gamma;','ge;','gt;','gt',\r
-    'hArr;','harr;','hearts;','hellip;','iacute;','iacute','icirc;','icirc',\r
-    'iexcl;','iexcl','igrave;','igrave','image;','infin;','int;','iota;',\r
-    'iquest;','iquest','isin;','iuml;','iuml','kappa;','lArr;','lambda;','lang;',\r
-    'laquo;','laquo','larr;','lceil;','ldquo;','le;','lfloor;','lowast;','loz;',\r
-    'lrm;','lsaquo;','lsquo;','lt;','lt','macr;','macr','mdash;','micro;','micro',\r
-    'middot;','middot','minus;','mu;','nabla;','nbsp;','nbsp','ndash;','ne;',\r
-    'ni;','not;','not','notin;','nsub;','ntilde;','ntilde','nu;','oacute;',\r
-    'oacute','ocirc;','ocirc','oelig;','ograve;','ograve','oline;','omega;',\r
-    'omicron;','oplus;','or;','ordf;','ordf','ordm;','ordm','oslash;','oslash',\r
-    'otilde;','otilde','otimes;','ouml;','ouml','para;','para','part;','permil;',\r
-    'perp;','phi;','pi;','piv;','plusmn;','plusmn','pound;','pound','prime;',\r
-    'prod;','prop;','psi;','quot;','quot','rArr;','radic;','rang;','raquo;',\r
-    'raquo','rarr;','rceil;','rdquo;','real;','reg;','reg','rfloor;','rho;',\r
-    'rlm;','rsaquo;','rsquo;','sbquo;','scaron;','sdot;','sect;','sect','shy;',\r
-    'shy','sigma;','sigmaf;','sim;','spades;','sub;','sube;','sum;','sup1;',\r
-    'sup1','sup2;','sup2','sup3;','sup3','sup;','supe;','szlig;','szlig','tau;',\r
-    'there4;','theta;','thetasym;','thinsp;','thorn;','thorn','tilde;','times;',\r
-    'times','trade;','uArr;','uacute;','uacute','uarr;','ucirc;','ucirc',\r
-    'ugrave;','ugrave','uml;','uml','upsih;','upsilon;','uuml;','uuml','weierp;',\r
-    'xi;','yacute;','yacute','yen;','yen','yuml;','yuml','zeta;','zwj;','zwnj;');\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
-        $data = str_replace("\r\n", "\n", $data);\r
-        $data = str_replace("\r", null, $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
-        return $this->tree->save();\r
-    }\r
-\r
-    private function char() {\r
-        return ($this->char < $this->EOF)\r
-            ? $this->data[$this->char]\r
-            : false;\r
-    }\r
-\r
-    private function character($s, $l = 0) {\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
-        return preg_replace('#^(['.$char_class.']+).*#s', '\\1', substr($this->data, $start));\r
-    }\r
-\r
-    private function dataState() {\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
-                $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(array(\r
-                'type' => self::CHARACTR,\r
-                'data' => $char\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
-            /* 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
-                $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(array(\r
-                'type' => self::CHARACTR,\r
-                'data' => $char\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(array(\r
-                'type' => self::CHARACTR,\r
-                'data' => substr($this->data, $this->char)\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(array(\r
-                'type' => self::CHARACTR,\r
-                'data' => $char\r
-            ));\r
-\r
-            $this->state = 'data';\r
-        }\r
-    }\r
-\r
-    private function entityDataState() {\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(array(\r
-            'type' => self::CHARACTR,\r
-            'data' => $char\r
-        ));\r
-\r
-        // Finally, switch to the data state.\r
-        $this->state = 'data';\r
-    }\r
-\r
-    private function tagOpenState() {\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(array(\r
-                        'type' => self::CHARACTR,\r
-                        'data' => '<'\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(array(\r
-                        'type' => self::CHARACTR,\r
-                        'data' => '<>'\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(array(\r
-                        'type' => self::CHARACTR,\r
-                        'data' => '<'\r
-                    ));\r
-\r
-                    $this->char--;\r
-                    $this->state = 'data';\r
-                }\r
-            break;\r
-        }\r
-    }\r
-\r
-    private function closeTagOpenState() {\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('/[\t\n\x0b\x0c >\/]/',\r
-        $this->character($this->char + 1 + strlen($next_node))) || $this->EOF === $this->char)))) {\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(array(\r
-                'type' => self::CHARACTR,\r
-                'data' => '</'\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(array(\r
-                    'type' => self::CHARACTR,\r
-                    'data' => '</'\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
-        // 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
-        // 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
-        // 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
-        // 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
-        // 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
-        // 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
-        // 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
-        // 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
-        // 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
-        /* 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(array(\r
-            'data' => $data,\r
-            'type' => self::COMMENT\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
-        /* 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
-        /* 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
-        /* 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
-        /* 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
-        /* 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
-        /* 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(array(\r
-                'name' => null,\r
-                'type' => self::DOCTYPE,\r
-                'error' => true\r
-            ));\r
-\r
-            $this->state = 'data';\r
-\r
-        } elseif($this->char === $this->EOF) {\r
-            $this->emitToken(array(\r
-                'name' => null,\r
-                'type' => self::DOCTYPE,\r
-                'error' => true\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
-        /* 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
-        /* 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
-        /* 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
-        $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 bellow.\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
-                $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 bellow.\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('&'.$entity.';', ENT_QUOTES, 'UTF-8');\r
-    }\r
-\r
-    private function emitToken($token) {\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
-        $this->state = null;\r
-        $this->tree->emitToken(array(\r
-            'type' => self::EOF\r
-        ));\r
-    }\r
-}\r
-\r
-class HTML5TreeConstructer {\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('a','b','big','em','font','i','nobr','s','small','strike','strong','tt','u');\r
-    private $special = array('address','area','base','basefont','bgsound',\r
-    'blockquote','body','br','center','col','colgroup','dd','dir','div','dl',\r
-    'dt','embed','fieldset','form','frame','frameset','h1','h2','h3','h4','h5',\r
-    'h6','head','hr','iframe','image','img','input','isindex','li','link',\r
-    'listing','menu','meta','noembed','noframes','noscript','ol','optgroup',\r
-    'option','p','param','plaintext','pre','script','select','spacer','style',\r
-    'tbody','textarea','tfoot','thead','title','tr','ul','wbr');\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
-        $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
-        switch($this->phase) {\r
-            case self::INIT_PHASE: return $this->initPhase($token); break;\r
-            case self::ROOT_PHASE: return $this->rootElementPhase($token); break;\r
-            case self::MAIN_PHASE: return $this->mainPhase($token); break;\r
-            case self::END_PHASE : return $this->trailingEndPhase($token); break;\r
-        }\r
-    }\r
-\r
-    private function initPhase($token) {\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
-            /* 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('/^[\t\n\x0b\x0c ]+$/',\r
-        $token['data'])) {\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
-        /* 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
-            /* 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
-            /* 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
-        /* 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: return $this->beforeHead($token); break;\r
-                case self::IN_HEAD:    return $this->inHead($token); break;\r
-                case self::AFTER_HEAD: return $this->afterHead($token); break;\r
-                case self::IN_BODY:    return $this->inBody($token); break;\r
-                case self::IN_TABLE:   return $this->inTable($token); break;\r
-                case self::IN_CAPTION: return $this->inCaption($token); break;\r
-                case self::IN_CGROUP:  return $this->inColumnGroup($token); break;\r
-                case self::IN_TBODY:   return $this->inTableBody($token); break;\r
-                case self::IN_ROW:     return $this->inRow($token); break;\r
-                case self::IN_CELL:    return $this->inCell($token); break;\r
-                case self::IN_SELECT:  return $this->inSelect($token); break;\r
-                case self::AFTER_BODY: return $this->afterBody($token); break;\r
-                case self::IN_FRAME:   return $this->inFrameset($token); break;\r
-                case self::AFTR_FRAME: return $this->afterFrameset($token); break;\r
-                case self::END_PHASE:  return $this->trailingEndPhase($token); break;\r
-            }\r
-        }\r
-    }\r
-\r
-    private function beforeHead($token) {\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
-            /* 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('/^[\t\n\x0b\x0c ]$/',\r
-        $token['data']))) {\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(array(\r
-                'name' => 'head',\r
-                'type' => HTML5::STARTTAG,\r
-                'attr' => array()\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
-        /* 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(end($this->stack)->nodeName,\r
-        array('title', 'style', 'script')))) {\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
-            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($token['name'],\r
-        array('base', 'link', 'meta'))) {\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
-            // 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(array(\r
-                    'name' => 'head',\r
-                    'type' => HTML5::ENDTAG\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
-        /* 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
-            /* 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($token['name'],\r
-        array('base', 'link', 'meta', 'script', 'style', 'title'))) {\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(array(\r
-                'name' => 'body',\r
-                'type' => HTML5::STARTTAG,\r
-                'attr' => array()\r
-            ));\r
-\r
-            return $this->inBody($token);\r
-        }\r
-    }\r
-\r
-    private function inBody($token) {\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': 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': case 'link': case 'meta': 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': case 'blockquote': case 'center': case 'dir':\r
-                case 'div': case 'dl': case 'fieldset': case 'listing':\r
-                case 'menu': case 'ol': case 'p': 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(array(\r
-                            'name' => 'p',\r
-                            'type' => HTML5::ENDTAG\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(array(\r
-                                'name' => 'p',\r
-                                'type' => HTML5::ENDTAG\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': case 'dd': 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(array(\r
-                            'name' => 'p',\r
-                            'type' => HTML5::ENDTAG\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
-                            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
-                            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(array(\r
-                            'name' => 'p',\r
-                            'type' => HTML5::ENDTAG\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': case 'h2': case 'h3': case 'h4': case 'h5': 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(array(\r
-                            'name' => 'p',\r
-                            'type' => HTML5::ENDTAG\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(array(\r
-                                'name' => 'a',\r
-                                'type' => HTML5::ENDTAG\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': case 'big': case 'em': case 'font': case 'i':\r
-                case 'nobr': case 's': case 'small': case 'strike':\r
-                case 'strong': case 'tt': 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(array(\r
-                            'name' => 'button',\r
-                            'type' => HTML5::ENDTAG\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': 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(array(\r
-                            'name' => 'p',\r
-                            'type' => HTML5::ENDTAG\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': case 'basefont': case 'bgsound': case 'br':\r
-                case 'embed': case 'img': case 'param': 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(array(\r
-                            'name' => 'p',\r
-                            'type' => HTML5::ENDTAG\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(array(\r
-                            'name' => 'body',\r
-                            'type' => HTML5::STARTTAG,\r
-                            'attr' => array()\r
-                        ));\r
-\r
-                        /* Act as if a start tag token with the tag name "hr" had\r
-                        been seen. */\r
-                        $this->inBody(array(\r
-                            'name' => 'hr',\r
-                            'type' => HTML5::STARTTAG,\r
-                            'attr' => array()\r
-                        ));\r
-\r
-                        /* Act as if a start tag token with the tag name "p" had\r
-                        been seen. */\r
-                        $this->inBody(array(\r
-                            'name' => 'p',\r
-                            'type' => HTML5::STARTTAG,\r
-                            'attr' => array()\r
-                        ));\r
-\r
-                        /* Act as if a start tag token with the tag name "label"\r
-                        had been seen. */\r
-                        $this->inBody(array(\r
-                            'name' => 'label',\r
-                            'type' => HTML5::STARTTAG,\r
-                            'attr' => array()\r
-                        ));\r
-\r
-                        /* Act as if a stream of character tokens had been seen. */\r
-                        $this->insertText('This is a searchable index. '.\r
-                        'Insert your search keywords here: ');\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(array(\r
-                            'name' => 'input',\r
-                            'type' => HTML5::STARTTAG,\r
-                            'attr' => $attr\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('This is a searchable index. '.\r
-                        'Insert your search keywords here: ');\r
-\r
-                        /* Act as if an end tag token with the tag name "label"\r
-                        had been seen. */\r
-                        $this->inBody(array(\r
-                            'name' => 'label',\r
-                            'type' => HTML5::ENDTAG\r
-                        ));\r
-\r
-                        /* Act as if an end tag token with the tag name "p" had\r
-                        been seen. */\r
-                        $this->inBody(array(\r
-                            'name' => 'p',\r
-                            'type' => HTML5::ENDTAG\r
-                        ));\r
-\r
-                        /* Act as if a start tag token with the tag name "hr" had\r
-                        been seen. */\r
-                        $this->inBody(array(\r
-                            'name' => 'hr',\r
-                            'type' => HTML5::ENDTAG\r
-                        ));\r
-\r
-                        /* Act as if an end tag token with the tag name "form" had\r
-                        been seen. */\r
-                        $this->inBody(array(\r
-                            'name' => 'form',\r
-                            'type' => HTML5::ENDTAG\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': case 'noembed': 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': case 'col': case 'colgroup': case 'frame':\r
-                case 'frameset': case 'head': case 'option': case 'optgroup':\r
-                case 'tbody': case 'td': case 'tfoot': case 'th': 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': case 'section': case 'nav': case 'article':\r
-                case 'aside': case 'header': case 'footer': 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(array(\r
-                        'name' => 'body',\r
-                        'type' => HTML5::ENDTAG\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': case 'blockquote': case 'center': case 'dir':\r
-                case 'div': case 'dl': case 'fieldset': case 'listing':\r
-                case 'menu': case 'ol': case 'pre': 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': case 'dt': 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': case 'h2': case 'h3': case 'h4': case 'h5': 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': case 'b': case 'big': case 'em': case 'font':\r
-                case 'i': case 'nobr': case 's': case 'small': case 'strike':\r
-                case 'strong': case 'tt': 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
-                            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': case 'marquee': 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': case 'basefont': case 'bgsound': case 'br':\r
-                case 'embed': case 'hr': case 'iframe': case 'image':\r
-                case 'img': case 'input': case 'isindex': case 'noembed':\r
-                case 'noframes': case 'param': case 'select': case 'spacer':\r
-                case 'table': case 'textarea': 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
-        $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
-            /* 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
-            /* 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
-            /* 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
-            $this->inTable(array(\r
-                'name' => 'colgroup',\r
-                'type' => HTML5::STARTTAG,\r
-                'attr' => array()\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($token['name'],\r
-        array('tbody', 'tfoot', 'thead'))) {\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
-            /* Act as if a start tag token with the tag name "tbody" had been\r
-            seen, then reprocess the current token. */\r
-            $this->inTable(array(\r
-                'name' => 'tbody',\r
-                'type' => HTML5::STARTTAG,\r
-                'attr' => array()\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
-            /* 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(array(\r
-                'name' => 'table',\r
-                'type' => HTML5::ENDTAG\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
-            /* 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($token['name'],\r
-        array('body', 'caption', 'col', 'colgroup', 'html', 'tbody', 'td',\r
-        'tfoot', 'th', 'thead', 'tr'))) {\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(end($this->stack)->nodeName,\r
-            array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {\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
-                    $this->foster_parent = $this->stack[$n - 1];\r
-                }\r
-            }\r
-\r
-            $this->inBody($token);\r
-        }\r
-    }\r
-\r
-    private function inCaption($token) {\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($token['name'],\r
-        array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',\r
-        'thead', 'tr'))) || ($token['type'] === HTML5::ENDTAG &&\r
-        $token['name'] === 'table')) {\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(array(\r
-                'name' => 'caption',\r
-                'type' => HTML5::ENDTAG\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($token['name'],\r
-        array('body', 'col', 'colgroup', 'html', 'tbody', 'tfoot', 'th',\r
-        'thead', 'tr'))) {\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
-        /* 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
-            /* 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
-            /* 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(array(\r
-                'name' => 'colgroup',\r
-                'type' => HTML5::ENDTAG\r
-            ));\r
-\r
-            return $this->inTable($token);\r
-        }\r
-    }\r
-\r
-    private function inTableBody($token) {\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
-            /* 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(array(\r
-                'name' => 'tr',\r
-                'type' => HTML5::STARTTAG,\r
-                'attr' => array()\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
-            /* 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($token['name'],\r
-        array('caption', 'col', 'colgroup', 'tbody', 'tfoor', 'thead'))) ||\r
-        ($token['type'] === HTML5::STARTTAG && $token['name'] === 'table')) {\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(array(\r
-                    'name' => end($this->stack)->nodeName,\r
-                    'type' => HTML5::ENDTAG\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($token['name'],\r
-        array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {\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
-        $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
-            /* 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($token['name'],\r
-        array('caption', 'col', 'colgroup', 'tbody', 'tfoot', 'thead', 'tr'))) {\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(array(\r
-                'name' => 'tr',\r
-                'type' => HTML5::ENDTAG\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
-            /* 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(array(\r
-                    'name' => 'tr',\r
-                    'type' => HTML5::ENDTAG\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($token['name'],\r
-        array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {\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
-        /* 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
-            /* 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($token['name'],\r
-        array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',\r
-        'thead', 'tr'))) {\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($token['name'],\r
-        array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',\r
-        'thead', 'tr'))) {\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($token['name'],\r
-        array('body', 'caption', 'col', 'colgroup', 'html'))) {\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($token['name'],\r
-        array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {\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
-        /* 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
-            /* 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(array(\r
-                    'name' => 'option',\r
-                    'type' => HTML5::ENDTAG\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
-            /* 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(array(\r
-                    'name' => 'option',\r
-                    'type' => HTML5::ENDTAG\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(array(\r
-                    'name' => 'optgroup',\r
-                    'type' => HTML5::ENDTAG\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
-            /* 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
-                $this->inSelect(array(\r
-                    'name' => 'option',\r
-                    'type' => HTML5::ENDTAG\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
-            /* 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
-            /* 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
-            /* Parse error. Act as if the token had been an end tag with the\r
-            tag name "select" instead. */\r
-            $this->inSelect(array(\r
-                'name' => 'select',\r
-                'type' => HTML5::ENDTAG\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($token['name'], array('caption', 'table', 'tbody',\r
-        'tfoot', 'thead', 'tr', 'td', 'th')) && $token['type'] === HTML5::ENDTAG) {\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(array(\r
-                    'name' => 'select',\r
-                    'type' => HTML5::ENDTAG\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
-        /* 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
-            /* 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
-        /* 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
-            /* 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
-            $this->insertElement($token);\r
-\r
-        /* An end tag with the tag name "frameset" */\r
-        } elseif($token['name'] === 'frameset' &&\r
-        $token['type'] === HTML5::ENDTAG) {\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
-            /* 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
-            /* 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
-        /* 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
-            /* 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
-            /* 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
-            /* 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
-        /* 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
-            /* 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
-            /* 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
-        // 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'] === '') $token['name'] = 'span'; // 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
-        $text = $this->dom->createTextNode($data);\r
-        $this->appendToRealParent($text);\r
-    }\r
-\r
-    private function insertComment($data) {\r
-        $comment = $this->dom->createComment($data);\r
-        $this->appendToRealParent($comment);\r
-    }\r
-\r
-    private function appendToRealParent($node) {\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
-                    $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
-            $this->foster_parent = null;\r
-        }\r
-    }\r
-\r
-    private function elementInScope($el, $table = false) {\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($node->tagName, array('caption', 'td',\r
-            'th', 'button', 'marquee', 'object'))) {\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
-        /* 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
-        /* 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
-        /* 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
-        $name = $node->tagName;\r
-        if(in_array($name, $this->special))\r
-            return self::SPECIAL;\r
-\r
-        elseif(in_array($name, $this->scoping))\r
-            return self::SCOPING;\r
-\r
-        elseif(in_array($name, $this->formatting))\r
-            return self::FORMATTING;\r
-\r
-        else\r
-            return self::PHRASING;\r
-    }\r
-\r
-    private function clearStackToTableContext($elements) {\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
-        /* 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
-        /* 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(array(\r
-                    'name' => $cell,\r
-                    'type' => HTML5::ENDTAG\r
-                ));\r
-\r
-                break;\r
-            }\r
-        }\r
-    }\r
-\r
-    public function save() {\r
-        return $this->dom;\r
-    }\r
-}\r
-?>\r
+<?php
+
+/**
+ * Experimental HTML5-based parser using Jeroen van der Meer's PH5P library.
+ * Occupies space in the HTML5 pseudo-namespace, which may cause conflicts.
+ * 
+ * @note
+ *    Recent changes to PHP's DOM extension have resulted in some fatal
+ *    error conditions with the original version of PH5P. Pending changes,
+ *    this lexer will punt to DirectLex if DOM throughs an exception.
+ */
+
+class HTMLPurifier_Lexer_PH5P extends HTMLPurifier_Lexer_DOMLex {
+    
+    public function tokenizeHTML($html, $config, $context) {
+        $new_html = $this->normalize($html, $config, $context);
+        $new_html = $this->wrapHTML($new_html, $config, $context);
+        try {
+            $parser = new HTML5($new_html);
+            $doc = $parser->save();
+        } catch (DOMException $e) {
+            // Uh oh, it failed. Punt to DirectLex.
+            $lexer = new HTMLPurifier_Lexer_DirectLex();
+            $context->register('PH5PError', $e); // save the error, so we can detect it
+            return $lexer->tokenizeHTML($html, $config, $context); // use original HTML
+        }
+        $tokens = array();
+        $this->tokenizeDOM(
+            $doc->getElementsByTagName('html')->item(0)-> // <html>
+                  getElementsByTagName('body')->item(0)-> //   <body>
+                  getElementsByTagName('div')->item(0)    //     <div>
+            , $tokens);
+        return $tokens;
+    }
+    
+}
+
+/*
+
+Copyright 2007 Jeroen van der Meer <http://jero.net/> 
+
+Permission is hereby granted, free of charge, to any person obtaining a 
+copy of this software and associated documentation files (the 
+"Software"), to deal in the Software without restriction, including 
+without limitation the rights to use, copy, modify, merge, publish, 
+distribute, sublicense, and/or sell copies of the Software, and to 
+permit persons to whom the Software is furnished to do so, subject to 
+the following conditions: 
+
+The above copyright notice and this permission notice shall be included 
+in all copies or substantial portions of the Software. 
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
+
+*/
+
+class HTML5 {
+    private $data;
+    private $char;
+    private $EOF;
+    private $state;
+    private $tree;
+    private $token;
+    private $content_model;
+    private $escape = false;
+    private $entities = array('AElig;','AElig','AMP;','AMP','Aacute;','Aacute',
+    'Acirc;','Acirc','Agrave;','Agrave','Alpha;','Aring;','Aring','Atilde;',
+    'Atilde','Auml;','Auml','Beta;','COPY;','COPY','Ccedil;','Ccedil','Chi;',
+    'Dagger;','Delta;','ETH;','ETH','Eacute;','Eacute','Ecirc;','Ecirc','Egrave;',
+    'Egrave','Epsilon;','Eta;','Euml;','Euml','GT;','GT','Gamma;','Iacute;',
+    'Iacute','Icirc;','Icirc','Igrave;','Igrave','Iota;','Iuml;','Iuml','Kappa;',
+    'LT;','LT','Lambda;','Mu;','Ntilde;','Ntilde','Nu;','OElig;','Oacute;',
+    'Oacute','Ocirc;','Ocirc','Ograve;','Ograve','Omega;','Omicron;','Oslash;',
+    'Oslash','Otilde;','Otilde','Ouml;','Ouml','Phi;','Pi;','Prime;','Psi;',
+    'QUOT;','QUOT','REG;','REG','Rho;','Scaron;','Sigma;','THORN;','THORN',
+    'TRADE;','Tau;','Theta;','Uacute;','Uacute','Ucirc;','Ucirc','Ugrave;',
+    'Ugrave','Upsilon;','Uuml;','Uuml','Xi;','Yacute;','Yacute','Yuml;','Zeta;',
+    'aacute;','aacute','acirc;','acirc','acute;','acute','aelig;','aelig',
+    'agrave;','agrave','alefsym;','alpha;','amp;','amp','and;','ang;','apos;',
+    'aring;','aring','asymp;','atilde;','atilde','auml;','auml','bdquo;','beta;',
+    'brvbar;','brvbar','bull;','cap;','ccedil;','ccedil','cedil;','cedil',
+    'cent;','cent','chi;','circ;','clubs;','cong;','copy;','copy','crarr;',
+    'cup;','curren;','curren','dArr;','dagger;','darr;','deg;','deg','delta;',
+    'diams;','divide;','divide','eacute;','eacute','ecirc;','ecirc','egrave;',
+    'egrave','empty;','emsp;','ensp;','epsilon;','equiv;','eta;','eth;','eth',
+    'euml;','euml','euro;','exist;','fnof;','forall;','frac12;','frac12',
+    'frac14;','frac14','frac34;','frac34','frasl;','gamma;','ge;','gt;','gt',
+    'hArr;','harr;','hearts;','hellip;','iacute;','iacute','icirc;','icirc',
+    'iexcl;','iexcl','igrave;','igrave','image;','infin;','int;','iota;',
+    'iquest;','iquest','isin;','iuml;','iuml','kappa;','lArr;','lambda;','lang;',
+    'laquo;','laquo','larr;','lceil;','ldquo;','le;','lfloor;','lowast;','loz;',
+    'lrm;','lsaquo;','lsquo;','lt;','lt','macr;','macr','mdash;','micro;','micro',
+    'middot;','middot','minus;','mu;','nabla;','nbsp;','nbsp','ndash;','ne;',
+    'ni;','not;','not','notin;','nsub;','ntilde;','ntilde','nu;','oacute;',
+    'oacute','ocirc;','ocirc','oelig;','ograve;','ograve','oline;','omega;',
+    'omicron;','oplus;','or;','ordf;','ordf','ordm;','ordm','oslash;','oslash',
+    'otilde;','otilde','otimes;','ouml;','ouml','para;','para','part;','permil;',
+    'perp;','phi;','pi;','piv;','plusmn;','plusmn','pound;','pound','prime;',
+    'prod;','prop;','psi;','quot;','quot','rArr;','radic;','rang;','raquo;',
+    'raquo','rarr;','rceil;','rdquo;','real;','reg;','reg','rfloor;','rho;',
+    'rlm;','rsaquo;','rsquo;','sbquo;','scaron;','sdot;','sect;','sect','shy;',
+    'shy','sigma;','sigmaf;','sim;','spades;','sub;','sube;','sum;','sup1;',
+    'sup1','sup2;','sup2','sup3;','sup3','sup;','supe;','szlig;','szlig','tau;',
+    'there4;','theta;','thetasym;','thinsp;','thorn;','thorn','tilde;','times;',
+    'times','trade;','uArr;','uacute;','uacute','uarr;','ucirc;','ucirc',
+    'ugrave;','ugrave','uml;','uml','upsih;','upsilon;','uuml;','uuml','weierp;',
+    'xi;','yacute;','yacute','yen;','yen','yuml;','yuml','zeta;','zwj;','zwnj;');
+
+    const PCDATA    = 0;
+    const RCDATA    = 1;
+    const CDATA     = 2;
+    const PLAINTEXT = 3;
+
+    const DOCTYPE  = 0;
+    const STARTTAG = 1;
+    const ENDTAG   = 2;
+    const COMMENT  = 3;
+    const CHARACTR = 4;
+    const EOF      = 5;
+
+    public function __construct($data) {
+        $data = str_replace("\r\n", "\n", $data);
+        $data = str_replace("\r", null, $data);
+
+        $this->data = $data;
+        $this->char = -1;
+        $this->EOF  = strlen($data);
+        $this->tree = new HTML5TreeConstructer;
+        $this->content_model = self::PCDATA;
+
+        $this->state = 'data';
+
+        while($this->state !== null) {
+            $this->{$this->state.'State'}();
+        }
+    }
+
+    public function save() {
+        return $this->tree->save();
+    }
+
+    private function char() {
+        return ($this->char < $this->EOF)
+            ? $this->data[$this->char]
+            : false;
+    }
+
+    private function character($s, $l = 0) {
+        if($s + $l < $this->EOF) {
+            if($l === 0) {
+                return $this->data[$s];
+            } else {
+                return substr($this->data, $s, $l);
+            }
+        }
+    }
+
+    private function characters($char_class, $start) {
+        return preg_replace('#^(['.$char_class.']+).*#s', '\\1', substr($this->data, $start));
+    }
+
+    private function dataState() {
+        // Consume the next input character
+        $this->char++;
+        $char = $this->char();
+
+        if($char === '&' && ($this->content_model === self::PCDATA || $this->content_model === self::RCDATA)) {
+            /* U+0026 AMPERSAND (&)
+            When the content model flag is set to one of the PCDATA or RCDATA
+            states: switch to the entity data state. Otherwise: treat it as per
+            the "anything else"    entry below. */
+            $this->state = 'entityData';
+
+        } elseif($char === '-') {
+            /* If the content model flag is set to either the RCDATA state or
+            the CDATA state, and the escape flag is false, and there are at
+            least three characters before this one in the input stream, and the
+            last four characters in the input stream, including this one, are
+            U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS,
+            and U+002D HYPHEN-MINUS ("<!--"), then set the escape flag to true. */
+            if(($this->content_model === self::RCDATA || $this->content_model ===
+            self::CDATA) && $this->escape === false &&
+            $this->char >= 3 && $this->character($this->char - 4, 4) === '<!--') {
+                $this->escape = true;
+            }
+
+            /* In any case, emit the input character as a character token. Stay
+            in the data state. */
+            $this->emitToken(array(
+                'type' => self::CHARACTR,
+                'data' => $char
+            ));
+
+        /* U+003C LESS-THAN SIGN (<) */
+        } elseif($char === '<' && ($this->content_model === self::PCDATA ||
+        (($this->content_model === self::RCDATA ||
+        $this->content_model === self::CDATA) && $this->escape === false))) {
+            /* When the content model flag is set to the PCDATA state: switch
+            to the tag open state.
+
+            When the content model flag is set to either the RCDATA state or
+            the CDATA state and the escape flag is false: switch to the tag
+            open state.
+
+            Otherwise: treat it as per the "anything else" entry below. */
+            $this->state = 'tagOpen';
+
+        /* U+003E GREATER-THAN SIGN (>) */
+        } elseif($char === '>') {
+            /* If the content model flag is set to either the RCDATA state or
+            the CDATA state, and the escape flag is true, and the last three
+            characters in the input stream including this one are U+002D
+            HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN ("-->"),
+            set the escape flag to false. */
+            if(($this->content_model === self::RCDATA ||
+            $this->content_model === self::CDATA) && $this->escape === true &&
+            $this->character($this->char, 3) === '-->') {
+                $this->escape = false;
+            }
+
+            /* In any case, emit the input character as a character token.
+            Stay in the data state. */
+            $this->emitToken(array(
+                'type' => self::CHARACTR,
+                'data' => $char
+            ));
+
+        } elseif($this->char === $this->EOF) {
+            /* EOF
+            Emit an end-of-file token. */
+            $this->EOF();
+
+        } elseif($this->content_model === self::PLAINTEXT) {
+            /* When the content model flag is set to the PLAINTEXT state
+            THIS DIFFERS GREATLY FROM THE SPEC: Get the remaining characters of
+            the text and emit it as a character token. */
+            $this->emitToken(array(
+                'type' => self::CHARACTR,
+                'data' => substr($this->data, $this->char)
+            ));
+
+            $this->EOF();
+
+        } else {
+            /* Anything else
+            THIS DIFFERS GREATLY FROM THE SPEC: Get as many character that
+            otherwise would also be treated as a character token and emit it
+            as a single character token. Stay in the data state. */
+            $len  = strcspn($this->data, '<&', $this->char);
+            $char = substr($this->data, $this->char, $len);
+            $this->char += $len - 1;
+
+            $this->emitToken(array(
+                'type' => self::CHARACTR,
+                'data' => $char
+            ));
+
+            $this->state = 'data';
+        }
+    }
+
+    private function entityDataState() {
+        // Attempt to consume an entity.
+        $entity = $this->entity();
+
+        // If nothing is returned, emit a U+0026 AMPERSAND character token.
+        // Otherwise, emit the character token that was returned.
+        $char = (!$entity) ? '&' : $entity;
+        $this->emitToken(array(
+            'type' => self::CHARACTR,
+            'data' => $char
+        ));
+
+        // Finally, switch to the data state.
+        $this->state = 'data';
+    }
+
+    private function tagOpenState() {
+        switch($this->content_model) {
+            case self::RCDATA:
+            case self::CDATA:
+                /* If the next input character is a U+002F SOLIDUS (/) character,
+                consume it and switch to the close tag open state. If the next
+                input character is not a U+002F SOLIDUS (/) character, emit a
+                U+003C LESS-THAN SIGN character token and switch to the data
+                state to process the next input character. */
+                if($this->character($this->char + 1) === '/') {
+                    $this->char++;
+                    $this->state = 'closeTagOpen';
+
+                } else {
+                    $this->emitToken(array(
+                        'type' => self::CHARACTR,
+                        'data' => '<'
+                    ));
+
+                    $this->state = 'data';
+                }
+            break;
+
+            case self::PCDATA:
+                // If the content model flag is set to the PCDATA state
+                // Consume the next input character:
+                $this->char++;
+                $char = $this->char();
+
+                if($char === '!') {
+                    /* U+0021 EXCLAMATION MARK (!)
+                    Switch to the markup declaration open state. */
+                    $this->state = 'markupDeclarationOpen';
+
+                } elseif($char === '/') {
+                    /* U+002F SOLIDUS (/)
+                    Switch to the close tag open state. */
+                    $this->state = 'closeTagOpen';
+
+                } elseif(preg_match('/^[A-Za-z]$/', $char)) {
+                    /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z
+                    Create a new start tag token, set its tag name to the lowercase
+                    version of the input character (add 0x0020 to the character's code
+                    point), then switch to the tag name state. (Don't emit the token
+                    yet; further details will be filled in before it is emitted.) */
+                    $this->token = array(
+                        'name'  => strtolower($char),
+                        'type'  => self::STARTTAG,
+                        'attr'  => array()
+                    );
+
+                    $this->state = 'tagName';
+
+                } elseif($char === '>') {
+                    /* U+003E GREATER-THAN SIGN (>)
+                    Parse error. Emit a U+003C LESS-THAN SIGN character token and a
+                    U+003E GREATER-THAN SIGN character token. Switch to the data state. */
+                    $this->emitToken(array(
+                        'type' => self::CHARACTR,
+                        'data' => '<>'
+                    ));
+
+                    $this->state = 'data';
+
+                } elseif($char === '?') {
+                    /* U+003F QUESTION MARK (?)
+                    Parse error. Switch to the bogus comment state. */
+                    $this->state = 'bogusComment';
+
+                } else {
+                    /* Anything else
+                    Parse error. Emit a U+003C LESS-THAN SIGN character token and
+                    reconsume the current input character in the data state. */
+                    $this->emitToken(array(
+                        'type' => self::CHARACTR,
+                        'data' => '<'
+                    ));
+
+                    $this->char--;
+                    $this->state = 'data';
+                }
+            break;
+        }
+    }
+
+    private function closeTagOpenState() {
+        $next_node = strtolower($this->characters('A-Za-z', $this->char + 1));
+        $the_same = count($this->tree->stack) > 0 && $next_node === end($this->tree->stack)->nodeName;
+
+        if(($this->content_model === self::RCDATA || $this->content_model === self::CDATA) &&
+        (!$the_same || ($the_same && (!preg_match('/[\t\n\x0b\x0c >\/]/',
+        $this->character($this->char + 1 + strlen($next_node))) || $this->EOF === $this->char)))) {
+            /* If the content model flag is set to the RCDATA or CDATA states then
+            examine the next few characters. If they do not match the tag name of
+            the last start tag token emitted (case insensitively), or if they do but
+            they are not immediately followed by one of the following characters:
+                * U+0009 CHARACTER TABULATION
+                * U+000A LINE FEED (LF)
+                * U+000B LINE TABULATION
+                * U+000C FORM FEED (FF)
+                * U+0020 SPACE
+                * U+003E GREATER-THAN SIGN (>)
+                * U+002F SOLIDUS (/)
+                * EOF
+            ...then there is a parse error. Emit a U+003C LESS-THAN SIGN character
+            token, a U+002F SOLIDUS character token, and switch to the data state
+            to process the next input character. */
+            $this->emitToken(array(
+                'type' => self::CHARACTR,
+                'data' => '</'
+            ));
+
+            $this->state = 'data';
+
+        } else {
+            /* Otherwise, if the content model flag is set to the PCDATA state,
+            or if the next few characters do match that tag name, consume the
+            next input character: */
+            $this->char++;
+            $char = $this->char();
+
+            if(preg_match('/^[A-Za-z]$/', $char)) {
+                /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z
+                Create a new end tag token, set its tag name to the lowercase version
+                of the input character (add 0x0020 to the character's code point), then
+                switch to the tag name state. (Don't emit the token yet; further details
+                will be filled in before it is emitted.) */
+                $this->token = array(
+                    'name'  => strtolower($char),
+                    'type'  => self::ENDTAG
+                );
+
+                $this->state = 'tagName';
+
+            } elseif($char === '>') {
+                /* U+003E GREATER-THAN SIGN (>)
+                Parse error. Switch to the data state. */
+                $this->state = 'data';
+
+            } elseif($this->char === $this->EOF) {
+                /* EOF
+                Parse error. Emit a U+003C LESS-THAN SIGN character token and a U+002F
+                SOLIDUS character token. Reconsume the EOF character in the data state. */
+                $this->emitToken(array(
+                    'type' => self::CHARACTR,
+                    'data' => '</'
+                ));
+
+                $this->char--;
+                $this->state = 'data';
+
+            } else {
+                /* Parse error. Switch to the bogus comment state. */
+                $this->state = 'bogusComment';
+            }
+        }
+    }
+
+    private function tagNameState() {
+        // Consume the next input character:
+        $this->char++;
+        $char = $this->character($this->char);
+
+        if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+            /* U+0009 CHARACTER TABULATION
+            U+000A LINE FEED (LF)
+            U+000B LINE TABULATION
+            U+000C FORM FEED (FF)
+            U+0020 SPACE
+            Switch to the before attribute name state. */
+            $this->state = 'beforeAttributeName';
+
+        } elseif($char === '>') {
+            /* U+003E GREATER-THAN SIGN (>)
+            Emit the current tag token. Switch to the data state. */
+            $this->emitToken($this->token);
+            $this->state = 'data';
+
+        } elseif($this->char === $this->EOF) {
+            /* EOF
+            Parse error. Emit the current tag token. Reconsume the EOF
+            character in the data state. */
+            $this->emitToken($this->token);
+
+            $this->char--;
+            $this->state = 'data';
+
+        } elseif($char === '/') {
+            /* U+002F SOLIDUS (/)
+            Parse error unless this is a permitted slash. Switch to the before
+            attribute name state. */
+            $this->state = 'beforeAttributeName';
+
+        } else {
+            /* Anything else
+            Append the current input character to the current tag token's tag name.
+            Stay in the tag name state. */
+            $this->token['name'] .= strtolower($char);
+            $this->state = 'tagName';
+        }
+    }
+
+    private function beforeAttributeNameState() {
+        // Consume the next input character:
+        $this->char++;
+        $char = $this->character($this->char);
+
+        if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+            /* U+0009 CHARACTER TABULATION
+            U+000A LINE FEED (LF)
+            U+000B LINE TABULATION
+            U+000C FORM FEED (FF)
+            U+0020 SPACE
+            Stay in the before attribute name state. */
+            $this->state = 'beforeAttributeName';
+
+        } elseif($char === '>') {
+            /* U+003E GREATER-THAN SIGN (>)
+            Emit the current tag token. Switch to the data state. */
+            $this->emitToken($this->token);
+            $this->state = 'data';
+
+        } elseif($char === '/') {
+            /* U+002F SOLIDUS (/)
+            Parse error unless this is a permitted slash. Stay in the before
+            attribute name state. */
+            $this->state = 'beforeAttributeName';
+
+        } elseif($this->char === $this->EOF) {
+            /* EOF
+            Parse error. Emit the current tag token. Reconsume the EOF
+            character in the data state. */
+            $this->emitToken($this->token);
+
+            $this->char--;
+            $this->state = 'data';
+
+        } else {
+            /* Anything else
+            Start a new attribute in the current tag token. Set that attribute's
+            name to the current input character, and its value to the empty string.
+            Switch to the attribute name state. */
+            $this->token['attr'][] = array(
+                'name'  => strtolower($char),
+                'value' => null
+            );
+
+            $this->state = 'attributeName';
+        }
+    }
+
+    private function attributeNameState() {
+        // Consume the next input character:
+        $this->char++;
+        $char = $this->character($this->char);
+
+        if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+            /* U+0009 CHARACTER TABULATION
+            U+000A LINE FEED (LF)
+            U+000B LINE TABULATION
+            U+000C FORM FEED (FF)
+            U+0020 SPACE
+            Stay in the before attribute name state. */
+            $this->state = 'afterAttributeName';
+
+        } elseif($char === '=') {
+            /* U+003D EQUALS SIGN (=)
+            Switch to the before attribute value state. */
+            $this->state = 'beforeAttributeValue';
+
+        } elseif($char === '>') {
+            /* U+003E GREATER-THAN SIGN (>)
+            Emit the current tag token. Switch to the data state. */
+            $this->emitToken($this->token);
+            $this->state = 'data';
+
+        } elseif($char === '/' && $this->character($this->char + 1) !== '>') {
+            /* U+002F SOLIDUS (/)
+            Parse error unless this is a permitted slash. Switch to the before
+            attribute name state. */
+            $this->state = 'beforeAttributeName';
+
+        } elseif($this->char === $this->EOF) {
+            /* EOF
+            Parse error. Emit the current tag token. Reconsume the EOF
+            character in the data state. */
+            $this->emitToken($this->token);
+
+            $this->char--;
+            $this->state = 'data';
+
+        } else {
+            /* Anything else
+            Append the current input character to the current attribute's name.
+            Stay in the attribute name state. */
+            $last = count($this->token['attr']) - 1;
+            $this->token['attr'][$last]['name'] .= strtolower($char);
+
+            $this->state = 'attributeName';
+        }
+    }
+
+    private function afterAttributeNameState() {
+        // Consume the next input character:
+        $this->char++;
+        $char = $this->character($this->char);
+
+        if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+            /* U+0009 CHARACTER TABULATION
+            U+000A LINE FEED (LF)
+            U+000B LINE TABULATION
+            U+000C FORM FEED (FF)
+            U+0020 SPACE
+            Stay in the after attribute name state. */
+            $this->state = 'afterAttributeName';
+
+        } elseif($char === '=') {
+            /* U+003D EQUALS SIGN (=)
+            Switch to the before attribute value state. */
+            $this->state = 'beforeAttributeValue';
+
+        } elseif($char === '>') {
+            /* U+003E GREATER-THAN SIGN (>)
+            Emit the current tag token. Switch to the data state. */
+            $this->emitToken($this->token);
+            $this->state = 'data';
+
+        } elseif($char === '/' && $this->character($this->char + 1) !== '>') {
+            /* U+002F SOLIDUS (/)
+            Parse error unless this is a permitted slash. Switch to the
+            before attribute name state. */
+            $this->state = 'beforeAttributeName';
+
+        } elseif($this->char === $this->EOF) {
+            /* EOF
+            Parse error. Emit the current tag token. Reconsume the EOF
+            character in the data state. */
+            $this->emitToken($this->token);
+
+            $this->char--;
+            $this->state = 'data';
+
+        } else {
+            /* Anything else
+            Start a new attribute in the current tag token. Set that attribute's
+            name to the current input character, and its value to the empty string.
+            Switch to the attribute name state. */
+            $this->token['attr'][] = array(
+                'name'  => strtolower($char),
+                'value' => null
+            );
+
+            $this->state = 'attributeName';
+        }
+    }
+
+    private function beforeAttributeValueState() {
+        // Consume the next input character:
+        $this->char++;
+        $char = $this->character($this->char);
+
+        if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+            /* U+0009 CHARACTER TABULATION
+            U+000A LINE FEED (LF)
+            U+000B LINE TABULATION
+            U+000C FORM FEED (FF)
+            U+0020 SPACE
+            Stay in the before attribute value state. */
+            $this->state = 'beforeAttributeValue';
+
+        } elseif($char === '"') {
+            /* U+0022 QUOTATION MARK (")
+            Switch to the attribute value (double-quoted) state. */
+            $this->state = 'attributeValueDoubleQuoted';
+
+        } elseif($char === '&') {
+            /* U+0026 AMPERSAND (&)
+            Switch to the attribute value (unquoted) state and reconsume
+            this input character. */
+            $this->char--;
+            $this->state = 'attributeValueUnquoted';
+
+        } elseif($char === '\'') {
+            /* U+0027 APOSTROPHE (')
+            Switch to the attribute value (single-quoted) state. */
+            $this->state = 'attributeValueSingleQuoted';
+
+        } elseif($char === '>') {
+            /* U+003E GREATER-THAN SIGN (>)
+            Emit the current tag token. Switch to the data state. */
+            $this->emitToken($this->token);
+            $this->state = 'data';
+
+        } else {
+            /* Anything else
+            Append the current input character to the current attribute's value.
+            Switch to the attribute value (unquoted) state. */
+            $last = count($this->token['attr']) - 1;
+            $this->token['attr'][$last]['value'] .= $char;
+
+            $this->state = 'attributeValueUnquoted';
+        }
+    }
+
+    private function attributeValueDoubleQuotedState() {
+        // Consume the next input character:
+        $this->char++;
+        $char = $this->character($this->char);
+
+        if($char === '"') {
+            /* U+0022 QUOTATION MARK (")
+            Switch to the before attribute name state. */
+            $this->state = 'beforeAttributeName';
+
+        } elseif($char === '&') {
+            /* U+0026 AMPERSAND (&)
+            Switch to the entity in attribute value state. */
+            $this->entityInAttributeValueState('double');
+
+        } elseif($this->char === $this->EOF) {
+            /* EOF
+            Parse error. Emit the current tag token. Reconsume the character
+            in the data state. */
+            $this->emitToken($this->token);
+
+            $this->char--;
+            $this->state = 'data';
+
+        } else {
+            /* Anything else
+            Append the current input character to the current attribute's value.
+            Stay in the attribute value (double-quoted) state. */
+            $last = count($this->token['attr']) - 1;
+            $this->token['attr'][$last]['value'] .= $char;
+
+            $this->state = 'attributeValueDoubleQuoted';
+        }
+    }
+
+    private function attributeValueSingleQuotedState() {
+        // Consume the next input character:
+        $this->char++;
+        $char = $this->character($this->char);
+
+        if($char === '\'') {
+            /* U+0022 QUOTATION MARK (')
+            Switch to the before attribute name state. */
+            $this->state = 'beforeAttributeName';
+
+        } elseif($char === '&') {
+            /* U+0026 AMPERSAND (&)
+            Switch to the entity in attribute value state. */
+            $this->entityInAttributeValueState('single');
+
+        } elseif($this->char === $this->EOF) {
+            /* EOF
+            Parse error. Emit the current tag token. Reconsume the character
+            in the data state. */
+            $this->emitToken($this->token);
+
+            $this->char--;
+            $this->state = 'data';
+
+        } else {
+            /* Anything else
+            Append the current input character to the current attribute's value.
+            Stay in the attribute value (single-quoted) state. */
+            $last = count($this->token['attr']) - 1;
+            $this->token['attr'][$last]['value'] .= $char;
+
+            $this->state = 'attributeValueSingleQuoted';
+        }
+    }
+
+    private function attributeValueUnquotedState() {
+        // Consume the next input character:
+        $this->char++;
+        $char = $this->character($this->char);
+
+        if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+            /* U+0009 CHARACTER TABULATION
+            U+000A LINE FEED (LF)
+            U+000B LINE TABULATION
+            U+000C FORM FEED (FF)
+            U+0020 SPACE
+            Switch to the before attribute name state. */
+            $this->state = 'beforeAttributeName';
+
+        } elseif($char === '&') {
+            /* U+0026 AMPERSAND (&)
+            Switch to the entity in attribute value state. */
+            $this->entityInAttributeValueState();
+
+        } elseif($char === '>') {
+            /* U+003E GREATER-THAN SIGN (>)
+            Emit the current tag token. Switch to the data state. */
+            $this->emitToken($this->token);
+            $this->state = 'data';
+
+        } else {
+            /* Anything else
+            Append the current input character to the current attribute's value.
+            Stay in the attribute value (unquoted) state. */
+            $last = count($this->token['attr']) - 1;
+            $this->token['attr'][$last]['value'] .= $char;
+
+            $this->state = 'attributeValueUnquoted';
+        }
+    }
+
+    private function entityInAttributeValueState() {
+        // Attempt to consume an entity.
+        $entity = $this->entity();
+
+        // If nothing is returned, append a U+0026 AMPERSAND character to the
+        // current attribute's value. Otherwise, emit the character token that
+        // was returned.
+        $char = (!$entity)
+            ? '&'
+            : $entity;
+
+        $last = count($this->token['attr']) - 1;
+        $this->token['attr'][$last]['value'] .= $char;
+    }
+
+    private function bogusCommentState() {
+        /* Consume every character up to the first U+003E GREATER-THAN SIGN
+        character (>) or the end of the file (EOF), whichever comes first. Emit
+        a comment token whose data is the concatenation of all the characters
+        starting from and including the character that caused the state machine
+        to switch into the bogus comment state, up to and including the last
+        consumed character before the U+003E character, if any, or up to the
+        end of the file otherwise. (If the comment was started by the end of
+        the file (EOF), the token is empty.) */
+        $data = $this->characters('^>', $this->char);
+        $this->emitToken(array(
+            'data' => $data,
+            'type' => self::COMMENT
+        ));
+
+        $this->char += strlen($data);
+
+        /* Switch to the data state. */
+        $this->state = 'data';
+
+        /* If the end of the file was reached, reconsume the EOF character. */
+        if($this->char === $this->EOF) {
+            $this->char = $this->EOF - 1;
+        }
+    }
+
+    private function markupDeclarationOpenState() {
+        /* If the next two characters are both U+002D HYPHEN-MINUS (-)
+        characters, consume those two characters, create a comment token whose
+        data is the empty string, and switch to the comment state. */
+        if($this->character($this->char + 1, 2) === '--') {
+            $this->char += 2;
+            $this->state = 'comment';
+            $this->token = array(
+                'data' => null,
+                'type' => self::COMMENT
+            );
+
+        /* Otherwise if the next seven chacacters are a case-insensitive match
+        for the word "DOCTYPE", then consume those characters and switch to the
+        DOCTYPE state. */
+        } elseif(strtolower($this->character($this->char + 1, 7)) === 'doctype') {
+            $this->char += 7;
+            $this->state = 'doctype';
+
+        /* Otherwise, is is a parse error. Switch to the bogus comment state.
+        The next character that is consumed, if any, is the first character
+        that will be in the comment. */
+        } else {
+            $this->char++;
+            $this->state = 'bogusComment';
+        }
+    }
+
+    private function commentState() {
+        /* Consume the next input character: */
+        $this->char++;
+        $char = $this->char();
+
+        /* U+002D HYPHEN-MINUS (-) */
+        if($char === '-') {
+            /* Switch to the comment dash state  */
+            $this->state = 'commentDash';
+
+        /* EOF */
+        } elseif($this->char === $this->EOF) {
+            /* Parse error. Emit the comment token. Reconsume the EOF character
+            in the data state. */
+            $this->emitToken($this->token);
+            $this->char--;
+            $this->state = 'data';
+
+        /* Anything else */
+        } else {
+            /* Append the input character to the comment token's data. Stay in
+            the comment state. */
+            $this->token['data'] .= $char;
+        }
+    }
+
+    private function commentDashState() {
+        /* Consume the next input character: */
+        $this->char++;
+        $char = $this->char();
+
+        /* U+002D HYPHEN-MINUS (-) */
+        if($char === '-') {
+            /* Switch to the comment end state  */
+            $this->state = 'commentEnd';
+
+        /* EOF */
+        } elseif($this->char === $this->EOF) {
+            /* Parse error. Emit the comment token. Reconsume the EOF character
+            in the data state. */
+            $this->emitToken($this->token);
+            $this->char--;
+            $this->state = 'data';
+
+        /* Anything else */
+        } else {
+            /* Append a U+002D HYPHEN-MINUS (-) character and the input
+            character to the comment token's data. Switch to the comment state. */
+            $this->token['data'] .= '-'.$char;
+            $this->state = 'comment';
+        }
+    }
+
+    private function commentEndState() {
+        /* Consume the next input character: */
+        $this->char++;
+        $char = $this->char();
+
+        if($char === '>') {
+            $this->emitToken($this->token);
+            $this->state = 'data';
+
+        } elseif($char === '-') {
+            $this->token['data'] .= '-';
+
+        } elseif($this->char === $this->EOF) {
+            $this->emitToken($this->token);
+            $this->char--;
+            $this->state = 'data';
+
+        } else {
+            $this->token['data'] .= '--'.$char;
+            $this->state = 'comment';
+        }
+    }
+
+    private function doctypeState() {
+        /* Consume the next input character: */
+        $this->char++;
+        $char = $this->char();
+
+        if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+            $this->state = 'beforeDoctypeName';
+
+        } else {
+            $this->char--;
+            $this->state = 'beforeDoctypeName';
+        }
+    }
+
+    private function beforeDoctypeNameState() {
+        /* Consume the next input character: */
+        $this->char++;
+        $char = $this->char();
+
+        if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+            // Stay in the before DOCTYPE name state.
+
+        } elseif(preg_match('/^[a-z]$/', $char)) {
+            $this->token = array(
+                'name' => strtoupper($char),
+                'type' => self::DOCTYPE,
+                'error' => true
+            );
+
+            $this->state = 'doctypeName';
+
+        } elseif($char === '>') {
+            $this->emitToken(array(
+                'name' => null,
+                'type' => self::DOCTYPE,
+                'error' => true
+            ));
+
+            $this->state = 'data';
+
+        } elseif($this->char === $this->EOF) {
+            $this->emitToken(array(
+                'name' => null,
+                'type' => self::DOCTYPE,
+                'error' => true
+            ));
+
+            $this->char--;
+            $this->state = 'data';
+
+        } else {
+            $this->token = array(
+                'name' => $char,
+                'type' => self::DOCTYPE,
+                'error' => true
+            );
+
+            $this->state = 'doctypeName';
+        }
+    }
+
+    private function doctypeNameState() {
+        /* Consume the next input character: */
+        $this->char++;
+        $char = $this->char();
+
+        if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+            $this->state = 'AfterDoctypeName';
+
+        } elseif($char === '>') {
+            $this->emitToken($this->token);
+            $this->state = 'data';
+
+        } elseif(preg_match('/^[a-z]$/', $char)) {
+            $this->token['name'] .= strtoupper($char);
+
+        } elseif($this->char === $this->EOF) {
+            $this->emitToken($this->token);
+            $this->char--;
+            $this->state = 'data';
+
+        } else {
+            $this->token['name'] .= $char;
+        }
+
+        $this->token['error'] = ($this->token['name'] === 'HTML')
+            ? false
+            : true;
+    }
+
+    private function afterDoctypeNameState() {
+        /* Consume the next input character: */
+        $this->char++;
+        $char = $this->char();
+
+        if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
+            // Stay in the DOCTYPE name state.
+
+        } elseif($char === '>') {
+            $this->emitToken($this->token);
+            $this->state = 'data';
+
+        } elseif($this->char === $this->EOF) {
+            $this->emitToken($this->token);
+            $this->char--;
+            $this->state = 'data';
+
+        } else {
+            $this->token['error'] = true;
+            $this->state = 'bogusDoctype';
+        }
+    }
+
+    private function bogusDoctypeState() {
+        /* Consume the next input character: */
+        $this->char++;
+        $char = $this->char();
+
+        if($char === '>') {
+            $this->emitToken($this->token);
+            $this->state = 'data';
+
+        } elseif($this->char === $this->EOF) {
+            $this->emitToken($this->token);
+            $this->char--;
+            $this->state = 'data';
+
+        } else {
+            // Stay in the bogus DOCTYPE state.
+        }
+    }
+
+    private function entity() {
+        $start = $this->char;
+
+        // This section defines how to consume an entity. This definition is
+        // used when parsing entities in text and in attributes.
+
+        // The behaviour depends on the identity of the next character (the
+        // one immediately after the U+0026 AMPERSAND character): 
+
+        switch($this->character($this->char + 1)) {
+            // U+0023 NUMBER SIGN (#)
+            case '#':
+
+                // The behaviour further depends on the character after the
+                // U+0023 NUMBER SIGN:
+                switch($this->character($this->char + 1)) {
+                    // U+0078 LATIN SMALL LETTER X
+                    // U+0058 LATIN CAPITAL LETTER X
+                    case 'x':
+                    case 'X':
+                        // Follow the steps below, but using the range of
+                        // characters U+0030 DIGIT ZERO through to U+0039 DIGIT
+                        // NINE, U+0061 LATIN SMALL LETTER A through to U+0066
+                        // LATIN SMALL LETTER F, and U+0041 LATIN CAPITAL LETTER
+                        // A, through to U+0046 LATIN CAPITAL LETTER F (in other
+                        // words, 0-9, A-F, a-f).
+                        $char = 1;
+                        $char_class = '0-9A-Fa-f';
+                    break;
+
+                    // Anything else
+                    default:
+                        // Follow the steps below, but using the range of
+                        // characters U+0030 DIGIT ZERO through to U+0039 DIGIT
+                        // NINE (i.e. just 0-9).
+                        $char = 0;
+                        $char_class = '0-9';
+                    break;
+                }
+
+                // Consume as many characters as match the range of characters
+                // given above.
+                $this->char++;
+                $e_name = $this->characters($char_class, $this->char + $char + 1);
+                $entity = $this->character($start, $this->char);
+                $cond = strlen($e_name) > 0;
+
+                // The rest of the parsing happens bellow.
+            break;
+
+            // Anything else
+            default:
+                // Consume the maximum number of characters possible, with the
+                // consumed characters case-sensitively matching one of the
+                // identifiers in the first column of the entities table.
+                $e_name = $this->characters('0-9A-Za-z;', $this->char + 1);
+                $len = strlen($e_name);
+
+                for($c = 1; $c <= $len; $c++) {
+                    $id = substr($e_name, 0, $c);
+                    $this->char++;
+
+                    if(in_array($id, $this->entities)) {
+                        if ($e_name[$c-1] !== ';') {
+                            if ($c < $len && $e_name[$c] == ';') {
+                                $this->char++; // consume extra semicolon
+                            }
+                        }
+                        $entity = $id;
+                        break;
+                    }
+                }
+
+                $cond = isset($entity);
+                // The rest of the parsing happens bellow.
+            break;
+        }
+
+        if(!$cond) {
+            // If no match can be made, then this is a parse error. No
+            // characters are consumed, and nothing is returned.
+            $this->char = $start;
+            return false;
+        }
+
+        // Return a character token for the character corresponding to the
+        // entity name (as given by the second column of the entities table).
+        return html_entity_decode('&'.$entity.';', ENT_QUOTES, 'UTF-8');
+    }
+
+    private function emitToken($token) {
+        $emit = $this->tree->emitToken($token);
+
+        if(is_int($emit)) {
+            $this->content_model = $emit;
+
+        } elseif($token['type'] === self::ENDTAG) {
+            $this->content_model = self::PCDATA;
+        }
+    }
+
+    private function EOF() {
+        $this->state = null;
+        $this->tree->emitToken(array(
+            'type' => self::EOF
+        ));
+    }
+}
+
+class HTML5TreeConstructer {
+    public $stack = array();
+
+    private $phase;
+    private $mode;
+    private $dom;
+    private $foster_parent = null;
+    private $a_formatting  = array();
+
+    private $head_pointer = null;
+    private $form_pointer = null;
+
+    private $scoping = array('button','caption','html','marquee','object','table','td','th');
+    private $formatting = array('a','b','big','em','font','i','nobr','s','small','strike','strong','tt','u');
+    private $special = array('address','area','base','basefont','bgsound',
+    'blockquote','body','br','center','col','colgroup','dd','dir','div','dl',
+    'dt','embed','fieldset','form','frame','frameset','h1','h2','h3','h4','h5',
+    'h6','head','hr','iframe','image','img','input','isindex','li','link',
+    'listing','menu','meta','noembed','noframes','noscript','ol','optgroup',
+    'option','p','param','plaintext','pre','script','select','spacer','style',
+    'tbody','textarea','tfoot','thead','title','tr','ul','wbr');
+
+    // The different phases.
+    const INIT_PHASE = 0;
+    const ROOT_PHASE = 1;
+    const MAIN_PHASE = 2;
+    const END_PHASE  = 3;
+
+    // The different insertion modes for the main phase.
+    const BEFOR_HEAD = 0;
+    const IN_HEAD    = 1;
+    const AFTER_HEAD = 2;
+    const IN_BODY    = 3;
+    const IN_TABLE   = 4;
+    const IN_CAPTION = 5;
+    const IN_CGROUP  = 6;
+    const IN_TBODY   = 7;
+    const IN_ROW     = 8;
+    const IN_CELL    = 9;
+    const IN_SELECT  = 10;
+    const AFTER_BODY = 11;
+    const IN_FRAME   = 12;
+    const AFTR_FRAME = 13;
+
+    // The different types of elements.
+    const SPECIAL    = 0;
+    const SCOPING    = 1;
+    const FORMATTING = 2;
+    const PHRASING   = 3;
+
+    const MARKER     = 0;
+
+    public function __construct() {
+        $this->phase = self::INIT_PHASE;
+        $this->mode = self::BEFOR_HEAD;
+        $this->dom = new DOMDocument;
+
+        $this->dom->encoding = 'UTF-8';
+        $this->dom->preserveWhiteSpace = true;
+        $this->dom->substituteEntities = true;
+        $this->dom->strictErrorChecking = false;
+    }
+
+    // Process tag tokens
+    public function emitToken($token) {
+        switch($this->phase) {
+            case self::INIT_PHASE: return $this->initPhase($token); break;
+            case self::ROOT_PHASE: return $this->rootElementPhase($token); break;
+            case self::MAIN_PHASE: return $this->mainPhase($token); break;
+            case self::END_PHASE : return $this->trailingEndPhase($token); break;
+        }
+    }
+
+    private function initPhase($token) {
+        /* Initially, the tree construction stage must handle each token
+        emitted from the tokenisation stage as follows: */
+
+        /* A DOCTYPE token that is marked as being in error
+        A comment token
+        A start tag token
+        An end tag token
+        A character token that is not one of one of U+0009 CHARACTER TABULATION,
+            U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+            or U+0020 SPACE
+        An end-of-file token */
+        if((isset($token['error']) && $token['error']) ||
+        $token['type'] === HTML5::COMMENT ||
+        $token['type'] === HTML5::STARTTAG ||
+        $token['type'] === HTML5::ENDTAG ||
+        $token['type'] === HTML5::EOF ||
+        ($token['type'] === HTML5::CHARACTR && isset($token['data']) &&
+        !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']))) {
+            /* This specification does not define how to handle this case. In
+            particular, user agents may ignore the entirety of this specification
+            altogether for such documents, and instead invoke special parse modes
+            with a greater emphasis on backwards compatibility. */
+
+            $this->phase = self::ROOT_PHASE;
+            return $this->rootElementPhase($token);
+
+        /* A DOCTYPE token marked as being correct */
+        } elseif(isset($token['error']) && !$token['error']) {
+            /* Append a DocumentType node to the Document  node, with the name
+            attribute set to the name given in the DOCTYPE token (which will be
+            "HTML"), and the other attributes specific to DocumentType objects
+            set to null, empty lists, or the empty string as appropriate. */
+            $doctype = new DOMDocumentType(null, null, 'HTML');
+
+            /* Then, switch to the root element phase of the tree construction
+            stage. */
+            $this->phase = self::ROOT_PHASE;
+
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE */
+        } elseif(isset($token['data']) && preg_match('/^[\t\n\x0b\x0c ]+$/',
+        $token['data'])) {
+            /* Append that character  to the Document node. */
+            $text = $this->dom->createTextNode($token['data']);
+            $this->dom->appendChild($text);
+        }
+    }
+
+    private function rootElementPhase($token) {
+        /* After the initial phase, as each token is emitted from the tokenisation
+        stage, it must be processed as described in this section. */
+
+        /* A DOCTYPE token */
+        if($token['type'] === HTML5::DOCTYPE) {
+            // Parse error. Ignore the token.
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the Document object with the data
+            attribute set to the data given in the comment token. */
+            $comment = $this->dom->createComment($token['data']);
+            $this->dom->appendChild($comment);
+
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE */
+        } elseif($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+            /* Append that character  to the Document node. */
+            $text = $this->dom->createTextNode($token['data']);
+            $this->dom->appendChild($text);
+
+        /* A character token that is not one of U+0009 CHARACTER TABULATION,
+            U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED
+            (FF), or U+0020 SPACE
+        A start tag token
+        An end tag token
+        An end-of-file token */
+        } elseif(($token['type'] === HTML5::CHARACTR &&
+        !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) ||
+        $token['type'] === HTML5::STARTTAG ||
+        $token['type'] === HTML5::ENDTAG ||
+        $token['type'] === HTML5::EOF) {
+            /* Create an HTMLElement node with the tag name html, in the HTML
+            namespace. Append it to the Document object. Switch to the main
+            phase and reprocess the current token. */
+            $html = $this->dom->createElement('html');
+            $this->dom->appendChild($html);
+            $this->stack[] = $html;
+
+            $this->phase = self::MAIN_PHASE;
+            return $this->mainPhase($token);
+        }
+    }
+
+    private function mainPhase($token) {
+        /* Tokens in the main phase must be handled as follows: */
+
+        /* A DOCTYPE token */
+        if($token['type'] === HTML5::DOCTYPE) {
+            // Parse error. Ignore the token.
+
+        /* A start tag token with the tag name "html" */
+        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'html') {
+            /* If this start tag token was not the first start tag token, then
+            it is a parse error. */
+
+            /* For each attribute on the token, check to see if the attribute
+            is already present on the top element of the stack of open elements.
+            If it is not, add the attribute and its corresponding value to that
+            element. */
+            foreach($token['attr'] as $attr) {
+                if(!$this->stack[0]->hasAttribute($attr['name'])) {
+                    $this->stack[0]->setAttribute($attr['name'], $attr['value']);
+                }
+            }
+
+        /* An end-of-file token */
+        } elseif($token['type'] === HTML5::EOF) {
+            /* Generate implied end tags. */
+            $this->generateImpliedEndTags();
+
+        /* Anything else. */
+        } else {
+            /* Depends on the insertion mode: */
+            switch($this->mode) {
+                case self::BEFOR_HEAD: return $this->beforeHead($token); break;
+                case self::IN_HEAD:    return $this->inHead($token); break;
+                case self::AFTER_HEAD: return $this->afterHead($token); break;
+                case self::IN_BODY:    return $this->inBody($token); break;
+                case self::IN_TABLE:   return $this->inTable($token); break;
+                case self::IN_CAPTION: return $this->inCaption($token); break;
+                case self::IN_CGROUP:  return $this->inColumnGroup($token); break;
+                case self::IN_TBODY:   return $this->inTableBody($token); break;
+                case self::IN_ROW:     return $this->inRow($token); break;
+                case self::IN_CELL:    return $this->inCell($token); break;
+                case self::IN_SELECT:  return $this->inSelect($token); break;
+                case self::AFTER_BODY: return $this->afterBody($token); break;
+                case self::IN_FRAME:   return $this->inFrameset($token); break;
+                case self::AFTR_FRAME: return $this->afterFrameset($token); break;
+                case self::END_PHASE:  return $this->trailingEndPhase($token); break;
+            }
+        }
+    }
+
+    private function beforeHead($token) {
+        /* Handle the token as follows: */
+
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE */
+        if($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+            /* Append the character to the current node. */
+            $this->insertText($token['data']);
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the current node with the data attribute
+            set to the data given in the comment token. */
+            $this->insertComment($token['data']);
+
+        /* A start tag token with the tag name "head" */
+        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') {
+            /* Create an element for the token, append the new element to the
+            current node and push it onto the stack of open elements. */
+            $element = $this->insertElement($token);
+
+            /* Set the head element pointer to this new element node. */
+            $this->head_pointer = $element;
+
+            /* Change the insertion mode to "in head". */
+            $this->mode = self::IN_HEAD;
+
+        /* A start tag token whose tag name is one of: "base", "link", "meta",
+        "script", "style", "title". Or an end tag with the tag name "html".
+        Or a character token that is not one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE. Or any other start tag token */
+        } elseif($token['type'] === HTML5::STARTTAG ||
+        ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') ||
+        ($token['type'] === HTML5::CHARACTR && !preg_match('/^[\t\n\x0b\x0c ]$/',
+        $token['data']))) {
+            /* Act as if a start tag token with the tag name "head" and no
+            attributes had been seen, then reprocess the current token. */
+            $this->beforeHead(array(
+                'name' => 'head',
+                'type' => HTML5::STARTTAG,
+                'attr' => array()
+            ));
+
+            return $this->inHead($token);
+
+        /* Any other end tag */
+        } elseif($token['type'] === HTML5::ENDTAG) {
+            /* Parse error. Ignore the token. */
+        }
+    }
+
+    private function inHead($token) {
+        /* Handle the token as follows: */
+
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE.
+
+        THIS DIFFERS FROM THE SPEC: If the current node is either a title, style
+        or script element, append the character to the current node regardless
+        of its content. */
+        if(($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || (
+        $token['type'] === HTML5::CHARACTR && in_array(end($this->stack)->nodeName,
+        array('title', 'style', 'script')))) {
+            /* Append the character to the current node. */
+            $this->insertText($token['data']);
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the current node with the data attribute
+            set to the data given in the comment token. */
+            $this->insertComment($token['data']);
+
+        } elseif($token['type'] === HTML5::ENDTAG &&
+        in_array($token['name'], array('title', 'style', 'script'))) {
+            array_pop($this->stack);
+            return HTML5::PCDATA;
+
+        /* A start tag with the tag name "title" */
+        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'title') {
+            /* Create an element for the token and append the new element to the
+            node pointed to by the head element pointer, or, if that is null
+            (innerHTML case), to the current node. */
+            if($this->head_pointer !== null) {
+                $element = $this->insertElement($token, false);
+                $this->head_pointer->appendChild($element);
+
+            } else {
+                $element = $this->insertElement($token);
+            }
+
+            /* Switch the tokeniser's content model flag  to the RCDATA state. */
+            return HTML5::RCDATA;
+
+        /* A start tag with the tag name "style" */
+        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'style') {
+            /* Create an element for the token and append the new element to the
+            node pointed to by the head element pointer, or, if that is null
+            (innerHTML case), to the current node. */
+            if($this->head_pointer !== null) {
+                $element = $this->insertElement($token, false);
+                $this->head_pointer->appendChild($element);
+
+            } else {
+                $this->insertElement($token);
+            }
+
+            /* Switch the tokeniser's content model flag  to the CDATA state. */
+            return HTML5::CDATA;
+
+        /* A start tag with the tag name "script" */
+        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'script') {
+            /* Create an element for the token. */
+            $element = $this->insertElement($token, false);
+            $this->head_pointer->appendChild($element);
+
+            /* Switch the tokeniser's content model flag  to the CDATA state. */
+            return HTML5::CDATA;
+
+        /* A start tag with the tag name "base", "link", or "meta" */
+        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+        array('base', 'link', 'meta'))) {
+            /* Create an element for the token and append the new element to the
+            node pointed to by the head element pointer, or, if that is null
+            (innerHTML case), to the current node. */
+            if($this->head_pointer !== null) {
+                $element = $this->insertElement($token, false);
+                $this->head_pointer->appendChild($element);
+                array_pop($this->stack);
+
+            } else {
+                $this->insertElement($token);
+            }
+
+        /* An end tag with the tag name "head" */
+        } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'head') {
+            /* If the current node is a head element, pop the current node off
+            the stack of open elements. */
+            if($this->head_pointer->isSameNode(end($this->stack))) {
+                array_pop($this->stack);
+
+            /* Otherwise, this is a parse error. */
+            } else {
+                // k
+            }
+
+            /* Change the insertion mode to "after head". */
+            $this->mode = self::AFTER_HEAD;
+
+        /* A start tag with the tag name "head" or an end tag except "html". */
+        } elseif(($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') ||
+        ($token['type'] === HTML5::ENDTAG && $token['name'] !== 'html')) {
+            // Parse error. Ignore the token.
+
+        /* Anything else */
+        } else {
+            /* If the current node is a head element, act as if an end tag
+            token with the tag name "head" had been seen. */
+            if($this->head_pointer->isSameNode(end($this->stack))) {
+                $this->inHead(array(
+                    'name' => 'head',
+                    'type' => HTML5::ENDTAG
+                ));
+
+            /* Otherwise, change the insertion mode to "after head". */
+            } else {
+                $this->mode = self::AFTER_HEAD;
+            }
+
+            /* Then, reprocess the current token. */
+            return $this->afterHead($token);
+        }
+    }
+
+    private function afterHead($token) {
+        /* Handle the token as follows: */
+
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE */
+        if($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+            /* Append the character to the current node. */
+            $this->insertText($token['data']);
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the current node with the data attribute
+            set to the data given in the comment token. */
+            $this->insertComment($token['data']);
+
+        /* A start tag token with the tag name "body" */
+        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'body') {
+            /* Insert a body element for the token. */
+            $this->insertElement($token);
+
+            /* Change the insertion mode to "in body". */
+            $this->mode = self::IN_BODY;
+
+        /* A start tag token with the tag name "frameset" */
+        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'frameset') {
+            /* Insert a frameset element for the token. */
+            $this->insertElement($token);
+
+            /* Change the insertion mode to "in frameset". */
+            $this->mode = self::IN_FRAME;
+
+        /* A start tag token whose tag name is one of: "base", "link", "meta",
+        "script", "style", "title" */
+        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+        array('base', 'link', 'meta', 'script', 'style', 'title'))) {
+            /* Parse error. Switch the insertion mode back to "in head" and
+            reprocess the token. */
+            $this->mode = self::IN_HEAD;
+            return $this->inHead($token);
+
+        /* Anything else */
+        } else {
+            /* Act as if a start tag token with the tag name "body" and no
+            attributes had been seen, and then reprocess the current token. */
+            $this->afterHead(array(
+                'name' => 'body',
+                'type' => HTML5::STARTTAG,
+                'attr' => array()
+            ));
+
+            return $this->inBody($token);
+        }
+    }
+
+    private function inBody($token) {
+        /* Handle the token as follows: */
+
+        switch($token['type']) {
+            /* A character token */
+            case HTML5::CHARACTR:
+                /* Reconstruct the active formatting elements, if any. */
+                $this->reconstructActiveFormattingElements();
+
+                /* Append the token's character to the current node. */
+                $this->insertText($token['data']);
+            break;
+
+            /* A comment token */
+            case HTML5::COMMENT:
+                /* Append a Comment node to the current node with the data
+                attribute set to the data given in the comment token. */
+                $this->insertComment($token['data']);
+            break;
+
+            case HTML5::STARTTAG:
+            switch($token['name']) {
+                /* A start tag token whose tag name is one of: "script",
+                "style" */
+                case 'script': case 'style':
+                    /* Process the token as if the insertion mode had been "in
+                    head". */
+                    return $this->inHead($token);
+                break;
+
+                /* A start tag token whose tag name is one of: "base", "link",
+                "meta", "title" */
+                case 'base': case 'link': case 'meta': case 'title':
+                    /* Parse error. Process the token as if the insertion mode
+                    had    been "in head". */
+                    return $this->inHead($token);
+                break;
+
+                /* A start tag token with the tag name "body" */
+                case 'body':
+                    /* Parse error. If the second element on the stack of open
+                    elements is not a body element, or, if the stack of open
+                    elements has only one node on it, then ignore the token.
+                    (innerHTML case) */
+                    if(count($this->stack) === 1 || $this->stack[1]->nodeName !== 'body') {
+                        // Ignore
+
+                    /* Otherwise, for each attribute on the token, check to see
+                    if the attribute is already present on the body element (the
+                    second element)    on the stack of open elements. If it is not,
+                    add the attribute and its corresponding value to that
+                    element. */
+                    } else {
+                        foreach($token['attr'] as $attr) {
+                            if(!$this->stack[1]->hasAttribute($attr['name'])) {
+                                $this->stack[1]->setAttribute($attr['name'], $attr['value']);
+                            }
+                        }
+                    }
+                break;
+
+                /* A start tag whose tag name is one of: "address",
+                "blockquote", "center", "dir", "div", "dl", "fieldset",
+                "listing", "menu", "ol", "p", "ul" */
+                case 'address': case 'blockquote': case 'center': case 'dir':
+                case 'div': case 'dl': case 'fieldset': case 'listing':
+                case 'menu': case 'ol': case 'p': case 'ul':
+                    /* If the stack of open elements has a p element in scope,
+                    then act as if an end tag with the tag name p had been
+                    seen. */
+                    if($this->elementInScope('p')) {
+                        $this->emitToken(array(
+                            'name' => 'p',
+                            'type' => HTML5::ENDTAG
+                        ));
+                    }
+
+                    /* Insert an HTML element for the token. */
+                    $this->insertElement($token);
+                break;
+
+                /* A start tag whose tag name is "form" */
+                case 'form':
+                    /* If the form element pointer is not null, ignore the
+                    token with a parse error. */
+                    if($this->form_pointer !== null) {
+                        // Ignore.
+
+                    /* Otherwise: */
+                    } else {
+                        /* If the stack of open elements has a p element in
+                        scope, then act as if an end tag with the tag name p
+                        had been seen. */
+                        if($this->elementInScope('p')) {
+                            $this->emitToken(array(
+                                'name' => 'p',
+                                'type' => HTML5::ENDTAG
+                            ));
+                        }
+
+                        /* Insert an HTML element for the token, and set the
+                        form element pointer to point to the element created. */
+                        $element = $this->insertElement($token);
+                        $this->form_pointer = $element;
+                    }
+                break;
+
+                /* A start tag whose tag name is "li", "dd" or "dt" */
+                case 'li': case 'dd': case 'dt':
+                    /* If the stack of open elements has a p  element in scope,
+                    then act as if an end tag with the tag name p had been
+                    seen. */
+                    if($this->elementInScope('p')) {
+                        $this->emitToken(array(
+                            'name' => 'p',
+                            'type' => HTML5::ENDTAG
+                        ));
+                    }
+
+                    $stack_length = count($this->stack) - 1;
+
+                    for($n = $stack_length; 0 <= $n; $n--) {
+                        /* 1. Initialise node to be the current node (the
+                        bottommost node of the stack). */
+                        $stop = false;
+                        $node = $this->stack[$n];
+                        $cat  = $this->getElementCategory($node->tagName);
+
+                        /* 2. If node is an li, dd or dt element, then pop all
+                        the    nodes from the current node up to node, including
+                        node, then stop this algorithm. */
+                        if($token['name'] === $node->tagName ||    ($token['name'] !== 'li'
+                        && ($node->tagName === 'dd' || $node->tagName === 'dt'))) {
+                            for($x = $stack_length; $x >= $n ; $x--) {
+                                array_pop($this->stack);
+                            }
+
+                            break;
+                        }
+
+                        /* 3. If node is not in the formatting category, and is
+                        not    in the phrasing category, and is not an address or
+                        div element, then stop this algorithm. */
+                        if($cat !== self::FORMATTING && $cat !== self::PHRASING &&
+                        $node->tagName !== 'address' && $node->tagName !== 'div') {
+                            break;
+                        }
+                    }
+
+                    /* Finally, insert an HTML element with the same tag
+                    name as the    token's. */
+                    $this->insertElement($token);
+                break;
+
+                /* A start tag token whose tag name is "plaintext" */
+                case 'plaintext':
+                    /* If the stack of open elements has a p  element in scope,
+                    then act as if an end tag with the tag name p had been
+                    seen. */
+                    if($this->elementInScope('p')) {
+                        $this->emitToken(array(
+                            'name' => 'p',
+                            'type' => HTML5::ENDTAG
+                        ));
+                    }
+
+                    /* Insert an HTML element for the token. */
+                    $this->insertElement($token);
+
+                    return HTML5::PLAINTEXT;
+                break;
+
+                /* A start tag whose tag name is one of: "h1", "h2", "h3", "h4",
+                "h5", "h6" */
+                case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6':
+                    /* If the stack of open elements has a p  element in scope,
+                    then act as if an end tag with the tag name p had been seen. */
+                    if($this->elementInScope('p')) {
+                        $this->emitToken(array(
+                            'name' => 'p',
+                            'type' => HTML5::ENDTAG
+                        ));
+                    }
+
+                    /* If the stack of open elements has in scope an element whose
+                    tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then
+                    this is a parse error; pop elements from the stack until an
+                    element with one of those tag names has been popped from the
+                    stack. */
+                    while($this->elementInScope(array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))) {
+                        array_pop($this->stack);
+                    }
+
+                    /* Insert an HTML element for the token. */
+                    $this->insertElement($token);
+                break;
+
+                /* A start tag whose tag name is "a" */
+                case 'a':
+                    /* If the list of active formatting elements contains
+                    an element whose tag name is "a" between the end of the
+                    list and the last marker on the list (or the start of
+                    the list if there is no marker on the list), then this
+                    is a parse error; act as if an end tag with the tag name
+                    "a" had been seen, then remove that element from the list
+                    of active formatting elements and the stack of open
+                    elements if the end tag didn't already remove it (it
+                    might not have if the element is not in table scope). */
+                    $leng = count($this->a_formatting);
+
+                    for($n = $leng - 1; $n >= 0; $n--) {
+                        if($this->a_formatting[$n] === self::MARKER) {
+                            break;
+
+                        } elseif($this->a_formatting[$n]->nodeName === 'a') {
+                            $this->emitToken(array(
+                                'name' => 'a',
+                                'type' => HTML5::ENDTAG
+                            ));
+                            break;
+                        }
+                    }
+
+                    /* Reconstruct the active formatting elements, if any. */
+                    $this->reconstructActiveFormattingElements();
+
+                    /* Insert an HTML element for the token. */
+                    $el = $this->insertElement($token);
+
+                    /* Add that element to the list of active formatting
+                    elements. */
+                    $this->a_formatting[] = $el;
+                break;
+
+                /* A start tag whose tag name is one of: "b", "big", "em", "font",
+                "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */
+                case 'b': case 'big': case 'em': case 'font': case 'i':
+                case 'nobr': case 's': case 'small': case 'strike':
+                case 'strong': case 'tt': case 'u':
+                    /* Reconstruct the active formatting elements, if any. */
+                    $this->reconstructActiveFormattingElements();
+
+                    /* Insert an HTML element for the token. */
+                    $el = $this->insertElement($token);
+
+                    /* Add that element to the list of active formatting
+                    elements. */
+                    $this->a_formatting[] = $el;
+                break;
+
+                /* A start tag token whose tag name is "button" */
+                case 'button':
+                    /* If the stack of open elements has a button element in scope,
+                    then this is a parse error; act as if an end tag with the tag
+                    name "button" had been seen, then reprocess the token. (We don't
+                    do that. Unnecessary.) */
+                    if($this->elementInScope('button')) {
+                        $this->inBody(array(
+                            'name' => 'button',
+                            'type' => HTML5::ENDTAG
+                        ));
+                    }
+
+                    /* Reconstruct the active formatting elements, if any. */
+                    $this->reconstructActiveFormattingElements();
+
+                    /* Insert an HTML element for the token. */
+                    $this->insertElement($token);
+
+                    /* Insert a marker at the end of the list of active
+                    formatting elements. */
+                    $this->a_formatting[] = self::MARKER;
+                break;
+
+                /* A start tag token whose tag name is one of: "marquee", "object" */
+                case 'marquee': case 'object':
+                    /* Reconstruct the active formatting elements, if any. */
+                    $this->reconstructActiveFormattingElements();
+
+                    /* Insert an HTML element for the token. */
+                    $this->insertElement($token);
+
+                    /* Insert a marker at the end of the list of active
+                    formatting elements. */
+                    $this->a_formatting[] = self::MARKER;
+                break;
+
+                /* A start tag token whose tag name is "xmp" */
+                case 'xmp':
+                    /* Reconstruct the active formatting elements, if any. */
+                    $this->reconstructActiveFormattingElements();
+
+                    /* Insert an HTML element for the token. */
+                    $this->insertElement($token);
+
+                    /* Switch the content model flag to the CDATA state. */
+                    return HTML5::CDATA;
+                break;
+
+                /* A start tag whose tag name is "table" */
+                case 'table':
+                    /* If the stack of open elements has a p element in scope,
+                    then act as if an end tag with the tag name p had been seen. */
+                    if($this->elementInScope('p')) {
+                        $this->emitToken(array(
+                            'name' => 'p',
+                            'type' => HTML5::ENDTAG
+                        ));
+                    }
+
+                    /* Insert an HTML element for the token. */
+                    $this->insertElement($token);
+
+                    /* Change the insertion mode to "in table". */
+                    $this->mode = self::IN_TABLE;
+                break;
+
+                /* A start tag whose tag name is one of: "area", "basefont",
+                "bgsound", "br", "embed", "img", "param", "spacer", "wbr" */
+                case 'area': case 'basefont': case 'bgsound': case 'br':
+                case 'embed': case 'img': case 'param': case 'spacer':
+                case 'wbr':
+                    /* Reconstruct the active formatting elements, if any. */
+                    $this->reconstructActiveFormattingElements();
+
+                    /* Insert an HTML element for the token. */
+                    $this->insertElement($token);
+
+                    /* Immediately pop the current node off the stack of open elements. */
+                    array_pop($this->stack);
+                break;
+
+                /* A start tag whose tag name is "hr" */
+                case 'hr':
+                    /* If the stack of open elements has a p element in scope,
+                    then act as if an end tag with the tag name p had been seen. */
+                    if($this->elementInScope('p')) {
+                        $this->emitToken(array(
+                            'name' => 'p',
+                            'type' => HTML5::ENDTAG
+                        ));
+                    }
+
+                    /* Insert an HTML element for the token. */
+                    $this->insertElement($token);
+
+                    /* Immediately pop the current node off the stack of open elements. */
+                    array_pop($this->stack);
+                break;
+
+                /* A start tag whose tag name is "image" */
+                case 'image':
+                    /* Parse error. Change the token's tag name to "img" and
+                    reprocess it. (Don't ask.) */
+                    $token['name'] = 'img';
+                    return $this->inBody($token);
+                break;
+
+                /* A start tag whose tag name is "input" */
+                case 'input':
+                    /* Reconstruct the active formatting elements, if any. */
+                    $this->reconstructActiveFormattingElements();
+
+                    /* Insert an input element for the token. */
+                    $element = $this->insertElement($token, false);
+
+                    /* If the form element pointer is not null, then associate the
+                    input element with the form element pointed to by the form
+                    element pointer. */
+                    $this->form_pointer !== null
+                        ? $this->form_pointer->appendChild($element)
+                        : end($this->stack)->appendChild($element);
+
+                    /* Pop that input element off the stack of open elements. */
+                    array_pop($this->stack);
+                break;
+
+                /* A start tag whose tag name is "isindex" */
+                case 'isindex':
+                    /* Parse error. */
+                    // w/e
+
+                    /* If the form element pointer is not null,
+                    then ignore the token. */
+                    if($this->form_pointer === null) {
+                        /* Act as if a start tag token with the tag name "form" had
+                        been seen. */
+                        $this->inBody(array(
+                            'name' => 'body',
+                            'type' => HTML5::STARTTAG,
+                            'attr' => array()
+                        ));
+
+                        /* Act as if a start tag token with the tag name "hr" had
+                        been seen. */
+                        $this->inBody(array(
+                            'name' => 'hr',
+                            'type' => HTML5::STARTTAG,
+                            'attr' => array()
+                        ));
+
+                        /* Act as if a start tag token with the tag name "p" had
+                        been seen. */
+                        $this->inBody(array(
+                            'name' => 'p',
+                            'type' => HTML5::STARTTAG,
+                            'attr' => array()
+                        ));
+
+                        /* Act as if a start tag token with the tag name "label"
+                        had been seen. */
+                        $this->inBody(array(
+                            'name' => 'label',
+                            'type' => HTML5::STARTTAG,
+                            'attr' => array()
+                        ));
+
+                        /* Act as if a stream of character tokens had been seen. */
+                        $this->insertText('This is a searchable index. '.
+                        'Insert your search keywords here: ');
+
+                        /* Act as if a start tag token with the tag name "input"
+                        had been seen, with all the attributes from the "isindex"
+                        token, except with the "name" attribute set to the value
+                        "isindex" (ignoring any explicit "name" attribute). */
+                        $attr = $token['attr'];
+                        $attr[] = array('name' => 'name', 'value' => 'isindex');
+
+                        $this->inBody(array(
+                            'name' => 'input',
+                            'type' => HTML5::STARTTAG,
+                            'attr' => $attr
+                        ));
+
+                        /* Act as if a stream of character tokens had been seen
+                        (see below for what they should say). */
+                        $this->insertText('This is a searchable index. '.
+                        'Insert your search keywords here: ');
+
+                        /* Act as if an end tag token with the tag name "label"
+                        had been seen. */
+                        $this->inBody(array(
+                            'name' => 'label',
+                            'type' => HTML5::ENDTAG
+                        ));
+
+                        /* Act as if an end tag token with the tag name "p" had
+                        been seen. */
+                        $this->inBody(array(
+                            'name' => 'p',
+                            'type' => HTML5::ENDTAG
+                        ));
+
+                        /* Act as if a start tag token with the tag name "hr" had
+                        been seen. */
+                        $this->inBody(array(
+                            'name' => 'hr',
+                            'type' => HTML5::ENDTAG
+                        ));
+
+                        /* Act as if an end tag token with the tag name "form" had
+                        been seen. */
+                        $this->inBody(array(
+                            'name' => 'form',
+                            'type' => HTML5::ENDTAG
+                        ));
+                    }
+                break;
+
+                /* A start tag whose tag name is "textarea" */
+                case 'textarea':
+                    $this->insertElement($token);
+
+                    /* Switch the tokeniser's content model flag to the
+                    RCDATA state. */
+                    return HTML5::RCDATA;
+                break;
+
+                /* A start tag whose tag name is one of: "iframe", "noembed",
+                "noframes" */
+                case 'iframe': case 'noembed': case 'noframes':
+                    $this->insertElement($token);
+
+                    /* Switch the tokeniser's content model flag to the CDATA state. */
+                    return HTML5::CDATA;
+                break;
+
+                /* A start tag whose tag name is "select" */
+                case 'select':
+                    /* Reconstruct the active formatting elements, if any. */
+                    $this->reconstructActiveFormattingElements();
+
+                    /* Insert an HTML element for the token. */
+                    $this->insertElement($token);
+
+                    /* Change the insertion mode to "in select". */
+                    $this->mode = self::IN_SELECT;
+                break;
+
+                /* A start or end tag whose tag name is one of: "caption", "col",
+                "colgroup", "frame", "frameset", "head", "option", "optgroup",
+                "tbody", "td", "tfoot", "th", "thead", "tr". */
+                case 'caption': case 'col': case 'colgroup': case 'frame':
+                case 'frameset': case 'head': case 'option': case 'optgroup':
+                case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead':
+                case 'tr':
+                    // Parse error. Ignore the token.
+                break;
+
+                /* A start or end tag whose tag name is one of: "event-source",
+                "section", "nav", "article", "aside", "header", "footer",
+                "datagrid", "command" */
+                case 'event-source': case 'section': case 'nav': case 'article':
+                case 'aside': case 'header': case 'footer': case 'datagrid':
+                case 'command':
+                    // Work in progress!
+                break;
+
+                /* A start tag token not covered by the previous entries */
+                default:
+                    /* Reconstruct the active formatting elements, if any. */
+                    $this->reconstructActiveFormattingElements();
+
+                    $this->insertElement($token, true, true);
+                break;
+            }
+            break;
+
+            case HTML5::ENDTAG:
+            switch($token['name']) {
+                /* An end tag with the tag name "body" */
+                case 'body':
+                    /* If the second element in the stack of open elements is
+                    not a body element, this is a parse error. Ignore the token.
+                    (innerHTML case) */
+                    if(count($this->stack) < 2 || $this->stack[1]->nodeName !== 'body') {
+                        // Ignore.
+
+                    /* If the current node is not the body element, then this
+                    is a parse error. */
+                    } elseif(end($this->stack)->nodeName !== 'body') {
+                        // Parse error.
+                    }
+
+                    /* Change the insertion mode to "after body". */
+                    $this->mode = self::AFTER_BODY;
+                break;
+
+                /* An end tag with the tag name "html" */
+                case 'html':
+                    /* Act as if an end tag with tag name "body" had been seen,
+                    then, if that token wasn't ignored, reprocess the current
+                    token. */
+                    $this->inBody(array(
+                        'name' => 'body',
+                        'type' => HTML5::ENDTAG
+                    ));
+
+                    return $this->afterBody($token);
+                break;
+
+                /* An end tag whose tag name is one of: "address", "blockquote",
+                "center", "dir", "div", "dl", "fieldset", "listing", "menu",
+                "ol", "pre", "ul" */
+                case 'address': case 'blockquote': case 'center': case 'dir':
+                case 'div': case 'dl': case 'fieldset': case 'listing':
+                case 'menu': case 'ol': case 'pre': case 'ul':
+                    /* If the stack of open elements has an element in scope
+                    with the same tag name as that of the token, then generate
+                    implied end tags. */
+                    if($this->elementInScope($token['name'])) {
+                        $this->generateImpliedEndTags();
+
+                        /* Now, if the current node is not an element with
+                        the same tag name as that of the token, then this
+                        is a parse error. */
+                        // w/e
+
+                        /* If the stack of open elements has an element in
+                        scope with the same tag name as that of the token,
+                        then pop elements from this stack until an element
+                        with that tag name has been popped from the stack. */
+                        for($n = count($this->stack) - 1; $n >= 0; $n--) {
+                            if($this->stack[$n]->nodeName === $token['name']) {
+                                $n = -1;
+                            }
+
+                            array_pop($this->stack);
+                        }
+                    }
+                break;
+
+                /* An end tag whose tag name is "form" */
+                case 'form':
+                    /* If the stack of open elements has an element in scope
+                    with the same tag name as that of the token, then generate
+                    implied    end tags. */
+                    if($this->elementInScope($token['name'])) {
+                        $this->generateImpliedEndTags();
+
+                    } 
+
+                    if(end($this->stack)->nodeName !== $token['name']) {
+                        /* Now, if the current node is not an element with the
+                        same tag name as that of the token, then this is a parse
+                        error. */
+                        // w/e
+
+                    } else {
+                        /* Otherwise, if the current node is an element with
+                        the same tag name as that of the token pop that element
+                        from the stack. */
+                        array_pop($this->stack);
+                    }
+
+                    /* In any case, set the form element pointer to null. */
+                    $this->form_pointer = null;
+                break;
+
+                /* An end tag whose tag name is "p" */
+                case 'p':
+                    /* If the stack of open elements has a p element in scope,
+                    then generate implied end tags, except for p elements. */
+                    if($this->elementInScope('p')) {
+                        $this->generateImpliedEndTags(array('p'));
+
+                        /* If the current node is not a p element, then this is
+                        a parse error. */
+                        // k
+
+                        /* If the stack of open elements has a p element in
+                        scope, then pop elements from this stack until the stack
+                        no longer has a p element in scope. */
+                        for($n = count($this->stack) - 1; $n >= 0; $n--) {
+                            if($this->elementInScope('p')) {
+                                array_pop($this->stack);
+
+                            } else {
+                                break;
+                            }
+                        }
+                    }
+                break;
+
+                /* An end tag whose tag name is "dd", "dt", or "li" */
+                case 'dd': case 'dt': case 'li':
+                    /* If the stack of open elements has an element in scope
+                    whose tag name matches the tag name of the token, then
+                    generate implied end tags, except for elements with the
+                    same tag name as the token. */
+                    if($this->elementInScope($token['name'])) {
+                        $this->generateImpliedEndTags(array($token['name']));
+
+                        /* If the current node is not an element with the same
+                        tag name as the token, then this is a parse error. */
+                        // w/e
+
+                        /* If the stack of open elements has an element in scope
+                        whose tag name matches the tag name of the token, then
+                        pop elements from this stack until an element with that
+                        tag name has been popped from the stack. */
+                        for($n = count($this->stack) - 1; $n >= 0; $n--) {
+                            if($this->stack[$n]->nodeName === $token['name']) {
+                                $n = -1;
+                            }
+
+                            array_pop($this->stack);
+                        }
+                    }
+                break;
+
+                /* An end tag whose tag name is one of: "h1", "h2", "h3", "h4",
+                "h5", "h6" */
+                case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6':
+                    $elements = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
+
+                    /* If the stack of open elements has in scope an element whose
+                    tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then
+                    generate implied end tags. */
+                    if($this->elementInScope($elements)) {
+                        $this->generateImpliedEndTags();
+
+                        /* Now, if the current node is not an element with the same
+                        tag name as that of the token, then this is a parse error. */
+                        // w/e
+
+                        /* If the stack of open elements has in scope an element
+                        whose tag name is one of "h1", "h2", "h3", "h4", "h5", or
+                        "h6", then pop elements from the stack until an element
+                        with one of those tag names has been popped from the stack. */
+                        while($this->elementInScope($elements)) {
+                            array_pop($this->stack);
+                        }
+                    }
+                break;
+
+                /* An end tag whose tag name is one of: "a", "b", "big", "em",
+                "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */
+                case 'a': case 'b': case 'big': case 'em': case 'font':
+                case 'i': case 'nobr': case 's': case 'small': case 'strike':
+                case 'strong': case 'tt': case 'u':
+                    /* 1. Let the formatting element be the last element in
+                    the list of active formatting elements that:
+                        * is between the end of the list and the last scope
+                        marker in the list, if any, or the start of the list
+                        otherwise, and
+                        * has the same tag name as the token.
+                    */
+                    while(true) {
+                        for($a = count($this->a_formatting) - 1; $a >= 0; $a--) {
+                            if($this->a_formatting[$a] === self::MARKER) {
+                                break;
+
+                            } elseif($this->a_formatting[$a]->tagName === $token['name']) {
+                                $formatting_element = $this->a_formatting[$a];
+                                $in_stack = in_array($formatting_element, $this->stack, true);
+                                $fe_af_pos = $a;
+                                break;
+                            }
+                        }
+
+                        /* If there is no such node, or, if that node is
+                        also in the stack of open elements but the element
+                        is not in scope, then this is a parse error. Abort
+                        these steps. The token is ignored. */
+                        if(!isset($formatting_element) || ($in_stack &&
+                        !$this->elementInScope($token['name']))) {
+                            break;
+
+                        /* Otherwise, if there is such a node, but that node
+                        is not in the stack of open elements, then this is a
+                        parse error; remove the element from the list, and
+                        abort these steps. */
+                        } elseif(isset($formatting_element) && !$in_stack) {
+                            unset($this->a_formatting[$fe_af_pos]);
+                            $this->a_formatting = array_merge($this->a_formatting);
+                            break;
+                        }
+
+                        /* 2. Let the furthest block be the topmost node in the
+                        stack of open elements that is lower in the stack
+                        than the formatting element, and is not an element in
+                        the phrasing or formatting categories. There might
+                        not be one. */
+                        $fe_s_pos = array_search($formatting_element, $this->stack, true);
+                        $length = count($this->stack);
+
+                        for($s = $fe_s_pos + 1; $s < $length; $s++) {
+                            $category = $this->getElementCategory($this->stack[$s]->nodeName);
+
+                            if($category !== self::PHRASING && $category !== self::FORMATTING) {
+                                $furthest_block = $this->stack[$s];
+                            }
+                        }
+
+                        /* 3. If there is no furthest block, then the UA must
+                        skip the subsequent steps and instead just pop all
+                        the nodes from the bottom of the stack of open
+                        elements, from the current node up to the formatting
+                        element, and remove the formatting element from the
+                        list of active formatting elements. */
+                        if(!isset($furthest_block)) {
+                            for($n = $length - 1; $n >= $fe_s_pos; $n--) {
+                                array_pop($this->stack);
+                            }
+
+                            unset($this->a_formatting[$fe_af_pos]);
+                            $this->a_formatting = array_merge($this->a_formatting);
+                            break;
+                        }
+
+                        /* 4. Let the common ancestor be the element
+                        immediately above the formatting element in the stack
+                        of open elements. */
+                        $common_ancestor = $this->stack[$fe_s_pos - 1];
+
+                        /* 5. If the furthest block has a parent node, then
+                        remove the furthest block from its parent node. */
+                        if($furthest_block->parentNode !== null) {
+                            $furthest_block->parentNode->removeChild($furthest_block);
+                        }
+
+                        /* 6. Let a bookmark note the position of the
+                        formatting element in the list of active formatting
+                        elements relative to the elements on either side
+                        of it in the list. */
+                        $bookmark = $fe_af_pos;
+
+                        /* 7. Let node and last node  be the furthest block.
+                        Follow these steps: */
+                        $node = $furthest_block;
+                        $last_node = $furthest_block;
+
+                        while(true) {
+                            for($n = array_search($node, $this->stack, true) - 1; $n >= 0; $n--) {
+                                /* 7.1 Let node be the element immediately
+                                prior to node in the stack of open elements. */
+                                $node = $this->stack[$n];
+
+                                /* 7.2 If node is not in the list of active
+                                formatting elements, then remove node from
+                                the stack of open elements and then go back
+                                to step 1. */
+                                if(!in_array($node, $this->a_formatting, true)) {
+                                    unset($this->stack[$n]);
+                                    $this->stack = array_merge($this->stack);
+
+                                } else {
+                                    break;
+                                }
+                            }
+
+                            /* 7.3 Otherwise, if node is the formatting
+                            element, then go to the next step in the overall
+                            algorithm. */
+                            if($node === $formatting_element) {
+                                break;
+
+                            /* 7.4 Otherwise, if last node is the furthest
+                            block, then move the aforementioned bookmark to
+                            be immediately after the node in the list of
+                            active formatting elements. */
+                            } elseif($last_node === $furthest_block) {
+                                $bookmark = array_search($node, $this->a_formatting, true) + 1;
+                            }
+
+                            /* 7.5 If node has any children, perform a
+                            shallow clone of node, replace the entry for
+                            node in the list of active formatting elements
+                            with an entry for the clone, replace the entry
+                            for node in the stack of open elements with an
+                            entry for the clone, and let node be the clone. */
+                            if($node->hasChildNodes()) {
+                                $clone = $node->cloneNode();
+                                $s_pos = array_search($node, $this->stack, true);
+                                $a_pos = array_search($node, $this->a_formatting, true);
+
+                                $this->stack[$s_pos] = $clone;
+                                $this->a_formatting[$a_pos] = $clone;
+                                $node = $clone;
+                            }
+
+                            /* 7.6 Insert last node into node, first removing
+                            it from its previous parent node if any. */
+                            if($last_node->parentNode !== null) {
+                                $last_node->parentNode->removeChild($last_node);
+                            }
+
+                            $node->appendChild($last_node);
+
+                            /* 7.7 Let last node be node. */
+                            $last_node = $node;
+                        }
+
+                        /* 8. Insert whatever last node ended up being in
+                        the previous step into the common ancestor node,
+                        first removing it from its previous parent node if
+                        any. */
+                        if($last_node->parentNode !== null) {
+                            $last_node->parentNode->removeChild($last_node);
+                        }
+
+                        $common_ancestor->appendChild($last_node);
+
+                        /* 9. Perform a shallow clone of the formatting
+                        element. */
+                        $clone = $formatting_element->cloneNode();
+
+                        /* 10. Take all of the child nodes of the furthest
+                        block and append them to the clone created in the
+                        last step. */
+                        while($furthest_block->hasChildNodes()) {
+                            $child = $furthest_block->firstChild;
+                            $furthest_block->removeChild($child);
+                            $clone->appendChild($child);
+                        }
+
+                        /* 11. Append that clone to the furthest block. */
+                        $furthest_block->appendChild($clone);
+
+                        /* 12. Remove the formatting element from the list
+                        of active formatting elements, and insert the clone
+                        into the list of active formatting elements at the
+                        position of the aforementioned bookmark. */
+                        $fe_af_pos = array_search($formatting_element, $this->a_formatting, true);
+                        unset($this->a_formatting[$fe_af_pos]);
+                        $this->a_formatting = array_merge($this->a_formatting);
+
+                        $af_part1 = array_slice($this->a_formatting, 0, $bookmark - 1);
+                        $af_part2 = array_slice($this->a_formatting, $bookmark, count($this->a_formatting));
+                        $this->a_formatting = array_merge($af_part1, array($clone), $af_part2);
+
+                        /* 13. Remove the formatting element from the stack
+                        of open elements, and insert the clone into the stack
+                        of open elements immediately after (i.e. in a more
+                        deeply nested position than) the position of the
+                        furthest block in that stack. */
+                        $fe_s_pos = array_search($formatting_element, $this->stack, true);
+                        $fb_s_pos = array_search($furthest_block, $this->stack, true);
+                        unset($this->stack[$fe_s_pos]);
+
+                        $s_part1 = array_slice($this->stack, 0, $fb_s_pos);
+                        $s_part2 = array_slice($this->stack, $fb_s_pos + 1, count($this->stack));
+                        $this->stack = array_merge($s_part1, array($clone), $s_part2);
+
+                        /* 14. Jump back to step 1 in this series of steps. */
+                        unset($formatting_element, $fe_af_pos, $fe_s_pos, $furthest_block);
+                    }
+                break;
+
+                /* An end tag token whose tag name is one of: "button",
+                "marquee", "object" */
+                case 'button': case 'marquee': case 'object':
+                    /* If the stack of open elements has an element in scope whose
+                    tag name matches the tag name of the token, then generate implied
+                    tags. */
+                    if($this->elementInScope($token['name'])) {
+                        $this->generateImpliedEndTags();
+
+                        /* Now, if the current node is not an element with the same
+                        tag name as the token, then this is a parse error. */
+                        // k
+
+                        /* Now, if the stack of open elements has an element in scope
+                        whose tag name matches the tag name of the token, then pop
+                        elements from the stack until that element has been popped from
+                        the stack, and clear the list of active formatting elements up
+                        to the last marker. */
+                        for($n = count($this->stack) - 1; $n >= 0; $n--) {
+                            if($this->stack[$n]->nodeName === $token['name']) {
+                                $n = -1;
+                            }
+
+                            array_pop($this->stack);
+                        }
+
+                        $marker = end(array_keys($this->a_formatting, self::MARKER, true));
+
+                        for($n = count($this->a_formatting) - 1; $n > $marker; $n--) {
+                            array_pop($this->a_formatting);
+                        }
+                    }
+                break;
+
+                /* Or an end tag whose tag name is one of: "area", "basefont",
+                "bgsound", "br", "embed", "hr", "iframe", "image", "img",
+                "input", "isindex", "noembed", "noframes", "param", "select",
+                "spacer", "table", "textarea", "wbr" */
+                case 'area': case 'basefont': case 'bgsound': case 'br':
+                case 'embed': case 'hr': case 'iframe': case 'image':
+                case 'img': case 'input': case 'isindex': case 'noembed':
+                case 'noframes': case 'param': case 'select': case 'spacer':
+                case 'table': case 'textarea': case 'wbr':
+                    // Parse error. Ignore the token.
+                break;
+
+                /* An end tag token not covered by the previous entries */
+                default:
+                    for($n = count($this->stack) - 1; $n >= 0; $n--) {
+                        /* Initialise node to be the current node (the bottommost
+                        node of the stack). */
+                        $node = end($this->stack);
+
+                        /* If node has the same tag name as the end tag token,
+                        then: */
+                        if($token['name'] === $node->nodeName) {
+                            /* Generate implied end tags. */
+                            $this->generateImpliedEndTags();
+
+                            /* If the tag name of the end tag token does not
+                            match the tag name of the current node, this is a
+                            parse error. */
+                            // k
+
+                            /* Pop all the nodes from the current node up to
+                            node, including node, then stop this algorithm. */
+                            for($x = count($this->stack) - $n; $x >= $n; $x--) {
+                                array_pop($this->stack);
+                            }
+                                    
+                        } else {
+                            $category = $this->getElementCategory($node);
+
+                            if($category !== self::SPECIAL && $category !== self::SCOPING) {
+                                /* Otherwise, if node is in neither the formatting
+                                category nor the phrasing category, then this is a
+                                parse error. Stop this algorithm. The end tag token
+                                is ignored. */
+                                return false;
+                            }
+                        }
+                    }
+                break;
+            }
+            break;
+        }
+    }
+
+    private function inTable($token) {
+        $clear = array('html', 'table');
+
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE */
+        if($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+            /* Append the character to the current node. */
+            $text = $this->dom->createTextNode($token['data']);
+            end($this->stack)->appendChild($text);
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the current node with the data
+            attribute set to the data given in the comment token. */
+            $comment = $this->dom->createComment($token['data']);
+            end($this->stack)->appendChild($comment);
+
+        /* A start tag whose tag name is "caption" */
+        } elseif($token['type'] === HTML5::STARTTAG &&
+        $token['name'] === 'caption') {
+            /* Clear the stack back to a table context. */
+            $this->clearStackToTableContext($clear);
+
+            /* Insert a marker at the end of the list of active
+            formatting elements. */
+            $this->a_formatting[] = self::MARKER;
+
+            /* Insert an HTML element for the token, then switch the
+            insertion mode to "in caption". */
+            $this->insertElement($token);
+            $this->mode = self::IN_CAPTION;
+
+        /* A start tag whose tag name is "colgroup" */
+        } elseif($token['type'] === HTML5::STARTTAG &&
+        $token['name'] === 'colgroup') {
+            /* Clear the stack back to a table context. */
+            $this->clearStackToTableContext($clear);
+
+            /* Insert an HTML element for the token, then switch the
+            insertion mode to "in column group". */
+            $this->insertElement($token);
+            $this->mode = self::IN_CGROUP;
+
+        /* A start tag whose tag name is "col" */
+        } elseif($token['type'] === HTML5::STARTTAG &&
+        $token['name'] === 'col') {
+            $this->inTable(array(
+                'name' => 'colgroup',
+                'type' => HTML5::STARTTAG,
+                'attr' => array()
+            ));
+
+            $this->inColumnGroup($token);
+
+        /* A start tag whose tag name is one of: "tbody", "tfoot", "thead" */
+        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+        array('tbody', 'tfoot', 'thead'))) {
+            /* Clear the stack back to a table context. */
+            $this->clearStackToTableContext($clear);
+
+            /* Insert an HTML element for the token, then switch the insertion
+            mode to "in table body". */
+            $this->insertElement($token);
+            $this->mode = self::IN_TBODY;
+
+        /* A start tag whose tag name is one of: "td", "th", "tr" */
+        } elseif($token['type'] === HTML5::STARTTAG &&
+        in_array($token['name'], array('td', 'th', 'tr'))) {
+            /* Act as if a start tag token with the tag name "tbody" had been
+            seen, then reprocess the current token. */
+            $this->inTable(array(
+                'name' => 'tbody',
+                'type' => HTML5::STARTTAG,
+                'attr' => array()
+            ));
+
+            return $this->inTableBody($token);
+
+        /* A start tag whose tag name is "table" */
+        } elseif($token['type'] === HTML5::STARTTAG &&
+        $token['name'] === 'table') {
+            /* Parse error. Act as if an end tag token with the tag name "table"
+            had been seen, then, if that token wasn't ignored, reprocess the
+            current token. */
+            $this->inTable(array(
+                'name' => 'table',
+                'type' => HTML5::ENDTAG
+            ));
+
+            return $this->mainPhase($token);
+
+        /* An end tag whose tag name is "table" */
+        } elseif($token['type'] === HTML5::ENDTAG &&
+        $token['name'] === 'table') {
+            /* If the stack of open elements does not have an element in table
+            scope with the same tag name as the token, this is a parse error.
+            Ignore the token. (innerHTML case) */
+            if(!$this->elementInScope($token['name'], true)) {
+                return false;
+
+            /* Otherwise: */
+            } else {
+                /* Generate implied end tags. */
+                $this->generateImpliedEndTags();
+
+                /* Now, if the current node is not a table element, then this
+                is a parse error. */
+                // w/e
+
+                /* Pop elements from this stack until a table element has been
+                popped from the stack. */
+                while(true) {
+                    $current = end($this->stack)->nodeName;
+                    array_pop($this->stack);
+
+                    if($current === 'table') {
+                        break;
+                    }
+                }
+
+                /* Reset the insertion mode appropriately. */
+                $this->resetInsertionMode();
+            }
+
+        /* An end tag whose tag name is one of: "body", "caption", "col",
+        "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr" */
+        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+        array('body', 'caption', 'col', 'colgroup', 'html', 'tbody', 'td',
+        'tfoot', 'th', 'thead', 'tr'))) {
+            // Parse error. Ignore the token.
+
+        /* Anything else */
+        } else {
+            /* Parse error. Process the token as if the insertion mode was "in
+            body", with the following exception: */
+
+            /* If the current node is a table, tbody, tfoot, thead, or tr
+            element, then, whenever a node would be inserted into the current
+            node, it must instead be inserted into the foster parent element. */
+            if(in_array(end($this->stack)->nodeName,
+            array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {
+                /* The foster parent element is the parent element of the last
+                table element in the stack of open elements, if there is a
+                table element and it has such a parent element. If there is no
+                table element in the stack of open elements (innerHTML case),
+                then the foster parent element is the first element in the
+                stack of open elements (the html  element). Otherwise, if there
+                is a table element in the stack of open elements, but the last
+                table element in the stack of open elements has no parent, or
+                its parent node is not an element, then the foster parent
+                element is the element before the last table element in the
+                stack of open elements. */
+                for($n = count($this->stack) - 1; $n >= 0; $n--) {
+                    if($this->stack[$n]->nodeName === 'table') {
+                        $table = $this->stack[$n];
+                        break;
+                    }
+                }
+
+                if(isset($table) && $table->parentNode !== null) {
+                    $this->foster_parent = $table->parentNode;
+
+                } elseif(!isset($table)) {
+                    $this->foster_parent = $this->stack[0];
+
+                } elseif(isset($table) && ($table->parentNode === null ||
+                $table->parentNode->nodeType !== XML_ELEMENT_NODE)) {
+                    $this->foster_parent = $this->stack[$n - 1];
+                }
+            }
+
+            $this->inBody($token);
+        }
+    }
+
+    private function inCaption($token) {
+        /* An end tag whose tag name is "caption" */
+        if($token['type'] === HTML5::ENDTAG && $token['name'] === 'caption') {
+            /* If the stack of open elements does not have an element in table
+            scope with the same tag name as the token, this is a parse error.
+            Ignore the token. (innerHTML case) */
+            if(!$this->elementInScope($token['name'], true)) {
+                // Ignore
+
+            /* Otherwise: */
+            } else {
+                /* Generate implied end tags. */
+                $this->generateImpliedEndTags();
+
+                /* Now, if the current node is not a caption element, then this
+                is a parse error. */
+                // w/e
+
+                /* Pop elements from this stack until a caption element has
+                been popped from the stack. */
+                while(true) {
+                    $node = end($this->stack)->nodeName;
+                    array_pop($this->stack);
+
+                    if($node === 'caption') {
+                        break;
+                    }
+                }
+
+                /* Clear the list of active formatting elements up to the last
+                marker. */
+                $this->clearTheActiveFormattingElementsUpToTheLastMarker();
+
+                /* Switch the insertion mode to "in table". */
+                $this->mode = self::IN_TABLE;
+            }
+
+        /* A start tag whose tag name is one of: "caption", "col", "colgroup",
+        "tbody", "td", "tfoot", "th", "thead", "tr", or an end tag whose tag
+        name is "table" */
+        } elseif(($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+        array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
+        'thead', 'tr'))) || ($token['type'] === HTML5::ENDTAG &&
+        $token['name'] === 'table')) {
+            /* Parse error. Act as if an end tag with the tag name "caption"
+            had been seen, then, if that token wasn't ignored, reprocess the
+            current token. */
+            $this->inCaption(array(
+                'name' => 'caption',
+                'type' => HTML5::ENDTAG
+            ));
+
+            return $this->inTable($token);
+
+        /* An end tag whose tag name is one of: "body", "col", "colgroup",
+        "html", "tbody", "td", "tfoot", "th", "thead", "tr" */
+        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+        array('body', 'col', 'colgroup', 'html', 'tbody', 'tfoot', 'th',
+        'thead', 'tr'))) {
+            // Parse error. Ignore the token.
+
+        /* Anything else */
+        } else {
+            /* Process the token as if the insertion mode was "in body". */
+            $this->inBody($token);
+        }
+    }
+
+    private function inColumnGroup($token) {
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE */
+        if($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+            /* Append the character to the current node. */
+            $text = $this->dom->createTextNode($token['data']);
+            end($this->stack)->appendChild($text);
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the current node with the data
+            attribute set to the data given in the comment token. */
+            $comment = $this->dom->createComment($token['data']);
+            end($this->stack)->appendChild($comment);
+
+        /* A start tag whose tag name is "col" */
+        } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'col') {
+            /* Insert a col element for the token. Immediately pop the current
+            node off the stack of open elements. */
+            $this->insertElement($token);
+            array_pop($this->stack);
+
+        /* An end tag whose tag name is "colgroup" */
+        } elseif($token['type'] === HTML5::ENDTAG &&
+        $token['name'] === 'colgroup') {
+            /* If the current node is the root html element, then this is a
+            parse error, ignore the token. (innerHTML case) */
+            if(end($this->stack)->nodeName === 'html') {
+                // Ignore
+
+            /* Otherwise, pop the current node (which will be a colgroup
+            element) from the stack of open elements. Switch the insertion
+            mode to "in table". */
+            } else {
+                array_pop($this->stack);
+                $this->mode = self::IN_TABLE;
+            }
+
+        /* An end tag whose tag name is "col" */
+        } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'col') {
+            /* Parse error. Ignore the token. */
+
+        /* Anything else */
+        } else {
+            /* Act as if an end tag with the tag name "colgroup" had been seen,
+            and then, if that token wasn't ignored, reprocess the current token. */
+            $this->inColumnGroup(array(
+                'name' => 'colgroup',
+                'type' => HTML5::ENDTAG
+            ));
+
+            return $this->inTable($token);
+        }
+    }
+
+    private function inTableBody($token) {
+        $clear = array('tbody', 'tfoot', 'thead', 'html');
+
+        /* A start tag whose tag name is "tr" */
+        if($token['type'] === HTML5::STARTTAG && $token['name'] === 'tr') {
+            /* Clear the stack back to a table body context. */
+            $this->clearStackToTableContext($clear);
+
+            /* Insert a tr element for the token, then switch the insertion
+            mode to "in row". */
+            $this->insertElement($token);
+            $this->mode = self::IN_ROW;
+
+        /* A start tag whose tag name is one of: "th", "td" */
+        } elseif($token['type'] === HTML5::STARTTAG &&
+        ($token['name'] === 'th' ||    $token['name'] === 'td')) {
+            /* Parse error. Act as if a start tag with the tag name "tr" had
+            been seen, then reprocess the current token. */
+            $this->inTableBody(array(
+                'name' => 'tr',
+                'type' => HTML5::STARTTAG,
+                'attr' => array()
+            ));
+
+            return $this->inRow($token);
+
+        /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */
+        } elseif($token['type'] === HTML5::ENDTAG &&
+        in_array($token['name'], array('tbody', 'tfoot', 'thead'))) {
+            /* If the stack of open elements does not have an element in table
+            scope with the same tag name as the token, this is a parse error.
+            Ignore the token. */
+            if(!$this->elementInScope($token['name'], true)) {
+                // Ignore
+
+            /* Otherwise: */
+            } else {
+                /* Clear the stack back to a table body context. */
+                $this->clearStackToTableContext($clear);
+
+                /* Pop the current node from the stack of open elements. Switch
+                the insertion mode to "in table". */
+                array_pop($this->stack);
+                $this->mode = self::IN_TABLE;
+            }
+
+        /* A start tag whose tag name is one of: "caption", "col", "colgroup",
+        "tbody", "tfoot", "thead", or an end tag whose tag name is "table" */
+        } elseif(($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+        array('caption', 'col', 'colgroup', 'tbody', 'tfoor', 'thead'))) ||
+        ($token['type'] === HTML5::STARTTAG && $token['name'] === 'table')) {
+            /* If the stack of open elements does not have a tbody, thead, or
+            tfoot element in table scope, this is a parse error. Ignore the
+            token. (innerHTML case) */
+            if(!$this->elementInScope(array('tbody', 'thead', 'tfoot'), true)) {
+                // Ignore.
+
+            /* Otherwise: */
+            } else {
+                /* Clear the stack back to a table body context. */
+                $this->clearStackToTableContext($clear);
+
+                /* Act as if an end tag with the same tag name as the current
+                node ("tbody", "tfoot", or "thead") had been seen, then
+                reprocess the current token. */
+                $this->inTableBody(array(
+                    'name' => end($this->stack)->nodeName,
+                    'type' => HTML5::ENDTAG
+                ));
+
+                return $this->mainPhase($token);
+            }
+
+        /* An end tag whose tag name is one of: "body", "caption", "col",
+        "colgroup", "html", "td", "th", "tr" */
+        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+        array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {
+            /* Parse error. Ignore the token. */
+
+        /* Anything else */
+        } else {
+            /* Process the token as if the insertion mode was "in table". */
+            $this->inTable($token);
+        }
+    }
+
+    private function inRow($token) {
+        $clear = array('tr', 'html');
+
+        /* A start tag whose tag name is one of: "th", "td" */
+        if($token['type'] === HTML5::STARTTAG &&
+        ($token['name'] === 'th' || $token['name'] === 'td')) {
+            /* Clear the stack back to a table row context. */
+            $this->clearStackToTableContext($clear);
+
+            /* Insert an HTML element for the token, then switch the insertion
+            mode to "in cell". */
+            $this->insertElement($token);
+            $this->mode = self::IN_CELL;
+
+            /* Insert a marker at the end of the list of active formatting
+            elements. */
+            $this->a_formatting[] = self::MARKER;
+
+        /* An end tag whose tag name is "tr" */
+        } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'tr') {
+            /* If the stack of open elements does not have an element in table
+            scope with the same tag name as the token, this is a parse error.
+            Ignore the token. (innerHTML case) */
+            if(!$this->elementInScope($token['name'], true)) {
+                // Ignore.
+
+            /* Otherwise: */
+            } else {
+                /* Clear the stack back to a table row context. */
+                $this->clearStackToTableContext($clear);
+
+                /* Pop the current node (which will be a tr element) from the
+                stack of open elements. Switch the insertion mode to "in table
+                body". */
+                array_pop($this->stack);
+                $this->mode = self::IN_TBODY;
+            }
+
+        /* A start tag whose tag name is one of: "caption", "col", "colgroup",
+        "tbody", "tfoot", "thead", "tr" or an end tag whose tag name is "table" */
+        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+        array('caption', 'col', 'colgroup', 'tbody', 'tfoot', 'thead', 'tr'))) {
+            /* Act as if an end tag with the tag name "tr" had been seen, then,
+            if that token wasn't ignored, reprocess the current token. */
+            $this->inRow(array(
+                'name' => 'tr',
+                'type' => HTML5::ENDTAG
+            ));
+
+            return $this->inCell($token);
+
+        /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */
+        } elseif($token['type'] === HTML5::ENDTAG &&
+        in_array($token['name'], array('tbody', 'tfoot', 'thead'))) {
+            /* If the stack of open elements does not have an element in table
+            scope with the same tag name as the token, this is a parse error.
+            Ignore the token. */
+            if(!$this->elementInScope($token['name'], true)) {
+                // Ignore.
+
+            /* Otherwise: */
+            } else {
+                /* Otherwise, act as if an end tag with the tag name "tr" had
+                been seen, then reprocess the current token. */
+                $this->inRow(array(
+                    'name' => 'tr',
+                    'type' => HTML5::ENDTAG
+                ));
+
+                return $this->inCell($token);
+            }
+
+        /* An end tag whose tag name is one of: "body", "caption", "col",
+        "colgroup", "html", "td", "th" */
+        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+        array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {
+            /* Parse error. Ignore the token. */
+
+        /* Anything else */
+        } else {
+            /* Process the token as if the insertion mode was "in table". */
+            $this->inTable($token);
+        }
+    }
+
+    private function inCell($token) {
+        /* An end tag whose tag name is one of: "td", "th" */
+        if($token['type'] === HTML5::ENDTAG &&
+        ($token['name'] === 'td' || $token['name'] === 'th')) {
+            /* If the stack of open elements does not have an element in table
+            scope with the same tag name as that of the token, then this is a
+            parse error and the token must be ignored. */
+            if(!$this->elementInScope($token['name'], true)) {
+                // Ignore.
+
+            /* Otherwise: */
+            } else {
+                /* Generate implied end tags, except for elements with the same
+                tag name as the token. */
+                $this->generateImpliedEndTags(array($token['name']));
+
+                /* Now, if the current node is not an element with the same tag
+                name as the token, then this is a parse error. */
+                // k
+
+                /* Pop elements from this stack until an element with the same
+                tag name as the token has been popped from the stack. */
+                while(true) {
+                    $node = end($this->stack)->nodeName;
+                    array_pop($this->stack);
+
+                    if($node === $token['name']) {
+                        break;
+                    }
+                }
+
+                /* Clear the list of active formatting elements up to the last
+                marker. */
+                $this->clearTheActiveFormattingElementsUpToTheLastMarker();
+
+                /* Switch the insertion mode to "in row". (The current node
+                will be a tr element at this point.) */
+                $this->mode = self::IN_ROW;
+            }
+
+        /* A start tag whose tag name is one of: "caption", "col", "colgroup",
+        "tbody", "td", "tfoot", "th", "thead", "tr" */
+        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+        array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
+        'thead', 'tr'))) {
+            /* If the stack of open elements does not have a td or th element
+            in table scope, then this is a parse error; ignore the token.
+            (innerHTML case) */
+            if(!$this->elementInScope(array('td', 'th'), true)) {
+                // Ignore.
+
+            /* Otherwise, close the cell (see below) and reprocess the current
+            token. */
+            } else {
+                $this->closeCell();
+                return $this->inRow($token);
+            }
+
+        /* A start tag whose tag name is one of: "caption", "col", "colgroup",
+        "tbody", "td", "tfoot", "th", "thead", "tr" */
+        } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
+        array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
+        'thead', 'tr'))) {
+            /* If the stack of open elements does not have a td or th element
+            in table scope, then this is a parse error; ignore the token.
+            (innerHTML case) */
+            if(!$this->elementInScope(array('td', 'th'), true)) {
+                // Ignore.
+
+            /* Otherwise, close the cell (see below) and reprocess the current
+            token. */
+            } else {
+                $this->closeCell();
+                return $this->inRow($token);
+            }
+
+        /* An end tag whose tag name is one of: "body", "caption", "col",
+        "colgroup", "html" */
+        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+        array('body', 'caption', 'col', 'colgroup', 'html'))) {
+            /* Parse error. Ignore the token. */
+
+        /* An end tag whose tag name is one of: "table", "tbody", "tfoot",
+        "thead", "tr" */
+        } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
+        array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {
+            /* If the stack of open elements does not have an element in table
+            scope with the same tag name as that of the token (which can only
+            happen for "tbody", "tfoot" and "thead", or, in the innerHTML case),
+            then this is a parse error and the token must be ignored. */
+            if(!$this->elementInScope($token['name'], true)) {
+                // Ignore.
+
+            /* Otherwise, close the cell (see below) and reprocess the current
+            token. */
+            } else {
+                $this->closeCell();
+                return $this->inRow($token);
+            }
+
+        /* Anything else */
+        } else {
+            /* Process the token as if the insertion mode was "in body". */
+            $this->inBody($token);
+        }
+    }
+
+    private function inSelect($token) {
+        /* Handle the token as follows: */
+
+        /* A character token */
+        if($token['type'] === HTML5::CHARACTR) {
+            /* Append the token's character to the current node. */
+            $this->insertText($token['data']);
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the current node with the data
+            attribute set to the data given in the comment token. */
+            $this->insertComment($token['data']);
+
+        /* A start tag token whose tag name is "option" */
+        } elseif($token['type'] === HTML5::STARTTAG &&
+        $token['name'] === 'option') {
+            /* If the current node is an option element, act as if an end tag
+            with the tag name "option" had been seen. */
+            if(end($this->stack)->nodeName === 'option') {
+                $this->inSelect(array(
+                    'name' => 'option',
+                    'type' => HTML5::ENDTAG
+                ));
+            }
+
+            /* Insert an HTML element for the token. */
+            $this->insertElement($token);
+
+        /* A start tag token whose tag name is "optgroup" */
+        } elseif($token['type'] === HTML5::STARTTAG &&
+        $token['name'] === 'optgroup') {
+            /* If the current node is an option element, act as if an end tag
+            with the tag name "option" had been seen. */
+            if(end($this->stack)->nodeName === 'option') {
+                $this->inSelect(array(
+                    'name' => 'option',
+                    'type' => HTML5::ENDTAG
+                ));
+            }
+
+            /* If the current node is an optgroup element, act as if an end tag
+            with the tag name "optgroup" had been seen. */
+            if(end($this->stack)->nodeName === 'optgroup') {
+                $this->inSelect(array(
+                    'name' => 'optgroup',
+                    'type' => HTML5::ENDTAG
+                ));
+            }
+
+            /* Insert an HTML element for the token. */
+            $this->insertElement($token);
+
+        /* An end tag token whose tag name is "optgroup" */
+        } elseif($token['type'] === HTML5::ENDTAG &&
+        $token['name'] === 'optgroup') {
+            /* First, if the current node is an option element, and the node
+            immediately before it in the stack of open elements is an optgroup
+            element, then act as if an end tag with the tag name "option" had
+            been seen. */
+            $elements_in_stack = count($this->stack);
+
+            if($this->stack[$elements_in_stack - 1]->nodeName === 'option' &&
+            $this->stack[$elements_in_stack - 2]->nodeName === 'optgroup') {
+                $this->inSelect(array(
+                    'name' => 'option',
+                    'type' => HTML5::ENDTAG
+                ));
+            }
+
+            /* If the current node is an optgroup element, then pop that node
+            from the stack of open elements. Otherwise, this is a parse error,
+            ignore the token. */
+            if($this->stack[$elements_in_stack - 1] === 'optgroup') {
+                array_pop($this->stack);
+            }
+
+        /* An end tag token whose tag name is "option" */
+        } elseif($token['type'] === HTML5::ENDTAG &&
+        $token['name'] === 'option') {
+            /* If the current node is an option element, then pop that node
+            from the stack of open elements. Otherwise, this is a parse error,
+            ignore the token. */
+            if(end($this->stack)->nodeName === 'option') {
+                array_pop($this->stack);
+            }
+
+        /* An end tag whose tag name is "select" */
+        } elseif($token['type'] === HTML5::ENDTAG &&
+        $token['name'] === 'select') {
+            /* If the stack of open elements does not have an element in table
+            scope with the same tag name as the token, this is a parse error.
+            Ignore the token. (innerHTML case) */
+            if(!$this->elementInScope($token['name'], true)) {
+                // w/e
+
+            /* Otherwise: */
+            } else {
+                /* Pop elements from the stack of open elements until a select
+                element has been popped from the stack. */
+                while(true) {
+                    $current = end($this->stack)->nodeName;
+                    array_pop($this->stack);
+
+                    if($current === 'select') {
+                        break;
+                    }
+                }
+
+                /* Reset the insertion mode appropriately. */
+                $this->resetInsertionMode();
+            }
+
+        /* A start tag whose tag name is "select" */
+        } elseif($token['name'] === 'select' &&
+        $token['type'] === HTML5::STARTTAG) {
+            /* Parse error. Act as if the token had been an end tag with the
+            tag name "select" instead. */
+            $this->inSelect(array(
+                'name' => 'select',
+                'type' => HTML5::ENDTAG
+            ));
+
+        /* An end tag whose tag name is one of: "caption", "table", "tbody",
+        "tfoot", "thead", "tr", "td", "th" */
+        } elseif(in_array($token['name'], array('caption', 'table', 'tbody',
+        'tfoot', 'thead', 'tr', 'td', 'th')) && $token['type'] === HTML5::ENDTAG) {
+            /* Parse error. */
+            // w/e
+
+            /* If the stack of open elements has an element in table scope with
+            the same tag name as that of the token, then act as if an end tag
+            with the tag name "select" had been seen, and reprocess the token.
+            Otherwise, ignore the token. */
+            if($this->elementInScope($token['name'], true)) {
+                $this->inSelect(array(
+                    'name' => 'select',
+                    'type' => HTML5::ENDTAG
+                ));
+
+                $this->mainPhase($token);
+            }
+
+        /* Anything else */
+        } else {
+            /* Parse error. Ignore the token. */
+        }
+    }
+
+    private function afterBody($token) {
+        /* Handle the token as follows: */
+
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE */
+        if($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+            /* Process the token as it would be processed if the insertion mode
+            was "in body". */
+            $this->inBody($token);
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the first element in the stack of open
+            elements (the html element), with the data attribute set to the
+            data given in the comment token. */
+            $comment = $this->dom->createComment($token['data']);
+            $this->stack[0]->appendChild($comment);
+
+        /* An end tag with the tag name "html" */
+        } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') {
+            /* If the parser was originally created in order to handle the
+            setting of an element's innerHTML attribute, this is a parse error;
+            ignore the token. (The element will be an html element in this
+            case.) (innerHTML case) */
+
+            /* Otherwise, switch to the trailing end phase. */
+            $this->phase = self::END_PHASE;
+
+        /* Anything else */
+        } else {
+            /* Parse error. Set the insertion mode to "in body" and reprocess
+            the token. */
+            $this->mode = self::IN_BODY;
+            return $this->inBody($token);
+        }
+    }
+
+    private function inFrameset($token) {
+        /* Handle the token as follows: */
+
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */
+        if($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+            /* Append the character to the current node. */
+            $this->insertText($token['data']);
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the current node with the data
+            attribute set to the data given in the comment token. */
+            $this->insertComment($token['data']);
+
+        /* A start tag with the tag name "frameset" */
+        } elseif($token['name'] === 'frameset' &&
+        $token['type'] === HTML5::STARTTAG) {
+            $this->insertElement($token);
+
+        /* An end tag with the tag name "frameset" */
+        } elseif($token['name'] === 'frameset' &&
+        $token['type'] === HTML5::ENDTAG) {
+            /* If the current node is the root html element, then this is a
+            parse error; ignore the token. (innerHTML case) */
+            if(end($this->stack)->nodeName === 'html') {
+                // Ignore
+
+            } else {
+                /* Otherwise, pop the current node from the stack of open
+                elements. */
+                array_pop($this->stack);
+
+                /* If the parser was not originally created in order to handle
+                the setting of an element's innerHTML attribute (innerHTML case),
+                and the current node is no longer a frameset element, then change
+                the insertion mode to "after frameset". */
+                $this->mode = self::AFTR_FRAME;
+            }
+
+        /* A start tag with the tag name "frame" */
+        } elseif($token['name'] === 'frame' &&
+        $token['type'] === HTML5::STARTTAG) {
+            /* Insert an HTML element for the token. */
+            $this->insertElement($token);
+
+            /* Immediately pop the current node off the stack of open elements. */
+            array_pop($this->stack);
+
+        /* A start tag with the tag name "noframes" */
+        } elseif($token['name'] === 'noframes' &&
+        $token['type'] === HTML5::STARTTAG) {
+            /* Process the token as if the insertion mode had been "in body". */
+            $this->inBody($token);
+
+        /* Anything else */
+        } else {
+            /* Parse error. Ignore the token. */
+        }
+    }
+
+    private function afterFrameset($token) {
+        /* Handle the token as follows: */
+
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */
+        if($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+            /* Append the character to the current node. */
+            $this->insertText($token['data']);
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the current node with the data
+            attribute set to the data given in the comment token. */
+            $this->insertComment($token['data']);
+
+        /* An end tag with the tag name "html" */
+        } elseif($token['name'] === 'html' &&
+        $token['type'] === HTML5::ENDTAG) {
+            /* Switch to the trailing end phase. */
+            $this->phase = self::END_PHASE;
+
+        /* A start tag with the tag name "noframes" */
+        } elseif($token['name'] === 'noframes' &&
+        $token['type'] === HTML5::STARTTAG) {
+            /* Process the token as if the insertion mode had been "in body". */
+            $this->inBody($token);
+
+        /* Anything else */
+        } else {
+            /* Parse error. Ignore the token. */
+        }
+    }
+
+    private function trailingEndPhase($token) {
+        /* After the main phase, as each token is emitted from the tokenisation
+        stage, it must be processed as described in this section. */
+
+        /* A DOCTYPE token */
+        if($token['type'] === HTML5::DOCTYPE) {
+            // Parse error. Ignore the token.
+
+        /* A comment token */
+        } elseif($token['type'] === HTML5::COMMENT) {
+            /* Append a Comment node to the Document object with the data
+            attribute set to the data given in the comment token. */
+            $comment = $this->dom->createComment($token['data']);
+            $this->dom->appendChild($comment);
+
+        /* A character token that is one of one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE */
+        } elseif($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
+            /* Process the token as it would be processed in the main phase. */
+            $this->mainPhase($token);
+
+        /* A character token that is not one of U+0009 CHARACTER TABULATION,
+        U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
+        or U+0020 SPACE. Or a start tag token. Or an end tag token. */
+        } elseif(($token['type'] === HTML5::CHARACTR &&
+        preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) ||
+        $token['type'] === HTML5::STARTTAG || $token['type'] === HTML5::ENDTAG) {
+            /* Parse error. Switch back to the main phase and reprocess the
+            token. */
+            $this->phase = self::MAIN_PHASE;
+            return $this->mainPhase($token);
+
+        /* An end-of-file token */
+        } elseif($token['type'] === HTML5::EOF) {
+            /* OMG DONE!! */
+        }
+    }
+
+    private function insertElement($token, $append = true, $check = false) {
+        // Proprietary workaround for libxml2's limitations with tag names
+        if ($check) {
+            // Slightly modified HTML5 tag-name modification,
+            // removing anything that's not an ASCII letter, digit, or hyphen
+            $token['name'] = preg_replace('/[^a-z0-9-]/i', '', $token['name']);
+            // Remove leading hyphens and numbers
+            $token['name'] = ltrim($token['name'], '-0..9');
+            // In theory, this should ever be needed, but just in case
+            if ($token['name'] === '') $token['name'] = 'span'; // arbitrary generic choice
+        }
+        
+        $el = $this->dom->createElement($token['name']);
+
+        foreach($token['attr'] as $attr) {
+            if(!$el->hasAttribute($attr['name'])) {
+                $el->setAttribute($attr['name'], $attr['value']);
+            }
+        }
+
+        $this->appendToRealParent($el);
+        $this->stack[] = $el;
+
+        return $el;
+    }
+
+    private function insertText($data) {
+        $text = $this->dom->createTextNode($data);
+        $this->appendToRealParent($text);
+    }
+
+    private function insertComment($data) {
+        $comment = $this->dom->createComment($data);
+        $this->appendToRealParent($comment);
+    }
+
+    private function appendToRealParent($node) {
+        if($this->foster_parent === null) {
+            end($this->stack)->appendChild($node);
+
+        } elseif($this->foster_parent !== null) {
+            /* If the foster parent element is the parent element of the
+            last table element in the stack of open elements, then the new
+            node must be inserted immediately before the last table element
+            in the stack of open elements in the foster parent element;
+            otherwise, the new node must be appended to the foster parent
+            element. */
+            for($n = count($this->stack) - 1; $n >= 0; $n--) {
+                if($this->stack[$n]->nodeName === 'table' &&
+                $this->stack[$n]->parentNode !== null) {
+                    $table = $this->stack[$n];
+                    break;
+                }
+            }
+
+            if(isset($table) && $this->foster_parent->isSameNode($table->parentNode))
+                $this->foster_parent->insertBefore($node, $table);
+            else
+                $this->foster_parent->appendChild($node);
+
+            $this->foster_parent = null;
+        }
+    }
+
+    private function elementInScope($el, $table = false) {
+        if(is_array($el)) {
+            foreach($el as $element) {
+                if($this->elementInScope($element, $table)) {
+                    return true;
+                }
+            }
+
+            return false;
+        }
+
+        $leng = count($this->stack);
+
+        for($n = 0; $n < $leng; $n++) {
+            /* 1. Initialise node to be the current node (the bottommost node of
+            the stack). */
+            $node = $this->stack[$leng - 1 - $n];
+
+            if($node->tagName === $el) {
+                /* 2. If node is the target node, terminate in a match state. */
+                return true;
+
+            } elseif($node->tagName === 'table') {
+                /* 3. Otherwise, if node is a table element, terminate in a failure
+                state. */
+                return false;
+
+            } elseif($table === true && in_array($node->tagName, array('caption', 'td',
+            'th', 'button', 'marquee', 'object'))) {
+                /* 4. Otherwise, if the algorithm is the "has an element in scope"
+                variant (rather than the "has an element in table scope" variant),
+                and node is one of the following, terminate in a failure state. */
+                return false;
+
+            } elseif($node === $node->ownerDocument->documentElement) {
+                /* 5. Otherwise, if node is an html element (root element), terminate
+                in a failure state. (This can only happen if the node is the topmost
+                node of the    stack of open elements, and prevents the next step from
+                being invoked if there are no more elements in the stack.) */
+                return false;
+            }
+
+            /* Otherwise, set node to the previous entry in the stack of open
+            elements and return to step 2. (This will never fail, since the loop
+            will always terminate in the previous step if the top of the stack
+            is reached.) */
+        }
+    }
+
+    private function reconstructActiveFormattingElements() {
+        /* 1. If there are no entries in the list of active formatting elements,
+        then there is nothing to reconstruct; stop this algorithm. */
+        $formatting_elements = count($this->a_formatting);
+
+        if($formatting_elements === 0) {
+            return false;
+        }
+
+        /* 3. Let entry be the last (most recently added) element in the list
+        of active formatting elements. */
+        $entry = end($this->a_formatting);
+
+        /* 2. If the last (most recently added) entry in the list of active
+        formatting elements is a marker, or if it is an element that is in the
+        stack of open elements, then there is nothing to reconstruct; stop this
+        algorithm. */
+        if($entry === self::MARKER || in_array($entry, $this->stack, true)) {
+            return false;
+        }
+
+        for($a = $formatting_elements - 1; $a >= 0; true) {
+            /* 4. If there are no entries before entry in the list of active
+            formatting elements, then jump to step 8. */
+            if($a === 0) {
+                $step_seven = false;
+                break;
+            }
+
+            /* 5. Let entry be the entry one earlier than entry in the list of
+            active formatting elements. */
+            $a--;
+            $entry = $this->a_formatting[$a];
+
+            /* 6. If entry is neither a marker nor an element that is also in
+            thetack of open elements, go to step 4. */
+            if($entry === self::MARKER || in_array($entry, $this->stack, true)) {
+                break;
+            }
+        }
+
+        while(true) {
+            /* 7. Let entry be the element one later than entry in the list of
+            active formatting elements. */
+            if(isset($step_seven) && $step_seven === true) {
+                $a++;
+                $entry = $this->a_formatting[$a];
+            }
+
+            /* 8. Perform a shallow clone of the element entry to obtain clone. */
+            $clone = $entry->cloneNode();
+
+            /* 9. Append clone to the current node and push it onto the stack
+            of open elements  so that it is the new current node. */
+            end($this->stack)->appendChild($clone);
+            $this->stack[] = $clone;
+
+            /* 10. Replace the entry for entry in the list with an entry for
+            clone. */
+            $this->a_formatting[$a] = $clone;
+
+            /* 11. If the entry for clone in the list of active formatting
+            elements is not the last entry in the list, return to step 7. */
+            if(end($this->a_formatting) !== $clone) {
+                $step_seven = true;
+            } else {
+                break;
+            }
+        }
+    }
+
+    private function clearTheActiveFormattingElementsUpToTheLastMarker() {
+        /* When the steps below require the UA to clear the list of active
+        formatting elements up to the last marker, the UA must perform the
+        following steps: */
+
+        while(true) {
+            /* 1. Let entry be the last (most recently added) entry in the list
+            of active formatting elements. */
+            $entry = end($this->a_formatting);
+
+            /* 2. Remove entry from the list of active formatting elements. */
+            array_pop($this->a_formatting);
+
+            /* 3. If entry was a marker, then stop the algorithm at this point.
+            The list has been cleared up to the last marker. */
+            if($entry === self::MARKER) {
+                break;
+            }
+        }
+    }
+
+    private function generateImpliedEndTags($exclude = array()) {
+        /* When the steps below require the UA to generate implied end tags,
+        then, if the current node is a dd element, a dt element, an li element,
+        a p element, a td element, a th  element, or a tr element, the UA must
+        act as if an end tag with the respective tag name had been seen and
+        then generate implied end tags again. */
+        $node = end($this->stack);
+        $elements = array_diff(array('dd', 'dt', 'li', 'p', 'td', 'th', 'tr'), $exclude);
+
+        while(in_array(end($this->stack)->nodeName, $elements)) {
+            array_pop($this->stack);
+        }
+    }
+
+    private function getElementCategory($node) {
+        $name = $node->tagName;
+        if(in_array($name, $this->special))
+            return self::SPECIAL;
+
+        elseif(in_array($name, $this->scoping))
+            return self::SCOPING;
+
+        elseif(in_array($name, $this->formatting))
+            return self::FORMATTING;
+
+        else
+            return self::PHRASING;
+    }
+
+    private function clearStackToTableContext($elements) {
+        /* When the steps above require the UA to clear the stack back to a
+        table context, it means that the UA must, while the current node is not
+        a table element or an html element, pop elements from the stack of open
+        elements. If this causes any elements to be popped from the stack, then
+        this is a parse error. */
+        while(true) {
+            $node = end($this->stack)->nodeName;
+
+            if(in_array($node, $elements)) {
+                break;
+            } else {
+                array_pop($this->stack);
+            }
+        }
+    }
+
+    private function resetInsertionMode() {
+        /* 1. Let last be false. */
+        $last = false;
+        $leng = count($this->stack);
+
+        for($n = $leng - 1; $n >= 0; $n--) {
+            /* 2. Let node be the last node in the stack of open elements. */
+            $node = $this->stack[$n];
+
+            /* 3. If node is the first node in the stack of open elements, then
+            set last to true. If the element whose innerHTML  attribute is being
+            set is neither a td  element nor a th element, then set node to the
+            element whose innerHTML  attribute is being set. (innerHTML  case) */
+            if($this->stack[0]->isSameNode($node)) {
+                $last = true;
+            }
+
+            /* 4. If node is a select element, then switch the insertion mode to
+            "in select" and abort these steps. (innerHTML case) */
+            if($node->nodeName === 'select') {
+                $this->mode = self::IN_SELECT;
+                break;
+
+            /* 5. If node is a td or th element, then switch the insertion mode
+            to "in cell" and abort these steps. */
+            } elseif($node->nodeName === 'td' || $node->nodeName === 'th') {
+                $this->mode = self::IN_CELL;
+                break;
+
+            /* 6. If node is a tr element, then switch the insertion mode to
+            "in    row" and abort these steps. */
+            } elseif($node->nodeName === 'tr') {
+                $this->mode = self::IN_ROW;
+                break;
+
+            /* 7. If node is a tbody, thead, or tfoot element, then switch the
+            insertion mode to "in table body" and abort these steps. */
+            } elseif(in_array($node->nodeName, array('tbody', 'thead', 'tfoot'))) {
+                $this->mode = self::IN_TBODY;
+                break;
+
+            /* 8. If node is a caption element, then switch the insertion mode
+            to "in caption" and abort these steps. */
+            } elseif($node->nodeName === 'caption') {
+                $this->mode = self::IN_CAPTION;
+                break;
+
+            /* 9. If node is a colgroup element, then switch the insertion mode
+            to "in column group" and abort these steps. (innerHTML case) */
+            } elseif($node->nodeName === 'colgroup') {
+                $this->mode = self::IN_CGROUP;
+                break;
+
+            /* 10. If node is a table element, then switch the insertion mode
+            to "in table" and abort these steps. */
+            } elseif($node->nodeName === 'table') {
+                $this->mode = self::IN_TABLE;
+                break;
+
+            /* 11. If node is a head element, then switch the insertion mode
+            to "in body" ("in body"! not "in head"!) and abort these steps.
+            (innerHTML case) */
+            } elseif($node->nodeName === 'head') {
+                $this->mode = self::IN_BODY;
+                break;
+
+            /* 12. If node is a body element, then switch the insertion mode to
+            "in body" and abort these steps. */
+            } elseif($node->nodeName === 'body') {
+                $this->mode = self::IN_BODY;
+                break;
+
+            /* 13. If node is a frameset element, then switch the insertion
+            mode to "in frameset" and abort these steps. (innerHTML case) */
+            } elseif($node->nodeName === 'frameset') {
+                $this->mode = self::IN_FRAME;
+                break;
+
+            /* 14. If node is an html element, then: if the head element
+            pointer is null, switch the insertion mode to "before head",
+            otherwise, switch the insertion mode to "after head". In either
+            case, abort these steps. (innerHTML case) */
+            } elseif($node->nodeName === 'html') {
+                $this->mode = ($this->head_pointer === null)
+                    ? self::BEFOR_HEAD
+                    : self::AFTER_HEAD;
+
+                break;
+
+            /* 15. If last is true, then set the insertion mode to "in body"
+            and    abort these steps. (innerHTML case) */
+            } elseif($last) {
+                $this->mode = self::IN_BODY;
+                break;
+            }
+        }
+    }
+
+    private function closeCell() {
+        /* If the stack of open elements has a td or th element in table scope,
+        then act as if an end tag token with that tag name had been seen. */
+        foreach(array('td', 'th') as $cell) {
+            if($this->elementInScope($cell, true)) {
+                $this->inCell(array(
+                    'name' => $cell,
+                    'type' => HTML5::ENDTAG
+                ));
+
+                break;
+            }
+        }
+    }
+
+    public function save() {
+        return $this->dom;
+    }
+}
+?>
index 1ca6271158477cf64b132105804e6e4aa4bd4a6e..0698c4e4577993b81b80fa6c7029afdcd682a286 100644 (file)
@@ -7,31 +7,61 @@ class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
 {
     
     /**
-     * Locally shared variable references
+     * Array stream of tokens being processed.
      */
-    protected $inputTokens, $inputIndex, $outputTokens, $currentNesting,
-        $currentInjector, $injectors;
+    protected $tokens;
+    
+    /**
+     * Current index in $tokens.
+     */
+    protected $t;
+    
+    /**
+     * Current nesting of elements.
+     */
+    protected $stack;
+    
+    /**
+     * Injectors active in this stream processing.
+     */
+    protected $injectors;
+    
+    /**
+     * Current instance of HTMLPurifier_Config.
+     */
+    protected $config;
+    
+    /**
+     * Current instance of HTMLPurifier_Context.
+     */
+    protected $context;
     
     public function execute($tokens, $config, $context) {
         
         $definition = $config->getHTMLDefinition();
         
         // local variables
-        $result = array();
         $generator = new HTMLPurifier_Generator($config, $context);
         $escape_invalid_tags = $config->get('Core', 'EscapeInvalidTags');
         $e = $context->get('ErrorCollector', true);
+        $t = false; // token index
+        $i = false; // injector index
+        $token      = false; // the current token
+        $reprocess  = false; // whether or not to reprocess the same token
+        $stack = array();
         
         // member variables
-        $this->currentNesting = array();
-        $this->inputIndex     = false;
-        $this->inputTokens    =& $tokens;
-        $this->outputTokens   =& $result;
+        $this->stack   =& $stack;
+        $this->t       =& $t;
+        $this->tokens  =& $tokens;
+        $this->config  = $config;
+        $this->context = $context;
         
         // context variables
-        $context->register('CurrentNesting', $this->currentNesting);
-        $context->register('InputIndex',     $this->inputIndex);
+        $context->register('CurrentNesting', $stack);
+        $context->register('InputIndex',     $t);
         $context->register('InputTokens',    $tokens);
+        $context->register('CurrentToken',   $token);
         
         // -- begin INJECTOR --
         
@@ -58,73 +88,119 @@ class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
             $this->injectors[] = $injector;
         }
         
-        // array index of the injector that resulted in an array
-        // substitution. This enables processTokens() to know which
-        // injectors are affected by the added tokens and which are
-        // not (namely, the ones after the current injector are not
-        // affected)
-        $this->currentInjector = false;
-        
         // give the injectors references to the definition and context
         // variables for performance reasons
-        foreach ($this->injectors as $i => $injector) {
+        foreach ($this->injectors as $ix => $injector) {
             $error = $injector->prepare($config, $context);
             if (!$error) continue;
-            array_splice($this->injectors, $i, 1); // rm the injector
+            array_splice($this->injectors, $ix, 1); // rm the injector
             trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING);
         }
         
-        // warning: most foreach loops follow the convention $i => $injector.
-        // Don't define these as loop-wide variables, please!
-        
         // -- end INJECTOR --
         
-        $token = false;
-        $context->register('CurrentToken', $token);
+        // a note on punting:
+        //      In order to reduce code duplication, whenever some code needs
+        //      to make HTML changes in order to make things "correct", the
+        //      new HTML gets sent through the purifier, regardless of its
+        //      status. This means that if we add a start token, because it
+        //      was totally necessary, we don't have to update nesting; we just
+        //      punt ($reprocess = true; continue;) and it does that for us.
         
         // isset is in loop because $tokens size changes during loop exec
-        for ($this->inputIndex = 0; isset($tokens[$this->inputIndex]); $this->inputIndex++) {
-            
-            // if all goes well, this token will be passed through unharmed
-            $token = $tokens[$this->inputIndex];
+        for (
+            $t = 0;
+            $t == 0 || isset($tokens[$t - 1]);
+            // only increment if we don't need to reprocess
+            $reprocess ? $reprocess = false : $t++
+        ) {
             
-            //printTokens($tokens, $this->inputIndex);
+            // check for a rewind
+            if (is_int($i) && $i >= 0) {
+                // possibility: disable rewinding if the current token has a
+                // rewind set on it already. This would offer protection from
+                // infinite loop, but might hinder some advanced rewinding.
+                $rewind_to = $this->injectors[$i]->getRewind();
+                if (is_int($rewind_to) && $rewind_to < $t) {
+                    if ($rewind_to < 0) $rewind_to = 0;
+                    while ($t > $rewind_to) {
+                        $t--;
+                        $prev = $tokens[$t];
+                        // indicate that other injectors should not process this token,
+                        // but we need to reprocess it
+                        unset($prev->skip[$i]);
+                        $prev->rewind = $i;
+                        if ($prev instanceof HTMLPurifier_Token_Start) array_pop($this->stack);
+                        elseif ($prev instanceof HTMLPurifier_Token_End) $this->stack[] = $prev->start;
+                    }
+                }
+                $i = false;
+            }
             
-            foreach ($this->injectors as $injector) {
-                if ($injector->skip > 0) $injector->skip--;
+            // handle case of document end
+            if (!isset($tokens[$t])) {
+                // kill processing if stack is empty
+                if (empty($this->stack)) break;
+                
+                // peek
+                $top_nesting = array_pop($this->stack);
+                $this->stack[] = $top_nesting;
+                
+                // send error
+                if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) {
+                    $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting);
+                }
+                
+                // append, don't splice, since this is the end
+                $tokens[] = new HTMLPurifier_Token_End($top_nesting->name);
+                
+                // punt!
+                $reprocess = true;
+                continue;
             }
             
+            // if all goes well, this token will be passed through unharmed
+            $token = $tokens[$t];
+            
+            //echo '<hr>';
+            //printTokens($tokens, $t);
+            //var_dump($this->stack);
+            
             // quick-check: if it's not a tag, no need to process
-            if (empty( $token->is_tag )) {
+            if (empty($token->is_tag)) {
                 if ($token instanceof HTMLPurifier_Token_Text) {
-                     // injector handler code; duplicated for performance reasons
-                     foreach ($this->injectors as $i => $injector) {
-                         if (!$injector->skip) $injector->handleText($token);
-                         if (is_array($token)) {
-                             $this->currentInjector = $i;
-                             break;
-                         }
-                     }
+                    foreach ($this->injectors as $i => $injector) {
+                        if (isset($token->skip[$i])) continue;
+                        if ($token->rewind !== null && $token->rewind !== $i) continue;
+                        $injector->handleText($token);
+                        $this->processToken($token, $i);
+                        $reprocess = true;
+                        break;
+                    }
                 }
-                $this->processToken($token, $config, $context);
+                // another possibility is a comment
                 continue;
             }
             
-            $info = $definition->info[$token->name]->child;
+            if (isset($definition->info[$token->name])) {
+                $type = $definition->info[$token->name]->child->type;
+            } else {
+                $type = false; // Type is unknown, treat accordingly
+            }
             
             // quick tag checks: anything that's *not* an end tag
             $ok = false;
-            if ($info->type === 'empty' && $token instanceof HTMLPurifier_Token_Start) {
-                // test if it claims to be a start tag but is empty
+            if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) {
+                // claims to be a start tag but is empty
                 $token = new HTMLPurifier_Token_Empty($token->name, $token->attr);
                 $ok = true;
-            } elseif ($info->type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) {
+            } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) {
                 // claims to be empty but really is a start tag
-                $token = array(
-                    new HTMLPurifier_Token_Start($token->name, $token->attr),
-                    new HTMLPurifier_Token_End($token->name)
-                );
-                $ok = true;
+                $this->swap(new HTMLPurifier_Token_End($token->name));
+                $this->insertBefore(new HTMLPurifier_Token_Start($token->name, $token->attr));
+                // punt (since we had to modify the input stream in a non-trivial way)
+                $reprocess = true;
+                continue;
             } elseif ($token instanceof HTMLPurifier_Token_Empty) {
                 // real empty token
                 $ok = true;
@@ -132,62 +208,88 @@ class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
                 // start tag
                 
                 // ...unless they also have to close their parent
-                if (!empty($this->currentNesting)) {
+                if (!empty($this->stack)) {
                     
-                    $parent = array_pop($this->currentNesting);
-                    $parent_info = $definition->info[$parent->name];
+                    $parent = array_pop($this->stack);
+                    $this->stack[] = $parent;
                     
-                    // this can be replaced with a more general algorithm:
-                    // if the token is not allowed by the parent, auto-close
-                    // the parent
-                    if (!isset($parent_info->child->elements[$token->name])) {
+                    if (isset($definition->info[$parent->name])) {
+                        $elements = $definition->info[$parent->name]->child->getNonAutoCloseElements($config);
+                        $autoclose = !isset($elements[$token->name]);
+                    } else {
+                        $autoclose = false;
+                    }
+                    
+                    if ($autoclose) {
                         if ($e) $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);
-                        // close the parent, then re-loop to reprocess token
-                        $result[] = new HTMLPurifier_Token_End($parent->name);
-                        $this->inputIndex--;
+                        // insert parent end tag before this tag
+                        $new_token = new HTMLPurifier_Token_End($parent->name);
+                        $new_token->start = $parent;
+                        $this->insertBefore($new_token);
+                        $reprocess = true;
                         continue;
                     }
                     
-                    $this->currentNesting[] = $parent; // undo the pop
                 }
                 $ok = true;
             }
             
-            // injector handler code; duplicated for performance reasons
             if ($ok) {
                 foreach ($this->injectors as $i => $injector) {
-                    if (!$injector->skip) $injector->handleElement($token);
-                    if (is_array($token)) {
-                        $this->currentInjector = $i;
-                        break;
+                    if (isset($token->skip[$i])) continue;
+                    if ($token->rewind !== null && $token->rewind !== $i) continue;
+                    $injector->handleElement($token);
+                    $this->processToken($token, $i);
+                    $reprocess = true;
+                    break;
+                }
+                if (!$reprocess) {
+                    // ah, nothing interesting happened; do normal processing
+                    $this->swap($token);
+                    if ($token instanceof HTMLPurifier_Token_Start) {
+                        $this->stack[] = $token;
+                    } elseif ($token instanceof HTMLPurifier_Token_End) {
+                        throw new HTMLPurifier_Exception('Improper handling of end tag in start code; possible error in MakeWellFormed');
                     }
                 }
-                $this->processToken($token, $config, $context);
                 continue;
             }
             
             // sanity check: we should be dealing with a closing tag
-            if (!$token instanceof HTMLPurifier_Token_End) continue;
+            if (!$token instanceof HTMLPurifier_Token_End) {
+                throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier');
+            }
             
             // make sure that we have something open
-            if (empty($this->currentNesting)) {
+            if (empty($this->stack)) {
                 if ($escape_invalid_tags) {
                     if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text');
-                    $result[] = new HTMLPurifier_Token_Text(
+                    $this->swap(new HTMLPurifier_Token_Text(
                         $generator->generateFromToken($token)
-                    );
-                } elseif ($e) {
-                    $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed');
+                    ));
+                } else {
+                    $this->remove();
+                    if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed');
                 }
+                $reprocess = true;
                 continue;
             }
             
-            // first, check for the simplest case: everything closes neatly
-            $current_parent = array_pop($this->currentNesting);
+            // first, check for the simplest case: everything closes neatly.
+            // Eventually, everything passes through here; if there are problems
+            // we modify the input stream accordingly and then punt, so that
+            // the tokens get processed again.
+            $current_parent = array_pop($this->stack);
             if ($current_parent->name == $token->name) {
-                $result[] = $token;
+                $token->start = $current_parent;
                 foreach ($this->injectors as $i => $injector) {
-                    $injector->notifyEnd($token);
+                    if (isset($token->skip[$i])) continue;
+                    if ($token->rewind !== null && $token->rewind !== $i) continue;
+                    $injector->handleEnd($token);
+                    $this->processToken($token, $i);
+                    $this->stack[] = $current_parent;
+                    $reprocess = true;
+                    break;
                 }
                 continue;
             }
@@ -195,47 +297,56 @@ class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
             // okay, so we're trying to close the wrong tag
             
             // undo the pop previous pop
-            $this->currentNesting[] = $current_parent;
+            $this->stack[] = $current_parent;
             
             // scroll back the entire nest, trying to find our tag.
             // (feature could be to specify how far you'd like to go)
-            $size = count($this->currentNesting);
+            $size = count($this->stack);
             // -2 because -1 is the last element, but we already checked that
             $skipped_tags = false;
-            for ($i = $size - 2; $i >= 0; $i--) {
-                if ($this->currentNesting[$i]->name == $token->name) {
-                    // current nesting is modified
-                    $skipped_tags = array_splice($this->currentNesting, $i);
+            for ($j = $size - 2; $j >= 0; $j--) {
+                if ($this->stack[$j]->name == $token->name) {
+                    $skipped_tags = array_slice($this->stack, $j);
                     break;
                 }
             }
             
-            // we still didn't find the tag, so remove
+            // we didn't find the tag, so remove
             if ($skipped_tags === false) {
                 if ($escape_invalid_tags) {
-                    $result[] = new HTMLPurifier_Token_Text(
+                    $this->swap(new HTMLPurifier_Token_Text(
                         $generator->generateFromToken($token)
-                    );
+                    ));
                     if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text');
-                } elseif ($e) {
-                    $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed');
+                } else {
+                    $this->remove();
+                    if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed');
                 }
+                $reprocess = true;
                 continue;
             }
             
-            // okay, we found it, close all the skipped tags
-            // note that skipped tags contains the element we need closed
-            for ($i = count($skipped_tags) - 1; $i >= 0; $i--) {
-                // please don't redefine $i!
-                if ($i && $e && !isset($skipped_tags[$i]->armor['MakeWellFormed_TagClosedError'])) {
-                    $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$i]);
-                }
-                $result[] = $new_token = new HTMLPurifier_Token_End($skipped_tags[$i]->name);
-                foreach ($this->injectors as $injector) {
-                    $injector->notifyEnd($new_token);
+            // do errors, in REVERSE $j order: a,b,c with </a></b></c>
+            $c = count($skipped_tags);
+            if ($e) {
+                for ($j = $c - 1; $j > 0; $j--) {
+                    // notice we exclude $j == 0, i.e. the current ending tag, from
+                    // the errors...
+                    if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) {
+                        $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]);
+                    }
                 }
             }
             
+            // insert tags, in FORWARD $j order: c,b,a with </a></b></c>
+            for ($j = 1; $j < $c; $j++) {
+                // ...as well as from the insertions
+                $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name);
+                $new_token->start = $skipped_tags[$j];
+                $this->insertBefore($new_token);
+            }
+            $reprocess = true;
+            continue;
         }
         
         $context->destroy('CurrentNesting');
@@ -243,59 +354,77 @@ class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
         $context->destroy('InputIndex');
         $context->destroy('CurrentToken');
         
-        // we're at the end now, fix all still unclosed tags (this is
-        // duplicated from the end of the loop with some slight modifications)
-        // not using $skipped_tags since it would invariably be all of them
-        if (!empty($this->currentNesting)) {
-            for ($i = count($this->currentNesting) - 1; $i >= 0; $i--) {
-                // please don't redefine $i!
-                if ($e && !isset($this->currentNesting[$i]->armor['MakeWellFormed_TagClosedError'])) {
-                    $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $this->currentNesting[$i]);
-                }
-                $result[] = $new_token = new HTMLPurifier_Token_End($this->currentNesting[$i]->name);
-                foreach ($this->injectors as $injector) {
-                    $injector->notifyEnd($new_token);
-                }
+        unset($this->injectors, $this->stack, $this->tokens, $this->t);
+        return $tokens;
+    }
+    
+    /**
+     * Processes arbitrary token values for complicated substitution patterns.
+     * In general:
+     * 
+     * If $token is an array, it is a list of tokens to substitute for the
+     * current token. These tokens then get individually processed. If there
+     * is a leading integer in the list, that integer determines how many
+     * tokens from the stream should be removed.
+     * 
+     * If $token is a regular token, it is swapped with the current token.
+     * 
+     * If $token is false, the current token is deleted.
+     * 
+     * If $token is an integer, that number of tokens (with the first token
+     * being the current one) will be deleted.
+     * 
+     * @param $token Token substitution value
+     * @param $injector Injector that performed the substitution; default is if
+     *        this is not an injector related operation.
+     */
+    protected function processToken($token, $injector = -1) {
+        
+        // normalize forms of token
+        if (is_object($token)) $token = array(1, $token);
+        if (is_int($token))    $token = array($token);
+        if ($token === false)  $token = array(1);
+        if (!is_array($token)) throw new HTMLPurifier_Exception('Invalid token type from injector');
+        if (!is_int($token[0])) array_unshift($token, 1);
+        if ($token[0] === 0) throw new HTMLPurifier_Exception('Deleting zero tokens is not valid');
+        
+        // $token is now an array with the following form:
+        // array(number nodes to delete, new node 1, new node 2, ...)
+        
+        $delete = array_shift($token);
+        $old = array_splice($this->tokens, $this->t, $delete, $token);
+        
+        if ($injector > -1) {
+            // determine appropriate skips
+            $oldskip = isset($old[0]) ? $old[0]->skip : array();
+            foreach ($token as $object) {
+                $object->skip = $oldskip;
+                $object->skip[$injector] = true;
             }
         }
         
-        unset($this->outputTokens, $this->injectors, $this->currentInjector,
-          $this->currentNesting, $this->inputTokens, $this->inputIndex);
-        
-        return $result;
     }
     
-    function processToken($token, $config, $context) {
-        if (is_array($token)) {
-            // the original token was overloaded by an injector, time
-            // to some fancy acrobatics
-            
-            // $this->inputIndex is decremented so that the entire set gets
-            // re-processed
-            array_splice($this->inputTokens, $this->inputIndex--, 1, $token);
-            
-            // adjust the injector skips based on the array substitution
-            if ($this->injectors) {
-                $offset = count($token);
-                for ($i = 0; $i <= $this->currentInjector; $i++) {
-                    // because of the skip back, we need to add one more
-                    // for uninitialized injectors. I'm not exactly
-                    // sure why this is the case, but I think it has to
-                    // do with the fact that we're decrementing skips
-                    // before re-checking text
-                    if (!$this->injectors[$i]->skip) $this->injectors[$i]->skip++;
-                    $this->injectors[$i]->skip += $offset;
-                }
-            }
-        } elseif ($token) {
-            // regular case
-            $this->outputTokens[] = $token;
-            if ($token instanceof HTMLPurifier_Token_Start) {
-                $this->currentNesting[] = $token;
-            } elseif ($token instanceof HTMLPurifier_Token_End) {
-                array_pop($this->currentNesting); // not actually used
-            }
-        }
+    /**
+     * Inserts a token before the current token. Cursor now points to this token
+     */
+    private function insertBefore($token) {
+        array_splice($this->tokens, $this->t, 0, array($token));
+    }
+
+    /**
+     * Removes current token. Cursor now points to new token occupying previously
+     * occupied space.
+     */
+    private function remove() {
+        array_splice($this->tokens, $this->t, 1);
+    }
+    
+    /**
+     * Swap current token with new token. Cursor points to new token (no change).
+     */
+    private function swap($token) {
+        $this->tokens[$this->t] = $token;
     }
     
 }
index 165308dd0cfaee537db8c2edb40db9f97a1fef17..6a6929904191b251fbcd1c744bbcc4c33f28ba4c 100644 (file)
@@ -19,6 +19,9 @@ class HTMLPurifier_Strategy_RemoveForeignElements extends HTMLPurifier_Strategy
         $escape_invalid_tags = $config->get('Core', 'EscapeInvalidTags');
         $remove_invalid_img  = $config->get('Core', 'RemoveInvalidImg');
         
+        // currently only used to determine if comments should be kept
+        $trusted = $config->get('HTML', 'Trusted');
+        
         $remove_script_contents = $config->get('Core', 'RemoveScriptContents');
         $hidden_elements     = $config->get('Core', 'HiddenElements');
         
@@ -125,6 +128,23 @@ class HTMLPurifier_Strategy_RemoveForeignElements extends HTMLPurifier_Strategy
                 if ($textify_comments !== false) {
                     $data = $token->data;
                     $token = new HTMLPurifier_Token_Text($data);
+                } elseif ($trusted) {
+                    // keep, but perform comment cleaning
+                    if ($e) {
+                        // perform check whether or not there's a trailing hyphen
+                        if (substr($token->data, -1) == '-') {
+                            $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Trailing hyphen in comment removed');
+                        }
+                    }
+                    $token->data = rtrim($token->data, '-');
+                    $found_double_hyphen = false;
+                    while (strpos($token->data, '--') !== false) {
+                        if ($e && !$found_double_hyphen) {
+                            $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Hyphens in comment collapsed');
+                        }
+                        $found_double_hyphen = true; // prevent double-erroring
+                        $token->data = str_replace('--', '-', $token->data);
+                    }
                 } else {
                     // strip comments
                     if ($e) $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed');
index e96897d1366abd0ec56435612bf36be1998afb74..e98271df485ab9d61bcab6a18dbf00fc41ab4522 100644 (file)
@@ -78,6 +78,7 @@ class HTMLPurifier_StringHashParser
             if (strncmp('--', $line, 2) === 0) {
                 // Multiline declaration
                 $state = trim($line, '- ');
+                if (!isset($ret[$state])) $ret[$state] = '';
                 continue;
             } elseif (!$state) {
                 $single = true;
@@ -94,7 +95,6 @@ class HTMLPurifier_StringHashParser
                 $single = false;
                 $state  = false;
             } else {
-                if (!isset($ret[$state])) $ret[$state] = '';
                 $ret[$state] .= "$line\n";
             }
         } while (!feof($fh));
index 8803307bda9eef68435cdcd8fc6ab36476d05706..942a61d129f69d75d8f156be93a93b8c30962641 100644 (file)
@@ -5,6 +5,7 @@
  */
 class HTMLPurifier_Token {
     public $line; /**< Line number node was on in source document. Null if unknown. */
+    public $col;  /**< Column of line node was on in source document. Null if unknown. */
     
     /**
      * Lookup array of processing that this token is exempt from.
@@ -13,17 +14,41 @@ class HTMLPurifier_Token {
      */
     public $armor = array();
     
+    /**
+     * Used during MakeWellFormed.
+     */
+    public $skip;
+    public $rewind;
+    
     public function __get($n) {
       if ($n === 'type') {
         trigger_error('Deprecated type property called; use instanceof', E_USER_NOTICE);
         switch (get_class($this)) {
-          case 'HTMLPurifier_Token_Start': return 'start';
-          case 'HTMLPurifier_Token_Empty': return 'empty';
-          case 'HTMLPurifier_Token_End': return 'end';
-          case 'HTMLPurifier_Token_Text': return 'text';
-          case 'HTMLPurifier_Token_Comment': return 'comment';
+          case 'HTMLPurifier_Token_Start':      return 'start';
+          case 'HTMLPurifier_Token_Empty':      return 'empty';
+          case 'HTMLPurifier_Token_End':        return 'end';
+          case 'HTMLPurifier_Token_Text':       return 'text';
+          case 'HTMLPurifier_Token_Comment':    return 'comment';
           default: return null;
         }
       }
     }
+    
+    /**
+     * Sets the position of the token in the source document.
+     */
+    public function position($l = null, $c = null) {
+        $this->line = $l;
+        $this->col  = $c;
+    }
+    
+    /**
+     * Convenience function for DirectLex settings line/col position.
+     */
+    public function rawPosition($l, $c) {
+        if ($c === -1) $l++;
+        $this->line = $l;
+        $this->col  = $c;
+    }
+    
 }
index 1571a40dc19976f906f99ca5ec75018bd12e5b94..6717478095702708e9faf045cc536a9ebcee92c2 100644 (file)
@@ -11,9 +11,10 @@ class HTMLPurifier_Token_Comment extends HTMLPurifier_Token
      * 
      * @param $data String comment data.
      */
-    public function __construct($data, $line = null) {
+    public function __construct($data, $line = null, $col = null) {
         $this->data = $data;
         $this->line = $line;
+        $this->col  = $col;
     }
 }
 
index fbf45e81cd6410a820c1fd2dfbd24d8e1609b188..13cba031d9f19f72ea293bc12b6f6ce50240064f 100644 (file)
@@ -9,5 +9,9 @@
  */
 class HTMLPurifier_Token_End extends HTMLPurifier_Token_Tag
 {
-    
+    /**
+     * Token that started this node. Added by MakeWellFormed. Please
+     * do not edit this!
+     */
+    public $start;
 }
index 43748f7008c3b1c072e67171777611574ad431f0..795c40f6653b184dfb9de3d8d61756c537a69ede 100644 (file)
@@ -33,7 +33,7 @@ class HTMLPurifier_Token_Tag extends HTMLPurifier_Token
      * @param $name String name.
      * @param $attr Associative array of attributes.
      */
-    public function __construct($name, $attr = array(), $line = null) {
+    public function __construct($name, $attr = array(), $line = null, $col = null) {
         $this->name = ctype_lower($name) ? $name : strtolower($name);
         foreach ($attr as $key => $value) {
             // normalization only necessary when key is not lowercase
@@ -49,5 +49,6 @@ class HTMLPurifier_Token_Tag extends HTMLPurifier_Token
         }
         $this->attr = $attr;
         $this->line = $line;
+        $this->col  = $col;
     }
 }
index 3942f8a0ae806416b34b077909674023ed75d6b1..02b53e5c843e6b561ca3a26599b29f424f78d555 100644 (file)
@@ -21,10 +21,11 @@ class HTMLPurifier_Token_Text extends HTMLPurifier_Token
      * 
      * @param $data String parsed character data.
      */
-    public function __construct($data, $line = null) {
+    public function __construct($data, $line = null, $col = null) {
         $this->data = $data;
         $this->is_whitespace = ctype_space($data);
         $this->line = $line;
+        $this->col  = $col;
     }
     
 }
index d48bce06bdf82fa56fbb819abaf2d84ad712d4a1..960e2b9b5a46d13b61c9015a99e4a04892087d54 100644 (file)
@@ -5,7 +5,7 @@ class HTMLPurifier_URIFilter_DisableExternal extends HTMLPurifier_URIFilter
     public $name = 'DisableExternal';
     protected $ourHostParts = false;
     public function prepare($config) {
-        $our_host = $config->get('URI', 'Host');
+        $our_host = $config->getDefinition('URI')->host;
         if ($our_host !== null) $this->ourHostParts = array_reverse(explode('.', $our_host));
     }
     public function filter(&$uri, $config, $context) {
index 289db51ad3a1614e087ac25a5c5e823c08ee6b99..89998267442baafb4c23ad848bb739962002ae54 100644 (file)
@@ -51,12 +51,18 @@ class HTMLPurifier_URIFilter_MakeAbsolute extends HTMLPurifier_URIFilter
         }
         if ($uri->path === '') {
             $uri->path = $this->base->path;
-        }elseif ($uri->path[0] !== '/') {
+        } elseif ($uri->path[0] !== '/') {
             // relative path, needs more complicated processing
             $stack = explode('/', $uri->path);
             $new_stack = array_merge($this->basePathStack, $stack);
+            if ($new_stack[0] !== '' && !is_null($this->base->host)) {
+                array_unshift($new_stack, '');
+            }
             $new_stack = $this->_collapseStack($new_stack);
             $uri->path = implode('/', $new_stack);
+        } else {
+            // absolute path, but still we should collapse
+            $uri->path = implode('/', $this->_collapseStack(explode('/', $uri->path)));
         }
         // re-combine
         $uri->scheme = $this->base->scheme;
@@ -71,6 +77,7 @@ class HTMLPurifier_URIFilter_MakeAbsolute extends HTMLPurifier_URIFilter
      */
     private function _collapseStack($stack) {
         $result = array();
+        $is_folder = false;
         for ($i = 0; isset($stack[$i]); $i++) {
             $is_folder = false;
             // absorb an internally duplicated slash
index ad6578e669b632d35edec56e0f40fd8c54507bd0..d82d2b920351b302cb47fadacad84402be19fe4a 100644 (file)
@@ -28,7 +28,11 @@ class HTMLPurifier_URIFilter_Munge extends HTMLPurifier_URIFilter
         $this->replace = array_map('rawurlencode', $this->replace);
         
         $new_uri = strtr($this->target, $this->replace);
-        $uri = $this->parser->parse($new_uri); // overwrite
+        $new_uri = $this->parser->parse($new_uri);
+        // don't redirect if the target host is the same as the 
+        // starting host
+        if ($uri->host === $new_uri->host) return true;
+        $uri = $new_uri; // overwrite
         return true;
     }
     
index 6e3046102baf57b92392c96bf3e0d8b31f740f99..d69a132b26a40c94e787770bf07556300bfc5c3f 100644 (file)
@@ -234,6 +234,18 @@ class HTMLPurifier_UnitConverter
      * Scales a float to $scale digits right of decimal point, like BCMath.
      */
     private function scale($r, $scale) {
+        if ($scale < 0) {
+            // The f sprintf type doesn't support negative numbers, so we
+            // need to cludge things manually. First get the string.
+            $r = sprintf('%.0f', (float) $r);
+            // Due to floating point precision loss, $r will more than likely
+            // look something like 4652999999999.9234. We grab one more digit
+            // than we need to precise from $r and then use that to round
+            // appropriately.
+            $precise = (string) round(substr($r, 0, strlen($r) + $scale), -1);
+            // Now we return it, truncating the zero that was rounded off.
+            return substr($precise, 0, -1) . str_repeat('0', -$scale + 1);
+        }
         return sprintf('%.' . $scale . 'f', (float) $r);
     }
     
index 99e67dbc4f0d29a34c076630008d35b35750085c..c9708ae0cd8fcaf81acce8900dbea41cab840468 100644 (file)
@@ -1,4 +1,4 @@
-Description of HTML Purifier v3.1.1 library import into Moodle
+Description of HTML Purifier v3.2.0 library import into Moodle
 
 Changes:
  * HMLTModule/Text.php - added  <nolink>, <tex>, <lang> and <algebra> tags