1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
|
<?php
namespace HTML5\Parser;
use HTML5\Elements;
/**
* Create an HTML5 DOM tree from events.
*
* This attempts to create a DOM from events emitted by a parser. This
* attempts (but does not guarantee) to up-convert older HTML documents
* to HTML5. It does this by applying HTML5's rules, but it will not
* change the architecture of the document itself.
*/
class DOMTreeBuilder implements EventHandler {
/**
* Defined in 8.2.5.
*/
const IM_INITIAL = 0;
const IM_BEFORE_HTML = 1;
const IM_BEFORE_HEAD = 2;
const IM_IN_HEAD = 3;
const IM_IN_HEAD_NOSCRIPT = 4;
const IM_AFTER_HEAD = 5;
const IM_IN_BODY = 6;
const IM_TEXT = 7;
const IM_IN_TABLE = 8;
const IM_IN_TABLE_TEXT = 9;
const IM_IN_CAPTION = 10;
const IM_IN_COLUMN_GROUP = 11;
const IM_IN_TABLE_BODY = 12;
const IM_IN_ROW = 13;
const IM_IN_CELL = 14;
const IM_IN_SELECT = 15;
const IM_IN_SELECT_IN_TABLE = 16;
const IM_AFTER_BODY = 17;
const IM_IN_FRAMESET = 18;
const IM_AFTER_FRAMESET = 19;
const IM_AFTER_AFTER_BODY = 20;
const IM_AFTER_AFTER_FRAMESET = 21;
const IM_IN_SVG = 22;
const IM_IN_MATHML = 23;
protected $stack = array();
protected $current; // Pointer in the tag hierarchy.
protected $doc;
protected $processor;
protected $insertMode = 0;
/**
* Quirks mode is enabled by default. Any document that is missing the
* DT will be considered to be in quirks mode.
*/
protected $quirks = TRUE;
public function __construct() {
$impl = new \DOMImplementation();
// XXX:
// Create the doctype. For now, we are always creating HTML5
// documents, and attempting to up-convert any older DTDs to HTML5.
$dt = $impl->createDocumentType('html');
//$this->doc = \DOMImplementation::createDocument(NULL, 'html', $dt);
$this->doc = $impl->createDocument(NULL, NULL, $dt);
$this->doc->errors = array();
// $this->current = $this->doc->documentElement;
$this->current = $this->doc; //->documentElement;
// Create a rules engine for tags.
$this->rules = new TreeBuildingRules($this->doc);
}
/**
* Get the document.
*/
public function document() {
return $this->doc;
}
/**
* Provide an instruction processor.
*
* This is used for handling Processor Instructions as they are
* inserted. If omitted, PI's are inserted directly into the DOM tree.
*/
public function setInstructionProcessor(\HTML5\InstructionProcessor $proc) {
$this->processor = $proc;
}
public function doctype($name, $idType = 0, $id = NULL, $quirks = FALSE) {
// This is used solely for setting quirks mode. Currently we don't
// try to preserve the inbound DT. We convert it to HTML5.
$this->quirks = $quirks;
if ($this->insertMode > self::IM_INITIAL) {
$this->parseError("Illegal placement of DOCTYPE tag. Ignoring: " . $name);
return;
}
$this->insertMode = self::IM_BEFORE_HTML;
}
/**
* Process the start tag.
*
* @todo
* - XMLNS namespace handling (we need to parse, even if it's not valid)
* - XLink, MathML and SVG namespace handling
* - Omission rules: 8.1.2.4 Optional tags
*/
public function startTag($name, $attributes = array(), $selfClosing = FALSE) {
$lname = $this->normalizeTagName($name);
// Make sure we have an html element.
if (!$this->doc->documentElement && $name !== 'html') {
$this->startTag('html');
}
// Set quirks mode if we're at IM_INITIAL with no doctype.
if ($this->insertMode == self::IM_INITIAL) {
$this->quirks = TRUE;
$this->parseError("No DOCTYPE specified.");
}
// SPECIAL TAG HANDLING:
// Spec says do this, and "don't ask."
if ($name == 'image') {
$name = 'img';
}
// Autoclose p tags where appropriate.
if ($this->insertMode >= self::IM_IN_BODY && Elements::isA($name, Elements::AUTOCLOSE_P)) {
$this->autoclose('p');
}
// Set insert mode:
switch ($name) {
case 'html':
$this->insertMode = self::IM_BEFORE_HEAD;
break;
case 'head':
if ($this->insertMode > self::IM_BEFORE_HEAD) {
$this->parseError("Unexpected head tag outside of head context.");
}
else {
$this->insertMode = self::IM_IN_HEAD;
}
break;
case 'body':
$this->insertMode = self::IM_IN_BODY;
break;
case 'svg':
$this->insertMode = self::IM_IN_SVG;
break;
case 'math':
$this->insertMode = self::IM_IN_MATHML;
break;
case 'noscript':
if ($this->insertMode == self::IM_IN_HEAD) {
$this->insertMode = self::IM_IN_HEAD_NOSCRIPT;
}
break;
}
// Special case handling for SVG.
if ($this->insertMode == self::IM_IN_SVG) {
$lname = Elements::normalizeSvgElement($lname);
}
$ele = $this->doc->createElement($lname);
foreach ($attributes as $aName => $aVal) {
if ($this->insertMode == self::IM_IN_SVG) {
$aName = Elements::normalizeSvgAttribute($aName);
}
elseif ($this->insertMode == self::IM_IN_MATHML) {
$aName = Elements::normalizeMathMlAttribute($aName);
}
$ele->setAttribute($aName, $aVal);
// This is necessary on a non-DTD schema, like HTML5.
if ($aName == 'id') {
$ele->setIdAttribute('id', TRUE);
}
}
// Some elements have special processing rules. Handle those separately.
if ($this->rules->hasRules($name)) {
$this->current = $this->rules->evaluate($ele, $this->current);
}
// Otherwise, it's a standard element.
else {
$this->current->appendChild($ele);
// XXX: Need to handle self-closing tags and unary tags.
if (!Elements::isA($name, Elements::VOID_TAG)) {
$this->current = $ele;
}
}
// Return the element mask, which the tokenizer can then use to set
// various processing rules.
return Elements::element($name);
}
public function endTag($name) {
$lname = $this->normalizeTagName($name);
// Ignore closing tags for unary elements.
if (Elements::isA($name, Elements::VOID_TAG)) {
return;
}
if ($this->insertMode <= self::IM_BEFORE_HTML) {
// 8.2.5.4.2
if (in_array($name, array('html', 'br', 'head', 'title'))) {
$this->startTag('html');
$this->endTag($name);
$this->insertMode = self::IM_BEFORE_HEAD;
return;
}
// Ignore the tag.
$this->parseError("Illegal closing tag at global scope.");
return;
}
if ($name != $lname) {
//fprintf(STDOUT, "Mismatch on %s and %s", $name, $lname);
return $this->quirksTreeResolver($lname);
}
// XXX: HTML has no parent. What do we do, though,
// if this element appears in the wrong place?
if ($lname == 'html') {
return;
}
//$this->current = $this->current->parentNode;
if (!$this->autoclose($name)) {
$this->parseError('Could not find closing tag for ' . $name);
}
//switch ($this->insertMode) {
switch ($lname) {
case "head":
$this->insertMode = self::IM_AFTER_HEAD;
break;
case "body":
$this->insertMode = self::IM_AFTER_BODY;
break;
case "svg":
case "mathml":
$this->insertMode = self::IM_IN_BODY;
break;
}
// 8.2.5.4.7
if ($name == 'sarcasm') {
$this->text("Take a deep breath.");
}
}
public function comment($cdata) {
// TODO: Need to handle case where comment appears outside of the HTML tag.
$node = $this->doc->createComment($cdata);
$this->current->appendChild($node);
}
public function text($data) {
// XXX: Hmmm.... should we really be this strict?
if ($this->insertMode < self::IM_IN_HEAD) {
$data = trim($data);
if (!empty($data)) {
//fprintf(STDOUT, "Unexpected insert mode: %d", $this->insertMode);
$this->parseError("Unexpected text. Ignoring: " . $data);
return;
}
}
//fprintf(STDOUT, "Appending text %s.", $data);
$node = $this->doc->createTextNode($data);
$this->current->appendChild($node);
}
public function eof() {
// If the $current isn't the $root, do we need to do anything?
}
public function parseError($msg, $line = 0, $col = 0) {
$this->doc->errors[] = sprintf("Line %d, Col %d: %s", $line, $col, $msg);
}
public function cdata($data) {
$node = $this->doc->createCDATASection($data);
$this->current->appendChild($node);
}
public function processingInstruction($name, $data = NULL) {
// XXX: Ignore initial XML declaration, per the spec.
if ($this->insertMode == self::IM_INITIAL && 'xml' == strtolower($name)) {
return;
}
// Important: The processor may modify the current DOM tree however
// it sees fit.
if (isset($this->processor)) {
$res = $processor->process($this->current, $name, $data);
if (!empty($res)) {
$this->current = $res;
}
return;
}
// Otherwise, this is just a dumb PI element.
$node = $this->doc->createProcessingInstruction($name, $data);
$this->current->appendChild($node);
}
// ==========================================================================
// UTILITIES
// ==========================================================================
protected function normalizeTagName($name) {
if (strpos($name, ':') !== FALSE) {
// We know from the grammar that there must be at least one other
// char besides :, since : is not a legal tag start.
$parts = explode(':', $name);
return array_pop($parts);
}
return $name;
}
protected function quirksTreeResolver($name) {
throw new \Exception("Not implemented.");
}
/**
* Automatically climb the tree and close the closest node with the matching $tag.
*/
protected function autoclose($tag) {
$working = $this->current;
do {
if ($working->nodeType != XML_ELEMENT_NODE) {
return FALSE;
}
if ($working->tagName == $tag) {
$this->current = $working->parentNode;
return TRUE;
}
} while ($working = $working->parentNode);
return FALSE;
}
/**
* Checks if the given tagname is an ancestor of the present candidate.
*
* If $this->current or anything above $this->current matches the given tag
* name, this returns TRUE.
*/
protected function isAncestor($tagname) {
$candidate = $this->current;
while ($candidate->nodeType === XML_ELEMENT_NODE) {
if ($candidate->tagName == $tagname) {
return TRUE;
}
$candidate = $candidate->parentNode;
}
return FALSE;
}
/**
* Returns TRUE if the immediate parent element is of the given tagname.
*/
protected function isParent($tagname) {
return $this->current->tagName == $tagname;
}
}
|