-
-
Notifications
You must be signed in to change notification settings - Fork 469
/
Copy pathParser.php
348 lines (312 loc) · 11.9 KB
/
Parser.php
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
<?php
declare(strict_types=1);
namespace PHPHtmlParser\Dom;
use PHPHtmlParser\Content;
use PHPHtmlParser\Contracts\Dom\ParserInterface;
use PHPHtmlParser\Dom\Node\AbstractNode;
use PHPHtmlParser\Dom\Node\HtmlNode;
use PHPHtmlParser\Dom\Node\TextNode;
use PHPHtmlParser\DTO\TagDTO;
use PHPHtmlParser\Enum\StringToken;
use PHPHtmlParser\Exceptions\ChildNotFoundException;
use PHPHtmlParser\Exceptions\CircularException;
use PHPHtmlParser\Exceptions\ContentLengthException;
use PHPHtmlParser\Exceptions\LogicalException;
use PHPHtmlParser\Exceptions\StrictException;
use PHPHtmlParser\Options;
use stringEncode\Encode;
class Parser implements ParserInterface
{
/**
* Attempts to parse the html in content.
*
* @throws ChildNotFoundException
* @throws CircularException
* @throws ContentLengthException
* @throws LogicalException
* @throws StrictException
*/
public function parse(Options $options, Content $content, int $size): AbstractNode
{
// add the root node
$root = new HtmlNode('root');
$root->setHtmlSpecialCharsDecode($options->isHtmlSpecialCharsDecode());
$activeNode = $root;
while ($activeNode !== null) {
if ($activeNode && is_object($activeNode->tag) && $activeNode->tag->name() === 'script'
&& $options->isCleanupInput() !== true
) {
$str = $content->copyUntil('</');
} else {
$str = $content->copyUntil('<');
}
if ($str == '') {
$tagDTO = $this->parseTag($options, $content, $size);
if (!$tagDTO->isStatus()) {
// we are done here
$activeNode = null;
continue;
}
// check if it was a closing tag
if ($tagDTO->isClosing()) {
$foundOpeningTag = true;
$originalNode = $activeNode;
while ($activeNode->getTag()->name() != $tagDTO->getTag()) {
$activeNode = $activeNode->getParent();
if ($activeNode === null) {
// we could not find opening tag
$activeNode = $originalNode;
$foundOpeningTag = false;
break;
}
}
if ($foundOpeningTag) {
$activeNode = $activeNode->getParent();
}
continue;
}
if ($tagDTO->getNode() === null) {
continue;
}
/** @var AbstractNode $node */
$node = $tagDTO->getNode();
$activeNode->addChild($node);
// check if node is self closing
if (!$node->getTag()->isSelfClosing()) {
$activeNode = $node;
}
} elseif ($options->isWhitespaceTextNode() ||
\trim($str) != ''
) {
// we found text we care about
$textNode = new TextNode($str, $options->isRemoveDoubleSpace());
$textNode->setHtmlSpecialCharsDecode($options->isHtmlSpecialCharsDecode());
$activeNode->addChild($textNode);
}
}
return $root;
}
/**
* Attempts to detect the charset that the html was sent in.
*
* @throws ChildNotFoundException
*/
public function detectCharset(Options $options, string $defaultCharset, AbstractNode $root): bool
{
// set the default
$encode = new Encode();
$encode->from($defaultCharset);
$encode->to($defaultCharset);
$enforceEncoding = $options->getEnforceEncoding();
if ($enforceEncoding !== null) {
// they want to enforce the given encoding
$encode->from($enforceEncoding);
$encode->to($enforceEncoding);
return false;
}
/** @var AbstractNode $meta */
$meta = $root->find('meta[http-equiv=Content-Type]', 0);
if ($meta == null) {
if (!$this->detectHTML5Charset($encode, $root)) {
// could not find meta tag
$root->propagateEncoding($encode);
return false;
}
return true;
}
$content = $meta->getAttribute('content');
if (\is_null($content)) {
// could not find content
$root->propagateEncoding($encode);
return false;
}
$matches = [];
if (\preg_match('/charset=([^;]+)/', $content, $matches)) {
$encode->from(\trim($matches[1]));
$root->propagateEncoding($encode);
return true;
}
// no charset found
$root->propagateEncoding($encode);
return false;
}
/**
* Attempt to parse a tag out of the content.
*
* @throws StrictException
* @throws ContentLengthException
* @throws LogicalException
* @throws StrictException
*/
private function parseTag(Options $options, Content $content, int $size): TagDTO
{
if ($content->char() != '<') {
// we are not at the beginning of a tag
return TagDTO::makeFromPrimitives();
}
// check if this is a closing tag
try {
$content->fastForward(1);
} catch (ContentLengthException $exception) {
// we are at the end of the file
return TagDTO::makeFromPrimitives();
}
if ($content->char() == '/') {
return $this->makeEndTag($content, $options);
}
if ($content->char() == '?') {
// special setting tag
$tag = $content->fastForward(1)
->copyByToken(StringToken::SLASH(), true);
$tag = (new Tag($tag))
->setOpening('<?')
->setClosing(' ?>')
->selfClosing();
} elseif($content->string(3) == '!--') {
// comment tag
$tag = $content->fastForward(3)
->copyByToken(StringToken::CLOSECOMMENT(), true);
$tag = (new Tag($tag))
->setOpening('<!--')
->setClosing('-->')
->selfClosing();
} else {
$tag = \strtolower($content->copyByToken(StringToken::SLASH(), true));
if (\trim($tag) == '') {
// no tag found, invalid < found
return TagDTO::makeFromPrimitives();
}
}
$node = new HtmlNode($tag);
$node->setHtmlSpecialCharsDecode($options->isHtmlSpecialCharsDecode());
$this->setUpAttributes($content, $size, $node, $options, $tag);
$content->skipByToken(StringToken::BLANK());
if ($content->char() == '/') {
// self closing tag
$node->getTag()->selfClosing();
$content->fastForward(1);
} elseif (\in_array($node->getTag()->name(), $options->getSelfClosing(), true)) {
// Should be a self closing tag, check if we are strict
if ($options->isStrict()) {
$character = $content->getPosition();
throw new StrictException("Tag '" . $node->getTag()->name() . "' is not self closing! (character #$character)");
}
// We force self closing on this tag.
$node->getTag()->selfClosing();
// Should this tag use a trailing slash?
if (\in_array($node->getTag()->name(), $options->getNoSlash(), true)) {
$node->getTag()->noTrailingSlash();
}
}
if ($content->canFastForward(1)) {
$content->fastForward(1);
}
return TagDTO::makeFromPrimitives(true, false, $node);
}
/**
* @throws ChildNotFoundException
*/
private function detectHTML5Charset(Encode $encode, AbstractNode $root): bool
{
/** @var AbstractNode|null $meta */
$meta = $root->find('meta[charset]', 0);
if ($meta == null) {
return false;
}
$encode->from(\trim($meta->getAttribute('charset')));
$root->propagateEncoding($encode);
return true;
}
/**
* @throws ContentLengthException
* @throws LogicalException
*/
private function makeEndTag(Content $content, Options $options): TagDTO
{
$tag = $content->fastForward(1)
->copyByToken(StringToken::SLASH(), true);
// move to end of tag
$content->copyUntil('>');
$content->fastForward(1);
// check if this closing tag counts
$tag = \strtolower($tag);
if (\in_array($tag, $options->getSelfClosing(), true)) {
return TagDTO::makeFromPrimitives(true);
}
return TagDTO::makeFromPrimitives(true, true, null, \strtolower($tag));
}
/**
* @param string|Tag $tag
*
* @throws ContentLengthException
* @throws LogicalException
* @throws StrictException
*/
private function setUpAttributes(Content $content, int $size, HtmlNode $node, Options $options, $tag): void
{
while (
$content->char() != '>' &&
$content->char() != '/'
) {
$space = $content->skipByToken(StringToken::BLANK(), true);
if (empty($space)) {
try {
$content->fastForward(1);
} catch (ContentLengthException $exception) {
// reached the end of the content
break;
}
continue;
}
$name = $content->copyByToken(StringToken::EQUAL(), true);
if ($name == '/') {
break;
}
if (empty($name)) {
$content->skipByToken(StringToken::BLANK());
continue;
}
$content->skipByToken(StringToken::BLANK());
if ($content->char() == '=') {
$content->fastForward(1)
->skipByToken(StringToken::BLANK());
switch ($content->char()) {
case '"':
$content->fastForward(1);
$string = $content->copyUntil('"', true);
do {
$moreString = $content->copyUntilUnless('"', '=>');
$string .= $moreString;
} while (\strlen($moreString) > 0 && $content->getPosition() < $size);
$content->fastForward(1);
$node->getTag()->setAttribute($name, $string);
break;
case "'":
$content->fastForward(1);
$string = $content->copyUntil("'", true);
do {
$moreString = $content->copyUntilUnless("'", '=>');
$string .= $moreString;
} while (\strlen($moreString) > 0 && $content->getPosition() < $size);
$content->fastForward(1);
$node->getTag()->setAttribute($name, $string, false);
break;
default:
$node->getTag()->setAttribute($name, $content->copyByToken(StringToken::ATTR(), true));
break;
}
} else {
// no value attribute
if ($options->isStrict()) {
// can't have this in strict html
$character = $content->getPosition();
throw new StrictException("Tag '$tag' has an attribute '$name' with out a value! (character #$character)");
}
$node->getTag()->setAttribute($name, null);
if ($content->char() != '>') {
$content->rewind(1);
}
}
}
}
}