]> git.mjollnir.org Git - moodle.git/commitdiff
MDL-11415 imported htmlpurifier 2.1.2
authorskodak <skodak>
Sun, 23 Sep 2007 15:47:26 +0000 (15:47 +0000)
committerskodak <skodak>
Sun, 23 Sep 2007 15:47:26 +0000 (15:47 +0000)
17 files changed:
lib/htmlpurifier/HTMLPurifier.php
lib/htmlpurifier/HTMLPurifier/AttrDef/URI.php
lib/htmlpurifier/HTMLPurifier/AttrDef/URI/Email.php
lib/htmlpurifier/HTMLPurifier/AttrTypes.php
lib/htmlpurifier/HTMLPurifier/CSSDefinition.php
lib/htmlpurifier/HTMLPurifier/Config.php
lib/htmlpurifier/HTMLPurifier/HTMLDefinition.php
lib/htmlpurifier/HTMLPurifier/HTMLModule/Object.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/HTMLModule/Text.php
lib/htmlpurifier/HTMLPurifier/HTMLModuleManager.php
lib/htmlpurifier/HTMLPurifier/Lexer.php
lib/htmlpurifier/HTMLPurifier/Lexer/DOMLex.php
lib/htmlpurifier/HTMLPurifier/Lexer/DirectLex.php
lib/htmlpurifier/HTMLPurifier/Lexer/PH5P.php [new file with mode: 0644]
lib/htmlpurifier/HTMLPurifier/Printer/ConfigForm.php
lib/htmlpurifier/HTMLPurifier/Printer/HTMLDefinition.php
lib/htmlpurifier/HTMLPurifier/URISchemeRegistry.php

index fa42e3bb7843a030a1d8508103ad600cc294c206..677c1e39952ed7649b35e07c340bbb139ef08e78 100644 (file)
@@ -22,7 +22,7 @@
  */
 
 /*
-    HTML Purifier 2.1.1 - Standards Compliant HTML Filtering
+    HTML Purifier 2.1.2 - Standards Compliant HTML Filtering
     Copyright (C) 2006 Edward Z. Yang
 
     This library is free software; you can redistribute it and/or
@@ -77,7 +77,7 @@ This directive has been available since 2.0.0.
 class HTMLPurifier
 {
     
-    var $version = '2.1.1';
+    var $version = '2.1.2';
     
     var $config;
     var $filters;
index dcf9849c45fd3deb90e9233aba2512c210a385c9..365748c037dfb0c4ff2cde9ceb29ae2db0538f89 100644 (file)
@@ -6,6 +6,7 @@ require_once 'HTMLPurifier/URIScheme.php';
 require_once 'HTMLPurifier/URISchemeRegistry.php';
 require_once 'HTMLPurifier/AttrDef/URI/Host.php';
 require_once 'HTMLPurifier/PercentEncoder.php';
+require_once 'HTMLPurifier/AttrDef/URI/Email.php';
 
 // special case filtering directives 
 
index 5a7085db7add01a9987fb2a9868356810165e674..aaec099a6e4e097ed91d00bddbbd1b3f843daebf 100644 (file)
@@ -1,6 +1,7 @@
 <?php
 
 require_once 'HTMLPurifier/AttrDef.php';
+require_once 'HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php';
 
 class HTMLPurifier_AttrDef_URI_Email extends HTMLPurifier_AttrDef
 {
index 4cb70be7ad920fe894f08532cd1b033a54a1c151..93abb0d02b75c45edfebf126517d9501cd7553b1 100644 (file)
@@ -44,6 +44,9 @@ class HTMLPurifier_AttrTypes
         $this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang();
         $this->info['Color']    = new HTMLPurifier_AttrDef_HTML_Color();
         
+        // unimplemented aliases
+        $this->info['ContentType'] = new HTMLPurifier_AttrDef_Text();
+        
         // number is really a positive integer (one or more digits)
         // FIXME: ^^ not always, see start and value of list items
         $this->info['Number']   = new HTMLPurifier_AttrDef_Integer(false, false, true);
index 8de2aa7b7093797619d47e4179ca9f7d35afb3ce..2acf7cf83b2f0e0af4854dea5b84e95b9114df49 100644 (file)
@@ -204,7 +204,7 @@ class HTMLPurifier_CSSDefinition extends HTMLPurifier_Definition
         $this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config);
         
         $this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum(array(
-            'collapse', 'seperate'));
+            'collapse', 'separate'));
         
         $this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum(array(
             'top', 'bottom'));
@@ -219,6 +219,8 @@ class HTMLPurifier_CSSDefinition extends HTMLPurifier_Definition
             new HTMLPurifier_AttrDef_CSS_Percentage()
         ));
         
+        $this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2);
+        
         // partial support
         $this->info['white-space'] = new HTMLPurifier_AttrDef_Enum(array('nowrap'));
         
index b9b77178e0913e0245708c3c44138448795f21b0..e04a4b0cc51ec438f37d53fba6f5756d5665b390 100644 (file)
@@ -42,7 +42,7 @@ class HTMLPurifier_Config
     /**
      * HTML Purifier's version
      */
-    var $version = '2.1.1';
+    var $version = '2.1.2';
     
     /**
      * Two-level associative array of configuration directives
index aaeb8bae38547cd1b1fc2bf904763697171b8d78..fe6bd1418776b4794ff60b427144355286686936 100644 (file)
@@ -330,7 +330,7 @@ class HTMLPurifier_HTMLDefinition extends HTMLPurifier_Definition
         if (isset($this->info_content_sets['Block'][$block_wrapper])) {
             $this->info_block_wrapper = $block_wrapper;
         } else {
-            trigger_error('Cannot use non-block element as block wrapper.',
+            trigger_error('Cannot use non-block element as block wrapper',
                 E_USER_ERROR);
         }
         
@@ -340,7 +340,7 @@ class HTMLPurifier_HTMLDefinition extends HTMLPurifier_Definition
             $this->info_parent = $parent;
             $this->info_parent_def = $def;
         } else {
-            trigger_error('Cannot use unrecognized element as parent.',
+            trigger_error('Cannot use unrecognized element as parent',
                 E_USER_ERROR);
             $this->info_parent_def = $this->manager->getElement($this->info_parent, true);
         }
diff --git a/lib/htmlpurifier/HTMLPurifier/HTMLModule/Object.php b/lib/htmlpurifier/HTMLPurifier/HTMLModule/Object.php
new file mode 100644 (file)
index 0000000..3373477
--- /dev/null
@@ -0,0 +1,47 @@
+<?php\r
+\r
+require_once 'HTMLPurifier/HTMLModule.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
+    var $name = 'Object';\r
+    \r
+    function HTMLPurifier_HTMLModule_Object() {\r
+        \r
+        $this->addElement('object', false, '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, 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
index 24a80dbc30a859d23d154af77090297ac842b388..ed5ef64a0354c3e1181274b5fec4af17d2ce40ad 100644 (file)
@@ -47,7 +47,7 @@ class HTMLPurifier_HTMLModule_Text extends HTMLPurifier_HTMLModule
         $this->addElement('algebra', true, 'Inline', 'Flow');
         $this->addElement('lang',    true, 'Inline', 'Flow', 'I18N');
         // Moodle specific elements - end
-
+        
         // Block Phrasal --------------------------------------------------
         $this->addElement('address',     true, 'Block', 'Inline', 'Common');
         $this->addElement('blockquote',  true, 'Block', 'Optional: Heading | Block | List', 'Common', array('cite' => 'URI') );
index d4f10d0c7c79c877689a1ed69015007a80b9ffc4..74a233ff2f9ed3181ba11b38556de2733ee3b84f 100644 (file)
@@ -29,6 +29,7 @@ require_once 'HTMLPurifier/HTMLModule/Scripting.php';
 require_once 'HTMLPurifier/HTMLModule/XMLCommonAttributes.php';
 require_once 'HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php';
 require_once 'HTMLPurifier/HTMLModule/Ruby.php';
+require_once 'HTMLPurifier/HTMLModule/Object.php';
 
 // tidy modules
 require_once 'HTMLPurifier/HTMLModule/Tidy.php';
@@ -172,7 +173,7 @@ class HTMLPurifier_HTMLModuleManager
         $common = array(
             'CommonAttributes', 'Text', 'Hypertext', 'List',
             'Presentation', 'Edit', 'Bdo', 'Tables', 'Image',
-            'StyleAttribute', 'Scripting'
+            'StyleAttribute', 'Scripting', 'Object'
         );
         $transitional = array('Legacy', 'Target');
         $xml = array('XMLCommonAttributes');
index b1bd1ed0e1724f839be5c5a946302ae2fa363767..78abebd07bfbb2313cab632572c588ff4e3d6b97 100644 (file)
@@ -189,6 +189,9 @@ class HTMLPurifier_Lexer
                 return new HTMLPurifier_Lexer_DOMLex();
             case 'DirectLex':
                 return new HTMLPurifier_Lexer_DirectLex();
+            case 'PH5P':
+                // experimental Lexer that must be manually included
+                return new HTMLPurifier_Lexer_PH5P();
             default:
                 trigger_error("Cannot instantiate unrecognized Lexer type " . htmlspecialchars($lexer), E_USER_ERROR);
         }
index 890c8a7efdcc24850bb1e5111afac928cc3cd092..56bd4a4828198aa82e43c7d3d6ed624370261e00 100644 (file)
@@ -53,14 +53,7 @@ class HTMLPurifier_Lexer_DOMLex extends HTMLPurifier_Lexer
         }
         
         // preprocess html, essential for UTF-8
-        $html =
-            '<!DOCTYPE html '.
-                'PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
-                '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.
-            '<html><head>'.
-            '<meta http-equiv="Content-Type" content="text/html;'.
-                ' charset=utf-8" />'.
-            '</head><body><div>'.$html.'</div></body></html>';
+        $html = $this->wrapHTML($html, $config, $context);
         
         $doc = new DOMDocument();
         $doc->encoding = 'UTF-8'; // theoretically, the above has this covered
@@ -177,5 +170,25 @@ class HTMLPurifier_Lexer_DOMLex extends HTMLPurifier_Lexer
         return '<!--' . str_replace('&', '&amp;', $matches[1]) . $matches[2];
     }
     
+    /**
+     * Wraps an HTML fragment in the necessary HTML
+     */
+    function wrapHTML($html, $config, &$context) {
+        $def = $config->getDefinition('HTML');
+        $ret = '';
+        
+        if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {
+            $ret .= '<!DOCTYPE html ';
+            if (!empty($def->doctype->dtdPublic)) $ret .= 'PUBLIC "' . $def->doctype->dtdPublic . '" ';
+            if (!empty($def->doctype->dtdSystem)) $ret .= '"' . $def->doctype->dtdSystem . '" ';
+            $ret .= '>';
+        }
+        
+        $ret .= '<html><head>';
+        $ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
+        $ret .= '</head><body><div>'.$html.'</div></body></html>';
+        return $ret;
+    }
+    
 }
 
index 759c8f50d270342129674f236f7901bf4140e8f8..b3639916d1debae688e85932766269561c6e1d53 100644 (file)
@@ -237,7 +237,7 @@ class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
                 // trailing slash. Remember, we could have a tag like <br>, so
                 // any later token processing scripts must convert improperly
                 // classified EmptyTags from StartTags.
-                $is_self_closing= (strpos($segment,'/') === $strlen_segment-1);
+                $is_self_closing= (strrpos($segment,'/') === $strlen_segment-1);
                 if ($is_self_closing) {
                     $strlen_segment--;
                     $segment = substr($segment, 0, $strlen_segment);
diff --git a/lib/htmlpurifier/HTMLPurifier/Lexer/PH5P.php b/lib/htmlpurifier/HTMLPurifier/Lexer/PH5P.php
new file mode 100644 (file)
index 0000000..5720c33
--- /dev/null
@@ -0,0 +1,3886 @@
+<?php\r
+\r
+require_once 'HTMLPurifier/Lexer/DOMLex.php';\r
+\r
+/**\r
+ * Experimental HTML5-based parser using Jeroen van der Meer's PH5P library.\r
+ * Requires PHP5, and occupies space in the HTML5 pseudo-namespace (may\r
+ * cause conflicts, sorry).\r
+ */\r
+\r
+class HTMLPurifier_Lexer_PH5P extends HTMLPurifier_Lexer_DOMLex {\r
+    \r
+    public function tokenizeHTML($html, $config, &$context) {\r
+        $html = $this->normalize($html, $config, $context);\r
+        $html = $this->wrapHTML( $html, $config, $context);\r
+        $parser = new HTML5($html);\r
+        $doc = $parser->save();\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
+// begin PHP5P source code here\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
+        $date = 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);\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) {\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(array $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($name) {\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
index 31da35f8acc24f0e3ccb27f4f65518bd36ac8829..21b8314bc5200040b4f6cba0e7e3e9a7dc4269e1 100644 (file)
@@ -25,7 +25,9 @@ class HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer
     
     /**
      * Whether or not to compress directive names, clipping them off
-     * after a certain amount of letters
+     * after a certain amount of letters. False to disable or integer letters
+     * before clipping.
+     * @protected
      */
     var $compress = false;
     
@@ -41,11 +43,13 @@ class HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer
         $this->docURL = $doc_url;
         $this->name   = $name;
         $this->compress = $compress;
+        // initialize sub-printers
         $this->fields['default']    = new HTMLPurifier_Printer_ConfigForm_default();
         $this->fields['bool']       = new HTMLPurifier_Printer_ConfigForm_bool();
     }
     
     /**
+     * Sets default column and row size for textareas in sub-printers
      * @param $cols Integer columns of textarea, null to use default
      * @param $rows Integer rows of textarea, null to use default
      */
@@ -55,15 +59,14 @@ class HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer
     }
     
     /**
-     * Retrieves styling, in case the directory it's in is not publically
-     * available
+     * Retrieves styling, in case it is not accessible by webserver
      */
     function getCSS() {
         return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.css');
     }
     
     /**
-     * Retrieves JavaScript, in case directory is not public
+     * Retrieves JavaScript, in case it is not accessible by webserver
      */
     function getJavaScript() {
         return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.js');
@@ -97,14 +100,14 @@ class HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer
             $ret .= $this->renderNamespace($ns, $directives);
         }
         if ($render_controls) {
-             $ret .= $this->start('tfoot');
+             $ret .= $this->start('tbody');
              $ret .= $this->start('tr');
                  $ret .= $this->start('td', array('colspan' => 2, 'class' => 'controls'));
-                     $ret .= $this->elementEmpty('input', array('type' => 'Submit', 'value' => 'Submit'));
+                     $ret .= $this->elementEmpty('input', array('type' => 'submit', 'value' => 'Submit'));
                      $ret .= '[<a href="?">Reset</a>]';
                  $ret .= $this->end('td');
              $ret .= $this->end('tr');
-             $ret .= $this->end('tfoot');
+             $ret .= $this->end('tbody');
         }
         $ret .= $this->end('table');
         return $ret;
index 52650c6308ee01d9d6c395acd63be5640adcb82b..4a0a90f1525c74460942794e23f1e9d5b1010539 100644 (file)
@@ -102,6 +102,7 @@ class HTMLPurifier_Printer_HTMLDefinition extends HTMLPurifier_Printer
             $ret .= $this->element('td', $this->listifyTagLookup($lookup));
             $ret .= $this->end('tr');
         }
+        $ret .= $this->end('table');
         return $ret;
     }
     
@@ -179,7 +180,8 @@ class HTMLPurifier_Printer_HTMLDefinition extends HTMLPurifier_Printer
                     $def->validateChildren(array(), $this->config, $context);
                 }
                 $elements = $def->elements;
-            } elseif ($def->type == 'chameleon') {
+            }
+            if ($def->type == 'chameleon') {
                 $attr['rowspan'] = 2;
             } elseif ($def->type == 'empty') {
                 $elements = array();
index 8cddb7f934c1e81c433d218d4f981f0fe2a1216b..6837fadaafcd8c516c4c252c2e39de21a7ff4d85 100644 (file)
@@ -1,5 +1,12 @@
 <?php
 
+require_once 'HTMLPurifier/URIScheme/http.php';
+require_once 'HTMLPurifier/URIScheme/https.php';
+require_once 'HTMLPurifier/URIScheme/mailto.php';
+require_once 'HTMLPurifier/URIScheme/ftp.php';
+require_once 'HTMLPurifier/URIScheme/nntp.php';
+require_once 'HTMLPurifier/URIScheme/news.php';
+
 HTMLPurifier_ConfigSchema::define(
     'URI', 'AllowedSchemes', array(
         'http'  => true, // "Hypertext Transfer Protocol", nuf' said
@@ -7,7 +14,6 @@ HTMLPurifier_ConfigSchema::define(
         // quite useful, but not necessary
         'mailto' => true,// Email
         'ftp'   => true, // "File Transfer Protocol"
-        'irc'   => true, // "Internet Relay Chat", usually needs another app
         // for Usenet, these two are similar, but distinct
         'nntp'  => true, // individual Netnews articles
         'news'  => true  // newsgroup or individual Netnews articles
@@ -54,12 +60,6 @@ class HTMLPurifier_URISchemeRegistry
      */
     var $schemes = array();
     
-    /**
-     * Directory where scheme objects can be found
-     * @private
-     */
-    var $_scheme_dir = null;
-    
     /**
      * Retrieves a scheme validator object
      * @param $scheme String scheme name like http or mailto
@@ -79,21 +79,16 @@ class HTMLPurifier_URISchemeRegistry
         }
         
         if (isset($this->schemes[$scheme])) return $this->schemes[$scheme];
-        if (empty($this->_dir)) $this->_dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier/URIScheme/';
-        
         if (!isset($allowed_schemes[$scheme])) return $null;
         
-        // this bit of reflection is not very efficient, and a bit
-        // hacky too
         $class = 'HTMLPurifier_URIScheme_' . $scheme;
-        if (!class_exists($class)) include_once $this->_dir . $scheme . '.php';
         if (!class_exists($class)) return $null;
         $this->schemes[$scheme] = new $class();
         return $this->schemes[$scheme];
     }
     
     /**
-     * Registers a custom scheme to the cache.
+     * Registers a custom scheme to the cache, bypassing reflection.
      * @param $scheme Scheme name
      * @param $scheme_obj HTMLPurifier_URIScheme object
      */