-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathDocument.php
1186 lines (1030 loc) · 42.7 KB
/
Document.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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace AmpProject\Dom;
use AmpProject\DevMode;
use AmpProject\Dom\Document\AfterLoadFilter;
use AmpProject\Dom\Document\AfterSaveFilter;
use AmpProject\Dom\Document\BeforeLoadFilter;
use AmpProject\Dom\Document\BeforeSaveFilter;
use AmpProject\Dom\Document\Filter;
use AmpProject\Dom\Document\Option;
use AmpProject\Encoding;
use AmpProject\Exception\FailedToRetrieveRequiredDomElement;
use AmpProject\Exception\InvalidDocumentFilter;
use AmpProject\Exception\MaxCssByteCountExceeded;
use AmpProject\Html\Attribute;
use AmpProject\Html\Tag;
use AmpProject\Optimizer\CssRule;
use AmpProject\Validator\Spec\CssRuleset\AmpNoTransformed;
use AmpProject\Validator\Spec\SpecRule;
use DOMComment;
use DOMDocument;
use DOMElement;
use DOMNode;
use DOMNodeList;
use DOMText;
use DOMXPath;
use ReflectionClass;
use ReflectionException;
use ReflectionNamedType;
/**
* Abstract away some of the difficulties of working with PHP's DOMDocument.
*
* @property DOMXPath $xpath XPath query object for this document.
* @property Element $html The document's <html> element.
* @property Element $head The document's <head> element.
* @property Element $body The document's <body> element.
* @property Element|null $charset The document's charset meta element.
* @property Element|null $viewport The document's viewport meta element.
* @property DOMNodeList $ampElements The document's <amp-*> elements.
* @property Element $ampCustomStyle The document's <style amp-custom> element.
* @property int $ampCustomStyleByteCount Count of bytes of CSS in the <style amp-custom> tag.
* @property int $inlineStyleByteCount Count of bytes of CSS in all of the inline style attributes.
* @property LinkManager $links Link manager to manage <link> tags in the <head>.
*
* @package ampproject/amp-toolbox
*/
final class Document extends DOMDocument
{
/**
* Default document type to use.
*
* @var string
*/
const DEFAULT_DOCTYPE = '<!DOCTYPE html>';
/**
* Regular expression to match the HTML doctype.
*
* @var string
*/
const HTML_DOCTYPE_REGEX_PATTERN = '#<!doctype\s+html[^>]+?>#si';
/*
* Regular expressions to fetch the individual structural tags.
* These patterns were optimized to avoid extreme backtracking on large documents.
*/
const HTML_STRUCTURE_DOCTYPE_PATTERN = '/^(?<doctype>[^<]*(?>\s*<!--.*?-->\s*)*<!doctype(?>\s+[^>]+)?>)/is';
const HTML_STRUCTURE_HTML_START_TAG = '/^(?<html_start>[^<]*(?>\s*<!--.*?-->\s*)*<html(?>\s+[^>]*)?>)/is';
const HTML_STRUCTURE_HTML_END_TAG = '/(?<html_end><\/html(?>\s+[^>]*)?>.*)$/is';
const HTML_STRUCTURE_HEAD_START_TAG = '/^[^<]*(?><!--.*?-->\s*)*(?><head(?>\s+[^>]*)?>)/is';
const HTML_STRUCTURE_BODY_START_TAG = '/^[^<]*(?><!--.*-->\s*)*(?><body(?>\s+[^>]*)?>)/is';
const HTML_STRUCTURE_BODY_END_TAG = '/(?><\/body(?>\s+[^>]*)?>.*)$/is';
const HTML_STRUCTURE_HEAD_TAG = '/^(?>[^<]*(?><head(?>\s+[^>]*)?>).*?<\/head(?>\s+[^>]*)?>)/is';
// Regex pattern used for removing Internet Explorer conditional comments.
const HTML_IE_CONDITIONAL_COMMENTS_PATTERN = '/<!--(?>\[if\s|<!\[endif)(?>[^>]+(?<!--)>)*(?>[^>]+(?<=--)>)/i';
/**
* Error message to use when the __get() is triggered for an unknown property.
*
* @var string
*/
const PROPERTY_GETTER_ERROR_MESSAGE = 'Undefined property: AmpProject\\Dom\\Document::';
// Attribute to use as a placeholder to move the emoji AMP symbol (⚡) over to DOM.
const EMOJI_AMP_ATTRIBUTE_PLACEHOLDER = 'emoji-amp';
/**
* XPath query to retrieve all <amp-*> tags, relative to the <body> node.
*
* @var string
*/
const XPATH_AMP_ELEMENTS_QUERY = ".//*[starts-with(name(), 'amp-')]";
/**
* XPath query to retrieve the <style amp-custom> tag, relative to the <head> node.
*
* @var string
*/
const XPATH_AMP_CUSTOM_STYLE_QUERY = './/style[@amp-custom]';
/**
* XPath query to fetch the inline style attributes, relative to the <body> node.
*
* @var string
*/
const XPATH_INLINE_STYLE_ATTRIBUTES_QUERY = './/@style';
/**
* Associative array for lazily-created, cached properties for the document.
*
* @var array
*/
private $properties = [];
/**
* Associative array of options to configure the behavior of the DOM document abstraction.
*
* @see Option::DEFAULTS For a list of available options.
*
* @var Options
*/
private $options;
/**
* Whether `data-ampdevmode` was initially set on the the document element.
*
* @var bool
*/
private $hasInitialAmpDevMode = false;
/**
* The original encoding of how the Dom\Document was created.
*
* This is stored to do an automatic conversion to UTF-8, which is a requirement for AMP.
*
* @var Encoding
*/
private $originalEncoding;
/**
* The maximum number of bytes of CSS that is enforced.
*
* A negative number will disable the byte count limit.
*
* @var int
*/
private $cssMaxByteCountEnforced = -1;
/**
* List of document filter class names.
*
* @var string[]
*/
private $filterClasses = [];
/**
* List of document filter class instances.
*
* @var Filter[]
*/
private $filters = [];
/**
* Unique ID manager for the Document instance.
*
* @var UniqueIdManager
*/
private $uniqueIdManager;
/**
* Creates a new AmpProject\Dom\Document object
*
* @link https://php.net/manual/domdocument.construct.php
*
* @param string $version Optional. The version number of the document as part of the XML declaration.
* @param string $encoding Optional. The encoding of the document as part of the XML declaration.
*/
public function __construct($version = '', $encoding = null)
{
$this->originalEncoding = new Encoding($encoding);
parent::__construct($version ?: '1.0', Encoding::AMP);
$this->registerNodeClass(DOMElement::class, Element::class);
$this->options = new Options(Option::DEFAULTS);
$this->uniqueIdManager = new UniqueIdManager();
$this->registerFilters(
[
Filter\DetectInvalidByteSequence::class,
Filter\SvgSourceAttributeEncoding::class,
Filter\AmpEmojiAttribute::class,
Filter\AmpBindAttributes::class,
Filter\SelfClosingTags::class,
Filter\SelfClosingSVGElements::class,
Filter\NoscriptElements::class,
Filter\DeduplicateTag::class,
Filter\ConvertHeadProfileToLink::class,
Filter\MustacheScriptTemplates::class,
Filter\DoctypeNode::class,
Filter\NormalizeHtmlAttributes::class,
Filter\DocumentEncoding::class,
Filter\HttpEquivCharset::class,
Filter\LibxmlCompatibility::class,
Filter\ProtectEsiTags::class,
Filter\NormalizeHtmlEntities::class,
]
);
}
/**
* Named constructor to provide convenient way of transforming HTML into DOM.
*
* Due to slow automatic encoding detection, it is recommended to provide an explicit
* charset either via a <meta charset> tag or via $options.
*
* @param string $html HTML to turn into a DOM.
* @param array|string $options Optional. Array of options to configure the document. Used as encoding if a string
* is passed. Defaults to an empty array.
* @return Document|false DOM generated from provided HTML, or false if the transformation failed.
*/
public static function fromHtml($html, $options = [])
{
// Assume options are the encoding if a string is passed, for BC reasons.
if (is_string($options)) {
$options = [Option::ENCODING => $options];
}
$encoding = $options[ Option::ENCODING ] ?? null;
$dom = new self('', $encoding);
if (! $dom->loadHTML($html, $options)) {
return false;
}
return $dom;
}
/**
* Named constructor to provide convenient way of transforming a HTML fragment into DOM.
*
* The difference to Document::fromHtml() is that fragments are not normalized as to their structure.
*
* Due to slow automatic encoding detection, it is recommended to pass in an explicit
* charset via $options.
*
* @param string $html HTML to turn into a DOM.
* @param array|string $options Optional. Array of options to configure the document. Used as encoding if a string
* is passed. Defaults to an empty array.
* @return Document|false DOM generated from provided HTML, or false if the transformation failed.
*/
public static function fromHtmlFragment($html, $options = [])
{
// Assume options are the encoding if a string is passed, for BC reasons.
if (is_string($options)) {
$options = [Option::ENCODING => $options];
}
$encoding = $options[ Option::ENCODING ] ?? null;
$dom = new self('', $encoding);
if (! $dom->loadHTMLFragment($html, $options)) {
return false;
}
return $dom;
}
/**
* Named constructor to provide convenient way of retrieving the DOM from a node.
*
* @param DOMNode $node Node to retrieve the DOM from. This is being modified by reference (!).
* @return Document DOM generated from provided HTML, or false if the transformation failed.
*/
public static function fromNode(DOMNode &$node)
{
/**
* Document of the node.
*
* If the node->ownerDocument returns null, the node is the document.
*
* @var DOMDocument
*/
$root = $node->ownerDocument === null ? $node : $node->ownerDocument;
if ($root instanceof self) {
return $root;
}
$dom = new self();
// We replace the $node by reference, to make sure the next lines of code will
// work as expected with the new document.
// Otherwise $dom and $node would refer to two different DOMDocuments.
$node = $dom->importNode($node, true);
$dom->appendChild($node);
$dom->hasInitialAmpDevMode = $dom->documentElement->hasAttribute(DevMode::DEV_MODE_ATTRIBUTE);
return $dom;
}
/**
* Reset the internal optimizations of the Document object.
*
* This might be needed if you are doing an operation that causes the cached
* nodes and XPath objects to point to the wrong document.
*
* @return self Reset version of the Document object.
*/
private function reset()
{
// Drop references to old DOM document.
unset($this->properties['xpath'], $this->properties['head'], $this->properties['body']);
// Reference of the document itself doesn't change here, but might need to change in the future.
return $this;
}
/**
* Load HTML from a string.
*
* @link https://php.net/manual/domdocument.loadhtml.php
*
* @param string $source The HTML string.
* @param array|int|string $options Optional. Array of options to configure the document. Used as additional Libxml
* parameters if an int or string is passed. Defaults to an empty array.
* @return bool true on success or false on failure.
*/
#[\ReturnTypeWillChange]
public function loadHTML($source, $options = [])
{
$source = $this->normalizeDocumentStructure($source);
$success = $this->loadHTMLFragment($source, $options);
if ($success) {
$this->insertMissingCharset();
// Do some further clean-up.
$this->moveInvalidHeadNodesToBody();
$this->movePostBodyNodesToBody();
}
return $success;
}
/**
* Load a HTML fragment from a string.
*
* @param string $source The HTML fragment string.
* @param array|int|string $options Optional. Array of options to configure the document. Used as additional Libxml
* parameters if an int or string is passed. Defaults to an empty array.
* @return bool true on success or false on failure.
*/
public function loadHTMLFragment($source, $options = [])
{
// Assume options are the additional libxml flags if a string or int is passed, for BC reasons.
if (is_string($options)) {
$options = (int) $options;
}
if (is_int($options)) {
$options = [Option::LIBXML_FLAGS => $options];
}
$this->options = $this->options->merge($options);
$this->reset();
foreach ($this->filterClasses as $filterClass) {
$filter = null;
try {
$filter = $this->instantiateFilter($filterClass);
$this->filters[] = $filter;
} catch (ReflectionException $exception) {
// A filter cannot properly be instantiated. Let's just skip loading it for now.
continue;
}
if (! $filter instanceof Filter) {
throw InvalidDocumentFilter::forFilter($filter);
}
if ($filter instanceof BeforeLoadFilter) {
$source = $filter->beforeLoad($source);
}
}
$success = parent::loadHTML($source, $this->options[Option::LIBXML_FLAGS]);
if ($success) {
foreach ($this->filters as $filter) {
if ($filter instanceof AfterLoadFilter) {
$filter->afterLoad($this);
}
}
$this->hasInitialAmpDevMode = $this->documentElement->hasAttribute(DevMode::DEV_MODE_ATTRIBUTE);
}
return $success;
}
/**
* Dumps the internal document into a string using HTML formatting.
*
* @link https://php.net/manual/domdocument.savehtml.php
*
* @param DOMNode|null $node Optional. Parameter to output a subset of the document.
* @return string The HTML, or false if an error occurred.
*/
#[\ReturnTypeWillChange]
public function saveHTML(?DOMNode $node = null)
{
return $this->saveHTMLFragment($node);
}
/**
* Dumps the internal document fragment into a string using HTML formatting.
*
* @param DOMNode|null $node Optional. Parameter to output a subset of the document.
* @return string The HTML fragment, or false if an error occurred.
*/
public function saveHTMLFragment(?DOMNode $node = null)
{
$filtersInReverse = array_reverse($this->filters);
foreach ($filtersInReverse as $filter) {
if ($filter instanceof BeforeSaveFilter) {
$filter->beforeSave($this);
}
}
if (null === $node || PHP_VERSION_ID >= 70300) {
$html = parent::saveHTML($node);
} else {
$html = $this->extractNodeViaFragmentBoundaries($node);
}
foreach ($filtersInReverse as $filter) {
if ($filter instanceof AfterSaveFilter) {
$html = $filter->afterSave($html);
}
}
return $html;
}
/**
* Get the current options of the Document instance.
*
* @return Options
*/
public function getOptions()
{
return $this->options;
}
/**
* Add the required utf-8 meta charset tag if it is still missing.
*/
private function insertMissingCharset()
{
// Bail if a charset tag is already present.
if ($this->xpath->query('.//meta[ @charset ]')->item(0)) {
return;
}
$charset = $this->createElement(Tag::META);
$charset->setAttribute(Attribute::CHARSET, Encoding::AMP);
$this->head->insertBefore($charset, $this->head->firstChild);
}
/**
* Extract a node's HTML via fragment boundaries.
*
* Temporarily adds fragment boundary comments in order to locate the desired node to extract from
* the given HTML document. This is required because libxml seems to only preserve whitespace when
* serializing when calling DOMDocument::saveHTML() on the entire document. If you pass the element
* to DOMDocument::saveHTML() then formatting whitespace gets added unexpectedly. This is seen to
* be fixed in PHP 7.3, but for older versions of PHP the following workaround is needed.
*
* @param DOMNode $node Node to extract the HTML for.
* @return string Extracted HTML string.
*/
private function extractNodeViaFragmentBoundaries(DOMNode $node)
{
$boundary = $this->uniqueIdManager->getUniqueId('fragment_boundary');
$startBoundary = $boundary . ':start';
$endBoundary = $boundary . ':end';
$commentStart = $this->createComment($startBoundary);
$commentEnd = $this->createComment($endBoundary);
$node->parentNode->insertBefore($commentStart, $node);
$node->parentNode->insertBefore($commentEnd, $node->nextSibling);
$pattern = '/^.*?'
. preg_quote("<!--{$startBoundary}-->", '/')
. '(.*)'
. preg_quote("<!--{$endBoundary}-->", '/')
. '.*?\s*$/s';
$html = preg_replace($pattern, '$1', parent::saveHTML());
$node->parentNode->removeChild($commentStart);
$node->parentNode->removeChild($commentEnd);
return $html;
}
/**
* Normalize the document structure.
*
* This makes sure the document adheres to the general structure that AMP requires:
* ```
* <!DOCTYPE html>
* <html>
* <head>
* <meta charset="utf-8">
* </head>
* <body>
* </body>
* </html>
* ```
*
* @param string $content Content to normalize the structure of.
* @return string Normalized content.
*/
private function normalizeDocumentStructure($content)
{
$matches = [];
$doctype = self::DEFAULT_DOCTYPE;
$htmlStart = '<html>';
$htmlEnd = '</html>';
// Strip IE conditional comments, which are supported by IE 5-9 only (which AMP doesn't support).
$content = preg_replace(self::HTML_IE_CONDITIONAL_COMMENTS_PATTERN, '', $content);
// Detect and strip <!doctype> tags.
if (preg_match(self::HTML_STRUCTURE_DOCTYPE_PATTERN, $content, $matches)) {
$doctype = $matches['doctype'];
$content = preg_replace(self::HTML_STRUCTURE_DOCTYPE_PATTERN, '', $content, 1);
}
// Detect and strip <html> tags.
if (preg_match(self::HTML_STRUCTURE_HTML_START_TAG, $content, $matches)) {
$htmlStart = $matches['html_start'];
$content = preg_replace(self::HTML_STRUCTURE_HTML_START_TAG, '', $content, 1);
preg_match(self::HTML_STRUCTURE_HTML_END_TAG, $content, $matches);
$htmlEnd = $matches['html_end'] ?? $htmlEnd;
$content = preg_replace(self::HTML_STRUCTURE_HTML_END_TAG, '', $content, 1);
}
// Detect <head> and <body> tags and add as needed.
if (! preg_match(self::HTML_STRUCTURE_HEAD_START_TAG, $content, $matches)) {
if (! preg_match(self::HTML_STRUCTURE_BODY_START_TAG, $content, $matches)) {
// Both <head> and <body> missing.
$content = "<head></head><body>{$content}</body>";
} else {
// Only <head> missing.
$content = "<head></head>{$content}";
}
} elseif (! preg_match(self::HTML_STRUCTURE_BODY_END_TAG, $content, $matches)) {
// Only <body> missing.
// @todo This is an expensive regex operation, look into further optimization.
$content = preg_replace(self::HTML_STRUCTURE_HEAD_TAG, '$0<body>', $content, 1, $count);
// Closing </head> tag is missing.
if (! $count) {
$content = $content . '</head><body>';
}
$content .= '</body>';
}
$content = "{$htmlStart}{$content}{$htmlEnd}";
// Reinsert a standard doctype (while preserving any potentially leading comments).
$doctype = preg_replace(self::HTML_DOCTYPE_REGEX_PATTERN, self::DEFAULT_DOCTYPE, $doctype);
$content = "{$doctype}{$content}";
return $content;
}
/**
* Normalize the structure of the document if it was already provided as a DOM.
*
* Warning: This method may not use any magic getters for html, head, or body.
*/
public function normalizeDomStructure()
{
if (! $this->documentElement) {
$this->appendChild($this->createElement(Tag::HTML));
}
if (Tag::HTML !== $this->documentElement->nodeName) {
$nextSibling = $this->documentElement->nextSibling;
/**
* The old document element that we need to remove and replace as we cannot just move it around.
*
* @var Element
*/
$oldDocumentElement = $this->removeChild($this->documentElement);
$html = $this->createElement(Tag::HTML);
$this->insertBefore($html, $nextSibling);
if ($oldDocumentElement->nodeName === Tag::HEAD) {
$head = $oldDocumentElement;
} else {
$head = $this->getElementsByTagName(Tag::HEAD)->item(0);
if (!$head) {
$head = $this->createElement(Tag::HEAD);
}
}
if (!$head instanceof Element) {
throw FailedToRetrieveRequiredDomElement::forHeadElement($head);
}
$this->properties['head'] = $head;
$html->appendChild($head);
if ($oldDocumentElement->nodeName === Tag::BODY) {
$body = $oldDocumentElement;
} else {
$body = $this->getElementsByTagName(Tag::BODY)->item(0);
if (!$body) {
$body = $this->createElement(Tag::BODY);
}
}
if (!$body instanceof Element) {
throw FailedToRetrieveRequiredDomElement::forBodyElement($body);
}
$this->properties['body'] = $body;
$html->appendChild($body);
if ($oldDocumentElement !== $body && $oldDocumentElement !== $this->head) {
$body->appendChild($oldDocumentElement);
}
} else {
$head = $this->getElementsByTagName(Tag::HEAD)->item(0);
if (!$head) {
$this->properties['head'] = $this->createElement(Tag::HEAD);
$this->documentElement->insertBefore($this->properties['head'], $this->documentElement->firstChild);
}
$body = $this->getElementsByTagName(Tag::BODY)->item(0);
if (!$body) {
$this->properties['body'] = $this->createElement(Tag::BODY);
$this->documentElement->appendChild($this->properties['body']);
}
}
$this->moveInvalidHeadNodesToBody();
$this->movePostBodyNodesToBody();
}
/**
* Move invalid head nodes back to the body.
*
* Warning: This method may not use any magic getters for html, head, or body.
*/
private function moveInvalidHeadNodesToBody()
{
// Walking backwards makes it easier to move elements in the expected order.
$node = $this->properties['head']->lastChild;
while ($node) {
$nextSibling = $node->previousSibling;
if (!$this->isValidHeadNode($node)) {
$this->properties['body']->insertBefore(
$this->properties['head']->removeChild($node),
$this->properties['body']->firstChild
);
}
$node = $nextSibling;
}
}
/**
* Move any nodes appearing after </body> or </html> to be appended to the <body>.
*
* This accounts for markup that is output at shutdown, such markup from Query Monitor. Not only is elements after
* the </body> not valid in AMP, but trailing elements after </html> will get wrapped in additional <html> elements.
* While comment nodes would be allowed in AMP, everything is moved regardless so that source stack comments will
* retain their relative position with the element nodes they annotate.
*
* Warning: This method may not use any magic getters for html, head, or body.
*/
private function movePostBodyNodesToBody()
{
// Move nodes (likely comments) from after the </body>.
while ($this->properties['body']->nextSibling) {
$this->properties['body']->appendChild($this->properties['body']->nextSibling);
}
// Move nodes from after the </html>.
while ($this->documentElement->nextSibling) {
$nextSibling = $this->documentElement->nextSibling;
if ($nextSibling instanceof Element && Tag::HTML === $nextSibling->nodeName) {
// Handle trailing elements getting wrapped in implicit duplicate <html>.
while ($nextSibling->firstChild) {
$this->properties['body']->appendChild($nextSibling->firstChild);
}
$nextSibling->parentNode->removeChild($nextSibling); // Discard now-empty implicit <html>.
} else {
$this->properties['body']->appendChild($this->documentElement->nextSibling);
}
}
}
/**
* Determine whether a node can be in the head.
*
* Warning: This method may not use any magic getters for html, head, or body.
*
* @link https://github.com/ampproject/amphtml/blob/445d6e3be8a5063e2738c6f90fdcd57f2b6208be/validator/engine/htmlparser.js#L83-L100
* @link https://www.w3.org/TR/html5/document-metadata.html
*
* @param DOMNode $node Node.
* @return bool Whether valid head node.
*/
public function isValidHeadNode(DOMNode $node)
{
return (
($node instanceof Element && in_array($node->nodeName, Tag::ELEMENTS_ALLOWED_IN_HEAD, true))
||
($node instanceof DOMText && preg_match('/^\s*$/', $node->nodeValue)) // Whitespace text nodes are OK.
||
$node instanceof DOMComment
);
}
/**
* Get the ID for an element.
*
* If the element does not have an ID, create one first.
*
* @param Element $element Element to get the ID for.
* @param string $prefix Optional. The prefix to use (should not have a trailing dash). Defaults to 'i-amp-id'.
* @return string ID to use.
*/
public function getElementId(Element $element, $prefix = 'i-amp')
{
if ($element->hasAttribute(Attribute::ID)) {
return $element->getAttribute(Attribute::ID);
}
$id = $this->uniqueIdManager->getUniqueId($prefix);
while ($this->getElementById($id) instanceof Element) {
$id = $this->uniqueIdManager->getUniqueId($prefix);
}
$element->setAttribute(Attribute::ID, $id);
return $id;
}
/**
* Determine whether `data-ampdevmode` was initially set on the document element.
*
* @return bool
*/
public function hasInitialAmpDevMode()
{
return $this->hasInitialAmpDevMode;
}
/**
* Add style(s) to the <style amp-custom> tag.
*
* @param string $style Style to add.
* @throws MaxCssByteCountExceeded If the allowed max byte count is exceeded.
*/
public function addAmpCustomStyle($style)
{
$style = trim($style, CssRule::CSS_TRIM_CHARACTERS);
$existingStyle = (string)$this->ampCustomStyle->textContent;
// Inject new styles before any potential source map annotation comment like: /*# sourceURL=amp-custom.css */.
// If not present, then just put it at the end of the stylesheet. This isn't strictly required, but putting the
// source map comments at the end is the convention.
$newStyle = preg_replace(
':(?=\s+/\*#[^*]+?\*/\s*$|$):s',
$style,
$existingStyle,
1
);
$newByteCount = strlen($newStyle);
if ($this->getRemainingCustomCssSpace() < ($newByteCount - $this->ampCustomStyleByteCount)) {
throw MaxCssByteCountExceeded::forAmpCustom($newStyle);
}
$this->ampCustomStyle->textContent = $newStyle;
$this->properties['ampCustomStyleByteCount'] = $newByteCount;
}
/**
* Add the given number of bytes ot the total inline style byte count.
*
* @param int $byteCount Bytes to add.
*/
public function addInlineStyleByteCount($byteCount)
{
$this->inlineStyleByteCount += $byteCount;
}
/**
* Get the remaining number bytes allowed for custom CSS.
*
* @return int
*/
public function getRemainingCustomCssSpace()
{
if ($this->cssMaxByteCountEnforced < 0) {
// No CSS byte count limit is being enforced, so return the next best thing to +∞.
return PHP_INT_MAX;
}
return max(
0,
$this->cssMaxByteCountEnforced - (int)$this->ampCustomStyleByteCount - (int)$this->inlineStyleByteCount
);
}
/**
* Get the array of allowed keys of lazily-created, cached properties.
* The array index is the key and the array value is the key's default value.
*
* @return array Array of allowed keys.
*/
protected function getAllowedKeys()
{
return [
'xpath',
Tag::HTML,
Tag::HEAD,
Tag::BODY,
Attribute::CHARSET,
Attribute::VIEWPORT,
'ampElements',
'ampCustomStyle',
'ampCustomStyleByteCount',
'inlineStyleByteCount',
'links',
];
}
/**
* Magic getter to implement lazily-created, cached properties for the document.
*
* @param string $name Name of the property to get.
* @return mixed Value of the property, or null if unknown property was requested.
*/
public function __get($name)
{
switch ($name) {
case 'xpath':
$this->properties['xpath'] = new DOMXPath($this);
return $this->properties['xpath'];
case Tag::HTML:
$html = $this->getElementsByTagName(Tag::HTML)->item(0);
if ($html === null) {
// Document was assembled manually and bypassed normalisation.
$this->normalizeDomStructure();
$html = $this->getElementsByTagName(Tag::HTML)->item(0);
}
if (!$html instanceof Element) {
throw FailedToRetrieveRequiredDomElement::forHtmlElement($html);
}
$this->properties['html'] = $html;
return $this->properties['html'];
case Tag::HEAD:
$head = $this->getElementsByTagName(Tag::HEAD)->item(0);
if ($head === null) {
// Document was assembled manually and bypassed normalisation.
$this->normalizeDomStructure();
$head = $this->getElementsByTagName(Tag::HEAD)->item(0);
}
if (!$head instanceof Element) {
throw FailedToRetrieveRequiredDomElement::forHeadElement($head);
}
$this->properties['head'] = $head;
return $this->properties['head'];
case Tag::BODY:
$body = $this->getElementsByTagName(Tag::BODY)->item(0);
if ($body === null) {
// Document was assembled manually and bypassed normalisation.
$this->normalizeDomStructure();
$body = $this->getElementsByTagName(Tag::BODY)->item(0);
}
if (!$body instanceof Element) {
throw FailedToRetrieveRequiredDomElement::forBodyElement($body);
}
$this->properties['body'] = $body;
return $this->properties['body'];
case Attribute::CHARSET:
// This is not cached as it could potentially be requested too early, before the viewport was added, and
// the cache would then store null without rechecking later on after the viewport has been added.
for ($node = $this->head->firstChild; $node !== null; $node = $node->nextSibling) {
if (
$node instanceof Element
&& $node->tagName === Tag::META
&& $node->getAttribute(Attribute::NAME) === Attribute::CHARSET
) {
return $node;
}
}
return null;
case Attribute::VIEWPORT:
// This is not cached as it could potentially be requested too early, before the viewport was added, and
// the cache would then store null without rechecking later on after the viewport has been added.
for ($node = $this->head->firstChild; $node !== null; $node = $node->nextSibling) {
if (
$node instanceof Element
&& $node->tagName === Tag::META
&& $node->getAttribute(Attribute::NAME) === Attribute::VIEWPORT
) {
return $node;
}
}
return null;
case 'ampElements':
// This is not cached as we clone some elements during SSR transformations to avoid ending up with
// partially transformed, broken elements.
return $this->xpath->query(self::XPATH_AMP_ELEMENTS_QUERY, $this->body)
?: new DOMNodeList();
case 'ampCustomStyle':
$ampCustomStyle = $this->xpath->query(self::XPATH_AMP_CUSTOM_STYLE_QUERY, $this->head)->item(0);
if (!$ampCustomStyle instanceof Element) {
$ampCustomStyle = $this->createElement(Tag::STYLE);
$ampCustomStyle->appendChild($this->createAttribute(Attribute::AMP_CUSTOM));
$this->head->appendChild($ampCustomStyle);
}
$this->properties['ampCustomStyle'] = $ampCustomStyle;
return $this->properties['ampCustomStyle'];
case 'ampCustomStyleByteCount':
if (!isset($this->properties['ampCustomStyle'])) {
$ampCustomStyle = $this->xpath->query(self::XPATH_AMP_CUSTOM_STYLE_QUERY, $this->head)->item(0);
if (!$ampCustomStyle instanceof Element) {
return 0;
}
$this->properties['ampCustomStyle'] = $ampCustomStyle;
}
if (!isset($this->properties['ampCustomStyleByteCount'])) {
$this->properties['ampCustomStyleByteCount'] =
strlen($this->properties['ampCustomStyle']->textContent);
}
return $this->properties['ampCustomStyleByteCount'];
case 'inlineStyleByteCount':
if (!isset($this->properties['inlineStyleByteCount'])) {
$this->properties['inlineStyleByteCount'] = 0;
$attributes = $this->xpath->query(
self::XPATH_INLINE_STYLE_ATTRIBUTES_QUERY,
$this->documentElement
);
foreach ($attributes as $attribute) {
$this->properties['inlineStyleByteCount'] += strlen($attribute->textContent);
}
}
return $this->properties['inlineStyleByteCount'];
case 'links':
if (! isset($this->properties['links'])) {
$this->properties['links'] = new LinkManager($this);
}
return $this->properties['links'];
}
// Mimic regular PHP behavior for missing notices.
trigger_error(self::PROPERTY_GETTER_ERROR_MESSAGE . $name, E_USER_NOTICE);
return null;
}