| 1 |
<?php |
| 2 |
declare( strict_types = 1 ); |
| 3 |
|
| 4 |
namespace Wikimedia\Parsoid\Wt2Html\DOM\Processors; |
| 5 |
|
| 6 |
use Error; |
| 7 |
use SplObjectStorage; |
| 8 |
use Wikimedia\Assert\Assert; |
| 9 |
use Wikimedia\Assert\UnreachableException; |
| 10 |
use Wikimedia\Parsoid\Config\Env; |
| 11 |
use Wikimedia\Parsoid\Core\DomSourceRange; |
| 12 |
use Wikimedia\Parsoid\Core\ElementRange; |
| 13 |
use Wikimedia\Parsoid\DOM\Document; |
| 14 |
use Wikimedia\Parsoid\DOM\Element; |
| 15 |
use Wikimedia\Parsoid\DOM\Node; |
| 16 |
use Wikimedia\Parsoid\DOM\Text; |
| 17 |
use Wikimedia\Parsoid\NodeData\DataParsoid; |
| 18 |
use Wikimedia\Parsoid\NodeData\TempData; |
| 19 |
use Wikimedia\Parsoid\NodeData\TemplateInfo; |
| 20 |
use Wikimedia\Parsoid\Utils\DOMCompat; |
| 21 |
use Wikimedia\Parsoid\Utils\DOMDataUtils; |
| 22 |
use Wikimedia\Parsoid\Utils\DOMUtils; |
| 23 |
use Wikimedia\Parsoid\Utils\PHPUtils; |
| 24 |
use Wikimedia\Parsoid\Utils\Utils; |
| 25 |
use Wikimedia\Parsoid\Utils\WTUtils; |
| 26 |
use Wikimedia\Parsoid\Wt2Html\Frame; |
| 27 |
|
| 28 |
/** |
| 29 |
* Template encapsulation happens in three steps. |
| 30 |
* |
| 31 |
* 1. findWrappableTemplateRanges |
| 32 |
* |
| 33 |
* Locate start and end metas. Walk upwards towards the root from both and |
| 34 |
* find a common ancestor A. The subtree rooted at A is now effectively the |
| 35 |
* scope of the dom template ouput. |
| 36 |
* |
| 37 |
* 2. findTopLevelNonOverlappingRanges |
| 38 |
* |
| 39 |
* Mark all nodes in a range and walk up to root from each range start to |
| 40 |
* determine overlaps, nesting. Merge overlapping and nested ranges to find |
| 41 |
* the subset of top-level non-overlapping ranges which will be wrapped as |
| 42 |
* individual units. |
| 43 |
* |
| 44 |
* 3. encapsulateTemplates |
| 45 |
* |
| 46 |
* For each non-overlapping range, |
| 47 |
* - compute a data-mw according to the DOM spec |
| 48 |
* - replace the start / end meta markers with transclusion type and data-mw |
| 49 |
* on the first DOM node |
| 50 |
* - add about ids on all top-level nodes of the range |
| 51 |
* |
| 52 |
* This is a simple high-level overview of the 3 steps to help understand this |
| 53 |
* code. |
| 54 |
* |
| 55 |
* FIXME: At some point, more of the details should be extracted and documented |
| 56 |
* in pseudo-code as an algorithm. |
| 57 |
* @module |
| 58 |
*/ |
| 59 |
class DOMRangeBuilder { |
| 60 |
|
| 61 |
private const MAP_TBODY_TR = [ |
| 62 |
'tbody' => true, |
| 63 |
'tr' => true |
| 64 |
]; |
| 65 |
|
| 66 |
/** @var Document */ |
| 67 |
private $document; |
| 68 |
|
| 69 |
/** @var Frame */ |
| 70 |
private $frame; |
| 71 |
|
| 72 |
/** @var Env */ |
| 73 |
protected $env; |
| 74 |
|
| 75 |
/** @var SplObjectStorage */ |
| 76 |
protected $nodeRanges; |
| 77 |
|
| 78 |
/** @var array<string|CompoundTemplateInfo>[] */ |
| 79 |
private $compoundTpls = []; |
| 80 |
|
| 81 |
/** @var string */ |
| 82 |
protected $traceType; |
| 83 |
|
| 84 |
public function __construct( |
| 85 |
Document $document, Frame $frame |
| 86 |
) { |
| 87 |
$this->document = $document; |
| 88 |
$this->frame = $frame; |
| 89 |
$this->env = $frame->getEnv(); |
| 90 |
$this->nodeRanges = new SplObjectStorage; |
| 91 |
$this->traceType = "tplwrap"; |
| 92 |
} |
| 93 |
|
| 94 |
protected function updateDSRForFirstRangeNode( Element $target, Element $source ): void { |
| 95 |
$srcDP = DOMDataUtils::getDataParsoid( $source ); |
| 96 |
$tgtDP = DOMDataUtils::getDataParsoid( $target ); |
| 97 |
|
| 98 |
// Since TSRs on template content tokens are cleared by the |
| 99 |
// template handler, all computed dsr values for template content |
| 100 |
// is always inferred from top-level content values and is safe. |
| 101 |
// So, do not overwrite a bigger end-dsr value. |
| 102 |
if ( isset( $srcDP->dsr->end ) && isset( $tgtDP->dsr->end ) && |
| 103 |
$tgtDP->dsr->end > $srcDP->dsr->end |
| 104 |
) { |
| 105 |
$tgtDP->dsr->start = $srcDP->dsr->start ?? null; |
| 106 |
} else { |
| 107 |
$tgtDP->dsr = clone $srcDP->dsr; |
| 108 |
$tgtDP->src = $srcDP->src ?? null; |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
/** |
| 113 |
* Get the DSR of the end of a DOMRange |
| 114 |
* |
| 115 |
* @param DOMRangeInfo $range |
| 116 |
* @return DomSourceRange|null |
| 117 |
*/ |
| 118 |
private static function getRangeEndDSR( DOMRangeInfo $range ): ?DomSourceRange { |
| 119 |
$endNode = $range->end; |
| 120 |
if ( $endNode instanceof Element ) { |
| 121 |
return DOMDataUtils::getDataParsoid( $endNode )->dsr ?? null; |
| 122 |
} else { |
| 123 |
// In the rare scenario where the last element of a range is not an ELEMENT, |
| 124 |
// extrapolate based on DSR of first leftmost sibling that is an ELEMENT. |
| 125 |
// We don't try any harder than this for now. |
| 126 |
$offset = 0; |
| 127 |
$n = $endNode->previousSibling; |
| 128 |
while ( $n && !( $n instanceof Element ) ) { |
| 129 |
if ( $n instanceof Text ) { |
| 130 |
$offset += strlen( $n->nodeValue ); |
| 131 |
} else { |
| 132 |
// A comment |
| 133 |
// @phan-suppress-next-line PhanTypeMismatchArgumentSuperType |
| 134 |
$offset += WTUtils::decodedCommentLength( $n ); |
| 135 |
} |
| 136 |
$n = $n->previousSibling; |
| 137 |
} |
| 138 |
|
| 139 |
$dsr = null; |
| 140 |
if ( $n ) { |
| 141 |
/** |
| 142 |
* The point of the above loop is to ensure we're working |
| 143 |
* with a Element if there is an $n. |
| 144 |
* |
| 145 |
* @var Element $n |
| 146 |
*/ |
| 147 |
'@phan-var Element $n'; |
| 148 |
$dsr = DOMDataUtils::getDataParsoid( $n )->dsr ?? null; |
| 149 |
} |
| 150 |
|
| 151 |
if ( $dsr && is_int( $dsr->end ?? null ) ) { |
| 152 |
$len = $endNode instanceof Text |
| 153 |
? strlen( $endNode->nodeValue ) |
| 154 |
// A comment |
| 155 |
// @phan-suppress-next-line PhanTypeMismatchArgumentSuperType |
| 156 |
: WTUtils::decodedCommentLength( $endNode ); |
| 157 |
$dsr = new DomSourceRange( |
| 158 |
$dsr->end + $offset, |
| 159 |
$dsr->end + $offset + $len, |
| 160 |
null, |
| 161 |
null |
| 162 |
); |
| 163 |
} |
| 164 |
|
| 165 |
return $dsr; |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
/** |
| 170 |
* Returns the range ID of a node - in the case of templates, its "about" attribute. |
| 171 |
* @param Element $node |
| 172 |
* @return string |
| 173 |
*/ |
| 174 |
protected function getRangeId( Element $node ): string { |
| 175 |
return DOMCompat::getAttribute( $node, "about" ); |
| 176 |
} |
| 177 |
|
| 178 |
/** |
| 179 |
* Find the common DOM ancestor of two DOM nodes. |
| 180 |
* |
| 181 |
* @param Element $startMeta |
| 182 |
* @param Element $endMeta |
| 183 |
* @param Element $endElem |
| 184 |
* @return DOMRangeInfo |
| 185 |
*/ |
| 186 |
private function getDOMRange( |
| 187 |
Element $startMeta, Element $endMeta, Element $endElem |
| 188 |
) { |
| 189 |
$range = $this->findEnclosingRange( $startMeta, $endMeta, $endElem ); |
| 190 |
$startsInFosterablePosn = DOMUtils::isFosterablePosition( $range->start ); |
| 191 |
$next = $range->start->nextSibling; |
| 192 |
|
| 193 |
// Detect empty content and handle them! |
| 194 |
if ( WTUtils::isTplMarkerMeta( $range->start ) && $next === $endElem ) { |
| 195 |
Assert::invariant( |
| 196 |
$range->start === $range->startElem, |
| 197 |
"Expected startElem to be same as range.start" |
| 198 |
); |
| 199 |
if ( $startsInFosterablePosn ) { |
| 200 |
// Expand range! |
| 201 |
$range->start = $range->end = $range->start->parentNode; |
| 202 |
$startsInFosterablePosn = false; |
| 203 |
} else { |
| 204 |
$emptySpan = $this->document->createElement( 'span' ); |
| 205 |
$range->start->parentNode->insertBefore( $emptySpan, $endElem ); |
| 206 |
} |
| 207 |
|
| 208 |
// Handle unwrappable content in fosterable positions |
| 209 |
// and expand template range, if required. |
| 210 |
// NOTE: Template marker meta tags are translated from comments |
| 211 |
// *after* the DOM has been built which is why they can show up in |
| 212 |
// fosterable positions in the DOM. |
| 213 |
} elseif ( $startsInFosterablePosn && |
| 214 |
( !( $range->start instanceof Element ) || |
| 215 |
( WTUtils::isTplMarkerMeta( $range->start ) && |
| 216 |
( !( $next instanceof Element ) || WTUtils::isTplMarkerMeta( $next ) ) ) |
| 217 |
) |
| 218 |
) { |
| 219 |
$rangeStartParent = $range->start->parentNode; |
| 220 |
|
| 221 |
// If we are in a table in a foster-element position, then all non-element |
| 222 |
// nodes will be white-space and comments. Skip over all of them and find |
| 223 |
// the first table content node. |
| 224 |
$noWS = true; |
| 225 |
$nodesToMigrate = []; |
| 226 |
$newStart = $range->start; |
| 227 |
$n = $range->start instanceof Element ? $next : $range->start; |
| 228 |
while ( !( $n instanceof Element ) ) { |
| 229 |
if ( $n instanceof Text ) { |
| 230 |
$noWS = false; |
| 231 |
} |
| 232 |
$nodesToMigrate[] = $n; |
| 233 |
$n = $n->nextSibling; |
| 234 |
$newStart = $n; |
| 235 |
} |
| 236 |
|
| 237 |
// As long as $newStart is a tr/tbody or we don't have whitespace |
| 238 |
// migrate $nodesToMigrate into $newStart. Pushing whitespace into |
| 239 |
// th/td/caption can change display semantics. |
| 240 |
if ( $newStart && ( $noWS || isset( self::MAP_TBODY_TR[DOMCompat::nodeName( $newStart )] ) ) ) { |
| 241 |
/** |
| 242 |
* The point of the above loop is to ensure we're working |
| 243 |
* with a Element if there is a $newStart. |
| 244 |
* |
| 245 |
* @var Element $newStart |
| 246 |
*/ |
| 247 |
'@phan-var Element $newStart'; |
| 248 |
$insertPosition = $newStart->firstChild; |
| 249 |
foreach ( $nodesToMigrate as $n ) { |
| 250 |
$newStart->insertBefore( $n, $insertPosition ); |
| 251 |
} |
| 252 |
$range->start = $newStart; |
| 253 |
// Update dsr to point to original start |
| 254 |
$this->updateDSRForFirstRangeNode( $range->start, $range->startElem ); |
| 255 |
} else { |
| 256 |
// If not, we are forced to expand the template range. |
| 257 |
$range->start = $range->end = $rangeStartParent; |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
// Ensure range->start is an element node since we want to |
| 262 |
// add/update the data-parsoid attribute to it. |
| 263 |
if ( !( $range->start instanceof Element ) ) { |
| 264 |
$span = $this->document->createElement( 'span' ); |
| 265 |
$range->start->parentNode->insertBefore( $span, $range->start ); |
| 266 |
$span->appendChild( $range->start ); |
| 267 |
$range->start = $span; |
| 268 |
$this->updateDSRForFirstRangeNode( $range->start, $range->startElem ); |
| 269 |
} |
| 270 |
|
| 271 |
$range->start = $this->getStartConsideringFosteredContent( $range->start ); |
| 272 |
|
| 273 |
// Use the negative test since it doesn't mark the range as flipped |
| 274 |
// if range.start === range.end |
| 275 |
if ( !DOMUtils::inSiblingOrder( $range->start, $range->end ) ) { |
| 276 |
// In foster-parenting situations, the end-meta tag (and hence range.end) |
| 277 |
// can show up before the range.start which would be the table itself. |
| 278 |
// So, we record this info for later analysis. |
| 279 |
$range->flipped = true; |
| 280 |
} |
| 281 |
|
| 282 |
$this->env->log( |
| 283 |
"trace/{$this->traceType}/findranges", |
| 284 |
static function () use ( &$range ) { |
| 285 |
$msg = ''; |
| 286 |
$dp1 = DOMDataUtils::getDataParsoid( $range->start ); |
| 287 |
$dp2 = DOMDataUtils::getDataParsoid( $range->end ); |
| 288 |
$tmp1 = $dp1->tmp; |
| 289 |
$tmp2 = $dp2->tmp; |
| 290 |
$dp1->tmp = null; |
| 291 |
$dp2->tmp = null; |
| 292 |
$msg .= "\n----------------------------------------------"; |
| 293 |
$msg .= "\nFound range : " . $range->id . '; flipped? ' . ( (string)$range->flipped ) . |
| 294 |
'; offset: ' . $range->startOffset; |
| 295 |
$msg .= "\nstart-elem : " . DOMCompat::getOuterHTML( $range->startElem ) . '; DP: ' . |
| 296 |
PHPUtils::jsonEncode( DOMDataUtils::getDataParsoid( $range->startElem ) ); |
| 297 |
$msg .= "\nend-elem : " . DOMCompat::getOuterHTML( $range->endElem ) . '; DP: ' . |
| 298 |
PHPUtils::jsonEncode( DOMDataUtils::getDataParsoid( $range->endElem ) ); |
| 299 |
$msg .= "\nstart : [TAG_ID " . ( $tmp1->tagId ?? '?' ) . ']: ' . |
| 300 |
DOMCompat::getOuterHTML( $range->start ) . |
| 301 |
'; DP: ' . PHPUtils::jsonEncode( $dp1 ); |
| 302 |
$msg .= "\nend : [TAG_ID " . ( $tmp2->tagId ?? '?' ) . ']: ' . |
| 303 |
DOMCompat::getOuterHTML( $range->end ) . |
| 304 |
'; DP: ' . PHPUtils::jsonEncode( $dp2 ); |
| 305 |
$msg .= "\n----------------------------------------------"; |
| 306 |
$dp1->tmp = $tmp1; |
| 307 |
$dp2->tmp = $tmp2; |
| 308 |
return $msg; |
| 309 |
} |
| 310 |
); |
| 311 |
|
| 312 |
return $range; |
| 313 |
} |
| 314 |
|
| 315 |
/** |
| 316 |
* Returns the current node if it's not just after fostered content, the first node |
| 317 |
* of fostered content otherwise. |
| 318 |
* @param Node $node |
| 319 |
* @return Node |
| 320 |
*/ |
| 321 |
protected function getStartConsideringFosteredContent( Node $node ): Node { |
| 322 |
if ( DOMCompat::nodeName( $node ) === 'table' ) { |
| 323 |
// If we have any fostered content, include it as well. |
| 324 |
for ( $previousSibling = $node->previousSibling; |
| 325 |
$previousSibling instanceof Element && |
| 326 |
!empty( DOMDataUtils::getDataParsoid( $previousSibling )->fostered ); |
| 327 |
$previousSibling = $node->previousSibling |
| 328 |
) { |
| 329 |
$node = $previousSibling; |
| 330 |
} |
| 331 |
} |
| 332 |
return $node; |
| 333 |
} |
| 334 |
|
| 335 |
private static function stripStartMeta( Element $meta ): void { |
| 336 |
if ( DOMCompat::nodeName( $meta ) === 'meta' ) { |
| 337 |
$meta->parentNode->removeChild( $meta ); |
| 338 |
} else { |
| 339 |
// Remove mw:* from the typeof. |
| 340 |
$type = DOMCompat::getAttribute( $meta, 'typeof' ); |
| 341 |
if ( $type !== null ) { |
| 342 |
$type = preg_replace( '/(?:^|\s)mw:[^\/]*(\/\S+|(?=$|\s))/D', '', $type ); |
| 343 |
$meta->setAttribute( 'typeof', $type ); |
| 344 |
} |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
private static function findToplevelEnclosingRange( |
| 349 |
array $nestingInfo, string $startId |
| 350 |
): ?string { |
| 351 |
// Walk up the implicit nesting tree to find the |
| 352 |
// top-level range within which rId is nested. |
| 353 |
// No cycles can exist since they have been suppressed. |
| 354 |
$visited = []; |
| 355 |
$rId = $startId; |
| 356 |
while ( isset( $nestingInfo[$rId] ) ) { |
| 357 |
if ( isset( $visited[$rId] ) ) { |
| 358 |
throw new Error( "Found a cycle in tpl-range nesting where there shouldn't have been one." ); |
| 359 |
} |
| 360 |
$visited[$rId] = true; |
| 361 |
$rId = $nestingInfo[$rId]; |
| 362 |
} |
| 363 |
return $rId === $startId ? null : $rId; |
| 364 |
} |
| 365 |
|
| 366 |
/** |
| 367 |
* Add a template to $this->compoundTpls |
| 368 |
* |
| 369 |
* @param string $compoundTplId |
| 370 |
* @param DOMRangeInfo $range |
| 371 |
* @param TemplateInfo $templateInfo |
| 372 |
*/ |
| 373 |
private function recordTemplateInfo( |
| 374 |
string $compoundTplId, DOMRangeInfo $range, TemplateInfo $templateInfo |
| 375 |
): void { |
| 376 |
$this->compoundTpls[$compoundTplId] ??= []; |
| 377 |
|
| 378 |
// Record template args info along with any intervening wikitext |
| 379 |
// between templates that are part of the same compound structure. |
| 380 |
/** @var array $tplArray */ |
| 381 |
$tplArray = &$this->compoundTpls[$compoundTplId]; |
| 382 |
$dp = DOMDataUtils::getDataParsoid( $range->startElem ); |
| 383 |
$dsr = $dp->dsr; |
| 384 |
|
| 385 |
if ( count( $tplArray ) > 0 ) { |
| 386 |
$prevTplInfo = PHPUtils::lastItem( $tplArray ); |
| 387 |
if ( $prevTplInfo->dsr->end < $dsr->start ) { |
| 388 |
$width = $dsr->start - $prevTplInfo->dsr->end; |
| 389 |
$tplArray[] = PHPUtils::safeSubstr( |
| 390 |
$this->frame->getSrcText(), $prevTplInfo->dsr->end, $width ); |
| 391 |
} |
| 392 |
} |
| 393 |
|
| 394 |
if ( !empty( $dp->unwrappedWT ) ) { |
| 395 |
$tplArray[] = (string)$dp->unwrappedWT; |
| 396 |
} |
| 397 |
|
| 398 |
// Get rid of src-offsets since they aren't needed anymore. |
| 399 |
foreach ( $templateInfo->paramInfos as $pi ) { |
| 400 |
$pi->srcOffsets = null; |
| 401 |
} |
| 402 |
$tplArray[] = new CompoundTemplateInfo( |
| 403 |
$dsr, $templateInfo, DOMUtils::hasTypeOf( $range->startElem, 'mw:Param' ) |
| 404 |
); |
| 405 |
} |
| 406 |
|
| 407 |
/** |
| 408 |
* Determine whether adding the given range would introduce a cycle in the |
| 409 |
* subsumedRanges graph. |
| 410 |
* |
| 411 |
* Nesting cycles with multiple ranges can show up because of foster |
| 412 |
* parenting scenarios if they are not detected and suppressed. |
| 413 |
* |
| 414 |
* @param string $start The ID of the new range |
| 415 |
* @param string $end The ID of the other range |
| 416 |
* @param string[] $subsumedRanges The subsumed ranges graph, encoded as an |
| 417 |
* array in which each element maps one string range ID to another range ID |
| 418 |
* @return bool |
| 419 |
*/ |
| 420 |
private static function introducesCycle( string $start, string $end, array $subsumedRanges ): bool { |
| 421 |
$visited = [ $start => true ]; |
| 422 |
$elt = $subsumedRanges[$end] ?? null; |
| 423 |
while ( $elt ) { |
| 424 |
if ( !empty( $visited[$elt] ) ) { |
| 425 |
return true; |
| 426 |
} |
| 427 |
$elt = $subsumedRanges[$elt] ?? null; |
| 428 |
} |
| 429 |
return false; |
| 430 |
} |
| 431 |
|
| 432 |
/** |
| 433 |
* Determine whether DOM ranges overlap. |
| 434 |
* |
| 435 |
* The `inSiblingOrder` check here is sufficient to determine overlaps |
| 436 |
* because the algorithm in `findWrappableTemplateRanges` will put the |
| 437 |
* start/end elements for intersecting ranges on the same plane and prev/ |
| 438 |
* curr are in textual order (which translates to dom order). |
| 439 |
* |
| 440 |
* @param DOMRangeInfo $prev |
| 441 |
* @param DOMRangeInfo $curr |
| 442 |
* @return bool |
| 443 |
*/ |
| 444 |
private static function rangesOverlap( DOMRangeInfo $prev, DOMRangeInfo $curr ): bool { |
| 445 |
$prevEnd = ( !$prev->flipped ) ? $prev->end : $prev->start; |
| 446 |
$currStart = ( !$curr->flipped ) ? $curr->start : $curr->end; |
| 447 |
return DOMUtils::inSiblingOrder( $currStart, $prevEnd ); |
| 448 |
} |
| 449 |
|
| 450 |
/** |
| 451 |
* Identify the elements of $tplRanges that are non-overlapping. |
| 452 |
* Record template info in $this->compoundTpls as we go. |
| 453 |
* |
| 454 |
* @param Node $docRoot |
| 455 |
* @param DOMRangeInfo[] $tplRanges The potentially overlapping ranges |
| 456 |
* @return DOMRangeInfo[] The non-overlapping ranges |
| 457 |
*/ |
| 458 |
public function findTopLevelNonOverlappingRanges( Node $docRoot, array $tplRanges ): array { |
| 459 |
// For each node, assign an attribute that is a record of all |
| 460 |
// tpl ranges it belongs to at the top-level. |
| 461 |
foreach ( $tplRanges as $r ) { |
| 462 |
$n = !$r->flipped ? $r->start : $r->end; |
| 463 |
$e = !$r->flipped ? $r->end : $r->start; |
| 464 |
|
| 465 |
while ( $n ) { |
| 466 |
if ( $n instanceof Element ) { |
| 467 |
$this->addNodeRange( $n, $r ); |
| 468 |
// Done |
| 469 |
if ( $n === $e ) { |
| 470 |
break; |
| 471 |
} |
| 472 |
} |
| 473 |
|
| 474 |
$n = $n->nextSibling; |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
// In the first pass over `numRanges` below, `subsumedRanges` is used to |
| 479 |
// record purely the nested ranges. However, in the second pass, we also |
| 480 |
// add the relationships between overlapping ranges so that |
| 481 |
// `findToplevelEnclosingRange` can use that information to add `argInfo` |
| 482 |
// to the right `compoundTpls`. This scenario can come up when you have |
| 483 |
// three ranges, 1 intersecting with 2 but not 3, and 3 nested in 2. |
| 484 |
$subsumedRanges = []; |
| 485 |
|
| 486 |
// For each range r:(s, e), walk up from s --> docRoot and if any of |
| 487 |
// these nodes have tpl-ranges (besides r itself) assigned to them, |
| 488 |
// then r is nested in those other templates and can be ignored. |
| 489 |
foreach ( $tplRanges as $r ) { |
| 490 |
$n = $r->start; |
| 491 |
|
| 492 |
while ( $n !== $docRoot ) { |
| 493 |
$ranges = $this->getNodeRanges( $n ); |
| 494 |
if ( $ranges ) { |
| 495 |
if ( $n !== $r->start ) { |
| 496 |
// 'r' is nested for sure |
| 497 |
// Record the outermost range in which 'r' is nested. |
| 498 |
$outermostId = null; |
| 499 |
$outermostOffset = null; |
| 500 |
foreach ( $ranges as $rangeId => $range ) { |
| 501 |
if ( $outermostId === null |
| 502 |
|| $range->startOffset < $outermostOffset |
| 503 |
) { |
| 504 |
$outermostId = $rangeId; |
| 505 |
$outermostOffset = $range->startOffset; |
| 506 |
} |
| 507 |
} |
| 508 |
$subsumedRanges[$r->id] = (string)$outermostId; |
| 509 |
break; |
| 510 |
} else { |
| 511 |
// n === r.start |
| 512 |
// |
| 513 |
// We have to make sure this is not an overlap scenario. |
| 514 |
// Find the ranges that r.start and r.end belong to and |
| 515 |
// compute their intersection. If this intersection has |
| 516 |
// another tpl range besides r itself, we have a winner! |
| 517 |
// |
| 518 |
// The code below does the above check efficiently. |
| 519 |
$eTpls = $this->getNodeRanges( $r->end ); |
| 520 |
$foundNesting = false; |
| 521 |
|
| 522 |
foreach ( $ranges as $otherId => $other ) { |
| 523 |
// - Don't record nesting cycles. |
| 524 |
// - Record the outermost range in which 'r' is nested in. |
| 525 |
if ( $otherId !== $r->id && |
| 526 |
!empty( $eTpls[$otherId] ) && |
| 527 |
// When we have identical ranges, pick the range with |
| 528 |
// the larger offset to be subsumed. |
| 529 |
( $r->start !== $other->start || |
| 530 |
$r->end !== $other->end || |
| 531 |
$other->startOffset < $r->startOffset |
| 532 |
) && |
| 533 |
!self::introducesCycle( $r->id, (string)$otherId, $subsumedRanges ) |
| 534 |
) { |
| 535 |
$foundNesting = true; |
| 536 |
if ( !isset( $subsumedRanges[$r->id] ) || |
| 537 |
$other->startOffset < $ranges[$subsumedRanges[$r->id]]->startOffset |
| 538 |
) { |
| 539 |
$subsumedRanges[$r->id] = (string)$otherId; |
| 540 |
} |
| 541 |
} |
| 542 |
} |
| 543 |
|
| 544 |
if ( $foundNesting ) { |
| 545 |
// 'r' is nested |
| 546 |
break; |
| 547 |
} |
| 548 |
} |
| 549 |
} |
| 550 |
|
| 551 |
// Move up |
| 552 |
$n = $n->parentNode; |
| 553 |
} |
| 554 |
} |
| 555 |
|
| 556 |
// Sort by start offset in source wikitext |
| 557 |
usort( $tplRanges, static function ( $r1, $r2 ) { |
| 558 |
return $r1->startOffset - $r2->startOffset; |
| 559 |
} ); |
| 560 |
|
| 561 |
// Since the tpl ranges are sorted in textual order (by start offset), |
| 562 |
// it is sufficient to only look at the most recent template to see |
| 563 |
// if the current one overlaps with the previous one. |
| 564 |
// |
| 565 |
// This works because we've already identify nested ranges and can ignore them. |
| 566 |
|
| 567 |
$newRanges = []; |
| 568 |
$prev = null; |
| 569 |
|
| 570 |
foreach ( $tplRanges as $r ) { |
| 571 |
$endTagToRemove = null; |
| 572 |
$startTagToStrip = null; |
| 573 |
|
| 574 |
// Extract tplargInfo |
| 575 |
$tmp = DOMDataUtils::getDataParsoid( $r->startElem )->getTemp(); |
| 576 |
$templateInfo = $tmp->tplarginfo ?? null; |
| 577 |
|
| 578 |
$this->verifyTplInfoExpectation( $templateInfo, $tmp ); |
| 579 |
|
| 580 |
$this->env->log( "trace/{$this->traceType}/merge", static function () use ( &$DOMDataUtils, &$r ) { |
| 581 |
$msg = ''; |
| 582 |
$dp1 = DOMDataUtils::getDataParsoid( $r->start ); |
| 583 |
$dp2 = DOMDataUtils::getDataParsoid( $r->end ); |
| 584 |
$tmp1 = $dp1->tmp; |
| 585 |
$tmp2 = $dp2->tmp; |
| 586 |
$dp1->tmp = null; |
| 587 |
$dp2->tmp = null; |
| 588 |
$msg .= "\n##############################################"; |
| 589 |
$msg .= "\nrange " . $r->id . '; r-start-elem: ' . DOMCompat::getOuterHTML( $r->startElem ) . |
| 590 |
'; DP: ' . PHPUtils::jsonEncode( DOMDataUtils::getDataParsoid( $r->startElem ) ); |
| 591 |
$msg .= "\nrange " . $r->id . '; r-end-elem: ' . DOMCompat::getOuterHTML( $r->endElem ) . |
| 592 |
'; DP: ' . PHPUtils::jsonEncode( DOMDataUtils::getDataParsoid( $r->endElem ) ); |
| 593 |
$msg .= "\nrange " . $r->id . '; r-start: [TAG_ID ' . ( $tmp1->tagId ?? '?' ) . ']: ' . |
| 594 |
DOMCompat::getOuterHTML( $r->start ) . '; DP: ' . PHPUtils::jsonEncode( $dp1 ); |
| 595 |
$msg .= "\nrange " . $r->id . '; r-end: [TAG_ID ' . ( $tmp2->tagId ?? '?' ) . ']: ' . |
| 596 |
DOMCompat::getOuterHTML( $r->end ) . '; DP: ' . PHPUtils::jsonEncode( $dp2 ); |
| 597 |
$msg .= "\n----------------------------------------------"; |
| 598 |
$dp1->tmp = $tmp1; |
| 599 |
$dp2->tmp = $tmp2; |
| 600 |
return $msg; |
| 601 |
} ); |
| 602 |
|
| 603 |
$enclosingRangeId = self::findToplevelEnclosingRange( |
| 604 |
$subsumedRanges, $r->id |
| 605 |
); |
| 606 |
if ( $enclosingRangeId ) { |
| 607 |
$this->env->log( "trace/{$this->traceType}/merge", '--nested in ', $enclosingRangeId, '--' ); |
| 608 |
|
| 609 |
// Nested -- ignore r |
| 610 |
$startTagToStrip = $r->startElem; |
| 611 |
$endTagToRemove = $r->endElem; |
| 612 |
if ( $templateInfo ) { |
| 613 |
// 'r' is nested in 'enclosingRange' at the top-level |
| 614 |
// So, enclosingRange gets r's argInfo |
| 615 |
$this->recordTemplateInfo( $enclosingRangeId, $r, $templateInfo ); |
| 616 |
} |
| 617 |
} elseif ( $prev && self::rangesOverlap( $prev, $r ) ) { |
| 618 |
// In the common case, in overlapping scenarios, r.start is |
| 619 |
// identical to prev.end. However, in fostered content scenarios, |
| 620 |
// there can true overlap of the ranges. |
| 621 |
$this->env->log( "trace/{$this->traceType}/merge", '--overlapped--' ); |
| 622 |
|
| 623 |
// See comment above, where `subsumedRanges` is defined. |
| 624 |
$subsumedRanges[$r->id] = $prev->id; |
| 625 |
|
| 626 |
// Overlapping ranges. |
| 627 |
// r is the regular kind |
| 628 |
// Merge r with prev |
| 629 |
|
| 630 |
// Note that if a table comes from a template, a foster box isn't |
| 631 |
// emitted so the enclosure isn't guaranteed. In pathological |
| 632 |
// cases, like where the table end tag isn't emitted, we can still |
| 633 |
// end up with flipped ranges if the template end marker gets into |
| 634 |
// a fosterable position (which can still happen despite being |
| 635 |
// emitted as a comment). |
| 636 |
Assert::invariant( !$r->flipped, |
| 637 |
'Flipped range should have been enclosed.' |
| 638 |
); |
| 639 |
|
| 640 |
$startTagToStrip = $r->startElem; |
| 641 |
$endTagToRemove = $prev->endElem; |
| 642 |
|
| 643 |
$prev->end = $r->end; |
| 644 |
$prev->endElem = $r->endElem; |
| 645 |
if ( WTUtils::isMarkerAnnotation( $r->endElem ) ) { |
| 646 |
$endDataMw = DOMDataUtils::getDataMw( $r->endElem ); |
| 647 |
$endDataMw->rangeId = $r->id; |
| 648 |
$prev->extendedByOverlapMerge = true; |
| 649 |
} |
| 650 |
|
| 651 |
// Update compoundTplInfo |
| 652 |
if ( $templateInfo ) { |
| 653 |
$this->recordTemplateInfo( $prev->id, $r, $templateInfo ); |
| 654 |
} |
| 655 |
} else { |
| 656 |
$this->env->log( "trace/{$this->traceType}/merge", '--normal--' ); |
| 657 |
|
| 658 |
// Default -- no overlap |
| 659 |
// Emit the merged range |
| 660 |
$newRanges[] = $r; |
| 661 |
$prev = $r; |
| 662 |
|
| 663 |
// Update compoundTpls |
| 664 |
if ( $templateInfo ) { |
| 665 |
$this->recordTemplateInfo( $r->id, $r, $templateInfo ); |
| 666 |
} |
| 667 |
} |
| 668 |
|
| 669 |
if ( $endTagToRemove ) { |
| 670 |
// Remove start and end meta-tags |
| 671 |
// Not necessary to remove the start tag, but good to cleanup |
| 672 |
$endTagToRemove->parentNode->removeChild( $endTagToRemove ); |
| 673 |
self::stripStartMeta( $startTagToStrip ); |
| 674 |
} |
| 675 |
} |
| 676 |
|
| 677 |
return $newRanges; |
| 678 |
} |
| 679 |
|
| 680 |
/** |
| 681 |
* Note that the case of nodeName varies with DOM implementation. This |
| 682 |
* method currently forces the name nodeName to uppercase. In the future |
| 683 |
* we can/should switch to using the "native" case of the DOM |
| 684 |
* implementation; we do a case-insensitive match (by converting the result |
| 685 |
* to the "native" case of the DOM implementation) in |
| 686 |
* EncapsulatedContentHandler when this value is used. |
| 687 |
* @param DOMRangeInfo $range |
| 688 |
* @return string|null nodeName with an optional "_$stx" suffix. |
| 689 |
*/ |
| 690 |
private static function findFirstTemplatedNode( DOMRangeInfo $range ): ?string { |
| 691 |
$firstNode = $range->start; |
| 692 |
|
| 693 |
// Skip tpl marker meta |
| 694 |
if ( WTUtils::isTplMarkerMeta( $firstNode ) ) { |
| 695 |
$firstNode = $firstNode->nextSibling; |
| 696 |
} |
| 697 |
|
| 698 |
// Walk past fostered nodes since they came from within a table |
| 699 |
// Note that this is not foolproof because in some scenarios, |
| 700 |
// fostered content is not marked up. Ex: when a table is templated, |
| 701 |
// and content from the table is fostered. |
| 702 |
$dp = DOMDataUtils::getDataParsoid( $firstNode ); |
| 703 |
while ( !empty( $dp->fostered ) ) { |
| 704 |
$firstNode = $firstNode->nextSibling; |
| 705 |
/** @var Element $firstNode */ |
| 706 |
DOMUtils::assertElt( $firstNode ); |
| 707 |
$dp = DOMDataUtils::getDataParsoid( $firstNode ); |
| 708 |
} |
| 709 |
|
| 710 |
// FIXME: It is harder to use META as a node name since this is a generic |
| 711 |
// placeholder for a whole bunch of things each of which has its own |
| 712 |
// newline constraint requirements. So, for now, I am skipping that |
| 713 |
// can of worms to prevent confusing the serializer with an overloaded |
| 714 |
// tag name. |
| 715 |
if ( DOMCompat::nodeName( $firstNode ) === 'meta' ) { |
| 716 |
return null; |
| 717 |
} |
| 718 |
|
| 719 |
// FIXME spec-compliant values would be upper-case, this is just a workaround |
| 720 |
// for current PHP DOM implementation and could be removed in the future |
| 721 |
// See discussion in the method comment above. |
| 722 |
$nodeName = mb_strtoupper( DOMCompat::nodeName( $firstNode ), "UTF-8" ); |
| 723 |
|
| 724 |
return !empty( $dp->stx ) ? $nodeName . '_' . $dp->stx : $nodeName; |
| 725 |
} |
| 726 |
|
| 727 |
/** |
| 728 |
* Encapsulation requires adding about attributes on the top-level |
| 729 |
* nodes of the range. This requires them to all be Elements. |
| 730 |
* |
| 731 |
* @param DOMRangeInfo $range |
| 732 |
*/ |
| 733 |
private function ensureElementsInRange( DOMRangeInfo $range ): void { |
| 734 |
$n = $range->start; |
| 735 |
$e = $range->end; |
| 736 |
$about = DOMCompat::getAttribute( $range->startElem, 'about' ); |
| 737 |
while ( $n ) { |
| 738 |
$next = $n->nextSibling; |
| 739 |
if ( $n instanceof Element ) { |
| 740 |
$n->setAttribute( 'about', $about ); |
| 741 |
} elseif ( DOMUtils::isFosterablePosition( $n ) ) { |
| 742 |
// NOTE: There cannot be any non-IEW text in fosterable position |
| 743 |
// since the HTML tree builder would already have fostered it out. |
| 744 |
// So, any non-element node found here is safe to delete since: |
| 745 |
// (a) this has no rendering output impact, and |
| 746 |
// (b) data-mw captures template output => we don't need |
| 747 |
// to preserve this for html2wt either. Removing this |
| 748 |
// lets us preserve DOM range continuity. |
| 749 |
$n->parentNode->removeChild( $n ); |
| 750 |
} else { |
| 751 |
// Add a span wrapper to let us add about-ids to represent |
| 752 |
// the DOM range as a contiguous chain of DOM nodes. |
| 753 |
$span = $this->document->createElement( 'span' ); |
| 754 |
$span->setAttribute( 'about', $about ); |
| 755 |
$dp = new DataParsoid; |
| 756 |
$dp->setTempFlag( TempData::WRAPPER ); |
| 757 |
DOMDataUtils::setDataParsoid( $span, $dp ); |
| 758 |
$n->parentNode->replaceChild( $span, $n ); |
| 759 |
$span->appendChild( $n ); |
| 760 |
$n = $span; |
| 761 |
} |
| 762 |
|
| 763 |
if ( $n === $e ) { |
| 764 |
break; |
| 765 |
} |
| 766 |
|
| 767 |
$n = $next; |
| 768 |
} |
| 769 |
} |
| 770 |
|
| 771 |
/** |
| 772 |
* Find the first element to be encapsulated. |
| 773 |
* Skip past marker metas and non-elements (which will all be IEW |
| 774 |
* in fosterable positions in a table). |
| 775 |
* |
| 776 |
* @param DOMRangeInfo $range |
| 777 |
* @return Element |
| 778 |
*/ |
| 779 |
private static function findEncapTarget( DOMRangeInfo $range ): Element { |
| 780 |
$encapTgt = $range->start; |
| 781 |
'@phan-var Node $encapTgt'; |
| 782 |
|
| 783 |
// Skip template-marker meta-tags. |
| 784 |
while ( WTUtils::isTplMarkerMeta( $encapTgt ) || |
| 785 |
!( $encapTgt instanceof Element ) |
| 786 |
) { |
| 787 |
// Detect unwrappable template and bail out early. |
| 788 |
if ( $encapTgt === $range->end || |
| 789 |
( !( $encapTgt instanceof Element ) && |
| 790 |
!DOMUtils::isFosterablePosition( $encapTgt ) |
| 791 |
) |
| 792 |
) { |
| 793 |
throw new Error( 'Cannot encapsulate transclusion. Start=' . |
| 794 |
DOMCompat::getOuterHTML( $range->startElem ) ); |
| 795 |
} |
| 796 |
$encapTgt = $encapTgt->nextSibling; |
| 797 |
} |
| 798 |
|
| 799 |
'@phan-var Element $encapTgt'; |
| 800 |
return $encapTgt; |
| 801 |
} |
| 802 |
|
| 803 |
/** |
| 804 |
* Add markers to the DOM around the non-overlapping ranges. |
| 805 |
* |
| 806 |
* @param DOMRangeInfo[] $nonOverlappingRanges |
| 807 |
*/ |
| 808 |
private function encapsulateTemplates( array $nonOverlappingRanges ): void { |
| 809 |
foreach ( $nonOverlappingRanges as $i => $range ) { |
| 810 |
|
| 811 |
// We should never have flipped overlapping ranges, and indeed that's |
| 812 |
// asserted in `findTopLevelNonOverlappingRanges`. Flipping results |
| 813 |
// in either completely nested ranges, or non-intersecting ranges. |
| 814 |
// |
| 815 |
// If the table causing the fostering is not transcluded, we emit a |
| 816 |
// foster box and wrap the whole table+fb in metas, producing nested |
| 817 |
// ranges. For ex, |
| 818 |
// |
| 819 |
// <table> |
| 820 |
// {{1x|<div>}} |
| 821 |
// |
| 822 |
// The tricky part is when the table *is* transcluded, and we omit the |
| 823 |
// foster box. The common case (for some definition of common) might |
| 824 |
// be like, |
| 825 |
// |
| 826 |
// {{1x|<table>}} |
| 827 |
// {{1x|<div>}} |
| 828 |
// |
| 829 |
// Here, #mwt1 leaves a table open and the end meta from #mwt2 is |
| 830 |
// fostered, since it gets closed into the div. The range for #mwt1 |
| 831 |
// is the entire table, which thankfully contains #mwt2, so we still |
| 832 |
// have the expected entire nesting. Any tricks to extend the range |
| 833 |
// of #mwt2 beyond the table (so that we have an overlapping range) will |
| 834 |
// inevitably result in the end meta not being fostered, and we avoid |
| 835 |
// this situation altogether. |
| 836 |
// |
| 837 |
// The very edgy case is as follows, |
| 838 |
// |
| 839 |
// {{1x|<table><div>}}</div> |
| 840 |
// {{1x|<div>}} |
| 841 |
// |
| 842 |
// where both end metas are fostered. Ignoring that we don't even |
| 843 |
// roundtrip the first transclusion properly on its own, here we have |
| 844 |
// a flipped range where, since the end meta for the first range was |
| 845 |
// also fostered, the ranges still don't overlap. |
| 846 |
|
| 847 |
// FIXME: The code below needs to be aware of flipped ranges. |
| 848 |
|
| 849 |
$this->ensureElementsInRange( $range ); |
| 850 |
|
| 851 |
$tplArray = $this->compoundTpls[$range->id] ?? null; |
| 852 |
Assert::invariant( (bool)$tplArray, 'No parts for template range!' ); |
| 853 |
|
| 854 |
$encapTgt = self::findEncapTarget( $range ); |
| 855 |
$encapValid = false; |
| 856 |
$encapDP = DOMDataUtils::getDataParsoid( $encapTgt ); |
| 857 |
|
| 858 |
// Update type-of (always even if tpl-encap below will fail). |
| 859 |
// This ensures that VE will still "edit-protect" this template |
| 860 |
// and not allow its content to be edited directly. |
| 861 |
$startElem = $range->startElem; |
| 862 |
if ( $startElem !== $encapTgt ) { |
| 863 |
$t1 = DOMCompat::getAttribute( $startElem, 'typeof' ); |
| 864 |
if ( $t1 !== null ) { |
| 865 |
foreach ( array_reverse( explode( ' ', $t1 ) ) as $t ) { |
| 866 |
DOMUtils::addTypeOf( $encapTgt, $t, true ); |
| 867 |
} |
| 868 |
} |
| 869 |
} |
| 870 |
|
| 871 |
/* ---------------------------------------------------------------- |
| 872 |
* We'll attempt to update dp1.dsr to reflect the entire range of |
| 873 |
* the template. This relies on a couple observations: |
| 874 |
* |
| 875 |
* 1. In the common case, dp2.dsr->end will be > dp1.dsr->end |
| 876 |
* If so, new range = dp1.dsr->start, dp2.dsr->end |
| 877 |
* |
| 878 |
* 2. But, foster parenting can complicate this when range.end is a table |
| 879 |
* and range.start has been fostered out of the table (range.end). |
| 880 |
* But, we need to verify this assumption. |
| 881 |
* |
| 882 |
* 2a. If dp2.dsr->start is smaller than dp1.dsr->start, this is a |
| 883 |
* confirmed case of range.start being fostered out of range.end. |
| 884 |
* |
| 885 |
* 2b. If dp2.dsr->start is unknown, we rely on fostered flag on |
| 886 |
* range.start, if any. |
| 887 |
* ---------------------------------------------------------------- */ |
| 888 |
$dp1 = DOMDataUtils::getDataParsoid( $range->start ); |
| 889 |
$dp1DSR = isset( $dp1->dsr ) ? clone $dp1->dsr : null; |
| 890 |
$dp2DSR = self::getRangeEndDSR( $range ); |
| 891 |
|
| 892 |
if ( $dp1DSR ) { |
| 893 |
if ( $dp2DSR ) { |
| 894 |
// Case 1. above |
| 895 |
if ( $dp2DSR->end > $dp1DSR->end ) { |
| 896 |
$dp1DSR->end = $dp2DSR->end; |
| 897 |
} |
| 898 |
|
| 899 |
// Case 2. above |
| 900 |
$endDsr = $dp2DSR->start; |
| 901 |
if ( DOMCompat::nodeName( $range->end ) === 'table' && |
| 902 |
$endDsr !== null && |
| 903 |
( $endDsr < $dp1DSR->start || !empty( $dp1->fostered ) ) |
| 904 |
) { |
| 905 |
$dp1DSR->start = $endDsr; |
| 906 |
} |
| 907 |
} |
| 908 |
|
| 909 |
// encapsulation possible only if dp1.dsr is valid |
| 910 |
$encapValid = Utils::isValidDSR( $dp1DSR ) && |
| 911 |
$dp1DSR->end >= $dp1DSR->start; |
| 912 |
} |
| 913 |
|
| 914 |
if ( $encapValid ) { |
| 915 |
// Find transclusion info from the array (skip past a wikitext element) |
| 916 |
/** @var CompoundTemplateInfo $firstTplInfo */ |
| 917 |
$firstTplInfo = is_string( $tplArray[0] ) ? $tplArray[1] : $tplArray[0]; |
| 918 |
|
| 919 |
// Add any leading wikitext |
| 920 |
if ( $firstTplInfo->dsr->start > $dp1DSR->start ) { |
| 921 |
// This gap in dsr (between the final encapsulated content, and the |
| 922 |
// content that actually came from a template) is indicative of this |
| 923 |
// being a mixed-template-content-block and/or multi-template-content-block |
| 924 |
// scenario. |
| 925 |
// |
| 926 |
// In this case, record the name of the first node in the encapsulated |
| 927 |
// content. During html -> wt serialization, newline constraints for |
| 928 |
// this entire block has to be determined relative to this node. |
| 929 |
$ftn = self::findFirstTemplatedNode( $range ); |
| 930 |
if ( $ftn !== null ) { |
| 931 |
$encapDP->firstWikitextNode = $ftn; |
| 932 |
} |
| 933 |
$width = $firstTplInfo->dsr->start - $dp1DSR->start; |
| 934 |
array_unshift( |
| 935 |
$tplArray, |
| 936 |
PHPUtils::safeSubstr( $this->frame->getSrcText(), $dp1DSR->start, $width ) |
| 937 |
); |
| 938 |
} |
| 939 |
|
| 940 |
// Add any trailing wikitext |
| 941 |
/** @var CompoundTemplateInfo $lastTplInfo */ |
| 942 |
$lastTplInfo = PHPUtils::lastItem( $tplArray ); |
| 943 |
if ( $lastTplInfo->dsr->end < $dp1DSR->end ) { |
| 944 |
$width = $dp1DSR->end - $lastTplInfo->dsr->end; |
| 945 |
$tplArray[] = PHPUtils::safeSubstr( $this->frame->getSrcText(), $lastTplInfo->dsr->end, $width ); |
| 946 |
} |
| 947 |
|
| 948 |
// Map the array of { dsr: .. , args: .. } objects to just the args property |
| 949 |
$infoIndex = 0; |
| 950 |
$parts = []; |
| 951 |
$pi = []; |
| 952 |
foreach ( $tplArray as $a ) { |
| 953 |
if ( is_string( $a ) ) { |
| 954 |
$parts[] = $a; |
| 955 |
} elseif ( $a instanceof CompoundTemplateInfo ) { |
| 956 |
// Remember the position of the transclusion relative |
| 957 |
// to other transclusions. Should match the index of |
| 958 |
// the corresponding private metadata in $templateInfos. |
| 959 |
$a->info->i = $infoIndex++; |
| 960 |
$a->info->type = 'template'; |
| 961 |
if ( $a->isParam ) { |
| 962 |
$a->info->type = 'templatearg'; |
| 963 |
} elseif ( $a->info->func ) { |
| 964 |
$a->info->type = 'parserfunction'; |
| 965 |
} |
| 966 |
$parts[] = $a->info; |
| 967 |
// FIXME: we throw away the array keys and rebuild them |
| 968 |
// again in WikitextSerializer |
| 969 |
$pi[] = array_values( $a->info->paramInfos ); |
| 970 |
} |
| 971 |
} |
| 972 |
|
| 973 |
// Set up dsr->start, dsr->end, and data-mw on the target node |
| 974 |
// Avoid clobbering existing (ex: extension) data-mw information (T214241) |
| 975 |
$encapDataMw = DOMDataUtils::getDataMw( $encapTgt ); |
| 976 |
$encapDataMw->parts = $parts; |
| 977 |
DOMDataUtils::setDataMw( $encapTgt, $encapDataMw ); |
| 978 |
$encapDP->pi = $pi; |
| 979 |
|
| 980 |
// Special case when mixed-attribute-and-content templates are |
| 981 |
// involved. This information is reliable and comes from the |
| 982 |
// AttributeExpander and gets around the problem of unmarked |
| 983 |
// fostered content that findFirstTemplatedNode runs into. |
| 984 |
$firstWikitextNode = DOMDataUtils::getDataParsoid( |
| 985 |
$range->startElem |
| 986 |
)->firstWikitextNode ?? null; |
| 987 |
if ( empty( $encapDP->firstWikitextNode ) && $firstWikitextNode ) { |
| 988 |
$encapDP->firstWikitextNode = $firstWikitextNode; |
| 989 |
} |
| 990 |
} else { |
| 991 |
$errors = [ 'Do not have necessary info. to encapsulate Tpl: ' . $i ]; |
| 992 |
$errors[] = 'Start Elt : ' . DOMCompat::getOuterHTML( $startElem ); |
| 993 |
$errors[] = 'End Elt : ' . DOMCompat::getOuterHTML( $range->endElem ); |
| 994 |
$errors[] = 'Start DSR : ' . PHPUtils::jsonEncode( $dp1DSR ?? 'no-start-dsr' ); |
| 995 |
$errors[] = 'End DSR : ' . PHPUtils::jsonEncode( $dp2DSR ?? [] ); |
| 996 |
$this->env->log( 'error', implode( "\n", $errors ) ); |
| 997 |
} |
| 998 |
|
| 999 |
// Make DSR range zero-width for fostered templates after |
| 1000 |
// setting up data-mw. However, since template encapsulation |
| 1001 |
// sometimes captures both fostered content as well as the table |
| 1002 |
// from which it was fostered from, in those scenarios, we should |
| 1003 |
// leave DSR info untouched. |
| 1004 |
// |
| 1005 |
// SSS FIXME: |
| 1006 |
// 1. Should we remove the fostered flag from the entire |
| 1007 |
// encapsulated block if we dont set dsr width range to zero |
| 1008 |
// since only part of the block is fostered, not the entire |
| 1009 |
// encapsulated block? |
| 1010 |
// |
| 1011 |
// 2. In both cases, should we mark these uneditable by adding |
| 1012 |
// mw:Placeholder to the typeof? |
| 1013 |
if ( !empty( $dp1->fostered ) ) { |
| 1014 |
$encapDataMw = DOMDataUtils::getDataMw( $encapTgt ); |
| 1015 |
if ( !$encapDataMw || |
| 1016 |
!$encapDataMw->parts || |
| 1017 |
count( $encapDataMw->parts ) === 1 |
| 1018 |
) { |
| 1019 |
$dp1DSR->end = $dp1DSR->start; |
| 1020 |
} |
| 1021 |
} |
| 1022 |
|
| 1023 |
// Update DSR after fostering-related fixes are done. |
| 1024 |
if ( $encapValid ) { |
| 1025 |
// encapInfo.dp points to DOMDataUtils.getDataParsoid(encapInfo.target) |
| 1026 |
// and all updates below update properties in that object tree. |
| 1027 |
if ( empty( $encapDP->dsr ) ) { |
| 1028 |
$encapDP->dsr = $dp1DSR; |
| 1029 |
} else { |
| 1030 |
$encapDP->dsr->start = $dp1DSR->start; |
| 1031 |
$encapDP->dsr->end = $dp1DSR->end; |
| 1032 |
} |
| 1033 |
$encapDP->src = $encapDP->dsr->substr( |
| 1034 |
$this->frame->getSrcText() |
| 1035 |
); |
| 1036 |
} |
| 1037 |
|
| 1038 |
// Remove startElem (=range.startElem) if a meta. If a meta, |
| 1039 |
// it is guaranteed to be a marker meta added to mark the start |
| 1040 |
// of the template. |
| 1041 |
if ( WTUtils::isTplMarkerMeta( $startElem ) ) { |
| 1042 |
$startElem->parentNode->removeChild( $startElem ); |
| 1043 |
} |
| 1044 |
|
| 1045 |
$range->endElem->parentNode->removeChild( $range->endElem ); |
| 1046 |
} |
| 1047 |
} |
| 1048 |
|
| 1049 |
/** |
| 1050 |
* Attach a range to a node. |
| 1051 |
* |
| 1052 |
* @param Element $node |
| 1053 |
* @param DOMRangeInfo $range |
| 1054 |
*/ |
| 1055 |
private function addNodeRange( Element $node, DOMRangeInfo $range ): void { |
| 1056 |
// With the native DOM extension, normally you assume that DOMNode |
| 1057 |
// objects are temporary -- you get a new DOMNode every time you |
| 1058 |
// traverse the DOM. But by retaining a reference in the |
| 1059 |
// SplObjectStorage, we ensure that the DOMNode object stays live while |
| 1060 |
// the pass is active. Then its address can be used as an index. |
| 1061 |
if ( !isset( $this->nodeRanges[$node] ) ) { |
| 1062 |
// We have to use an object as the data because |
| 1063 |
// SplObjectStorage::offsetGet() does not provide an lval. |
| 1064 |
$this->nodeRanges[$node] = new DOMRangeInfoArray; |
| 1065 |
} |
| 1066 |
$this->nodeRanges[$node]->ranges[$range->id] = $range; |
| 1067 |
} |
| 1068 |
|
| 1069 |
/** |
| 1070 |
* Get the ranges attached to this node, indexed by range ID. |
| 1071 |
* |
| 1072 |
* @param Element $node |
| 1073 |
* @return DOMRangeInfo[]|null |
| 1074 |
*/ |
| 1075 |
private function getNodeRanges( Element $node ): ?array { |
| 1076 |
return $this->nodeRanges[$node]->ranges ?? null; |
| 1077 |
} |
| 1078 |
|
| 1079 |
/** |
| 1080 |
* Recursively walk the DOM tree. Find wrappable template ranges and return them. |
| 1081 |
* |
| 1082 |
* @param Node $rootNode |
| 1083 |
* @return DOMRangeInfo[] |
| 1084 |
*/ |
| 1085 |
protected function findWrappableMetaRanges( Node $rootNode ): array { |
| 1086 |
$tpls = []; |
| 1087 |
$tplRanges = []; |
| 1088 |
$this->findWrappableTemplateRangesRecursive( $rootNode, $tpls, $tplRanges ); |
| 1089 |
return $tplRanges; |
| 1090 |
} |
| 1091 |
|
| 1092 |
/** |
| 1093 |
* Recursive helper for findWrappableTemplateRanges() |
| 1094 |
* |
| 1095 |
* @param Node $rootNode |
| 1096 |
* @param ElementRange[] &$tpls Template start and end elements by ID |
| 1097 |
* @param DOMRangeInfo[] &$tplRanges Template range info |
| 1098 |
*/ |
| 1099 |
private function findWrappableTemplateRangesRecursive( |
| 1100 |
Node $rootNode, array &$tpls, array &$tplRanges |
| 1101 |
): void { |
| 1102 |
$elem = $rootNode->firstChild; |
| 1103 |
|
| 1104 |
while ( $elem ) { |
| 1105 |
// get the next sibling before doing anything since |
| 1106 |
// we may delete elem as part of encapsulation |
| 1107 |
$nextSibling = $elem->nextSibling; |
| 1108 |
|
| 1109 |
if ( $elem instanceof Element ) { |
| 1110 |
$metaType = $this->matchMetaType( $elem ); |
| 1111 |
|
| 1112 |
// Ignore templates without tsr. |
| 1113 |
// |
| 1114 |
// These are definitely nested in other templates / extensions |
| 1115 |
// and need not be wrapped themselves since they |
| 1116 |
// can never be edited directly. |
| 1117 |
// |
| 1118 |
// NOTE: We are only testing for tsr presence on the start-elem |
| 1119 |
// because wikitext errors can lead to parse failures and no tsr |
| 1120 |
// on end-meta-tags. |
| 1121 |
// |
| 1122 |
// Ex: "<ref>{{1x|bar}}<!--bad-></ref>" |
| 1123 |
if ( $metaType !== null && |
| 1124 |
( !empty( DOMDataUtils::getDataParsoid( $elem )->tsr ) || |
| 1125 |
str_ends_with( $metaType, '/End' ) |
| 1126 |
) |
| 1127 |
) { |
| 1128 |
$about = $this->getRangeId( $elem ); |
| 1129 |
$tpl = $tpls[$about] ?? null; |
| 1130 |
// Is this a start marker? |
| 1131 |
if ( !str_ends_with( $metaType, '/End' ) ) { |
| 1132 |
if ( $tpl ) { |
| 1133 |
$tpl->startElem = $elem; |
| 1134 |
// content or end marker existed already |
| 1135 |
if ( !empty( $tpl->endElem ) ) { |
| 1136 |
// End marker was foster-parented. |
| 1137 |
// Found actual start tag. |
| 1138 |
$tplRanges[] = $this->getDOMRange( |
| 1139 |
$elem, $tpl->endElem, $tpl->endElem ); |
| 1140 |
} else { |
| 1141 |
// should not happen! |
| 1142 |
throw new UnreachableException( "start found after content for $about." ); |
| 1143 |
} |
| 1144 |
} else { |
| 1145 |
$tpl = new ElementRange; |
| 1146 |
$tpl->startElem = $elem; |
| 1147 |
$tpls[$about] = $tpl; |
| 1148 |
} |
| 1149 |
} else { |
| 1150 |
// elem is the end-meta tag |
| 1151 |
if ( $tpl ) { |
| 1152 |
/* ------------------------------------------------------------ |
| 1153 |
* Special case: In some cases, the entire template content can |
| 1154 |
* get fostered out of a table, not just the start/end marker. |
| 1155 |
* |
| 1156 |
* Simplest example: |
| 1157 |
* |
| 1158 |
* {| |
| 1159 |
* {{1x|foo}} |
| 1160 |
* |} |
| 1161 |
* |
| 1162 |
* More complex example: |
| 1163 |
* |
| 1164 |
* {| |
| 1165 |
* {{1x| |
| 1166 |
* a |
| 1167 |
* b |
| 1168 |
* |
| 1169 |
* c |
| 1170 |
* }} |
| 1171 |
* |} |
| 1172 |
* |
| 1173 |
* Since meta-tags don't normally get fostered out, this scenario |
| 1174 |
* only arises when the entire content including meta-tags was |
| 1175 |
* wrapped in p-tags. So, we look to see if: |
| 1176 |
* 1. the end-meta-tag's parent has a table sibling, |
| 1177 |
* 2. the start meta's parent is marked as fostered. |
| 1178 |
* If so, we recognize this as an adoption scenario and fix up |
| 1179 |
* DSR of start-meta-tag's parent to include the table's DSR. |
| 1180 |
* ------------------------------------------------------------*/ |
| 1181 |
$sm = $tpl->startElem; |
| 1182 |
|
| 1183 |
// TODO: this should only happen in fairly specific cases of the |
| 1184 |
// annotation processing and should eventually be handled properly. |
| 1185 |
// In the meantime, we create and log an exception to have an idea |
| 1186 |
// of the amplitude of the problem. |
| 1187 |
if ( $sm === null ) { |
| 1188 |
throw new RangeBuilderException( 'No start tag found for the range' ); |
| 1189 |
} |
| 1190 |
$em = $elem; |
| 1191 |
$ee = $em; |
| 1192 |
$tbl = $em->parentNode->nextSibling; |
| 1193 |
|
| 1194 |
// Dont get distracted by a newline node -- skip over it |
| 1195 |
// Unsure why it shows up occasionally |
| 1196 |
if ( $tbl && $tbl instanceof Text && $tbl->nodeValue === "\n" ) { |
| 1197 |
$tbl = $tbl->nextSibling; |
| 1198 |
} |
| 1199 |
|
| 1200 |
$dp = !DOMUtils::atTheTop( $sm->parentNode ) ? |
| 1201 |
DOMDataUtils::getDataParsoid( $sm->parentNode ) : null; |
| 1202 |
if ( $tbl && DOMCompat::nodeName( $tbl ) === 'table' && !empty( $dp->fostered ) ) { |
| 1203 |
'@phan-var Element $tbl'; /** @var Element $tbl */ |
| 1204 |
$tblDP = DOMDataUtils::getDataParsoid( $tbl ); |
| 1205 |
if ( isset( $dp->tsr->start ) && $dp->tsr->start !== null && |
| 1206 |
isset( $tblDP->dsr->start ) && $tblDP->dsr->start === null |
| 1207 |
) { |
| 1208 |
$tblDP->dsr->start = $dp->tsr->start; |
| 1209 |
} |
| 1210 |
$tbl->setAttribute( 'about', $about ); // set about on elem |
| 1211 |
$ee = $tbl; |
| 1212 |
} |
| 1213 |
$tplRanges[] = $this->getDOMRange( $sm, $em, $ee ); |
| 1214 |
} else { |
| 1215 |
// The end tag can appear before the start tag if it is fostered out |
| 1216 |
// of the table and the start tag is not. |
| 1217 |
// It can even technically happen that both tags are fostered out of |
| 1218 |
// a table and that the range is flipped: while the fostered content of |
| 1219 |
// single table is fostered in-order, the ordering might change |
| 1220 |
// across tables if the tags are not initially fostered by the same |
| 1221 |
// table. |
| 1222 |
$tpl = new ElementRange; |
| 1223 |
$tpl->endElem = $elem; |
| 1224 |
$tpls[$about] = $tpl; |
| 1225 |
} |
| 1226 |
} |
| 1227 |
} else { |
| 1228 |
$this->findWrappableTemplateRangesRecursive( $elem, $tpls, $tplRanges ); |
| 1229 |
} |
| 1230 |
} |
| 1231 |
|
| 1232 |
$elem = $nextSibling; |
| 1233 |
} |
| 1234 |
} |
| 1235 |
|
| 1236 |
/** |
| 1237 |
* Returns the meta type of the element if it exists and matches the type expected by the |
| 1238 |
* current class, null otherwise |
| 1239 |
* @param Element $elem the element to check |
| 1240 |
* @return string|null |
| 1241 |
*/ |
| 1242 |
protected function matchMetaType( Element $elem ): ?string { |
| 1243 |
// for this class we're interested in the template type |
| 1244 |
return WTUtils::matchTplType( $elem ); |
| 1245 |
} |
| 1246 |
|
| 1247 |
protected function verifyTplInfoExpectation( ?TemplateInfo $templateInfo, TempData $tmp ): void { |
| 1248 |
if ( !$templateInfo ) { |
| 1249 |
// An assertion here is probably an indication that we're |
| 1250 |
// mistakenly doing template wrapping in a nested context. |
| 1251 |
Assert::invariant( $tmp->getFlag( TempData::FROM_FOSTER ), 'Template range without arginfo.' ); |
| 1252 |
} |
| 1253 |
} |
| 1254 |
|
| 1255 |
public function execute( Node $root ): void { |
| 1256 |
$tplRanges = $this->findWrappableMetaRanges( $root ); |
| 1257 |
if ( count( $tplRanges ) > 0 ) { |
| 1258 |
$nonOverlappingRanges = $this->findTopLevelNonOverlappingRanges( $root, $tplRanges ); |
| 1259 |
$this->encapsulateTemplates( $nonOverlappingRanges ); |
| 1260 |
} |
| 1261 |
} |
| 1262 |
|
| 1263 |
/** |
| 1264 |
* Creates a range that encloses $startMeta and $endMeta |
| 1265 |
* |
| 1266 |
* @param Element $startMeta |
| 1267 |
* @param Element $endMeta |
| 1268 |
* @param ?Element $endElem |
| 1269 |
* @return DOMRangeInfo |
| 1270 |
*/ |
| 1271 |
protected function findEnclosingRange( |
| 1272 |
Element $startMeta, Element $endMeta, ?Element $endElem = null |
| 1273 |
): DOMRangeInfo { |
| 1274 |
$range = new DOMRangeInfo( |
| 1275 |
Utils::stripParsoidIdPrefix( $this->getRangeId( $startMeta ) ), |
| 1276 |
DOMDataUtils::getDataParsoid( $startMeta )->tsr->start, |
| 1277 |
$startMeta, |
| 1278 |
$endMeta |
| 1279 |
); |
| 1280 |
|
| 1281 |
// Find common ancestor of startMeta and endElem |
| 1282 |
$startAncestors = DOMUtils::pathToRoot( $startMeta ); |
| 1283 |
$elem = $endElem ?? $endMeta; |
| 1284 |
$parentNode = $elem->parentNode; |
| 1285 |
while ( $parentNode && $parentNode->nodeType !== XML_DOCUMENT_NODE ) { |
| 1286 |
$i = array_search( $parentNode, $startAncestors, true ); |
| 1287 |
if ( $i === 0 ) { |
| 1288 |
throw new UnreachableException( |
| 1289 |
'The startMeta cannot be the common ancestor.' |
| 1290 |
); |
| 1291 |
} elseif ( $i > 0 ) { |
| 1292 |
$range->start = $startAncestors[$i - 1]; |
| 1293 |
$range->end = $elem; |
| 1294 |
break; |
| 1295 |
} |
| 1296 |
$elem = $parentNode; |
| 1297 |
$parentNode = $elem->parentNode; |
| 1298 |
} |
| 1299 |
|
| 1300 |
return $range; |
| 1301 |
} |
| 1302 |
} |