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
|
<?php
namespace HTML5\Serializer;
/**
* Traverser for walking a DOM tree.
*
* This is a concrete traverser designed to convert a DOM tree into an
* HTML5 document. It is not intended to be a generic DOMTreeWalker
* implementation.
*
* @see http://www.w3.org/TR/2012/CR-html5-20121217/syntax.html#serializing-html-fragments
*/
class Traverser {
static $block_elements = 'html|body|head|p|div|h[1-6]|title|script|link|meta|section|article|table|tbody|tr|th|td';
// TODO: Refactor this into an element mask.
static $literal_elements = array(
'style' => 1,
'script' => 1,
'xmp' => 1,
'iframe' => 1,
'noembed' => 1,
'noframes' => 1,
'plaintext' => 1,
);
/**
* Unary elements.
* HTML5 section 8.3:
* If current node is an
* area, base, basefont, bgsound, br, col, command, embed, frame, hr, img,
* input, keygen, link, meta, param, source, track or wbr element, then
* continue on to the next child node at this point.
*/
static $unary_elements = 'area|base|basefont|bgsound|br|col|command|embed|frame|hr|img';
/** Namespaces that should be treated as "local" to HTML5. */
static $local_ns = array(
'http://www.w3.org/1999/xhtml' => 'html',
'http://www.w3.org/1998/Math/MathML' => 'mathml',
'http://www.w3.org/2000/svg' => 'svg',
);
protected $dom;
protected $out;
protected $pretty = TRUE;
const DOCTYPE = '<!DOCTYPE html>';
/**
* Create a traverser.
*
* @param DOMNode|DOMNodeList $dom
* The document or node to traverse.
* @param resource $out
* A stream that allows writing. The traverser will output into this
* stream.
*/
public function __construct($dom, $out) {
$this->dom = $dom;
$this->out = $out;
}
/**
* Determine whether output should be formatted.
*
* IMPORTANT: Neither option will GUARANTEE that the spacing of the output
* will exactly match the spacing of an origin document. The HTML5 specification
* does not require any such behavior.
*
* Semantically (according to the HTML5 spec's definition), either flag
* will produce an identical document. (Insignificant
* whitespace does not impact semantics).
*
* @param boolean $useFormatting
* If TRUE (default) output will be formatted. If FALSE,
* the little or no formatting is done.
*/
public function formatOutput($useFormatting = TRUE) {
$this->pretty = $useFormatting;
}
/**
* Tell the traverser to walk the DOM.
*
* @return resource $out
* Returns the output stream.
*/
public function walk() {
// If DOMDocument, start with the DOCTYPE and travers.
if ($this->dom instanceof \DOMDocument) {
$this->doctype();
$this->document($this->dom);
}
// If NodeList, loop
elseif ($this->dom instanceof \DOMNodeList) {
// Loop through the list
}
// Else assume this is a DOMNode-like datastructure.
else {
$this->node($this->dom);
}
return $this->out;
}
protected function doctype() {
$this->wr(self::DOCTYPE);
$this->nl();
}
protected function document($node) {
$this->node($node->documentElement);
$this->nl();
}
protected function node($node) {
switch ($node->nodeType) {
case XML_ELEMENT_NODE:
$this->element($node);
break;
case XML_TEXT_NODE:
$this->text($node);
break;
case XML_CDATA_SECTION_NODE:
$this->cdata($node);
break;
// FIXME: It appears that the parser doesn't do PI's.
case XML_PI_NODE:
$this->processorInstruction($ele);
break;
case XML_COMMENT_NODE:
$this->comment($node);
break;
// Currently we don't support embedding DTDs.
default:
print '<!-- Skipped -->';
break;
}
}
protected function element($ele) {
$name = $ele->tagName;
$block = $this->pretty && $this->isBlock($name);
// Per spec:
// If the element has a declared namespace in the HTML, MathML or
// SVG namespaces, we use the lname instead of the tagName.
if ($this->isLocalElement($ele)) {
$name = $ele->localName;
}
// TODO: Really need to fix the spacing.
// Add a newline for a block element.
if ($block) $this->nl();
$this->openTag($ele);
// Handle children.
if ($ele->hasChildNodes()) {
$this->children($ele->childNodes);
}
// If not unary, add a closing tag.
if (!$this->isUnary($name)) {
$this->closeTag($ele);
if ($block) $this->nl();
}
}
protected function text($ele) {
if ($this->isLiteral($ele)) {
$this->wr($ele->wholeText);
return;
}
// FIXME: This probably needs some flags set.
$this->wr($this->enc($ele->wholeText));
}
protected function cdata($ele) {
$this->wr('<![CDATA[')->wr($ele->wholeText)->wr(']]>');
}
protected function comment($ele) {
$this->wr('<!--')->wr($ele->data)->wr('-->');
}
protected function processorInstruction($ele) {
$this->wr('<?')->wr($ele->target)->wr(' ')->wr($ele->data)->wr(' ?>');
}
protected function children($nl) {
foreach ($nl as $node) {
$this->node($node);
}
}
protected function openTag($ele) {
// FIXME: Needs support for SVG, MathML, and namespaced XML.
$this->wr('<')->wr($ele->tagName);
$this->attrs($ele);
$this->wr('>');
}
protected function attrs($ele) {
// FIXME: Needs support for xml, xmlns, xlink, and namespaced elements.
if (!$ele->hasAttributes()) {
return $this;
}
// TODO: Currently, this always writes name="value", and does not do
// value-less attributes.
$map = $ele->attributes;
$len = $map->length;
for ($i = 0; $i < $len; ++$i) {
$node = $map->item($i);
$val = $this->enc($node->value);
// XXX: The spec says that we need to ensure that anything in
// the XML, XMLNS, or XLink NS's should use the canonical
// prefix. It seems that DOM does this for us already, but there
// may be exceptions.
$this->wr(' ')->wr($node->name)->wr('="')->wr($val)->wr('"');
}
}
protected function closeTag($ele) {
// FIXME: Needs support for SVG, MathML, and namespaced XML.
$this->wr('</')->wr($ele->tagName)->wr('>');
}
protected function wr($text) {
fwrite($this->out, $text);
return $this;
}
protected function nl() {
fwrite($this->out, PHP_EOL);
return $this;
}
protected function enc($text) {
$flags = ENT_QUOTES;
// TODO: Verify on PHP 5.4 that this works as desired.
if (defined('ENT_HTML5')) {
$flags = ENT_HTML5|ENT_SUBSTITUTE;
}
$ret = htmlentities($text, $flags, 'UTF-8');
//if ($ret != $text) printf("Replaced [%s] with [%s]", $text, $ret);
return $ret;
}
/**
* Is an unary tag.
*
* @param string $name
* The name of the element to test.
*
* @return bool
* True if Unary and false otherwise.
*/
protected function isUnary($name) {
return (bool)preg_match('/^(' . self::$unary_elements . ')$/i', $name);
}
/**
* Is block element.
*
* @param string $name
* The name of the element to test if a block level element
*
* @return bool
* If the element is block level or not.
*/
protected function isBlock($name) {
return (bool)preg_match('/^(' . self::$block_elements . ')$/i', $name);
}
protected function isLiteral($element) {
if (!$element->parentNode) {
return FALSE;
}
return isset(self::$literal_elements[$element->parentNode->tagName]);
}
protected function isLocalElement($ele) {
$uri = $ele->namespaceURI;
if (empty($uri)) {
return FALSE;
}
return isset(self::$local_ns[$uri]);
}
}
|