Debian Codegraph @

vendor/wikimedia/parsoid/src/Wt2Html/XMLSerializer.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Wt2Html;
5
6 use Wikimedia\Assert\Assert;
7 use Wikimedia\Parsoid\DOM\Comment;
8 use Wikimedia\Parsoid\DOM\Document;
9 use Wikimedia\Parsoid\DOM\DocumentFragment;
10 use Wikimedia\Parsoid\DOM\Element;
11 use Wikimedia\Parsoid\DOM\Node;
12 use Wikimedia\Parsoid\DOM\Text;
13 use Wikimedia\Parsoid\Utils\DOMCompat;
14 use Wikimedia\Parsoid\Utils\DOMDataUtils;
15 use Wikimedia\Parsoid\Utils\DOMUtils;
16 use Wikimedia\Parsoid\Utils\PHPUtils;
17 use Wikimedia\Parsoid\Utils\WTUtils;
18 use Wikimedia\Parsoid\Wikitext\Consts;
19
20 /**
21 * Stand-alone XMLSerializer for DOM3 documents.
22 *
23 * The output is identical to standard XHTML5 DOM serialization, as given by
24 * http://www.w3.org/TR/html-polyglot/
25 * and
26 * https://html.spec.whatwg.org/multipage/syntax.html#serialising-html-fragments
27 * except that we may quote attributes with single quotes, *only* where that would
28 * result in more compact output than the standard double-quoted serialization.
29 */
30 class XMLSerializer {
31
32 // https://html.spec.whatwg.org/#serialising-html-fragments
33 private static $alsoSerializeAsVoid = [
34 'basefont' => true,
35 'bgsound' => true,
36 'frame' => true,
37 'keygen' => true
38 ];
39
40 /**
41 * Elements that strip leading newlines
42 * http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#html-fragment-serialization-algorithm
43 */
44 private const NEWLINE_STRIPPING_ELEMENTS = [
45 'pre' => true,
46 'textarea' => true,
47 'listing' => true
48 ];
49
50 private const ENTITY_ENCODINGS = [
51 'single' => [ '<' => '&lt;', '&' => '&amp;', "'" => '&apos;' ],
52 'double' => [ '<' => '&lt;', '&' => '&amp;', '"' => '&quot;' ],
53 'xml' => [ '<' => '&lt;', '&' => '&amp;', "\u{0338}" => '&#x338;' ],
54 ];
55
56 /**
57 * HTML entity encoder helper.
58 * Only supports the few entities we'll actually need: <&'"
59 * @param string $raw Input string
60 * @param string $encodeChars Set of characters to encode, "single", "double", or "xml"
61 * @return string
62 */
63 private static function encodeHtmlEntities( string $raw, string $encodeChars ): string {
64 return strtr( $raw, self::ENTITY_ENCODINGS[$encodeChars] );
65 }
66
67 /**
68 * Modify the attribute array, replacing data-object-id with JSON
69 * encoded data. This is just a debugging hack, not to be confused with
70 * DOMDataUtils::storeDataAttribs()
71 *
72 * @param Element $node
73 * @param array &$attrs
74 * @param bool $keepTmp
75 * @param bool $storeDiffMark
76 */
77 private static function dumpDataAttribs(
78 Element $node, array &$attrs, bool $keepTmp, bool $storeDiffMark
79 ) {
80 if ( !isset( $attrs[DOMDataUtils::DATA_OBJECT_ATTR_NAME] ) ) {
81 return;
82 }
83 $codec = DOMDataUtils::getCodec( $node->ownerDocument );
84 $nd = DOMDataUtils::getNodeData( $node );
85 $pd = $nd->parsoid_diff ?? null;
86 if ( $pd && $storeDiffMark ) {
87 $attrs['data-parsoid-diff'] = PHPUtils::jsonEncode( $pd );
88 }
89 $dp = $nd->parsoid;
90 if ( $dp ) {
91 if ( !$keepTmp ) {
92 $dp = clone $dp;
93 // @phan-suppress-next-line PhanTypeObjectUnsetDeclaredProperty
94 unset( $dp->tmp );
95 }
96 $attrs['data-parsoid'] = $codec->toJsonString(
97 $dp, DOMDataUtils::getCodecHints()['data-parsoid']
98 );
99 }
100 $dmw = $nd->mw;
101 if ( $dmw ) {
102 $attrs['data-mw'] = $codec->toJsonString(
103 $dmw, DOMDataUtils::getCodecHints()['data-mw']
104 );
105 }
106 unset( $attrs[DOMDataUtils::DATA_OBJECT_ATTR_NAME] );
107 }
108
109 /**
110 * Serialize an HTML DOM3 node to XHTML. The XHTML and associated information will be fed
111 * step-by-step to the callback given in $accum.
112 * @param Node $node
113 * @param array $options See {@link XMLSerializer::serialize()}
114 * @param callable $accum function( $bit, $node, $flag )
115 * - $bit: (string) piece of HTML code
116 * - $node: (Node) ??
117 * - $flag: (string|null) 'start' or 'end' (??)
118 */
119 private static function serializeToString( Node $node, array $options, callable $accum ): void {
120 $smartQuote = $options['smartQuote'];
121 $saveData = $options['saveData'];
122 switch ( $node->nodeType ) {
123 case XML_ELEMENT_NODE:
124 DOMUtils::assertElt( $node );
125 $child = $node->firstChild;
126 $nodeName = DOMCompat::nodeName( $node );
127 $localName = $node->localName;
128 $accum( '<' . $localName, $node );
129 $attrs = DOMUtils::attributes( $node );
130 if ( $saveData ) {
131 self::dumpDataAttribs( $node, $attrs, $options['keepTmp'], $options['storeDiffMark'] );
132 }
133 foreach ( $attrs as $an => $av ) {
134 if ( $smartQuote
135 // More double quotes than single quotes in value?
136 && substr_count( $av, '"' ) > substr_count( $av, "'" )
137 ) {
138 // use single quotes
139 $accum( ' ' . $an . "='"
140 . self::encodeHtmlEntities( $av, 'single' ) . "'",
141 $node );
142 } else {
143 // use double quotes
144 $accum( ' ' . $an . '="'
145 . self::encodeHtmlEntities( $av, 'double' ) . '"',
146 $node );
147 }
148 }
149 if ( $child || (
150 !isset( Consts::$HTML['VoidTags'][$nodeName] ) &&
151 !isset( self::$alsoSerializeAsVoid[$nodeName] )
152 ) ) {
153 $accum( '>', $node, 'start' );
154 // if is cdata child node
155 if ( DOMUtils::isRawTextElement( $node ) ) {
156 // TODO: perform context-sensitive escaping?
157 // Currently this content is not normally part of our DOM, so
158 // no problem. If it was, we'd probably have to do some
159 // tag-specific escaping. Examples:
160 // * < to \u003c in <script>
161 // * < to \3c in <style>
162 // ...
163 if ( $child ) {
164 $accum( $child->nodeValue, $node );
165 }
166 } else {
167 if ( $child && isset( self::NEWLINE_STRIPPING_ELEMENTS[$localName] )
168 && $child->nodeType === XML_TEXT_NODE && str_starts_with( $child->nodeValue, "\n" )
169 ) {
170 /* If current node is a pre, textarea, or listing element,
171 * and the first child node of the element, if any, is a
172 * Text node whose character data has as its first
173 * character a U+000A LINE FEED (LF) character, then
174 * append a U+000A LINE FEED (LF) character. */
175 $accum( "\n", $node );
176 }
177 while ( $child ) {
178 self::serializeToString( $child, $options, $accum );
179 $child = $child->nextSibling;
180 }
181 }
182 $accum( '</' . $localName . '>', $node, 'end' );
183 } else {
184 $accum( '/>', $node, 'end' );
185 }
186 return;
187
188 case XML_DOCUMENT_NODE:
189 case XML_DOCUMENT_FRAG_NODE:
190 '@phan-var Document|DocumentFragment $node';
191 // @var Document|DocumentFragment $node
192 $child = $node->firstChild;
193 while ( $child ) {
194 self::serializeToString( $child, $options, $accum );
195 $child = $child->nextSibling;
196 }
197 return;
198
199 case XML_TEXT_NODE:
200 '@phan-var Text $node'; // @var Text $node
201 $accum( self::encodeHtmlEntities( $node->nodeValue, 'xml' ), $node );
202 return;
203
204 case XML_COMMENT_NODE:
205 // According to
206 // http://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml
207 // we could throw an exception here if node.data would not create
208 // a "well-formed" XML comment. But we use entity encoding when
209 // we create the comment node to ensure that node.data will always
210 // be okay; see DOMUtils.encodeComment().
211 '@phan-var Comment $node'; // @var Comment $node
212 $accum( '<!--' . $node->nodeValue . '-->', $node );
213 return;
214
215 default:
216 $accum( '??' . DOMCompat::nodeName( $node ), $node );
217 }
218 }
219
220 /**
221 * Add data to an output/memory array (used when serialize() was called with the
222 * captureOffsets flag).
223 * @param array &$out Output array, see {@link self::serialize()} for details on the
224 * 'html' and 'offset' fields. The other fields (positions are 0-based
225 * and refer to UTF-8 byte indices):
226 * - start: position in the HTML of the end of the opening tag of <body>
227 * - last: (Node) last "about sibling" of the currently processed element
228 * (see {@link WTUtils::getAboutSiblings()}
229 * - uid: the ID of the element
230 * @param string $bit A piece of the HTML string
231 * @param Node $node The DOM node $bit is a part of
232 * @param ?string $flag 'start' when receiving the final part of the opening tag
233 * of an element, 'end' when receiving the final part of the closing tag of an element
234 * or the final part of a self-closing element.
235 */
236 private static function accumOffsets(
237 array &$out, string $bit, Node $node, ?string $flag = null
238 ): void {
239 if ( DOMUtils::atTheTop( $node ) ) {
240 $out['html'] .= $bit;
241 if ( $flag === 'start' ) {
242 $out['start'] = strlen( $out['html'] );
243 } elseif ( $flag === 'end' ) {
244 $out['start'] = null;
245 $out['uid'] = null;
246 }
247 } elseif (
248 !( $node instanceof Element ) || $out['start'] === null ||
249 !DOMUtils::atTheTop( $node->parentNode )
250 ) {
251 // In case you're wondering, out.start may never be set if body
252 // isn't a child of the node passed to serializeToString, or if it
253 // is the node itself but options.innerXML is true.
254 $out['html'] .= $bit;
255 if ( $out['uid'] !== null ) {
256 $out['offsets'][$out['uid']]['html'][1] += strlen( $bit );
257 }
258 } else {
259 $newUid = DOMCompat::getAttribute( $node, 'id' );
260 // Encapsulated siblings don't have generated ids (but may have an id),
261 // so associate them with preceding content.
262 if ( $newUid && $newUid !== $out['uid'] && !$out['last'] ) {
263 if ( !WTUtils::isEncapsulationWrapper( $node ) ) {
264 $out['uid'] = $newUid;
265 } elseif ( WTUtils::isFirstEncapsulationWrapperNode( $node ) ) {
266 $about = DOMCompat::getAttribute( $node, 'about' );
267 $aboutSiblings = WTUtils::getAboutSiblings( $node, $about );
268 $out['last'] = end( $aboutSiblings );
269 $out['uid'] = $newUid;
270 }
271 }
272 if ( $out['last'] === $node && $flag === 'end' ) {
273 $out['last'] = null;
274 }
275 Assert::invariant( $out['uid'] !== null, 'uid cannot be null' );
276 if ( !isset( $out['offsets'][$out['uid']] ) ) {
277 $dt = strlen( $out['html'] ) - $out['start'];
278 $out['offsets'][$out['uid']] = [ 'html' => [ $dt, $dt ] ];
279 }
280 $out['html'] .= $bit;
281 $out['offsets'][$out['uid']]['html'][1] += strlen( $bit );
282 }
283 }
284
285 /**
286 * Serialize an HTML DOM3 node to an XHTML string.
287 *
288 * @param Node $node
289 * @param array $options
290 * - smartQuote (bool, default true): use single quotes for attributes when that's less escaping
291 * - innerXML (bool, default false): only serialize the contents of $node, exclude $node itself
292 * - captureOffsets (bool, default false): return tag position data (see below)
293 * - addDoctype (bool, default true): prepend a DOCTYPE when a full HTML document is serialized
294 * - saveData (bool, default false): Copy the NodeData into JSON attributes. This is for
295 * debugging purposes only, the normal code path is to use DOMDataUtils::storeDataAttribs().
296 * - keepTmp (bool, default false): When saving data, include DataParsoid::$tmp.
297 * @return array An array with the following data:
298 * - html: the serialized HTML
299 * - offsets: the start and end position of each element in the HTML, in a
300 * [ $uid => [ 'html' => [ $start, $end ] ], ... ] format where $uid is the element's
301 * Parsoid ID, $start is the 0-based index of the first character of the element and
302 * $end is the index of the first character of the opening tag of the next sibling element,
303 * or the index of the last character of the element's closing tag if there is no next
304 * sibling. The positions are relative to the end of the opening <body> tag
305 * (the DOCTYPE header is not counted), and only present when the captureOffsets flag is set.
306 */
307 public static function serialize( Node $node, array $options = [] ): array {
308 $options += [
309 'smartQuote' => true,
310 'innerXML' => false,
311 'captureOffsets' => false,
312 'addDoctype' => true,
313 'saveData' => false,
314 'keepTmp' => false,
315 'storeDiffMark' => false,
316 ];
317 if ( $node instanceof Document ) {
318 $node = $node->documentElement;
319 }
320 $out = [ 'html' => '', 'offsets' => [], 'start' => null, 'uid' => null, 'last' => null ];
321 $accum = $options['captureOffsets']
322 ? function ( string $bit, Node $node, ?string $flag = null ) use ( &$out ): void {
323 self::accumOffsets( $out, $bit, $node, $flag );
324 }
325 : static function ( string $bit ) use ( &$out ): void {
326 $out['html'] .= $bit;
327 };
328
329 if ( $options['innerXML'] ) {
330 for ( $child = $node->firstChild; $child; $child = $child->nextSibling ) {
331 self::serializeToString( $child, $options, $accum );
332 }
333 } else {
334 self::serializeToString( $node, $options, $accum );
335 }
336 // Ensure there's a doctype for documents.
337 if ( !$options['innerXML'] && DOMCompat::nodeName( $node ) === 'html' && $options['addDoctype'] ) {
338 $out['html'] = "<!DOCTYPE html>\n" . $out['html'];
339 }
340 // Drop the bookkeeping
341 unset( $out['start'], $out['uid'], $out['last'] );
342 if ( !$options['captureOffsets'] ) {
343 unset( $out['offsets'] );
344 }
345 return $out;
346 }
347
348 }