Debian Codegraph @

vendor/wikimedia/parsoid/src/Utils/DOMDataUtils.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Utils;
5
6 use Composer\Semver\Semver;
7 use stdClass;
8 use Wikimedia\Assert\Assert;
9 use Wikimedia\Assert\UnreachableException;
10 use Wikimedia\JsonCodec\Hint;
11 use Wikimedia\JsonCodec\JsonCodec;
12 use Wikimedia\Parsoid\Core\PageBundle;
13 use Wikimedia\Parsoid\DOM\Document;
14 use Wikimedia\Parsoid\DOM\Element;
15 use Wikimedia\Parsoid\DOM\Node;
16 use Wikimedia\Parsoid\NodeData\DataBag;
17 use Wikimedia\Parsoid\NodeData\DataMw;
18 use Wikimedia\Parsoid\NodeData\DataMwI18n;
19 use Wikimedia\Parsoid\NodeData\DataParsoid;
20 use Wikimedia\Parsoid\NodeData\I18nInfo;
21 use Wikimedia\Parsoid\NodeData\NodeData;
22 use Wikimedia\Parsoid\NodeData\TempData;
23
24 /**
25 * These helpers pertain to HTML and data attributes of a node.
26 */
27 class DOMDataUtils {
28 public const DATA_OBJECT_ATTR_NAME = 'data-object-id';
29
30 /**
31 * Return the dynamic "bag" property of a Document.
32 * @param Document $doc
33 * @return DataBag
34 */
35 public static function getBag( Document $doc ): DataBag {
36 // This is a dynamic property; it is not declared.
37 // All references go through here so we can suppress phan's complaint.
38 // @phan-suppress-next-line PhanUndeclaredProperty
39 return $doc->bag;
40 }
41
42 /**
43 * Return the JsonCodec used for rich attributes in a Document.
44 * @param Document $doc
45 * @return JsonCodec
46 */
47 public static function getCodec( Document $doc ): JsonCodec {
48 // This is a dynamic property; it is not declared.
49 // All references go through here so we can suppress phan's complaint.
50 // @phan-suppress-next-line PhanUndeclaredProperty
51 return $doc->codec;
52 }
53
54 public static function prepareDoc( Document $doc ): void {
55 // `bag` is a deliberate dynamic property; see DOMDataUtils::getBag()
56 // @phan-suppress-next-line PhanUndeclaredProperty dynamic property
57 $doc->bag = new DataBag();
58 // `codec` is a deliberate dynamic property; see DOMDataUtils::getCodec()
59 // @phan-suppress-next-line PhanUndeclaredProperty dynamic property
60 $doc->codec = new JsonCodec();
61
62 // Cache the head and body.
63 DOMCompat::getHead( $doc );
64 DOMCompat::getBody( $doc );
65 }
66
67 /**
68 * @param Document $topLevelDoc
69 * @param Document $childDoc
70 */
71 public static function prepareChildDoc( Document $topLevelDoc, Document $childDoc ) {
72 // @phan-suppress-next-line PhanUndeclaredProperty dynamic property
73 Assert::invariant( $topLevelDoc->bag instanceof DataBag, 'doc bag not set' );
74 // @phan-suppress-next-line PhanUndeclaredProperty dynamic property
75 $childDoc->bag = $topLevelDoc->bag;
76 // @phan-suppress-next-line PhanUndeclaredProperty dynamic property
77 $childDoc->codec = $topLevelDoc->codec;
78 }
79
80 /**
81 * Stash $obj in $doc and return an id for later retrieval
82 * @param Document $doc
83 * @param NodeData $obj
84 * @return int
85 */
86 public static function stashObjectInDoc( Document $doc, NodeData $obj ): int {
87 return self::getBag( $doc )->stashObject( $obj );
88 }
89
90 /**
91 * Does this node have any attributes?
92 * @param Element $node
93 * @return bool
94 */
95 public static function noAttrs( Element $node ): bool {
96 // The 'xmlns' attribute is "invisible" T235295
97 if ( $node->hasAttribute( 'xmlns' ) ) {
98 return false;
99 }
100 $numAttrs = count( $node->attributes );
101 return $numAttrs === 0 ||
102 ( $numAttrs === 1 && $node->hasAttribute( self::DATA_OBJECT_ATTR_NAME ) );
103 }
104
105 /**
106 * Get data object from a node.
107 *
108 * @param Element $node node
109 * @return NodeData
110 */
111 public static function getNodeData( Element $node ): NodeData {
112 if ( !$node->hasAttribute( self::DATA_OBJECT_ATTR_NAME ) ) {
113 // Initialized on first request
114 $dataObject = new NodeData;
115 self::setNodeData( $node, $dataObject );
116 return $dataObject;
117 }
118
119 $nodeId = DOMCompat::getAttribute( $node, self::DATA_OBJECT_ATTR_NAME );
120 if ( $nodeId !== null ) {
121 $dataObject = self::getBag( $node->ownerDocument )->getObject( (int)$nodeId );
122 } else {
123 $dataObject = null; // Make phan happy
124 }
125 Assert::invariant( isset( $dataObject ), 'Bogus nodeId given!' );
126 if ( isset( $dataObject->storedId ) ) {
127 throw new UnreachableException(
128 'Trying to fetch node data without loading! ' .
129 // If this node's data-object id is different from storedId,
130 // it will indicate that the data-parsoid object was shared
131 // between nodes without getting cloned. Useful for debugging.
132 'Node id: ' . $nodeId .
133 'Stored data: ' . PHPUtils::jsonEncode( $dataObject )
134 );
135 }
136 return $dataObject;
137 }
138
139 /**
140 * Set node data.
141 *
142 * @param Element $node node
143 * @param NodeData $data data
144 */
145 public static function setNodeData( Element $node, NodeData $data ): void {
146 $nodeId = self::stashObjectInDoc( $node->ownerDocument, $data );
147 $node->setAttribute( self::DATA_OBJECT_ATTR_NAME, (string)$nodeId );
148 }
149
150 /**
151 * Get data parsoid info from a node.
152 *
153 * @param Element $node node
154 * @return DataParsoid
155 */
156 public static function getDataParsoid( Element $node ): DataParsoid {
157 $data = self::getNodeData( $node );
158 $data->parsoid ??= new DataParsoid;
159 return $data->parsoid;
160 }
161
162 /**
163 * Set data parsoid info on a node.
164 *
165 * @param Element $node node
166 * @param DataParsoid $dp data-parsoid
167 */
168 public static function setDataParsoid( Element $node, DataParsoid $dp ): void {
169 $data = self::getNodeData( $node );
170 $data->parsoid = $dp;
171 }
172
173 /**
174 * Returns the i18n information of a node. This is in private access because it shouldn't
175 * typically be used directly; instead getDataNodeI18n and getDataAttrI18n should be used.
176 * @param Element $node
177 * @return DataMwI18n|null
178 */
179 private static function getDataMwI18n( Element $node ): ?DataMwI18n {
180 $data = self::getNodeData( $node );
181 // We won't set a default value for this property
182 return $data->i18n ?? null;
183 }
184
185 /**
186 * Sets the i18n information of a node. This is in private access because it shouldn't
187 * typically be used directly; instead setDataNodeI18n and setDataAttrI18n should be used.
188 */
189 private static function setDataMwI18n( Element $node, DataMwI18n $i18n ) {
190 $data = self::getNodeData( $node );
191 $data->i18n = $i18n;
192 }
193
194 /**
195 * Retrieves internationalization (i18n) information of a node (typically for localization)
196 * @param Element $node
197 * @return ?I18nInfo
198 */
199 public static function getDataNodeI18n( Element $node ): ?I18nInfo {
200 $data = self::getNodeData( $node );
201 // We won't set a default value for this property
202 if ( !isset( $data->i18n ) ) {
203 return null;
204 }
205 return $data->i18n->getSpanInfo();
206 }
207
208 /**
209 * Sets internationalization (i18n) information of a node, used for later localization
210 */
211 public static function setDataNodeI18n( Element $node, I18nInfo $i18n ) {
212 $data = self::getNodeData( $node );
213 $data->i18n ??= new DataMwI18n();
214 $data->i18n->setSpanInfo( $i18n );
215 }
216
217 /**
218 * Retrieves internationalization (i18n) information of an attribute value (typically for
219 * localization)
220 * @param Element $node
221 * @param string $name
222 * @return ?I18nInfo
223 */
224 public static function getDataAttrI18n( Element $node, string $name ): ?I18nInfo {
225 $data = self::getNodeData( $node );
226 // We won't set a default value for this property
227 if ( !isset( $data->i18n ) ) {
228 return null;
229 }
230 return $data->i18n->getAttributeInfo( $name );
231 }
232
233 /**
234 * Sets internationalization (i18n) information of a attribute value, used for later
235 * localization
236 * @param Element $node
237 * @param string $name
238 * @param I18nInfo $i18n
239 */
240 public static function setDataAttrI18n( Element $node, string $name, I18nInfo $i18n ) {
241 $data = self::getNodeData( $node );
242 $data->i18n ??= new DataMwI18n();
243 $data->i18n->setAttributeInfo( $name, $i18n );
244 }
245
246 /**
247 * @param Element $node
248 * @return array
249 */
250 public static function getDataAttrI18nNames( Element $node ): array {
251 $data = self::getNodeData( $node );
252 // We won't set a default value for this property
253 if ( !isset( $data->i18n ) ) {
254 return [];
255 }
256 return $data->i18n->getAttributeNames();
257 }
258
259 /**
260 * Get data diff info from a node.
261 *
262 * @param Element $node node
263 * @return ?stdClass
264 */
265 public static function getDataParsoidDiff( Element $node ): ?stdClass {
266 $data = self::getNodeData( $node );
267 // We won't set a default value for this property
268 return $data->parsoid_diff ?? null;
269 }
270
271 /**
272 * Set data diff info on a node.
273 *
274 * @param Element $node node
275 * @param ?stdClass $diffObj data-parsoid-diff object
276 */
277 public static function setDataParsoidDiff( Element $node, ?stdClass $diffObj ): void {
278 $data = self::getNodeData( $node );
279 $data->parsoid_diff = $diffObj;
280 }
281
282 /**
283 * Get data meta wiki info from a node.
284 *
285 * @param Element $node node
286 * @return DataMw
287 */
288 public static function getDataMw( Element $node ): DataMw {
289 $data = self::getNodeData( $node );
290 $data->mw ??= new DataMw;
291 return $data->mw;
292 }
293
294 /**
295 * Set data meta wiki info from a node.
296 *
297 * @param Element $node node
298 * @param ?DataMw $dmw data-mw
299 */
300 public static function setDataMw( Element $node, ?DataMw $dmw ): void {
301 $data = self::getNodeData( $node );
302 $data->mw = $dmw;
303 }
304
305 /**
306 * Check if there is meta wiki info in a node.
307 *
308 * @param Element $node node
309 * @return bool
310 */
311 public static function validDataMw( Element $node ): bool {
312 return (array)self::getDataMw( $node ) !== [];
313 }
314
315 /**
316 * Check if there is i18n info on a node (for the node or its attributes)
317 * @param Element $node
318 * @return bool
319 */
320 public static function validDataMwI18n( Element $node ): bool {
321 return self::getDataMwI18n( $node ) !== null;
322 }
323
324 /**
325 * Get an object from a JSON-encoded XML attribute on a node.
326 *
327 * @param Element $node node
328 * @param string $name name
329 * @param mixed $defaultVal
330 * @return mixed
331 */
332 public static function getJSONAttribute( Element $node, string $name, $defaultVal ) {
333 $attVal = DOMCompat::getAttribute( $node, $name );
334 if ( $attVal === null ) {
335 return $defaultVal;
336 }
337 $decoded = PHPUtils::jsonDecode( $attVal, false );
338 if ( $decoded !== null ) {
339 return $decoded;
340 } else {
341 error_log( 'ERROR: Could not decode attribute-val ' . $attVal .
342 ' for ' . $name . ' on node ' . DOMCompat::nodeName( $node ) );
343 return $defaultVal;
344 }
345 }
346
347 /**
348 * Set a attribute on a node with a JSON-encoded object.
349 *
350 * @param Element $node node
351 * @param string $name Name of the attribute.
352 * @param mixed $obj value of the attribute to
353 */
354 public static function setJSONAttribute( Element $node, string $name, $obj ): void {
355 $val = $obj === [] ? '{}' : PHPUtils::jsonEncode( $obj );
356 $node->setAttribute( $name, $val );
357 }
358
359 /**
360 * Set shadow info on a node; similar to the method on tokens.
361 * Records a key = value pair in data-parsoid['a'] property.
362 *
363 * This is effectively a call of 'setShadowInfoIfModified' except
364 * there is no original value, so by definition, $val is modified.
365 *
366 * @param Element $node node
367 * @param string $name Name of the attribute.
368 * @param mixed $val val
369 */
370 public static function setShadowInfo( Element $node, string $name, $val ): void {
371 $dp = self::getDataParsoid( $node );
372 $dp->a ??= [];
373 $dp->sa ??= [];
374 $dp->a[$name] = $val;
375 }
376
377 /**
378 * Set shadow info on a node; similar to the method on tokens.
379 *
380 * If the new value ($val) for the key ($name) is different from the
381 * original value ($origVal):
382 * - the new value is recorded in data-parsoid->a and
383 * - the original value is recorded in data-parsoid->sa
384 *
385 * @param Element $node node
386 * @param string $name Name of the attribute.
387 * @param mixed $val val
388 * @param mixed $origVal original value (null is a valid value)
389 * @param bool $skipOrig
390 */
391 public static function setShadowInfoIfModified(
392 Element $node, string $name, $val, $origVal, bool $skipOrig = false
393 ): void {
394 if ( !$skipOrig && ( $val === $origVal || $origVal === null ) ) {
395 return;
396 }
397 $dp = self::getDataParsoid( $node );
398 $dp->a ??= [];
399 $dp->sa ??= [];
400 // FIXME: This is a hack to not overwrite already shadowed info.
401 // We should either fix the call site that depends on this
402 // behaviour to do an explicit check, or double down on this
403 // by porting it to the token method as well.
404 if ( !$skipOrig && !array_key_exists( $name, $dp->a ) ) {
405 $dp->sa[$name] = $origVal;
406 }
407 $dp->a[$name] = $val;
408 }
409
410 /**
411 * Set an attribute and shadow info to a node.
412 * Similar to the method on tokens
413 *
414 * @param Element $node node
415 * @param string $name Name of the attribute.
416 * @param mixed $val value
417 * @param mixed $origVal original value
418 * @param bool $skipOrig
419 */
420 public static function addNormalizedAttribute(
421 Element $node, string $name, $val, $origVal, bool $skipOrig = false
422 ): void {
423 if ( $name === 'id' ) {
424 DOMCompat::setIdAttribute( $node, $val );
425 } else {
426 $node->setAttribute( $name, $val );
427 }
428 self::setShadowInfoIfModified( $node, $name, $val, $origVal, $skipOrig );
429 }
430
431 /**
432 * Get this document's pagebundle object
433 * @param Document $doc
434 * @return PageBundle
435 */
436 public static function getPageBundle( Document $doc ): PageBundle {
437 return self::getBag( $doc )->getPageBundle();
438 }
439
440 /**
441 * Removes the `data-*` attribute from a node, and migrates the data to the
442 * document's JSON store. Generates a unique id with the following format:
443 * ```
444 * mw<base64-encoded counter>
445 * ```
446 * but attempts to keep user defined ids.
447 *
448 * TODO: Note that $data is effective a partial PageBundle containing
449 * only the 'parsoid' and 'mw' properties.
450 *
451 * @param Element $node node
452 * @param stdClass $data data
453 * @param array $idIndex Index of used id attributes in the DOM
454 */
455 public static function storeInPageBundle(
456 Element $node, stdClass $data, array $idIndex
457 ): void {
458 $hints = self::getCodecHints();
459 $uid = DOMCompat::getAttribute( $node, 'id' );
460 $document = $node->ownerDocument;
461 $pb = self::getPageBundle( $document );
462 $codec = self::getCodec( $document );
463 $docDp = &$pb->parsoid;
464 $origId = $uid;
465 if ( $uid !== null && array_key_exists( $uid, $docDp['ids'] ) ) {
466 $uid = null;
467 }
468 if ( $uid === '' ) {
469 $uid = null;
470 }
471 if ( $uid === null ) {
472 do {
473 $docDp['counter'] += 1;
474 // PORT-FIXME: NOTE that we aren't updating the idIndex here because
475 // we are generating unique ids that will not conflict. In any case,
476 // the idIndex is a workaround for the PHP DOM's issues and we might
477 // switch out of this in the future anyway.
478 $uid = 'mw' . PHPUtils::counterToBase64( $docDp['counter'] );
479 } while ( isset( $idIndex[$uid] ) );
480 self::addNormalizedAttribute( $node, 'id', $uid, $origId );
481 }
482 // Convert from DataParsoid/DataMw objects to associative array
483 $docDp['ids'][$uid] = $codec->toJsonArray( $data->parsoid, $hints['data-parsoid'] );
484 if ( isset( $data->mw ) ) {
485 $pb->mw['ids'][$uid] = $codec->toJsonArray( $data->mw, $hints['data-mw'] );
486 }
487 }
488
489 /**
490 * Helper function to create static Hint objects for JsonCodec.
491 * @return array<Hint>
492 */
493 public static function getCodecHints(): array {
494 static $hints = null;
495 if ( $hints === null ) {
496 $hints = [
497 'data-parsoid' => Hint::build( DataParsoid::class, Hint::ALLOW_OBJECT ),
498 'data-mw' => Hint::build( DataMw::class, Hint::ALLOW_OBJECT ),
499 ];
500 }
501 return $hints;
502 }
503
504 /**
505 * @param Document $doc doc
506 * @param PageBundle $pb object
507 */
508 public static function injectPageBundle( Document $doc, PageBundle $pb ): void {
509 $script = DOMUtils::appendToHead( $doc, 'script', [
510 'id' => 'mw-pagebundle',
511 'type' => 'application/x-mw-pagebundle',
512 ] );
513 $script->appendChild( $doc->createTextNode( $pb->encodeForHeadElement() ) );
514 }
515
516 /**
517 * @param Document $doc doc
518 * @return stdClass|null
519 */
520 public static function extractPageBundle( Document $doc ): ?stdClass {
521 $pb = null;
522 $dpScriptElt = DOMCompat::getElementById( $doc, 'mw-pagebundle' );
523 if ( $dpScriptElt ) {
524 $dpScriptElt->parentNode->removeChild( $dpScriptElt );
525 // we actually want arrays in the page bundle rather than stdClasses; but we still
526 // want to access the object properties
527 $pb = (object)PHPUtils::jsonDecode( $dpScriptElt->textContent );
528 // Forward-compatibility with Parsoid 0.23
529 if ( isset( $pb->counters['nodedata'] ) && isset( $pb->parsoid ) ) {
530 $pb->parsoid['counter'] = $pb->counters['nodedata'];
531 }
532 }
533 return $pb;
534 }
535
536 /**
537 * Walk DOM from node downward calling loadDataAttribs
538 *
539 * @param Node $node node
540 * @param array $options options
541 */
542 public static function visitAndLoadDataAttribs( Node $node, array $options = [] ): void {
543 DOMUtils::visitDOM( $node, [ self::class, 'loadDataAttribs' ], $options );
544 }
545
546 /**
547 * These are intended be used on a document after post-processing, so that
548 * the underlying .dataobject is transparently applied (in the store case)
549 * and reloaded (in the load case), rather than worrying about keeping
550 * the attributes up-to-date throughout that phase. For the most part,
551 * using this.ppTo* should be sufficient and using these directly should be
552 * avoided.
553 *
554 * @param Node $node node
555 * @param array $options options
556 */
557 public static function loadDataAttribs( Node $node, array $options ): void {
558 if ( !( $node instanceof Element ) ) {
559 return;
560 }
561 // Reset the node data object's stored state, since we're reloading it
562 self::setNodeData( $node, new NodeData );
563 $codec = self::getCodec( $node->ownerDocument );
564 $dataParsoidAttr = DOMCompat::getAttribute( $node, 'data-parsoid' );
565 $dp = $codec->newFromJsonString(
566 $dataParsoidAttr ?? '{}', self::getCodecHints()['data-parsoid']
567 );
568 if ( !empty( $options['markNew'] ) ) {
569 $dp->setTempFlag( TempData::IS_NEW, $dataParsoidAttr === null );
570 }
571 self::setDataParsoid( $node, $dp );
572 $node->removeAttribute( 'data-parsoid' );
573
574 $dataMwAttr = DOMCompat::getAttribute( $node, 'data-mw' );
575 $dmw = $dataMwAttr === null ? null :
576 $codec->newFromJsonString( $dataMwAttr, self::getCodecHints()['data-mw'] );
577 self::setDataMw( $node, $dmw );
578 $node->removeAttribute( 'data-mw' );
579
580 $dpd = self::getJSONAttribute( $node, 'data-parsoid-diff', null );
581 self::setDataParsoidDiff( $node, $dpd );
582 $node->removeAttribute( 'data-parsoid-diff' );
583 $dataI18n = DOMCompat::getAttribute( $node, 'data-mw-i18n' );
584 if ( $dataI18n !== null ) {
585 $i18n = DataMwI18n::fromJson( PHPUtils::jsonDecode( $dataI18n, true ) );
586 self::setDataMwI18n( $node, $i18n );
587 $node->removeAttribute( 'data-mw-i18n' );
588 }
589 }
590
591 /**
592 * Builds an index of id attributes seen in the DOM
593 * @param Node $node
594 * @return array
595 */
596 public static function usedIdIndex( Node $node ): array {
597 $index = [];
598 DOMUtils::visitDOM( DOMCompat::getBody( $node->ownerDocument ),
599 static function ( Node $n, ?array $options = null ) use ( &$index ) {
600 if ( $n instanceof Element ) {
601 $id = DOMCompat::getAttribute( $n, 'id' );
602 if ( $id !== null ) {
603 $index[$id] = true;
604 }
605 }
606 },
607 []
608 );
609 return $index;
610 }
611
612 /**
613 * Walk DOM from node downward calling storeDataAttribs
614 *
615 * @param Node $node node
616 * @param array $options options
617 */
618 public static function visitAndStoreDataAttribs( Node $node, array $options = [] ): void {
619 // PORT-FIXME: storeDataAttribs calls storeInPageBundle which calls getElementById.
620 // PHP's `getElementById` implementation is broken, and we work around that by
621 // using Zest which uses XPath. So, getElementById call can be O(n) and calling it
622 // on on every element of the DOM via vistDOM here makes it O(n^2) instead of O(n).
623 // So, we work around that by building an index and avoiding getElementById entirely
624 // in storeInPageBundle.
625 if ( !empty( $options['storeInPageBundle'] ) ) {
626 $options['idIndex'] = self::usedIdIndex( $node );
627 }
628 DOMUtils::visitDOM( $node, [ self::class, 'storeDataAttribs' ], $options );
629 }
630
631 /**
632 * Copy data attributes from the bag to either JSON-encoded attributes on
633 * each node, or the page bundle, erasing the data-object-id attributes.
634 *
635 * @param Node $node node
636 * @param ?array $options options
637 * - discardDataParsoid: Discard DataParsoid objects instead of storing them
638 * - keepTmp: Preserve DataParsoid::$tmp
639 * - storeInPageBundle: If true, data will be stored in the page bundle
640 * instead of data-parsoid and data-mw.
641 * - env: The Env object required for various features
642 * - idIndex: Array of used ID attributes
643 */
644 public static function storeDataAttribs( Node $node, ?array $options = null ): void {
645 $hints = self::getCodecHints();
646 $options ??= [];
647 if ( !( $node instanceof Element ) ) {
648 return;
649 }
650 Assert::invariant( empty( $options['discardDataParsoid'] ) || empty( $options['keepTmp'] ),
651 'Conflicting options: discardDataParsoid and keepTmp are both enabled.' );
652 $codec = self::getCodec( $node->ownerDocument );
653 $dp = self::getDataParsoid( $node );
654 $discardDataParsoid = !empty( $options['discardDataParsoid'] );
655 if ( $dp->getTempFlag( TempData::IS_NEW ) ) {
656 // Only necessary to support the cite extension's getById,
657 // that's already been loaded once.
658 //
659 // This is basically a hack to ensure that DOMUtils.isNewElt
660 // continues to work since we effectively rely on the absence
661 // of data-parsoid to identify new elements. But, loadDataAttribs
662 // creates an empty {} if one doesn't exist. So, this hack
663 // ensures that a loadDataAttribs + storeDataAttribs pair don't
664 // dirty the node by introducing an empty data-parsoid attribute
665 // where one didn't exist before.
666 //
667 // Ideally, we'll find a better solution for this edge case later.
668 $discardDataParsoid = true;
669 }
670 $data = null;
671 if ( !$discardDataParsoid ) {
672 if ( empty( $options['keepTmp'] ) ) {
673 // @phan-suppress-next-line PhanTypeObjectUnsetDeclaredProperty
674 unset( $dp->tmp );
675 }
676
677 if ( !empty( $options['storeInPageBundle'] ) ) {
678 $data ??= new stdClass;
679 $data->parsoid = $dp;
680 } else {
681 $node->setAttribute(
682 'data-parsoid',
683 PHPUtils::jsonEncode(
684 $codec->toJsonArray( $dp, $hints['data-parsoid'] )
685 )
686 );
687 }
688 }
689
690 // Strip invalid data-mw attributes
691 if ( self::validDataMw( $node ) ) {
692 if (
693 !empty( $options['storeInPageBundle'] ) && isset( $options['env'] ) &&
694 // The pagebundle didn't have data-mw before 999.x
695 Semver::satisfies( $options['env']->getOutputContentVersion(), '^999.0.0' )
696 ) {
697 $data ??= new stdClass;
698 $data->mw = self::getDataMw( $node );
699 } else {
700 $node->setAttribute(
701 'data-mw',
702 PHPUtils::jsonEncode(
703 $codec->toJsonArray( self::getDataMw( $node ), $hints['data-mw'] )
704 )
705 );
706 }
707 }
708
709 if ( self::validDataMwI18n( $node ) ) {
710 self::setJSONAttribute( $node, 'data-mw-i18n', self::getDataMwI18n( $node ) );
711 }
712
713 // Store pagebundle
714 if ( $data !== null ) {
715 self::storeInPageBundle( $node, $data, $options['idIndex'] );
716 }
717
718 // Indicate that this node's data has been stored so that if we try
719 // to access it after the fact we're aware and remove the attribute
720 // since it's no longer needed.
721 $nd = self::getNodeData( $node );
722 $id = DOMCompat::getAttribute( $node, self::DATA_OBJECT_ATTR_NAME );
723 $nd->storedId = $id !== null ? intval( $id ) : null;
724 $node->removeAttribute( self::DATA_OBJECT_ATTR_NAME );
725 }
726
727 /**
728 * Clones a node and its data bag
729 * @param Element $elt
730 * @param bool $deep
731 * @return Element
732 */
733 public static function cloneNode( Element $elt, bool $deep ): Element {
734 $clone = $elt->cloneNode( $deep );
735 '@phan-var Element $clone'; // @var Element $clone
736 // We do not need to worry about $deep because a shallow clone does not have child nodes,
737 // so it's always cloning data on the cloned tree (which may be empty).
738 self::fixClonedData( $clone );
739 return $clone;
740 }
741
742 /**
743 * Recursively fixes cloned data from $elt: to avoid conflicts of element IDs, we clone the
744 * data and set it in the node with a new element ID (which setNodeData does).
745 * @param Element $elt
746 */
747 private static function fixClonedData( Element $elt ) {
748 if ( $elt->hasAttribute( self::DATA_OBJECT_ATTR_NAME ) ) {
749 self::setNodeData( $elt, self::getNodeData( $elt )->cloneNodeData() );
750 }
751 foreach ( $elt->childNodes as $child ) {
752 if ( $child instanceof Element ) {
753 self::fixClonedData( $child );
754 }
755 }
756 }
757 }