| 1 |
<?php |
| 2 |
declare( strict_types = 1 ); |
| 3 |
|
| 4 |
namespace Wikimedia\Parsoid\Wt2Html\DOM\Handlers; |
| 5 |
|
| 6 |
use Wikimedia\Assert\Assert; |
| 7 |
use Wikimedia\Parsoid\Config\Env; |
| 8 |
use Wikimedia\Parsoid\Core\Sanitizer; |
| 9 |
use Wikimedia\Parsoid\DOM\Comment; |
| 10 |
use Wikimedia\Parsoid\DOM\Element; |
| 11 |
use Wikimedia\Parsoid\DOM\Node; |
| 12 |
use Wikimedia\Parsoid\DOM\Text; |
| 13 |
use Wikimedia\Parsoid\NodeData\DataMw; |
| 14 |
use Wikimedia\Parsoid\NodeData\TempData; |
| 15 |
use Wikimedia\Parsoid\NodeData\TemplateInfo; |
| 16 |
use Wikimedia\Parsoid\Utils\DiffDOMUtils; |
| 17 |
use Wikimedia\Parsoid\Utils\DOMCompat; |
| 18 |
use Wikimedia\Parsoid\Utils\DOMDataUtils; |
| 19 |
use Wikimedia\Parsoid\Utils\DOMUtils; |
| 20 |
use Wikimedia\Parsoid\Utils\DTState; |
| 21 |
use Wikimedia\Parsoid\Utils\PHPUtils; |
| 22 |
use Wikimedia\Parsoid\Utils\Utils; |
| 23 |
use Wikimedia\Parsoid\Utils\WTUtils; |
| 24 |
use Wikimedia\Parsoid\Wt2Html\Frame; |
| 25 |
use Wikimedia\Parsoid\Wt2Html\PegTokenizer; |
| 26 |
|
| 27 |
/** |
| 28 |
* Provides DOMTraverser visitors that fix template-induced interrupted table cell parsing |
| 29 |
* by recombining table cells and/or reparsing table cell content as attributes. |
| 30 |
* - handleTableCellTemplates |
| 31 |
*/ |
| 32 |
class TableFixups { |
| 33 |
|
| 34 |
private static function isSimpleTemplatedSpan( Node $node ): bool { |
| 35 |
return DOMCompat::nodeName( $node ) === 'span' && |
| 36 |
DOMUtils::hasTypeOf( $node, 'mw:Transclusion' ) && |
| 37 |
DOMUtils::allChildrenAreTextOrComments( $node ); |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* @param list<string|TemplateInfo> &$parts |
| 42 |
* @param Frame $frame |
| 43 |
* @param int $offset1 |
| 44 |
* @param int $offset2 |
| 45 |
*/ |
| 46 |
private static function fillDSRGap( array &$parts, Frame $frame, int $offset1, int $offset2 ): void { |
| 47 |
if ( $offset1 < $offset2 ) { |
| 48 |
$parts[] = PHPUtils::safeSubstr( $frame->getSrcText(), $offset1, $offset2 - $offset1 ); |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Hoist transclusion information from cell content / attributes |
| 54 |
* onto the cell itself. |
| 55 |
*/ |
| 56 |
private static function hoistTransclusionInfo( |
| 57 |
DTState $dtState, array $transclusions, Element $td |
| 58 |
): void { |
| 59 |
// Initialize dsr for $td |
| 60 |
// In `handleTableCellTemplates`, we're creating a cell w/o dsr info. |
| 61 |
$tdDp = DOMDataUtils::getDataParsoid( $td ); |
| 62 |
if ( !Utils::isValidDSR( $tdDp->dsr ?? null ) ) { |
| 63 |
$tplDp = DOMDataUtils::getDataParsoid( $transclusions[0] ); |
| 64 |
Assert::invariant( Utils::isValidDSR( $tplDp->dsr ?? null ), 'Expected valid DSR' ); |
| 65 |
$tdDp->dsr = clone $tplDp->dsr; |
| 66 |
} |
| 67 |
|
| 68 |
// Build up $parts, $pi to set up the combined transclusion info on $td. |
| 69 |
// Note that content for all but the last template has been swallowed into |
| 70 |
// the attributes of $td. |
| 71 |
$parts = []; |
| 72 |
$pi = []; |
| 73 |
$lastTpl = null; |
| 74 |
$prevDp = null; |
| 75 |
$frame = $dtState->options['frame']; |
| 76 |
|
| 77 |
$index = 0; |
| 78 |
foreach ( $transclusions as $i => $tpl ) { |
| 79 |
$tplDp = DOMDataUtils::getDataParsoid( $tpl ); |
| 80 |
Assert::invariant( Utils::isValidDSR( $tplDp->dsr ?? null ), 'Expected valid DSR' ); |
| 81 |
|
| 82 |
// Plug DSR gaps between transclusions |
| 83 |
if ( !$prevDp ) { |
| 84 |
self::fillDSRGap( $parts, $frame, $tdDp->dsr->start, $tplDp->dsr->start ); |
| 85 |
} else { |
| 86 |
self::fillDSRGap( $parts, $frame, $prevDp->dsr->end, $tplDp->dsr->start ); |
| 87 |
} |
| 88 |
|
| 89 |
// Assimilate $tpl's data-mw and data-parsoid pi info |
| 90 |
$dmw = DOMDataUtils::getDataMw( $tpl ); |
| 91 |
foreach ( $dmw->parts ?? [] as $part ) { |
| 92 |
// Template index is relative to other transclusions. |
| 93 |
// This index is used to extract whitespace information from |
| 94 |
// data-parsoid and that array only includes info for templates. |
| 95 |
// So skip over strings here. |
| 96 |
if ( !is_string( $part ) ) { |
| 97 |
// Cloning is strictly not needed here, but mimicking |
| 98 |
// code in WrapSectionsState.php |
| 99 |
$part = clone $part; |
| 100 |
$part->i = $index++; |
| 101 |
} |
| 102 |
$parts[] = $part; |
| 103 |
} |
| 104 |
PHPUtils::pushArray( $pi, $tplDp->pi ?? [ [] ] ); |
| 105 |
DOMDataUtils::setDataMw( $tpl, null ); |
| 106 |
|
| 107 |
$lastTpl = $tpl; |
| 108 |
$prevDp = $tplDp; |
| 109 |
} |
| 110 |
|
| 111 |
$aboutId = DOMCompat::getAttribute( $lastTpl, 'about' ); |
| 112 |
|
| 113 |
// Hoist transclusion information to $td. |
| 114 |
$td->setAttribute( 'typeof', 'mw:Transclusion' ); |
| 115 |
$td->setAttribute( 'about', $aboutId ); |
| 116 |
|
| 117 |
// Add wikitext for the table cell content following $lastTpl |
| 118 |
self::fillDSRGap( $parts, $frame, $prevDp->dsr->end, $tdDp->dsr->end ); |
| 119 |
|
| 120 |
// Save the new data-mw on the td |
| 121 |
$dmw = new DataMw( [] ); |
| 122 |
$dmw->parts = $parts; |
| 123 |
DOMDataUtils::setDataMw( $td, $dmw ); |
| 124 |
$tdDp->pi = $pi; |
| 125 |
|
| 126 |
// td wraps everything now. |
| 127 |
// Remove template encapsulation from here on. |
| 128 |
// This simplifies the problem of analyzing the <td> |
| 129 |
// for additional fixups (|| Boo || Baz) by potentially |
| 130 |
// invoking 'reparseTemplatedAttributes' on split cells |
| 131 |
// with some modifications. |
| 132 |
$child = $lastTpl; |
| 133 |
|
| 134 |
// Transclusions may be nested in elements in some ugly wikitext so |
| 135 |
// make sure we're starting at a direct descendant of td |
| 136 |
while ( $child->parentNode !== $td ) { |
| 137 |
$child = $child->parentNode; |
| 138 |
} |
| 139 |
|
| 140 |
while ( $child ) { |
| 141 |
if ( |
| 142 |
DOMCompat::nodeName( $child ) === 'span' && |
| 143 |
DOMCompat::getAttribute( $child, 'about' ) === $aboutId |
| 144 |
) { |
| 145 |
// Remove the encapsulation attributes. If there are no more attributes left, |
| 146 |
// the span wrapper is useless and can be removed. |
| 147 |
$child->removeAttribute( 'about' ); |
| 148 |
$child->removeAttribute( 'typeof' ); |
| 149 |
if ( DOMDataUtils::noAttrs( $child ) ) { |
| 150 |
$next = $child->firstChild ?: $child->nextSibling; |
| 151 |
DOMUtils::migrateChildren( $child, $td, $child ); |
| 152 |
$child->parentNode->removeChild( $child ); |
| 153 |
$child = $next; |
| 154 |
} else { |
| 155 |
$child = $child->nextSibling; |
| 156 |
} |
| 157 |
} else { |
| 158 |
$child = $child->nextSibling; |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
// $dtState->tplInfo can be null when information is hoisted |
| 163 |
// from children to $td because DOMTraverser hasn't seen the |
| 164 |
// children yet! |
| 165 |
if ( !$dtState->tplInfo ) { |
| 166 |
$dtState->tplInfo = (object)[ |
| 167 |
'first' => $td, |
| 168 |
'last' => $td, |
| 169 |
'clear' => false |
| 170 |
]; |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
/** |
| 175 |
* Collect potential attribute content. |
| 176 |
* |
| 177 |
* We expect this to be text nodes without a pipe character followed by one or |
| 178 |
* more nowiki spans, followed by a template encapsulation with pure-text and |
| 179 |
* nowiki content. Collection stops when encountering a pipe character. |
| 180 |
* |
| 181 |
* @param Env $env |
| 182 |
* @param Element $cell known to be <td> / <th> |
| 183 |
* @param ?Element $templateWrapper |
| 184 |
* @return ?array |
| 185 |
*/ |
| 186 |
public static function collectAttributishContent( |
| 187 |
Env $env, Element $cell, ?Element $templateWrapper |
| 188 |
): ?array { |
| 189 |
$buf = []; |
| 190 |
$nowikis = []; |
| 191 |
$transclusions = $templateWrapper ? [ $templateWrapper ] : []; |
| 192 |
|
| 193 |
// Some of this logic could be replaced by DSR-based recovery of |
| 194 |
// wikitext that is outside templates. But since we have to walk over |
| 195 |
// templated content in this fashion anyway, we might as well use the |
| 196 |
// same logic uniformly. |
| 197 |
|
| 198 |
$traverse = static function ( ?Node $child ) use ( |
| 199 |
&$traverse, &$buf, &$nowikis, &$transclusions |
| 200 |
): bool { |
| 201 |
while ( $child ) { |
| 202 |
if ( $child instanceof Comment ) { |
| 203 |
// Legacy parser strips comments during parsing => drop them. |
| 204 |
} elseif ( $child instanceof Text ) { |
| 205 |
$text = $child->nodeValue; |
| 206 |
$buf[] = $text; |
| 207 |
|
| 208 |
// Are we done accumulating? |
| 209 |
if ( preg_match( '/(?:^|[^|])\|(?:[^|]|$)/D', $text ) ) { |
| 210 |
return true; |
| 211 |
} |
| 212 |
} else { |
| 213 |
'@phan-var Element $child'; /** @var Element $child */ |
| 214 |
if ( DOMUtils::hasTypeOf( $child, 'mw:Transclusion' ) ) { |
| 215 |
$transclusions[] = $child; |
| 216 |
} |
| 217 |
|
| 218 |
if ( WTUtils::isFirstExtensionWrapperNode( $child ) ) { |
| 219 |
// "|" chars in extension content don't trigger table-cell parsing |
| 220 |
// since they have higher precedence in tokenization. The extension |
| 221 |
// content will simply be dropped (but any side effects it had will |
| 222 |
// continue to apply. Ex: <ref> tags might leave an orphaned ref in |
| 223 |
// the <references> section). |
| 224 |
$child = WTUtils::skipOverEncapsulatedContent( $child ); |
| 225 |
continue; |
| 226 |
} elseif ( DOMUtils::hasTypeOf( $child, 'mw:Entity' ) ) { |
| 227 |
// Get entity's wikitext source, not rendered content. |
| 228 |
// " " is "\n" which breaks attribute parsing! |
| 229 |
$buf[] = DOMDataUtils::getDataParsoid( $child )->src ?? $child->textContent; |
| 230 |
} elseif ( DOMUtils::hasTypeOf( $child, 'mw:Nowiki' ) ) { |
| 231 |
// Nowiki span were added to protect otherwise |
| 232 |
// meaningful wikitext chars used in attributes. |
| 233 |
// Save the content and add in a marker to splice out later. |
| 234 |
$nowikis[] = $child->textContent; |
| 235 |
$buf[] = '<nowiki-marker>'; |
| 236 |
} elseif ( DOMUtils::hasRel( $child, 'mw:WikiLink' ) || |
| 237 |
WTUtils::isGeneratedFigure( $child ) |
| 238 |
) { |
| 239 |
// Wikilinks/images abort attribute parsing |
| 240 |
return true; |
| 241 |
} else { |
| 242 |
if ( $traverse( $child->firstChild ) ) { |
| 243 |
return true; |
| 244 |
} |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
$child = $child->nextSibling; |
| 249 |
} |
| 250 |
|
| 251 |
return false; |
| 252 |
}; |
| 253 |
|
| 254 |
if ( $traverse( $cell->firstChild ) ) { |
| 255 |
return [ |
| 256 |
'txt' => implode( '', $buf ), |
| 257 |
'nowikis' => $nowikis, |
| 258 |
'transclusions' => $transclusions, |
| 259 |
]; |
| 260 |
} else { |
| 261 |
return null; |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
/** |
| 266 |
* T46498, second part of T52603 |
| 267 |
* |
| 268 |
* Handle wikitext like |
| 269 |
* ``` |
| 270 |
* {| |
| 271 |
* |{{nom|Bar}} |
| 272 |
* |} |
| 273 |
* ``` |
| 274 |
* where nom expands to `style="foo" class="bar"|Bar`. The attributes are |
| 275 |
* tokenized and stripped from the table contents. |
| 276 |
* |
| 277 |
* This method works well for the templates documented in |
| 278 |
* https://en.wikipedia.org/wiki/Template:Table_cell_templates/doc |
| 279 |
* |
| 280 |
* Nevertheless, there are some limitations: |
| 281 |
* - We assume that attributes don't contain wiki markup (apart from <nowiki>) |
| 282 |
* and end up in text or nowiki nodes. |
| 283 |
* - Only a single table cell is produced / opened by the template that |
| 284 |
* contains the attributes. This limitation could be lifted with more |
| 285 |
* aggressive re-parsing if really needed in practice. |
| 286 |
* - There is only a single transclusion in the table cell content. This |
| 287 |
* limitation can be lifted with more advanced data-mw construction. |
| 288 |
* |
| 289 |
* $cell known to be <td> / <th> |
| 290 |
*/ |
| 291 |
public static function reparseTemplatedAttributes( |
| 292 |
DTState $dtState, Element $cell, ?Element $templateWrapper |
| 293 |
): void { |
| 294 |
$env = $dtState->env; |
| 295 |
$frame = $dtState->options['frame']; |
| 296 |
// Collect attribute content and examine it |
| 297 |
$attributishContent = self::collectAttributishContent( $env, $cell, $templateWrapper ); |
| 298 |
if ( !$attributishContent ) { |
| 299 |
return; |
| 300 |
} |
| 301 |
|
| 302 |
/** |
| 303 |
* FIXME: These checks are insufficient. |
| 304 |
* Previous rounds of table fixups might have created this cell without |
| 305 |
* any templated content (the while loop in handleTableCellTemplates). |
| 306 |
* Till we figure out a reliable test for this, we'll reparse attributes always. |
| 307 |
* |
| 308 |
* // This DOM pass is trying to bridge broken parses across |
| 309 |
* // template boundaries. So, if templates aren't involved, |
| 310 |
* // no reason to reparse. |
| 311 |
* if ( count( $attributishContent['transclusions'] ) === 0 && |
| 312 |
* !WTUtils::fromEncapsulatedContent( $cell ) |
| 313 |
* ) { |
| 314 |
* return; |
| 315 |
* } |
| 316 |
*/ |
| 317 |
|
| 318 |
$attrText = $attributishContent['txt']; |
| 319 |
if ( !preg_match( '/(^[^|]+\|)([^|]|$)/D', $attrText, $matches ) ) { |
| 320 |
return; |
| 321 |
} |
| 322 |
$attributishPrefix = $matches[1]; |
| 323 |
|
| 324 |
// Splice in nowiki content. We added in <nowiki> markers to prevent the |
| 325 |
// above regexps from matching on nowiki-protected chars. |
| 326 |
if ( str_contains( $attributishPrefix, '<nowiki-marker>' ) ) { |
| 327 |
$attributishPrefix = preg_replace_callback( |
| 328 |
'/<nowiki-marker>/', |
| 329 |
static function ( $unused ) use ( &$attributishContent ) { |
| 330 |
// This is a little tricky. We want to use the content from the |
| 331 |
// nowikis to reparse the string to key/val pairs but the rule, |
| 332 |
// single_cell_table_args, will invariably get tripped up on |
| 333 |
// newlines which, to this point, were shuttled through in the |
| 334 |
// nowiki. Core sanitizer will do this replacement in attr vals |
| 335 |
// so it's a safe normalization to do here. |
| 336 |
return preg_replace( '/\s+/', ' ', array_shift( $attributishContent['nowikis'] ) ); |
| 337 |
}, |
| 338 |
$attributishPrefix |
| 339 |
); |
| 340 |
} |
| 341 |
|
| 342 |
// re-parse the attributish prefix |
| 343 |
if ( !$dtState->tokenizer ) { |
| 344 |
$dtState->tokenizer = new PegTokenizer( $env ); |
| 345 |
} |
| 346 |
$attributeTokens = $dtState->tokenizer->tokenizeTableCellAttributes( $attributishPrefix, false ); |
| 347 |
|
| 348 |
// No attributes => nothing more to do! |
| 349 |
if ( !$attributeTokens ) { |
| 350 |
return; |
| 351 |
} |
| 352 |
|
| 353 |
// Note that `row_syntax_table_args` (the rule used for tokenizing above) |
| 354 |
// returns an array consisting of [table_attributes, spaces, pipe] |
| 355 |
$attrs = $attributeTokens[0]; |
| 356 |
|
| 357 |
// Sanitize attrs and transfer them to the td node |
| 358 |
Sanitizer::applySanitizedArgs( $env->getSiteConfig(), $cell, $attrs ); |
| 359 |
$cellDp = DOMDataUtils::getDataParsoid( $cell ); |
| 360 |
// Reparsed cells start off as non-mergeable-table cells |
| 361 |
// and preserve that property after reparsing |
| 362 |
$cellDp->setTempFlag( TempData::NON_MERGEABLE_TABLE_CELL ); |
| 363 |
$cellDp->setTempFlag( TempData::NO_ATTRS, false ); |
| 364 |
|
| 365 |
// If the transclusion node was embedded within the td node, |
| 366 |
// lift up the about group to the td node. |
| 367 |
$transclusions = $attributishContent['transclusions']; |
| 368 |
if ( $transclusions && ( $cell !== $transclusions[0] || count( $transclusions ) > 1 ) ) { |
| 369 |
self::hoistTransclusionInfo( $dtState, $transclusions, $cell ); |
| 370 |
} |
| 371 |
|
| 372 |
// Drop content that has been consumed by the reparsed attribute content. |
| 373 |
// NOTE: We serialize and reparse data-object-id attributes as well which |
| 374 |
// ensures stashed data-* attributes continue to be usable. |
| 375 |
// FIXME: This is too naive. What about all the care we showed in `collectAttributishContent`? |
| 376 |
DOMCompat::setInnerHTML( $cell, |
| 377 |
preg_replace( '/^[^|]*\|/', '', DOMCompat::getInnerHTML( $cell ) ) ); |
| 378 |
} |
| 379 |
|
| 380 |
/** |
| 381 |
* Possibilities: |
| 382 |
* - $cell and $prev are both <td>s (or both <th>s) |
| 383 |
* - Common case |
| 384 |
* - Ex: "|align=left {{tpl returning | foobar}}" |
| 385 |
* So, "|align=left |foobar" is the combined string |
| 386 |
* - Combined cell is a <td> (will be <th> if both were <th>s) |
| 387 |
* - We assign new attributes to $cell and drop $prev |
| 388 |
* - $cell is <td> and $prev is <th> |
| 389 |
* - Ex: "!align=left {{tpl returning | foobar}}" |
| 390 |
* So, "!align=left |foobar" is the combined string |
| 391 |
* - The combined cell will be a <th> with attributes "align=left" |
| 392 |
* and content "foobar" |
| 393 |
* - $cell is <th> and $prev is <td> |
| 394 |
* - Ex: "|align=left {{tpl returning !scope=row | foobar}}" |
| 395 |
* So "|align=left !scope=row | foobar" is the combined string |
| 396 |
* and we need to drop the th-attributes entirely after combining |
| 397 |
* - The combined cell will be a <td> |
| 398 |
* - $cell's attribute is dropped |
| 399 |
* - $prev's content is dropped |
| 400 |
* |
| 401 |
* FIXME: There are a number of other merge possibilities that end up |
| 402 |
* in this function that aren't accounted for yet! Couple of them are |
| 403 |
* in the unsupported scenario 1/2 buckets below. |
| 404 |
* |
| 405 |
* @param DTState $dtState |
| 406 |
* @param Element $cell |
| 407 |
* @return bool |
| 408 |
*/ |
| 409 |
private static function combineAttrsWithPreviousCell( DTState $dtState, Element $cell ): bool { |
| 410 |
// UNSUPPORTED SCENARIO 1: |
| 411 |
// In this cell-combining scenario, $prev can have attributes only if it |
| 412 |
// also had content. See example below: |
| 413 |
// Ex: |class="foo"|bar{{1x|1={{!}}foo}} |
| 414 |
// should parse as <td class="foo">bar|foo</td> |
| 415 |
// In this case, the attributes/content of $cell would end up as the |
| 416 |
// content of the combined cell. |
| 417 |
// |
| 418 |
// UNSUPPORTED SCENARIO 2: |
| 419 |
// The template produced attributes as well as maybe a new cell. |
| 420 |
// Ex: |class="foo"{{1x| foo}} and |class="foo"{{1x| foo}} |
| 421 |
// We let the more general 'reparseTemplatedAttributes' code handle |
| 422 |
// this scenario for now. |
| 423 |
$prev = $cell->previousSibling; |
| 424 |
DOMUtils::assertElt( $prev ); |
| 425 |
$prevDp = DOMDataUtils::getDataParsoid( $prev ); |
| 426 |
|
| 427 |
// If $prevDp has attributes already, we don't want to reparse content |
| 428 |
// as the attributes. However, we might be in unsupported scenario 1 |
| 429 |
// above, but that's definitionally still unsupported so bail for now. |
| 430 |
if ( !$prevDp->getTempFlag( TempData::NO_ATTRS ) ) { |
| 431 |
return false; |
| 432 |
} |
| 433 |
|
| 434 |
// Build the attribute string |
| 435 |
$frame = $dtState->options['frame']; |
| 436 |
$prevCellSrc = PHPUtils::safeSubstr( |
| 437 |
$frame->getSrcText(), $prevDp->dsr->start, $prevDp->dsr->length() |
| 438 |
); |
| 439 |
$reparseSrc = substr( $prevCellSrc, $prevDp->dsr->openWidth ); |
| 440 |
|
| 441 |
// The previous cell had NO_ATTRS, from the check above, but the cell |
| 442 |
// ends in a vertical bar. This isn't a scenario where we'll combine |
| 443 |
// the cell content to form attributes, so there's no sense in trying |
| 444 |
// to tokenize them below; they probably already failed during the |
| 445 |
// original tokenizing However, the trailing vertical probably does |
| 446 |
// want to be hoisted into the next cell, to combine to form row syntax. |
| 447 |
if ( substr( $reparseSrc, -1 ) === "|" ) { |
| 448 |
return false; |
| 449 |
} |
| 450 |
|
| 451 |
// "|" or "!", but doesn't matter since we discard that anyway |
| 452 |
$reparseSrc .= "|"; |
| 453 |
|
| 454 |
// Reparse the attributish prefix |
| 455 |
$env = $dtState->env; |
| 456 |
if ( !$dtState->tokenizer ) { |
| 457 |
$dtState->tokenizer = new PegTokenizer( $env ); |
| 458 |
} |
| 459 |
$attributeTokens = $dtState->tokenizer->tokenizeTableCellAttributes( $reparseSrc, false ); |
| 460 |
if ( !is_array( $attributeTokens ) ) { |
| 461 |
$env->log( "error/wt2html", |
| 462 |
"TableFixups: Failed to successfully reparse $reparseSrc as table cell attributes" ); |
| 463 |
return false; |
| 464 |
} |
| 465 |
|
| 466 |
// Update data-mw, DSR if $cell is an encapsulation wrapper |
| 467 |
$cellDp = DOMDataUtils::getDataParsoid( $cell ); |
| 468 |
if ( DOMUtils::hasTypeOf( $cell, 'mw:Transclusion' ) ) { |
| 469 |
$dataMW = DOMDataUtils::getDataMw( $cell ); |
| 470 |
array_unshift( $dataMW->parts, $prevCellSrc ); |
| 471 |
$cellDSR = $cellDp->dsr ?? null; |
| 472 |
if ( $cellDSR && $cellDSR->start ) { |
| 473 |
$cellDSR->start -= strlen( $prevCellSrc ); |
| 474 |
} |
| 475 |
} |
| 476 |
|
| 477 |
$parent = $cell->parentNode; |
| 478 |
if ( DOMCompat::nodeName( $cell ) === DOMCompat::nodeName( $prev ) ) { |
| 479 |
// Matching cell types |
| 480 |
$combinedCell = $cell; |
| 481 |
$combinedCellDp = $cellDp; |
| 482 |
$parent->removeChild( $prev ); |
| 483 |
} else { |
| 484 |
// Different cell types |
| 485 |
$combinedCell = $prev; |
| 486 |
|
| 487 |
// Remove all content on $prev which will |
| 488 |
// become the new combined cell |
| 489 |
while ( $prev->firstChild ) { |
| 490 |
$prev->removeChild( $prev->firstChild ); |
| 491 |
} |
| 492 |
// Note that this implicitly migrates data-mw and data-parsoid |
| 493 |
foreach ( DOMUtils::attributes( $cell ) as $k => $v ) { |
| 494 |
$combinedCell->setAttribute( $k, $v ); |
| 495 |
} |
| 496 |
DOMUtils::migrateChildren( $cell, $combinedCell ); |
| 497 |
$parent->removeChild( $cell ); |
| 498 |
|
| 499 |
$combinedCellDp = DOMDataUtils::getDataParsoid( $combinedCell ); |
| 500 |
} |
| 501 |
|
| 502 |
// Note that `row_syntax_table_args` (the rule used for tokenizing above) |
| 503 |
// returns an array consisting of [table_attributes, spaces, pipe] |
| 504 |
$attrs = $attributeTokens[0]; |
| 505 |
Sanitizer::applySanitizedArgs( $env->getSiteConfig(), $combinedCell, $attrs ); |
| 506 |
// Combined cells don't merge further |
| 507 |
$combinedCellDp->setTempFlag( TempData::NON_MERGEABLE_TABLE_CELL ); |
| 508 |
$combinedCellDp->setTempFlag( TempData::NO_ATTRS, false ); |
| 509 |
|
| 510 |
return true; |
| 511 |
} |
| 512 |
|
| 513 |
private const NO_REPARSING = 0; |
| 514 |
private const COMBINE_WITH_PREV_CELL = 1; |
| 515 |
private const OTHER_REPARSE = 2; |
| 516 |
|
| 517 |
/** |
| 518 |
* $cell is known to be <td>/<th> |
| 519 |
*/ |
| 520 |
private static function getReparseType( Element $cell, DTState $dtState ): int { |
| 521 |
$inTplContent = $dtState->tplInfo !== null; |
| 522 |
$dp = DOMDataUtils::getDataParsoid( $cell ); |
| 523 |
if ( !$dp->getTempFlag( TempData::NON_MERGEABLE_TABLE_CELL ) && |
| 524 |
!$dp->getTempFlag( TempData::FAILED_REPARSE ) && |
| 525 |
// This is a good proxy for what we need: "Is $cell a template wrapper?". |
| 526 |
// That info won't be available for nested templates unless we want |
| 527 |
// to use a more expensive hacky check. |
| 528 |
// "inTplContent" is sufficient because we won't have mergeable |
| 529 |
// cells for wikitext that doesn't get any part of its content from |
| 530 |
// templates because NON_MERGEABLE_TABLE_CELL prevents such merges. |
| 531 |
$inTplContent |
| 532 |
) { |
| 533 |
// Look for opportunities where table cells could combine. This requires |
| 534 |
// $cell to be a templated cell. But, we don't support combining |
| 535 |
// templated cells with other templated cells. So, previous sibling |
| 536 |
// cannot be templated. |
| 537 |
// |
| 538 |
// So, bail out of scenarios where prevDp comes from a template (the checks |
| 539 |
// for isValidDSR( $prevDp-> dsr ) and valid opening tag width catch this. |
| 540 |
$prev = $cell->previousSibling; |
| 541 |
$prevDp = $prev instanceof Element ? DOMDataUtils::getDataParsoid( $prev ) : null; |
| 542 |
if ( $prevDp && |
| 543 |
!WTUtils::hasLiteralHTMLMarker( $prevDp ) && |
| 544 |
Utils::isValidDSR( $prevDp->dsr ?? null, true ) && |
| 545 |
!DOMUtils::hasTypeOf( $prev, 'mw:Transclusion' ) && |
| 546 |
!str_contains( DOMCompat::getInnerHTML( $prev ), "\n" ) |
| 547 |
) { |
| 548 |
return self::COMBINE_WITH_PREV_CELL; |
| 549 |
} |
| 550 |
} |
| 551 |
|
| 552 |
$cellIsTd = DOMCompat::nodeName( $cell ) === 'td'; |
| 553 |
$testRE = $cellIsTd ? '/[|]/' : '/[!|]/'; |
| 554 |
$child = $cell->firstChild; |
| 555 |
while ( $child ) { |
| 556 |
if ( !$inTplContent && DOMUtils::hasTypeOf( $child, 'mw:Transclusion' ) ) { |
| 557 |
$inTplContent = true; |
| 558 |
} |
| 559 |
|
| 560 |
if ( $inTplContent && |
| 561 |
$child instanceof Text && |
| 562 |
preg_match( $testRE, $child->textContent ) |
| 563 |
) { |
| 564 |
return self::OTHER_REPARSE; |
| 565 |
} |
| 566 |
|
| 567 |
if ( $child instanceof Element ) { |
| 568 |
if ( WTUtils::isFirstExtensionWrapperNode( $child ) ) { |
| 569 |
// "|" chars in extension/language variant content don't trigger |
| 570 |
// table-cell parsing since they have higher precedence in tokenization |
| 571 |
$child = WTUtils::skipOverEncapsulatedContent( $child ); |
| 572 |
} else { |
| 573 |
if ( DOMUtils::hasRel( $child, 'mw:WikiLink' ) || |
| 574 |
WTUtils::isGeneratedFigure( $child ) |
| 575 |
) { |
| 576 |
// Wikilinks/images abort attribute parsing |
| 577 |
return self::NO_REPARSING; |
| 578 |
} |
| 579 |
// FIXME: Ugly for now |
| 580 |
$outerHTML = DOMCompat::getOuterHTML( $child ); |
| 581 |
if ( preg_match( $testRE, $outerHTML ) && |
| 582 |
( $inTplContent || preg_match( '/"mw:Transclusion"/', $outerHTML ) ) |
| 583 |
) { |
| 584 |
// A "|" char in the HTML will trigger table cell tokenization. |
| 585 |
// Ex: "| foobar <div> x | y </div>" will split the <div> |
| 586 |
// in table-cell tokenization context. |
| 587 |
return self::OTHER_REPARSE; |
| 588 |
} |
| 589 |
$child = $child->nextSibling; |
| 590 |
} |
| 591 |
} else { |
| 592 |
$child = $child->nextSibling; |
| 593 |
} |
| 594 |
} |
| 595 |
|
| 596 |
return self::NO_REPARSING; |
| 597 |
} |
| 598 |
|
| 599 |
/** |
| 600 |
* In a wikitext-syntax-table-parsing context, the meaning of |
| 601 |
* "|", "||", "!", "!!" is context-sensitive. Additionally, the |
| 602 |
* complete syntactical construct for a table cell (including leading |
| 603 |
* pipes, attributes, and content-separating pipe char) might straddle |
| 604 |
* a template boundary - with some content coming from the top-level and |
| 605 |
* some from a template. |
| 606 |
* |
| 607 |
* This impacts parsing of tables when some cells are templated since |
| 608 |
* Parsoid parses template content independent of top-level content |
| 609 |
* (without any preceding context). This means that Parsoid's table-cell |
| 610 |
* parsing in templated contexts might be incorrect |
| 611 |
* |
| 612 |
* To deal with this, Parsoid implements this table-fixups pass that |
| 613 |
* has to deal with cell-merging and cell-reparsing scenarios. |
| 614 |
* |
| 615 |
* HTML-syntax cells and non-templated cells without any templated content |
| 616 |
* are not subject to this transformation and can be skipped right away. |
| 617 |
* |
| 618 |
* FIXME: This pass can benefit from a customized procsssor rather than |
| 619 |
* piggyback on top of DOMTraverser since the DOM can be significantly |
| 620 |
* mutated in these handlers. |
| 621 |
* |
| 622 |
* @param Element $cell $cell is known to be <td>/<th> |
| 623 |
* @param DTState $dtState |
| 624 |
* @return mixed |
| 625 |
*/ |
| 626 |
public static function handleTableCellTemplates( Element $cell, DTState $dtState ) { |
| 627 |
if ( WTUtils::isLiteralHTMLNode( $cell ) ) { |
| 628 |
return true; |
| 629 |
} |
| 630 |
|
| 631 |
// Deal with <th> special case where "!! foo" is parsed as <th>! foo</th> |
| 632 |
// but should have been parsed as <th>foo</th> when not the first child |
| 633 |
if ( DOMCompat::nodeName( $cell ) === 'th' && |
| 634 |
DOMUtils::hasTypeOf( $cell, 'mw:Transclusion' ) && |
| 635 |
// This is checking that previous sibling is not "\n" which would |
| 636 |
// signal that this <th> is on a fresh line and the "!" shouldn't be stripped. |
| 637 |
// If this weren't template output, we would check for "stx" === 'row'. |
| 638 |
// FIXME: Note that ths check is fragile and doesn't work always, but this is |
| 639 |
// the price we pay for Parsoid's independent template parsing! |
| 640 |
$cell->previousSibling instanceof Element |
| 641 |
) { |
| 642 |
$fc = DiffDOMUtils::firstNonSepChild( $cell ); |
| 643 |
if ( $fc instanceof Text ) { |
| 644 |
$leadingText = $fc->nodeValue; |
| 645 |
if ( str_starts_with( $leadingText, "!" ) ) { |
| 646 |
$fc->nodeValue = substr( $leadingText, 1 ); |
| 647 |
} |
| 648 |
} |
| 649 |
} |
| 650 |
|
| 651 |
$reparseType = self::getReparseType( $cell, $dtState ); |
| 652 |
if ( $reparseType === self::NO_REPARSING ) { |
| 653 |
return true; |
| 654 |
} |
| 655 |
|
| 656 |
$cellDp = DOMDataUtils::getDataParsoid( $cell ); |
| 657 |
if ( $reparseType === self::COMBINE_WITH_PREV_CELL ) { |
| 658 |
if ( self::combineAttrsWithPreviousCell( $dtState, $cell ) ) { |
| 659 |
return true; |
| 660 |
} else { |
| 661 |
// Clear property and retry $cell for other reparses |
| 662 |
// The DOMTraverser will resume the handler on the |
| 663 |
// returned $cell. |
| 664 |
$cellDp->setTempFlag( TempData::FAILED_REPARSE ); |
| 665 |
return $cell; |
| 666 |
} |
| 667 |
} |
| 668 |
|
| 669 |
// If the cell didn't have attrs, extract and reparse templated attrs |
| 670 |
if ( $cellDp->getTempFlag( TempData::NO_ATTRS ) ) { |
| 671 |
$frame = $dtState->options['frame']; |
| 672 |
$templateWrapper = DOMUtils::hasTypeOf( $cell, 'mw:Transclusion' ) ? $cell : null; |
| 673 |
self::reparseTemplatedAttributes( $dtState, $cell, $templateWrapper ); |
| 674 |
} |
| 675 |
|
| 676 |
// Now, examine the <td> to see if it hides additional <td>s |
| 677 |
// and split it up if required. |
| 678 |
// |
| 679 |
// DOMTraverser will process the new cell and invoke |
| 680 |
// handleTableCellTemplates on it which ensures that |
| 681 |
// if any addition attribute fixup or splits are required, |
| 682 |
// they will get done. |
| 683 |
$newCell = null; |
| 684 |
$isTd = DOMCompat::nodeName( $cell ) === 'td'; |
| 685 |
$ownerDoc = $cell->ownerDocument; |
| 686 |
$child = $cell->firstChild; |
| 687 |
while ( $child ) { |
| 688 |
$next = $child->nextSibling; |
| 689 |
|
| 690 |
if ( $newCell ) { |
| 691 |
$newCell->appendChild( $child ); |
| 692 |
} elseif ( $child instanceof Text || self::isSimpleTemplatedSpan( $child ) ) { |
| 693 |
// FIXME: This skips over scenarios like <div>foo||bar</div>. |
| 694 |
$cellName = DOMCompat::nodeName( $cell ); |
| 695 |
$hasSpanWrapper = !( $child instanceof Text ); |
| 696 |
$match = $match1 = $match2 = null; |
| 697 |
|
| 698 |
// Find the first match of || |
| 699 |
preg_match( '/^((?:[^|]*(?:\|[^|])?)*)\|\|([^|].*)?$/D', $child->textContent, $match1 ); |
| 700 |
if ( $isTd ) { |
| 701 |
$match = $match1; |
| 702 |
} else { |
| 703 |
// Find the first match !! |
| 704 |
preg_match( '/^((?:[^!]*(?:\![^!])?)*)\!\!([^!].*)?$/D', $child->textContent, $match2 ); |
| 705 |
|
| 706 |
// Pick the shortest match |
| 707 |
if ( $match1 && $match2 ) { |
| 708 |
$match = strlen( $match1[1] ?? '' ) < strlen( $match2[1] ?? '' ) |
| 709 |
? $match1 |
| 710 |
: $match2; |
| 711 |
} else { |
| 712 |
$match = $match1 ?: $match2; |
| 713 |
} |
| 714 |
} |
| 715 |
|
| 716 |
if ( $match ) { |
| 717 |
$child->textContent = $match[1] ?? ''; |
| 718 |
|
| 719 |
$newCell = $ownerDoc->createElement( $cellName ); |
| 720 |
if ( $hasSpanWrapper ) { |
| 721 |
/** |
| 722 |
* $hasSpanWrapper above ensures $child is a span. |
| 723 |
* |
| 724 |
* @var Element $child |
| 725 |
*/ |
| 726 |
'@phan-var Element $child'; |
| 727 |
// Fix up transclusion wrapping |
| 728 |
$about = DOMCompat::getAttribute( $child, 'about' ); |
| 729 |
self::hoistTransclusionInfo( $dtState, [ $child ], $cell ); |
| 730 |
} else { |
| 731 |
// Refetch the about attribute since 'reparseTemplatedAttributes' |
| 732 |
// might have added one to it. |
| 733 |
$about = DOMCompat::getAttribute( $cell, 'about' ); |
| 734 |
} |
| 735 |
|
| 736 |
// about may not be present if the cell was inside |
| 737 |
// wrapped template content rather than being part |
| 738 |
// of the outermost wrapper. |
| 739 |
if ( $about !== null ) { |
| 740 |
$newCell->setAttribute( 'about', $about ); |
| 741 |
if ( $dtState->tplInfo && $dtState->tplInfo->last === $cell ) { |
| 742 |
$dtState->tplInfo->last = $newCell; |
| 743 |
} |
| 744 |
} |
| 745 |
$newCell->appendChild( $ownerDoc->createTextNode( $match[2] ?? '' ) ); |
| 746 |
$cell->parentNode->insertBefore( $newCell, $cell->nextSibling ); |
| 747 |
|
| 748 |
// Set data-parsoid noAttrs flag |
| 749 |
$newCellDp = DOMDataUtils::getDataParsoid( $newCell ); |
| 750 |
// This new cell has 'row' stx (would be set if the tokenizer had parsed it) |
| 751 |
$newCellDp->stx = 'row'; |
| 752 |
$newCellDp->setTempFlag( TempData::NO_ATTRS ); |
| 753 |
// It is important to set this so that when $newCell is processed by this pass, |
| 754 |
// it won't accidentally recombine again with the previous cell! |
| 755 |
$newCellDp->setTempFlag( TempData::NON_MERGEABLE_TABLE_CELL ); |
| 756 |
} |
| 757 |
} |
| 758 |
|
| 759 |
$child = $next; |
| 760 |
} |
| 761 |
|
| 762 |
return true; |
| 763 |
} |
| 764 |
} |