Debian Codegraph @

extensions/Cite/src/Parsoid/References.php

raw symbols SCIP
1 <?php
2 declare( strict_types = 1 );
3 // phpcs:disable MediaWiki.WhiteSpace.SpaceBeforeSingleLineComment.NewLineComment
4 // @phan-file-suppress MediaWikiNoEmptyIfDefined Phan thinks the @property docs in the DataParsoid
5 // class are a guarantee, but they aren't
6
7 namespace Cite\Parsoid;
8
9 use Closure;
10 use MediaWiki\Config\Config;
11 use stdClass;
12 use Wikimedia\Parsoid\Core\DomSourceRange;
13 use Wikimedia\Parsoid\DOM\DocumentFragment;
14 use Wikimedia\Parsoid\DOM\Element;
15 use Wikimedia\Parsoid\DOM\Node;
16 use Wikimedia\Parsoid\Ext\DOMDataUtils;
17 use Wikimedia\Parsoid\Ext\DOMUtils;
18 use Wikimedia\Parsoid\Ext\ExtensionTagHandler;
19 use Wikimedia\Parsoid\Ext\ParsoidExtensionAPI;
20 use Wikimedia\Parsoid\Ext\PHPUtils;
21 use Wikimedia\Parsoid\Ext\WTUtils;
22 use Wikimedia\Parsoid\NodeData\DataMw;
23 use Wikimedia\Parsoid\NodeData\DataMwError;
24 use Wikimedia\Parsoid\NodeData\DataParsoid;
25 use Wikimedia\Parsoid\Utils\DOMCompat;
26
27 /**
28 * @license GPL-2.0-or-later
29 */
30 class References extends ExtensionTagHandler {
31 private Config $mainConfig;
32
33 public function __construct( Config $mainConfig ) {
34 $this->mainConfig = $mainConfig;
35 }
36
37 private static function hasRef( Node $node ): bool {
38 $c = $node->firstChild;
39 while ( $c ) {
40 if ( $c instanceof Element ) {
41 if ( WTUtils::isSealedFragmentOfType( $c, 'ref' ) ) {
42 return true;
43 }
44 if ( self::hasRef( $c ) ) {
45 return true;
46 }
47 }
48 $c = $c->nextSibling;
49 }
50 return false;
51 }
52
53 private function createReferences(
54 ParsoidExtensionAPI $extApi, DocumentFragment $domFragment,
55 array $refsOpts, ?callable $modifyDp, bool $autoGenerated = false
56 ): Element {
57 $doc = $domFragment->ownerDocument;
58
59 $ol = $doc->createElement( 'ol' );
60 DOMCompat::getClassList( $ol )->add( 'mw-references', 'references' );
61
62 DOMUtils::migrateChildren( $domFragment, $ol );
63
64 // Support the `responsive` parameter
65 if ( $refsOpts['responsive'] !== null ) {
66 $responsiveWrap = $refsOpts['responsive'] !== '0';
67 } else {
68 $responsiveWrap = (bool)$this->mainConfig->get( 'CiteResponsiveReferences' );
69 }
70
71 if ( $responsiveWrap ) {
72 $div = $doc->createElement( 'div' );
73 DOMCompat::getClassList( $div )->add( 'mw-references-wrap' );
74 $div->appendChild( $ol );
75 $frag = $div;
76 } else {
77 $frag = $ol;
78 }
79
80 if ( $autoGenerated ) {
81 // FIXME: This is very much trying to copy ExtensionHandler::onDocument
82 DOMUtils::addAttributes( $frag, [
83 'typeof' => 'mw:Extension/references',
84 'about' => $extApi->newAboutId()
85 ] );
86 $dataMw = new DataMw( [
87 'name' => 'references',
88 'attrs' => new stdClass
89 ] );
90 // Dont emit empty keys
91 if ( $refsOpts['group'] ) {
92 $dataMw->attrs->group = $refsOpts['group'];
93 }
94 DOMDataUtils::setDataMw( $frag, $dataMw );
95 }
96
97 $dp = DOMDataUtils::getDataParsoid( $frag );
98 if ( $refsOpts['group'] ) { // No group for the empty string either
99 $dp->group = $refsOpts['group'];
100 $ol->setAttribute( 'data-mw-group', $refsOpts['group'] );
101 }
102 if ( $modifyDp ) {
103 $modifyDp( $dp );
104 }
105
106 // These module namess are copied from Cite extension.
107 // They are hardcoded there as well.
108 $metadata = $extApi->getMetadata();
109 $metadata->addModules( [ 'ext.cite.ux-enhancements' ] );
110 $metadata->addModuleStyles( [ 'ext.cite.parsoid.styles', 'ext.cite.styles' ] );
111
112 return $frag;
113 }
114
115 private function extractRefFromNode(
116 ParsoidExtensionAPI $extApi, Element $node, ReferencesData $refsData
117 ): void {
118 $doc = $node->ownerDocument;
119 $errs = [];
120
121 // This is data-parsoid from the dom fragment node that's gone through
122 // dsr computation and template wrapping.
123 $nodeDp = DOMDataUtils::getDataParsoid( $node );
124 $isTplWrapper = DOMUtils::hasTypeOf( $node, 'mw:Transclusion' );
125 $contentId = $nodeDp->html;
126 $tplDmw = $isTplWrapper ? DOMDataUtils::getDataMw( $node ) : null;
127
128 // This is the <sup> that's the meat of the sealed fragment
129 $c = $extApi->getContentDOM( $contentId )->firstChild;
130 DOMUtils::assertElt( $c );
131 $cDp = DOMDataUtils::getDataParsoid( $c );
132 $refDmw = DOMDataUtils::getDataMw( $c );
133
134 // Use the about attribute on the wrapper with priority, since it's
135 // only added when the wrapper is a template sibling.
136 $about = DOMCompat::getAttribute( $node, 'about' ) ??
137 DOMCompat::getAttribute( $c, 'about' );
138 '@phan-var string $about'; // assert that $about is non-null
139
140 // FIXME(SSS): Need to clarify semantics here.
141 // If both the containing <references> elt as well as the nested <ref>
142 // elt has a group attribute, what takes precedence?
143 $groupName = $refDmw->attrs->group ?? $refsData->referencesGroup;
144 $group = $refsData->getRefGroup( $groupName );
145
146 if (
147 $refsData->inReferencesContent() &&
148 $groupName !== $refsData->referencesGroup
149 ) {
150 $errs[] = new DataMwError(
151 'cite_error_references_group_mismatch',
152 [ $refDmw->attrs->group ]
153 );
154 }
155
156 // NOTE: This will have been trimmed in Utils::getExtArgInfo()'s call
157 // to TokenUtils::kvToHash() and ExtensionHandler::normalizeExtOptions()
158 $refName = $refDmw->attrs->name ?? '';
159 $followName = $refDmw->attrs->follow ?? '';
160 $refDir = strtolower( $refDmw->attrs->dir ?? '' );
161
162 // Add ref-index linkback
163 $linkBack = $doc->createElement( 'sup' );
164
165 $ref = null;
166
167 $hasRefName = strlen( $refName ) > 0;
168 $hasFollow = strlen( $followName ) > 0;
169
170 $validFollow = false;
171
172 if ( $hasFollow ) {
173 // Always wrap follows content so that there's no ambiguity
174 // where to find it when roundtripping
175 $span = $doc->createElement( 'span' );
176 DOMUtils::addTypeOf( $span, 'mw:Cite/Follow' );
177 $span->setAttribute( 'about', $about );
178 $span->appendChild(
179 $doc->createTextNode( ' ' )
180 );
181 DOMUtils::migrateChildren( $c, $span );
182 $c->appendChild( $span );
183 }
184
185 $html = '';
186 $contentDiffers = false;
187
188 if ( $hasRefName ) {
189 if ( $hasFollow ) {
190 // Presumably, "name" has higher precedence
191 $errs[] = new DataMwError( 'cite_error_ref_follow_conflicts' );
192 }
193 if ( isset( $group->indexByName[$refName] ) ) {
194 $ref = $group->indexByName[$refName];
195 // If there are multiple <ref>s with the same name, but different content,
196 // the content of the first <ref> shows up in the <references> section.
197 // in order to ensure lossless RT-ing for later <refs>, we have to record
198 // HTML inline for all of them.
199 if ( $ref->contentId ) {
200 if ( $ref->cachedHtml === null ) {
201 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive
202 $refContent = $extApi->getContentDOM( $ref->contentId )->firstChild;
203 $ref->cachedHtml = $extApi->domToHtml( $refContent, true, false );
204 }
205 // See the test, "Forward-referenced ref with magical follow edge case"
206 // Ideally, we should strip the mw:Cite/Follow wrappers before comparing
207 // But, we are going to ignore this edge case as not worth the complexity.
208 $html = $extApi->domToHtml( $c, true, false );
209 $contentDiffers = ( $html !== $ref->cachedHtml );
210 }
211 } else {
212 if ( $refsData->inReferencesContent() ) {
213 $errs[] = new DataMwError(
214 'cite_error_references_missing_key',
215 [ $refDmw->attrs->name ]
216 );
217 }
218 }
219 } else {
220 if ( $hasFollow ) {
221 // This is a follows ref, so check that a named ref has already
222 // been defined
223 if ( isset( $group->indexByName[$followName] ) ) {
224 $validFollow = true;
225 $ref = $group->indexByName[$followName];
226 } else {
227 // FIXME: This key isn't exactly appropriate since this
228 // is more general than just being in a <references>
229 // section and it's the $followName we care about, but the
230 // extension to the legacy parser doesn't have an
231 // equivalent key and just outputs something wacky.
232 $errs[] = new DataMwError(
233 'cite_error_references_missing_key',
234 [ $refDmw->attrs->follow ]
235 );
236 }
237 } elseif ( $refsData->inReferencesContent() ) {
238 $errs[] = new DataMwError( 'cite_error_references_no_key' );
239 }
240 }
241
242 // Process nested ref-in-ref
243 //
244 // Do this before possibly adding the a ref below or
245 // migrating contents out of $c if we have a valid follow
246 if ( empty( $cDp->empty ) && self::hasRef( $c ) ) {
247 if ( $contentDiffers ) {
248 $refsData->pushEmbeddedContentFlag();
249 }
250 $this->processRefs( $extApi, $refsData, $c );
251 if ( $contentDiffers ) {
252 $refsData->popEmbeddedContentFlag();
253 // If we have refs and the content differs, we need to
254 // reserialize now that we processed the refs. Unfortunately,
255 // the cachedHtml we compared against already had its refs
256 // processed so that would presumably never match and this will
257 // always be considered a redefinition. The implementation for
258 // the legacy parser also considers this a redefinition so
259 // there is likely little content out there like this :)
260 $html = $extApi->domToHtml( $c, true, true );
261 }
262 }
263
264 if ( $validFollow ) {
265 // Migrate content from the follow to the ref
266 if ( $ref->contentId ) {
267 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive
268 $refContent = $extApi->getContentDOM( $ref->contentId )->firstChild;
269 DOMUtils::migrateChildren( $c, $refContent );
270 } else {
271 // Otherwise, we have a follow that comes after a named
272 // ref without content so use the follow fragment as
273 // the content
274 // This will be set below with `$ref->contentId = $contentId;`
275 }
276 } else {
277 // If we have !$ref, one might have been added in the call to
278 // processRefs, ie. a self-referential ref. We could try to look
279 // it up again, but Parsoid is choosing not to support that.
280 // Even worse would be if it tried to redefine itself!
281
282 if ( !$ref ) {
283 $ref = $refsData->add( $extApi, $groupName, $refName, $refDir );
284 }
285
286 // Handle linkbacks
287 if ( $refsData->inEmbeddedContent() ) {
288 $ref->embeddedNodes[] = $about;
289 } else {
290 $ref->nodes[] = $linkBack;
291 $ref->linkbacks[] = $ref->key . '-' . count( $ref->linkbacks );
292 }
293 }
294
295 if ( isset( $refDmw->attrs->dir ) ) {
296 if ( $refDir !== 'rtl' && $refDir !== 'ltr' ) {
297 $errs[] = new DataMwError( 'cite_error_ref_invalid_dir', [ $refDir ] );
298 } elseif ( $ref->dir !== '' && $ref->dir !== $refDir ) {
299 $errs[] = new DataMwError( 'cite_error_ref_conflicting_dir', [ $ref->name ] );
300 }
301 }
302
303 // FIXME: At some point this error message can be changed to a warning, as Parsoid Cite now
304 // supports numerals as a name without it being an actual error, but core Cite does not.
305 // Follow refs do not duplicate the error which can be correlated with the original ref.
306 if ( ctype_digit( $refName ) ) {
307 $errs[] = new DataMwError( 'cite_error_ref_numeric_key' );
308 }
309
310 // Check for missing content, added ?? '' to fix T259676 crasher
311 // FIXME: See T260082 for a more complete description of cause and deeper fix
312 $missingContent = ( !empty( $cDp->empty ) || trim( $refDmw->body->extsrc ?? '' ) === '' );
313
314 if ( $missingContent ) {
315 // Check for missing name and content to generate error code
316 //
317 // In references content, refs should be used for definition so missing content
318 // is an error. It's possible that no name is present (!hasRefName), which also
319 // gets the error "cite_error_references_no_key" above, so protect against that.
320 if ( $refsData->inReferencesContent() ) {
321 $errs[] = new DataMwError(
322 'cite_error_empty_references_define',
323 [ $refDmw->attrs->name ?? '', $refDmw->attrs->group ?? '' ]
324 );
325 } elseif ( !$hasRefName ) {
326 if ( !empty( $cDp->selfClose ) ) {
327 $errs[] = new DataMwError( 'cite_error_ref_no_key' );
328 } else {
329 $errs[] = new DataMwError( 'cite_error_ref_no_input' );
330 }
331 }
332
333 if ( !empty( $cDp->selfClose ) ) {
334 unset( $refDmw->body );
335 } else {
336 // Empty the <sup> since we've serialized its children and
337 // removing it below asserts everything has been migrated out
338 DOMCompat::replaceChildren( $c );
339 $refDmw->body = (object)[ 'html' => $refDmw->body->extsrc ?? '' ];
340 }
341 } else {
342 if ( $ref->contentId && !$validFollow ) {
343 // Empty the <sup> since we've serialized its children and
344 // removing it below asserts everything has been migrated out
345 DOMCompat::replaceChildren( $c );
346 }
347 if ( $contentDiffers ) {
348 // TODO: Since this error is being placed on the ref, the
349 // key should arguably be "cite_error_ref_duplicate_key"
350 $errs[] = new DataMwError(
351 'cite_error_references_duplicate_key',
352 [ $refDmw->attrs->name ]
353 );
354 $refDmw->body = (object)[ 'html' => $html ];
355 } else {
356 $refDmw->body = (object)[ 'id' => 'mw-reference-text-' . $ref->target ];
357 }
358 }
359
360 $class = 'mw-ref reference';
361 if ( $validFollow ) {
362 $class .= ' mw-ref-follow';
363 }
364
365 $lastLinkback = $ref->linkbacks[count( $ref->linkbacks ) - 1] ?? null;
366 DOMUtils::addAttributes( $linkBack, [
367 'about' => $about,
368 'class' => $class,
369 'id' => ( $refsData->inEmbeddedContent() || $validFollow ) ?
370 null : ( $ref->name ? $lastLinkback : $ref->id ),
371 'rel' => 'dc:references',
372 'typeof' => DOMCompat::getAttribute( $node, 'typeof' ),
373 ]
374 );
375 DOMUtils::removeTypeOf( $linkBack, 'mw:DOMFragment/sealed/ref' );
376 DOMUtils::addTypeOf( $linkBack, 'mw:Extension/ref' );
377
378 $dataParsoid = new DataParsoid;
379 if ( isset( $nodeDp->src ) ) {
380 $dataParsoid->src = $nodeDp->src;
381 }
382 if ( isset( $nodeDp->dsr ) ) {
383 $dataParsoid->dsr = $nodeDp->dsr;
384 }
385 if ( isset( $nodeDp->pi ) ) {
386 $dataParsoid->pi = $nodeDp->pi;
387 }
388 DOMDataUtils::setDataParsoid( $linkBack, $dataParsoid );
389
390 $dmw = $isTplWrapper ? $tplDmw : $refDmw;
391 DOMDataUtils::setDataMw( $linkBack, $dmw );
392
393 // FIXME(T214241): Should the errors be added to data-mw if
394 // $isTplWrapper? Here and other calls to addErrorsToNode.
395 if ( $errs ) {
396 self::addErrorsToNode( $linkBack, $errs );
397 }
398
399 // refLink is the link to the citation
400 $refLink = $doc->createElement( 'a' );
401 DOMUtils::addAttributes( $refLink, [
402 'href' => $extApi->getPageUri() . '#' . $ref->target,
403 'style' => 'counter-reset: mw-Ref ' . $ref->groupIndex . ';',
404 ] );
405 if ( $ref->group ) {
406 $refLink->setAttribute( 'data-mw-group', $ref->group );
407 }
408
409 // refLink-span which will contain a default rendering of the cite link
410 // for browsers that don't support counters
411 $refLinkSpan = $doc->createElement( 'span' );
412 $refLinkSpan->setAttribute( 'class', 'mw-reflink-text' );
413 $refLinkSpan->appendChild( $doc->createTextNode(
414 '[' . ( $ref->group ? $ref->group . ' ' : '' ) . $ref->groupIndex . ']'
415 ) );
416
417 $refLink->appendChild( $refLinkSpan );
418 $linkBack->appendChild( $refLink );
419
420 // Checking if the <ref> is nested in a link
421 $aParent = DOMUtils::findAncestorOfName( $node, 'a' );
422 if ( $aParent !== null ) {
423 // If we find a parent link, we hoist the reference up, just after the link
424 // But if there's multiple references in a single link, we want to insert in order -
425 // so we look for other misnested references before inserting
426 $insertionPoint = $aParent->nextSibling;
427 while ( $insertionPoint instanceof Element &&
428 DOMCompat::nodeName( $insertionPoint ) === 'sup' &&
429 !empty( DOMDataUtils::getDataParsoid( $insertionPoint )->misnested )
430 ) {
431 $insertionPoint = $insertionPoint->nextSibling;
432 }
433 $aParent->parentNode->insertBefore( $linkBack, $insertionPoint );
434 // set misnested to true and DSR to zero-sized to avoid round-tripping issues
435 $dsrOffset = DOMDataUtils::getDataParsoid( $aParent )->dsr->end ?? null;
436 // we created that node hierarchy above, so we know that it only contains these nodes,
437 // hence there's no need for a visitor
438 self::setMisnested( $linkBack, $dsrOffset );
439 self::setMisnested( $refLink, $dsrOffset );
440 self::setMisnested( $refLinkSpan, $dsrOffset );
441 $parentAbout = DOMCompat::getAttribute( $aParent, 'about' );
442 if ( $parentAbout !== null ) {
443 $linkBack->setAttribute( 'about', $parentAbout );
444 }
445 $node->parentNode->removeChild( $node );
446 } else {
447 // if not, we insert it where we planned in the first place
448 $node->parentNode->replaceChild( $linkBack, $node );
449 }
450
451 // Keep the first content to compare multiple <ref>s with the same name.
452 if ( $ref->contentId === null && !$missingContent ) {
453 $ref->contentId = $contentId;
454 // Use the dir parameter only from the full definition of a named ref tag
455 $ref->dir = $refDir;
456 } else {
457 DOMCompat::remove( $c );
458 $extApi->clearContentDOM( $contentId );
459 }
460 }
461
462 /**
463 * Sets a node as misnested and its DSR as zero-width.
464 */
465 private static function setMisnested( Element $node, ?int $offset ) {
466 $dataParsoid = DOMDataUtils::getDataParsoid( $node );
467 $dataParsoid->misnested = true;
468 $dataParsoid->dsr = new DomSourceRange( $offset, $offset, null, null );
469 }
470
471 /**
472 * @param Element $node
473 * @param list<DataMwError> $errs
474 */
475 private static function addErrorsToNode( Element $node, array $errs ): void {
476 DOMUtils::addTypeOf( $node, 'mw:Error' );
477 $dmw = DOMDataUtils::getDataMw( $node );
478 $dmw->errors = is_array( $dmw->errors ?? null ) ?
479 array_merge( $dmw->errors, $errs ) : $errs;
480 }
481
482 private function insertReferencesIntoDOM(
483 ParsoidExtensionAPI $extApi, Element $refsNode,
484 ReferencesData $refsData, bool $autoGenerated = false
485 ): void {
486 $isTplWrapper = DOMUtils::hasTypeOf( $refsNode, 'mw:Transclusion' );
487 $dp = DOMDataUtils::getDataParsoid( $refsNode );
488 $group = $dp->group ?? '';
489 $refGroup = $refsData->getRefGroup( $group );
490
491 // Iterate through the ref list to back-patch typeof and data-mw error
492 // information into ref for errors only known at time of references
493 // insertion. Refs in the top level dom will be processed immediately,
494 // whereas embedded refs will be gathered for batch processing, since
495 // we need to parse embedded content to find them.
496 if ( $refGroup ) {
497 $autoGeneratedWithGroup = ( $autoGenerated && $group !== '' );
498 foreach ( $refGroup->refs as $ref ) {
499 $errs = [];
500 // Mark all refs that are part of a group that is autogenerated
501 if ( $autoGeneratedWithGroup ) {
502 $errs[] = new DataMwError(
503 'cite_error_group_refs_without_references',
504 [ $group ]
505 );
506 }
507 // Mark all refs that are named without content
508 if ( ( $ref->name !== '' ) && $ref->contentId === null ) {
509 // TODO: Since this error is being placed on the ref,
510 // the key should arguably be "cite_error_ref_no_text"
511 $errs[] = new DataMwError(
512 'cite_error_references_no_text',
513 [ $ref->name ]
514 );
515 }
516 if ( $errs ) {
517 foreach ( $ref->nodes as $node ) {
518 self::addErrorsToNode( $node, $errs );
519 }
520 foreach ( $ref->embeddedNodes as $about ) {
521 $refsData->embeddedErrors[$about] = $errs;
522 }
523 }
524 }
525 }
526
527 // Note that `$sup`s here are probably all we really need to check for
528 // errors caught with `$refsData->inReferencesContent()` but it's
529 // probably easier to just know that state while they're being
530 // constructed.
531 $nestedRefsHTML = array_map(
532 static function ( Element $sup ) use ( $extApi ) {
533 return $extApi->domToHtml( $sup, false, true ) . "\n";
534 },
535 PHPUtils::iterable_to_array( DOMCompat::querySelectorAll(
536 $refsNode, 'sup[typeof~=\'mw:Extension/ref\']'
537 ) )
538 );
539
540 if ( !$isTplWrapper ) {
541 $dataMw = DOMDataUtils::getDataMw( $refsNode );
542 // Mark this auto-generated so that we can skip this during
543 // html -> wt and so that clients can strip it if necessary.
544 if ( $autoGenerated ) {
545 $dataMw->autoGenerated = true;
546 } elseif ( $nestedRefsHTML ) {
547 $dataMw->body = (object)[ 'html' => "\n" . implode( $nestedRefsHTML ) ];
548 } elseif ( empty( $dp->selfClose ) ) {
549 $dataMw->body = (object)[ 'html' => '' ];
550 } else {
551 unset( $dataMw->body );
552 }
553 unset( $dp->selfClose );
554 }
555
556 // Deal with responsive wrapper
557 if ( DOMUtils::hasClass( $refsNode, 'mw-references-wrap' ) ) {
558 // NOTE: The default Cite implementation hardcodes this threshold to 10.
559 // We use a configurable parameter here primarily for test coverage purposes.
560 // See citeParserTests.txt where we set a threshold of 1 or 2.
561 $rrThreshold = $this->mainConfig->get( 'CiteResponsiveReferencesThreshold' ) ?? 10;
562 if ( $refGroup && count( $refGroup->refs ) > $rrThreshold ) {
563 DOMCompat::getClassList( $refsNode )->add( 'mw-references-columns' );
564 }
565 $refsNode = $refsNode->firstChild;
566 }
567 DOMUtils::assertElt( $refsNode );
568
569 // Remove all children from the references node
570 //
571 // Ex: When {{Reflist}} is reused from the cache, it comes with
572 // a bunch of references as well. We have to remove all those cached
573 // references before generating fresh references.
574 DOMCompat::replaceChildren( $refsNode );
575
576 if ( $refGroup ) {
577 foreach ( $refGroup->refs as $ref ) {
578 $refGroup->renderLine( $extApi, $refsNode, $ref );
579 }
580 }
581
582 // Remove the group from refsData
583 $refsData->removeRefGroup( $group );
584 }
585
586 /**
587 * Process `<ref>`s left behind after the DOM is fully processed.
588 * We process them as if there was an implicit `<references />` tag at
589 * the end of the DOM.
590 *
591 * @param ParsoidExtensionAPI $extApi
592 * @param ReferencesData $refsData
593 * @param Node $node
594 */
595 public function insertMissingReferencesIntoDOM(
596 ParsoidExtensionAPI $extApi, ReferencesData $refsData, Node $node
597 ): void {
598 $doc = $node->ownerDocument;
599 foreach ( $refsData->getRefGroups() as $groupName => $refsGroup ) {
600 $domFragment = $doc->createDocumentFragment();
601 $frag = $this->createReferences(
602 $extApi,
603 $domFragment,
604 [
605 // Force string cast here since in the foreach above, $groupName
606 // is an array key. In that context, number-like strings are
607 // silently converted to a numeric value!
608 // Ex: In <ref group="2" />, the "2" becomes 2 in the foreach
609 'group' => (string)$groupName,
610 'responsive' => null,
611 ],
612 static function ( $dp ) use ( $extApi ) {
613 // The new references come out of "nowhere", so to make selser work
614 // properly, add a zero-sized DSR pointing to the end of the document.
615 $content = $extApi->getPageConfig()->getRevisionContent()->getContent( 'main' );
616 $contentLength = strlen( $content );
617 $dp->dsr = new DomSourceRange( $contentLength, $contentLength, 0, 0 );
618 },
619 true
620 );
621
622 // Add a \n before the <ol> so that when serialized to wikitext,
623 // each <references /> tag appears on its own line.
624 $node->appendChild( $doc->createTextNode( "\n" ) );
625 $node->appendChild( $frag );
626
627 $this->insertReferencesIntoDOM( $extApi, $frag, $refsData, true );
628 }
629 }
630
631 private function processEmbeddedRefs(
632 ParsoidExtensionAPI $extApi, ReferencesData $refsData, string $str
633 ): string {
634 $domFragment = $extApi->htmlToDom( $str );
635 $this->processRefs( $extApi, $refsData, $domFragment );
636 return $extApi->domToHtml( $domFragment, true, true );
637 }
638
639 public function processRefs(
640 ParsoidExtensionAPI $extApi, ReferencesData $refsData, Node $node
641 ): void {
642 $child = $node->firstChild;
643 while ( $child !== null ) {
644 $nextChild = $child->nextSibling;
645 if ( $child instanceof Element ) {
646 if ( WTUtils::isSealedFragmentOfType( $child, 'ref' ) ) {
647 $this->extractRefFromNode( $extApi, $child, $refsData );
648 } elseif ( DOMUtils::hasTypeOf( $child, 'mw:Extension/references' ) ) {
649 if ( !$refsData->inReferencesContent() ) {
650 $refsData->referencesGroup =
651 DOMDataUtils::getDataParsoid( $child )->group ?? '';
652 }
653 $refsData->pushEmbeddedContentFlag( 'references' );
654 if ( $child->hasChildNodes() ) {
655 $this->processRefs( $extApi, $refsData, $child );
656 }
657 $refsData->popEmbeddedContentFlag();
658 if ( !$refsData->inReferencesContent() ) {
659 $refsData->referencesGroup = '';
660 $this->insertReferencesIntoDOM( $extApi, $child, $refsData, false );
661 }
662 } else {
663 $refsData->pushEmbeddedContentFlag();
664 // Look for <ref>s embedded in data attributes
665 $extApi->processAttributeEmbeddedHTML( $child,
666 function ( string $html ) use ( $extApi, $refsData ) {
667 return $this->processEmbeddedRefs( $extApi, $refsData, $html );
668 }
669 );
670 $refsData->popEmbeddedContentFlag();
671 if ( $child->hasChildNodes() ) {
672 $this->processRefs( $extApi, $refsData, $child );
673 }
674 }
675 }
676 $child = $nextChild;
677 }
678 }
679
680 /**
681 * Traverse into all the embedded content and mark up the refs in there
682 * that have errors that weren't known before the content was serialized.
683 *
684 * Some errors are only known at the time when we're inserting the
685 * references lists, at which point, embedded content has already been
686 * serialized and stored, so we no longer have live access to it. We
687 * therefore map about ids to errors for a ref at that time, and then do
688 * one final walk of the dom to peak into all the embedded content and
689 * mark up the errors where necessary.
690 *
691 * @param ParsoidExtensionAPI $extApi
692 * @param ReferencesData $refsData
693 * @param Node $node
694 */
695 public function addEmbeddedErrors(
696 ParsoidExtensionAPI $extApi, ReferencesData $refsData, Node $node
697 ): void {
698 $processEmbeddedErrors = function ( string $html ) use ( $extApi, $refsData ) {
699 // Similar to processEmbeddedRefs
700 $domFragment = $extApi->htmlToDom( $html );
701 $this->addEmbeddedErrors( $extApi, $refsData, $domFragment );
702 return $extApi->domToHtml( $domFragment, true, true );
703 };
704 $processBodyHtml = static function ( Element $n ) use ( $processEmbeddedErrors ) {
705 $dataMw = DOMDataUtils::getDataMw( $n );
706 if ( isset( $dataMw->body->html ) ) {
707 $dataMw->body->html = $processEmbeddedErrors(
708 $dataMw->body->html
709 );
710 }
711 };
712 $child = $node->firstChild;
713 while ( $child !== null ) {
714 $nextChild = $child->nextSibling;
715 if ( $child instanceof Element ) {
716 if ( DOMUtils::hasTypeOf( $child, 'mw:Extension/ref' ) ) {
717 $processBodyHtml( $child );
718 $about = DOMCompat::getAttribute( $child, 'about' );
719 '@phan-var string $about'; // assert $about is non-null
720 $errs = $refsData->embeddedErrors[$about] ?? null;
721 if ( $errs ) {
722 self::addErrorsToNode( $child, $errs );
723 }
724 } elseif ( DOMUtils::hasTypeOf( $child, 'mw:Extension/references' ) ) {
725 $processBodyHtml( $child );
726 } else {
727 $extApi->processAttributeEmbeddedHTML(
728 $child, $processEmbeddedErrors
729 );
730 }
731 if ( $child->hasChildNodes() ) {
732 $this->addEmbeddedErrors( $extApi, $refsData, $child );
733 }
734 }
735 $child = $nextChild;
736 }
737 }
738
739 /** @inheritDoc */
740 public function sourceToDom(
741 ParsoidExtensionAPI $extApi, string $txt, array $extArgs
742 ): DocumentFragment {
743 $domFragment = $extApi->extTagToDOM(
744 $extArgs,
745 $txt,
746 [
747 'parseOpts' => [ 'extTag' => 'references' ],
748 ]
749 );
750
751 $refsOpts = $extApi->extArgsToArray( $extArgs ) + [
752 'group' => null,
753 'responsive' => null,
754 ];
755
756 // Detect invalid parameters on the references tag
757 $knownAttributes = [ 'group', 'responsive' ];
758 foreach ( $refsOpts as $key => $value ) {
759 if ( !in_array( strtolower( (string)$key ), $knownAttributes, true ) ) {
760 $extApi->pushError( 'cite_error_references_invalid_parameters' );
761 break;
762 }
763 }
764
765 $frag = $this->createReferences(
766 $extApi,
767 $domFragment,
768 $refsOpts,
769 static function ( $dp ) use ( $extApi ) {
770 $dp->src = $extApi->extTag->getSource();
771 // Setting redundant info on fragment.
772 // $docBody->firstChild info feels cumbersome to use downstream.
773 if ( $extApi->extTag->isSelfClosed() ) {
774 $dp->selfClose = true;
775 }
776 }
777 );
778 $domFragment->appendChild( $frag );
779 return $domFragment;
780 }
781
782 /** @inheritDoc */
783 public function processAttributeEmbeddedHTML(
784 ParsoidExtensionAPI $extApi, Element $elt, Closure $proc
785 ): void {
786 $dataMw = DOMDataUtils::getDataMw( $elt );
787 if ( isset( $dataMw->body->html ) ) {
788 $dataMw->body->html = $proc( $dataMw->body->html );
789 }
790 }
791
792 /** @inheritDoc */
793 public function domToWikitext(
794 ParsoidExtensionAPI $extApi, Element $node, bool $wrapperUnmodified
795 ) {
796 $dataMw = DOMDataUtils::getDataMw( $node );
797 // Autogenerated references aren't considered erroneous (the extension to the legacy
798 // parser also generates them) and are not suppressed when serializing because apparently
799 // that's the behaviour Parsoid clients want. However, autogenerated references *with
800 // group attributes* are errors (the legacy extension doesn't generate them at all) and
801 // are suppressed when serialized since we considered them an error while parsing and
802 // don't want them to persist in the content.
803 if ( !empty( $dataMw->autoGenerated ) && ( $dataMw->attrs->group ?? '' ) !== '' ) {
804 return '';
805 } else {
806 $startTagSrc = $extApi->extStartTagToWikitext( $node );
807 if ( empty( $dataMw->body ) ) {
808 return $startTagSrc; // We self-closed this already.
809 } else {
810 if ( isset( $dataMw->body->html ) ) {
811 $src = $extApi->htmlToWikitext(
812 [ 'extName' => $dataMw->name ],
813 $dataMw->body->html
814 );
815 return $startTagSrc . $src . '</' . $dataMw->name . '>';
816 } else {
817 $extApi->log( 'error',
818 'References body unavailable for: ' . DOMCompat::getOuterHTML( $node )
819 );
820 return ''; // Drop it!
821 }
822 }
823 }
824 }
825
826 /** @inheritDoc */
827 public function lintHandler(
828 ParsoidExtensionAPI $extApi, Element $refs, callable $defaultHandler
829 ): bool {
830 $dataMw = DOMDataUtils::getDataMw( $refs );
831 if ( isset( $dataMw->body->html ) ) {
832 $fragment = $extApi->htmlToDom( $dataMw->body->html );
833 $defaultHandler( $fragment );
834 }
835 return true;
836 }
837
838 /** @inheritDoc */
839 public function diffHandler(
840 ParsoidExtensionAPI $extApi, callable $domDiff, Element $origNode,
841 Element $editedNode
842 ): bool {
843 $origDataMw = DOMDataUtils::getDataMw( $origNode );
844 $editedDataMw = DOMDataUtils::getDataMw( $editedNode );
845
846 if ( isset( $origDataMw->body->html ) && isset( $editedDataMw->body->html ) ) {
847 $origFragment = $extApi->htmlToDom(
848 $origDataMw->body->html, $origNode->ownerDocument,
849 [ 'markNew' => true ]
850 );
851 $editedFragment = $extApi->htmlToDom(
852 $editedDataMw->body->html, $editedNode->ownerDocument,
853 [ 'markNew' => true ]
854 );
855 return call_user_func( $domDiff, $origFragment, $editedFragment );
856 }
857
858 // FIXME: Similar to DOMDiff::subtreeDiffers, maybe $editNode should
859 // be marked as inserted to avoid losing any edits, at the cost of
860 // more normalization
861
862 return false;
863 }
864 }