Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
36.84% covered (danger)
36.84%
70 / 190
0.00% covered (danger)
0.00%
0 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
CleanUp
36.84% covered (danger)
36.84%
70 / 190
0.00% covered (danger)
0.00%
0 / 7
2517.55
0.00% covered (danger)
0.00%
0 / 1
 stripMarkerMetas
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
90
 isEmptyNode
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
182
 handleEmptyElements
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
420
 inNativeContent
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 trimWhiteSpace
92.86% covered (success)
92.86%
39 / 42
0.00% covered (danger)
0.00%
0 / 1
19.13
 finalCleanup
79.49% covered (warning)
79.49%
31 / 39
0.00% covered (danger)
0.00%
0 / 1
30.39
 markDiscardableDataParsoid
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Wt2Html\DOM\Handlers;
5
6use Wikimedia\Assert\Assert;
7use Wikimedia\Parsoid\Config\Env;
8use Wikimedia\Parsoid\Core\DOMCompat;
9use Wikimedia\Parsoid\Core\DomSourceRange;
10use Wikimedia\Parsoid\DOM\Comment;
11use Wikimedia\Parsoid\DOM\Element;
12use Wikimedia\Parsoid\DOM\Node;
13use Wikimedia\Parsoid\DOM\Text;
14use Wikimedia\Parsoid\NodeData\TempData;
15use Wikimedia\Parsoid\Utils\DOMDataUtils;
16use Wikimedia\Parsoid\Utils\DOMUtils;
17use Wikimedia\Parsoid\Utils\DTState;
18use Wikimedia\Parsoid\Utils\Utils;
19use Wikimedia\Parsoid\Utils\WTUtils;
20use Wikimedia\Parsoid\Wikitext\Consts;
21use Wikimedia\Parsoid\Wt2Html\TT\PreHandler;
22
23class CleanUp {
24    /**
25     * @param Element $node
26     * @return bool|?Node
27     */
28    public static function stripMarkerMetas( Element $node ) {
29        // This meta tag can never have data-mw associated with it.
30        // If it were produced by a template, it would always have a <pre>
31        // wrapper around which carries any relevant data-mw & typeof properties.
32        $isIndentPreSpace = PreHandler::isIndentPreWS( $node );
33        if ( $isIndentPreSpace ||
34            DOMUtils::hasTypeOf( $node, "mw:Placeholder/UnclosedComment" ) ||
35            // Sometimes a non-tpl meta node might get the mw:Transclusion typeof
36            // element attached to it. So, check if the node has data-mw,
37            // in which case we also have to keep it.
38            ( DOMDataUtils::getDataMw( $node )->isEmpty() && (
39                (
40                    DOMUtils::hasTypeOf( $node, 'mw:Placeholder/StrippedTag' ) &&
41                    // NOTE: In ComputeDSR, we don't zero out the width of these
42                    // markers because they're staying in the DOM and serializeDOMNode
43                    // only handles a few cases of zero width nodes.
44                    !DOMUtils::isNestedInListItem( $node )
45                ) ||
46                DOMUtils::hasTypeOf( $node, 'mw:Transclusion' )
47            ) )
48        ) {
49            $nextNode = $node->nextSibling;
50            $parent = $node->parentNode;
51            if ( $isIndentPreSpace ) {
52                $dsr = DOMDataUtils::getDataParsoid( $parent )->dsr ?? null;
53                if ( $dsr ) {
54                    // @see explanation in PreHandler::newIndentPreWS()
55                    $dsr->openWidth = 1;
56                }
57                // Strip this in the cleanup handler since
58                // DOM passes till the end may need DSR info from this tag.
59                return true;
60            } else {
61                $parent->removeChild( $node );
62                // stop the traversal, since this node is no longer in the DOM.
63                return $nextNode;
64            }
65        } else {
66            return true;
67        }
68    }
69
70    /**
71     * The following are considered "empty node"s:
72     * - Comments, rendering transparent nodes, nowiki spans without content
73     *   are all stripped  by the core parser.
74     * - Text nodes with whitespace don't count either.
75     * - Parsoid-added span wrappers around other "empty node"s.
76     *
77     * @param Node $node
78     * @param bool &$hasRTNodes Set to true if the node contained rendering transparent nodes.
79     *   Note this value is only reliable if ::isEmptyNode() returns true.
80     * @return bool
81     */
82    private static function isEmptyNode( Node $node, bool &$hasRTNodes ): bool {
83        for ( $n = $node->firstChild; $n !== null; $n = $n->nextSibling ) {
84            if ( $n instanceof Comment ) {
85                continue;
86            } elseif ( $n instanceof Text ) {
87                if ( !preg_match( '/^[ \t\r\n]*$/D', $n->nodeValue ) ) {
88                    return false;
89                }
90                continue;
91            } elseif ( $n instanceof Element ) {
92                if ( isset( Consts::$Output['FlaggedEmptyElts'][DOMUtils::nodeName( $n )] ) ) {
93                    if ( self::isEmptyNode( $n, $hasRTNodes ) ) {
94                        continue;
95                    } else {
96                        return false;
97                    }
98                }
99                if ( WTUtils::isRenderingTransparentNode( $n ) || DOMUtils::hasClass( $n, 'mw-empty-elt' ) ) {
100                    $hasRTNodes = true;
101                    continue;
102                }
103                if (
104                    (
105                        DOMUtils::hasTypeOf( $n, 'mw:Nowiki' ) ||
106                        DOMDataUtils::getDataParsoid( $n )->getTempFlag( TempData::WRAPPER )
107                    ) && self::isEmptyNode( $n, $hasRTNodes )
108                ) {
109                    continue;
110                }
111                return false;
112            } else {
113                return false;
114            }
115        }
116        return true;
117    }
118
119    // These template-wrapping attributes can be ignored while looking for
120    // empty elements. Note that data-mw & data-parsoid are unlikely to exist
121    // at this stage of DOM processing. This is conservative but safe.
122    // In this case, it is also sufficient since only p, li, tr can be deleted.
123    public const ALLOWED_TPL_WRAPPER_ATTRS = [
124        'about' => 1,
125        'typeof' => 1,
126        'data-parsoid' => 1,
127        'data-mw' => 1
128    ];
129
130    /**
131     * @param Node $node
132     * @param DTState $state
133     * @return bool|?Node
134     */
135    public static function handleEmptyElements( Node $node, DTState $state ) {
136        // Set by isEmptyNode() to indicate whether a node which is "empty" contained
137        // invisible "rendering transparent" nodes.
138        $hasRTNodes = false;
139
140        // Remove mw-empty-elt span nodes introduced by DOMRangeBuilder
141        // that are deletable (IEW children only, if any).
142        if ( $node instanceof Element && DOMUtils::nodeName( $node ) === 'span' &&
143            DOMUtils::hasClass( $node, 'mw-empty-elt' )
144        ) {
145            if ( WTUtils::isFirstEncapsulationWrapperNode( $node ) ) {
146                return true;
147            }
148
149            if ( !$node->hasChildNodes() ||
150                ( $node->childElementCount === 1 && DOMUtils::isIEW( $node->firstChild ) )
151            ) {
152                $next = $node->nextSibling;
153                DOMCompat::remove( $node );
154                return $next;
155            }
156            return true;
157        }
158
159        if ( !( $node instanceof Element ) ||
160            !isset( Consts::$Output['FlaggedEmptyElts'][DOMUtils::nodeName( $node )] ) ||
161            !self::isEmptyNode( $node, $hasRTNodes )
162        ) {
163            return true;
164        }
165
166        // While RemexCompatFormatter::element in the legacy parser will only
167        // mark these nodes as empty elements if they don't have any
168        // attributes, Parser::handleTables will drop empty wikitext syntax
169        // trs, regardless of attributes.
170        if ( DOMUtils::nodeName( $node ) !== 'tr' || WTUtils::isLiteralHTMLNode( $node ) ) {
171            foreach ( DOMCompat::attributes( $node ) as $name => $_value ) {
172                // Skip the Parsoid-added data attribute and template-wrapping attributes
173                if ( $name === DOMDataUtils::DATA_OBJECT_ATTR_NAME ||
174                    ( ( $state->tplInfo ?? null ) && isset( self::ALLOWED_TPL_WRAPPER_ATTRS[$name] ) )
175                ) {
176                    continue;
177                }
178                return true;
179            }
180        }
181
182        /**
183         * The node is known to be empty and a deletion candidate
184         * - If node is part of template content and is not the
185         *   first encapsulation wrapper node, and doesn't contain
186         *   any rendering transparent nodes, it can be deleted.
187         * - If not, we add the mw-empty-elt class so that wikis
188         *   can decide what to do with them.
189         */
190        if (
191            $state->tplInfo &&
192            $state->tplInfo->first !== $node &&
193            !$hasRTNodes
194        ) {
195            $nextNode = $node->nextSibling;
196            $node->parentNode->removeChild( $node );
197            return $nextNode;
198        }
199
200        DOMCompat::getClassList( $node )->add( 'mw-empty-elt' );
201        return true;
202    }
203
204    /**
205     * FIXME: Worry about "about" siblings
206     *
207     * @param Env $env
208     * @param Element $node
209     * @return bool
210     */
211    private static function inNativeContent( Env $env, Element $node ): bool {
212        while ( !DOMUtils::atTheTop( $node ) ) {
213            if ( WTUtils::getNativeExt( $env, $node ) !== null ) {
214                return true;
215            }
216            $node = $node->parentNode;
217        }
218        return false;
219    }
220
221    /**
222     * Whitespace in this function refers to [ \t] only
223     * @param Element $node
224     * @param ?DomSourceRange $dsr
225     */
226    private static function trimWhiteSpace( Element $node, ?DomSourceRange $dsr ): void {
227        // Trim leading ws (on the first line)
228        $trimmedLen = 0;
229        $updateDSR = true;
230        $skipped = false;
231        for ( $c = $node->firstChild; $c; $c = $next ) {
232            $next = $c->nextSibling;
233            if ( $c instanceof Text && preg_match( '/^[ \t]*$/D', $c->nodeValue ) ) {
234                $node->removeChild( $c );
235                $trimmedLen += strlen( $c->nodeValue );
236                $updateDSR = !$skipped;
237            } elseif ( $c instanceof Element && DOMUtils::hasTypeOf( $c, 'mw:DisplaySpace' ) ) {
238                $node->removeChild( $c );
239                // even though content of node is 2-byte character (NBSP), original space was 1-byte character
240                $trimmedLen += 1;
241                $updateDSR = !$skipped;
242            } elseif ( !WTUtils::isRenderingTransparentNode( $c ) ) {
243                break;
244            } else {
245                // We are now skipping over a rendering transparent node
246                // and will trim additional whitespace => we cannot reliably
247                // maintain info about trimmed whitespace.
248                $skipped = true;
249            }
250        }
251
252        if ( $c instanceof Text &&
253            preg_match( '/^([ \t]+)([\s\S]*)$/D', $c->nodeValue, $matches )
254        ) {
255            $updateDSR = !$skipped;
256            $c->nodeValue = $matches[2];
257            $trimmedLen += strlen( $matches[1] );
258        }
259
260        if ( $dsr ) {
261            $dsr->leadingWS = $updateDSR ? $trimmedLen : -1;
262        }
263
264        // Trim trailing ws (on the last line)
265        $trimmedLen = 0;
266        $updateDSR = true;
267        $skipped = false;
268        for ( $c = $node->lastChild; $c; $c = $prev ) {
269            $prev = $c->previousSibling;
270            if ( $c instanceof Text && preg_match( '/^[ \t]*$/D', $c->nodeValue ) ) {
271                $trimmedLen += strlen( $c->nodeValue );
272                $node->removeChild( $c );
273                $updateDSR = !$skipped;
274            } elseif ( !WTUtils::isRenderingTransparentNode( $c ) ) {
275                break;
276            } else {
277                // We are now skipping over a rendering transparent node
278                // and will trim additional whitespace => we cannot reliably
279                // maintain info about trimmed whitespace.
280                $skipped = true;
281            }
282        }
283
284        if ( $c instanceof Text &&
285            preg_match( '/^([\s\S]*\S)([ \t]+)$/D', $c->nodeValue, $matches )
286        ) {
287            $updateDSR = !$skipped;
288            $c->nodeValue = $matches[1];
289            $trimmedLen += strlen( $matches[2] );
290        }
291
292        if ( $dsr ) {
293            $dsr->trailingWS = $updateDSR ? $trimmedLen : -1;
294        }
295    }
296
297    /**
298     * Perform some final cleanup
299     *
300     * @param Node $node
301     * @param DTState $state
302     * @return bool|?Node The next node or true to continue with $node->nextSibling
303     */
304    public static function finalCleanup( Node $node, DTState $state ) {
305        if ( !( $node instanceof Element ) ) {
306            return true;
307        }
308
309        Assert::invariant( $state->atTopLevel, 'This pass should only be run on the top-level' );
310
311        $dp = DOMDataUtils::getDataParsoid( $node );
312        // Delete from data parsoid, wikitext originating autoInsertedEnd info
313        if (
314            !empty( $dp->autoInsertedEnd ) &&
315            !WTUtils::hasLiteralHTMLMarker( $dp ) &&
316            isset( Consts::$WTTagsWithNoClosingTags[DOMUtils::nodeName( $node )] ) &&
317            !WTUtils::serializeChildTableTagAsHTML( $node )
318        ) {
319            unset( $dp->autoInsertedEnd );
320        }
321
322        $isFirstEncapsulationWrapperNode = ( $state->tplInfo->first ?? null ) === $node ||
323            // Traversal isn't done with tplInfo for section tags, but we should
324            // still clean them up as if they are the head of encapsulation.
325            WTUtils::isParsoidSectionTag( $node );
326
327        // Remove dp.src from elements that have non-empty data-mw and dsr.
328        // This should reduce data-parsoid bloat.
329        //
330        // Presence of data-mw is a proxy for us knowing how to serialize
331        // this content from HTML. Token handlers should strip src for
332        // content where data-mw isn't necessary and html2wt knows how to
333        // handle the HTML markup.
334        $validDSR = Utils::isValidDSR( $dp->dsr ?? null ) &&
335            !DOMDataUtils::getDataMw( $node )->isEmpty();
336        $isPageProp = DOMUtils::nodeName( $node ) === 'meta' &&
337            str_starts_with( DOMCompat::getAttribute( $node, 'property' ) ?? '', 'mw:PageProp/' );
338        if ( $validDSR && !$isPageProp ) {
339            unset( $dp->src );
340        } elseif ( $isFirstEncapsulationWrapperNode && empty( $dp->tsr ) ) {
341            // Transcluded nodes will not have dp.tsr set
342            // and don't need dp.src either.
343            unset( $dp->src );
344        }
345
346        // Remove tsr
347        if ( property_exists( $dp, 'tsr' ) ) {
348            unset( $dp->tsr );
349        }
350
351        // Various places, like ContentUtils::shiftDSR, can set this to `null`
352        if ( property_exists( $dp, 'dsr' ) && $dp->dsr === null ) {
353            unset( $dp->dsr );
354        }
355
356        // Make dsr zero-range for fostered content
357        // to prevent selser from duplicating this content
358        // outside the table from where this came.
359        //
360        // But, do not zero it out if the node has template encapsulation
361        // information.  That will be disastrous (see T54638, T54488).
362        if ( !empty( $dp->fostered ) && !empty( $dp->dsr ) && !$isFirstEncapsulationWrapperNode ) {
363            $dp->dsr->start = $dp->dsr->end;
364        }
365
366        // Strip nowiki spans from encapsulated content but leave behind
367        // wrappers on root nodes since they have valid about ids and we
368        // don't want to break the about-chain by stripping the wrapper
369        // and associated ids (we cannot add an about id on the nowiki-ed
370        // content since that would be a text node).
371        if ( ( $state->tplInfo ?? null ) && !WTUtils::isEncapsulatedDOMForestRoot( $node ) &&
372             DOMUtils::hasTypeOf( $node, 'mw:Nowiki' )
373        ) {
374            DOMUtils::migrateChildren( $node, $node->parentNode, $node->nextSibling );
375            $next = $node->nextSibling;
376            $node->parentNode->removeChild( $node );
377            return $next;
378        }
379
380        // Strip IndentPre marker metas
381        if ( PreHandler::isIndentPreWS( $node ) ) {
382            $nextNode = $node->nextSibling;
383            $node->parentNode->removeChild( $node );
384            return $nextNode;
385        }
386
387        // Trim whitespace from some wikitext markup
388        // not involving explicit HTML tags (T157481)
389        if ( !WTUtils::hasLiteralHTMLMarker( $dp ) &&
390            isset( Consts::$WikitextTagsWithTrimmableWS[DOMUtils::nodeName( $node )] )
391        ) {
392            self::trimWhiteSpace( $node, $dp->dsr ?? null );
393        }
394
395        return true;
396    }
397
398    /**
399     * Mark which data-parsoid attributes can be discarded
400     *
401     * @param Node $node
402     * @param DTState $state
403     * @return bool|?Node The next node or true to continue with $node->nextSibling
404     */
405    public static function markDiscardableDataParsoid( Node $node, DTState $state ) {
406        if ( !( $node instanceof Element ) ) {
407            return true;
408        }
409        Assert::invariant( $state->atTopLevel, 'This pass should only be run on the top-level' );
410
411        $env = $state->env;
412        $dp = DOMDataUtils::getDataParsoid( $node );
413        $isFirstEncapsulationWrapperNode = ( $state->tplInfo->first ?? null ) === $node ||
414            // Traversal isn't done with tplInfo for section tags, but we should
415            // still clean them up as if they are the head of encapsulation.
416            WTUtils::isParsoidSectionTag( $node );
417
418        // Strip data-parsoid from templated content, where unnecessary.
419        $discardDataParsoid = (
420            ( $state->tplInfo ?? null ) &&
421            // Always keep info for the first node
422            !$isFirstEncapsulationWrapperNode &&
423            // We can't remove data-parsoid from inside <references> text,
424            // as that's the only HTML representation we have left for it.
425            !self::inNativeContent( $env, $node ) &&
426            // FIXME(T100856): stx is semantic info and should probably be
427            // moved out of data-parsoid.  We can't remove dp from nodes
428            // with stx information for two scenarios.
429            //
430            // 1. The serializer uses stx information in some cases to
431            // emit the right newline separators.
432            //
433            // For example, "a\n\nb" and "<p>a</p><p>b/p>" both generate
434            // identical html but serialize to different wikitext.
435            //
436            // This is only needed for the last top-level node.
437            //
438            // 2. We omit heading wrapping for html literals in core's
439            // OutputTransform stages and need a way to distinguish them.
440            ( empty( $dp->stx ) || !(
441                ( $state->tplInfo->last ?? null ) === $node ||
442                DOMUtils::isHeading( $node )
443            ) )
444        );
445
446        // Mark this as an empty AND new data-parsoid
447        if ( $discardDataParsoid ) {
448            // We cannot unset data-parsoid because any code that runs after
449            // this that calls DOMDataUtils::getDataParsoid will reinitialize
450            // it to an empty object.
451            $dp->setTempFlag( TempData::DISCARDABLE_DP );
452        }
453
454        return true;
455    }
456
457}