Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.76% covered (success)
94.76%
271 / 286
81.48% covered (warning)
81.48%
22 / 27
CRAP
0.00% covered (danger)
0.00%
0 / 1
CommentUtils
94.76% covered (success)
94.76%
271 / 286
81.48% covered (warning)
81.48%
22 / 27
167.88
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isBlockElement
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 isRenderingTransparentNode
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
11
 isOurGeneratedNode
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 cantHaveElementChildren
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
7
 isCommentSeparator
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
15
 isCommentContent
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 childIndexOf
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 contains
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 closestElement
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 closestElementWithSibling
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
72
 getTranscludedFromElement
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
10
 getHeadlineNode
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
5.93
 htmlTrim
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getIndentLevel
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
 getCoveredSiblings
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 getFullyCoveredSiblings
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 unwrapParsoidSections
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 getTitleFromUrl
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
6
 linearWalk
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 linearWalkBackwards
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 getRangeFirstNode
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 getRangeLastNode
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 compareRanges
88.00% covered (warning)
88.00%
22 / 25
0.00% covered (danger)
0.00%
0 / 1
23.91
 compareRangesAlmostEqualBoundaries
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
15
 isSingleCommentSignedBy
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
9
 getNewTopicsSubscriptionId
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace MediaWiki\Extension\DiscussionTools;
4
5use LogicException;
6use MediaWiki\Config\Config;
7use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentCommentItem;
8use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentThreadItem;
9use MediaWiki\MainConfigNames;
10use MediaWiki\Title\Title;
11use Wikimedia\Assert\Assert;
12use Wikimedia\Parsoid\DOM\Comment;
13use Wikimedia\Parsoid\DOM\Element;
14use Wikimedia\Parsoid\DOM\Node;
15use Wikimedia\Parsoid\DOM\Text;
16use Wikimedia\Parsoid\Utils\DOMCompat;
17
18class CommentUtils {
19
20    private function __construct() {
21    }
22
23    private const BLOCK_ELEMENT_TYPES = [
24        'div', 'p',
25        // Tables
26        'table', 'tbody', 'thead', 'tfoot', 'caption', 'th', 'tr', 'td',
27        // Lists
28        'ul', 'ol', 'li', 'dl', 'dt', 'dd',
29        // HTML5 heading content
30        'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup',
31        // HTML5 sectioning content
32        'article', 'aside', 'body', 'nav', 'section', 'footer', 'header', 'figure',
33        'figcaption', 'fieldset', 'details', 'blockquote',
34        // Other
35        'hr', 'button', 'canvas', 'center', 'col', 'colgroup', 'embed',
36        'map', 'object', 'pre', 'progress', 'video'
37    ];
38
39    /**
40     * @param Node $node
41     * @return bool Node is a block element
42     */
43    public static function isBlockElement( Node $node ): bool {
44        return $node instanceof Element &&
45            in_array( strtolower( $node->tagName ), static::BLOCK_ELEMENT_TYPES, true );
46    }
47
48    private const SOL_TRANSPARENT_LINK_REGEX =
49        '/(?:^|\s)mw:PageProp\/(?:Category|redirect|Language)(?=$|\s)/D';
50
51    /**
52     * @param Node $node
53     * @return bool Node is considered a rendering-transparent node in Parsoid
54     */
55    public static function isRenderingTransparentNode( Node $node ): bool {
56        $nextSibling = $node->nextSibling;
57        return (
58            $node instanceof Comment ||
59            ( $node instanceof Element && (
60                strtolower( $node->tagName ) === 'meta' ||
61                (
62                    strtolower( $node->tagName ) === 'link' &&
63                    preg_match( static::SOL_TRANSPARENT_LINK_REGEX, $node->getAttribute( 'rel' ) ?? '' )
64                ) ||
65                // Empty inline templates, e.g. tracking templates. (T269036)
66                // But not empty nodes that are just the start of a non-empty template about-group. (T290940)
67                (
68                    strtolower( $node->tagName ) === 'span' &&
69                    in_array( 'mw:Transclusion', explode( ' ', $node->getAttribute( 'typeof' ) ?? '' ), true ) &&
70                    !static::htmlTrim( DOMCompat::getInnerHTML( $node ) ) &&
71                    (
72                        !$nextSibling || !( $nextSibling instanceof Element ) ||
73                        // Maybe we should be checking all of the about-grouped nodes to see if they're empty,
74                        // but that's prooobably not needed in practice, and it leads to a quadratic worst case.
75                        $nextSibling->getAttribute( 'about' ) !== $node->getAttribute( 'about' )
76                    )
77                )
78            ) )
79        );
80    }
81
82    /**
83     * @param Node $node
84     * @return bool Node was added to the page by DiscussionTools
85     */
86    public static function isOurGeneratedNode( Node $node ): bool {
87        return $node instanceof Element && (
88            DOMCompat::getClassList( $node )->contains( 'ext-discussiontools-init-replylink-buttons' ) ||
89            $node->hasAttribute( 'data-mw-comment-start' ) ||
90            $node->hasAttribute( 'data-mw-comment-end' )
91        );
92    }
93
94    /**
95     * Elements which can't have element children (but some may have text content).
96     */
97    private const NO_ELEMENT_CHILDREN_ELEMENT_TYPES = [
98        // https://html.spec.whatwg.org/multipage/syntax.html#elements-2
99        // Void elements
100        'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
101        'link', 'meta', 'param', 'source', 'track', 'wbr',
102        // Raw text elements
103        'script', 'style',
104        // Escapable raw text elements
105        'textarea', 'title',
106        // Foreign elements
107        'math', 'svg',
108        // Treated like text when scripting is enabled in the parser
109        // https://html.spec.whatwg.org/#the-noscript-element
110        'noscript',
111        // Replaced elements (that aren't already included above)
112        // https://html.spec.whatwg.org/multipage/rendering.html#replaced-elements
113        // They might allow element children, but they aren't rendered on the page.
114        'audio', 'canvas', 'iframe', 'object', 'video',
115    ];
116
117    /**
118     * @param Node $node
119     * @return bool If true, node can't have element children. If false, it's complicated.
120     */
121    public static function cantHaveElementChildren( Node $node ): bool {
122        return (
123            $node instanceof Comment ||
124            ( $node instanceof Element && (
125                in_array( strtolower( $node->tagName ), static::NO_ELEMENT_CHILDREN_ELEMENT_TYPES, true ) ||
126                // Thumbnail wrappers generated by MediaTransformOutput::linkWrap (T301427),
127                // for compatibility with TimedMediaHandler.
128                // There is no better way to detect them, and we can't insert markers here,
129                // because the media DOM CSS depends on specific tag names and their order :(
130                // TODO See if we can remove this condition when wgParserEnableLegacyMediaDOM=false
131                // is enabled everywhere.
132                (
133                    in_array( strtolower( $node->tagName ), [ 'a', 'span' ], true ) &&
134                    $node->firstChild &&
135                    // We always step inside a child node so this can't be infinite, silly Phan
136                    // @phan-suppress-next-line PhanInfiniteRecursion
137                    static::cantHaveElementChildren( $node->firstChild )
138                ) ||
139                // Do not insert anything inside figures when using wgParserEnableLegacyMediaDOM=false,
140                // because their CSS can't handle it (T320285).
141                strtolower( $node->tagName ) === 'figure'
142            ) )
143        );
144    }
145
146    /**
147     * Check whether the node is a comment separator (instead of a part of the comment).
148     */
149    public static function isCommentSeparator( Node $node ): bool {
150        if ( !( $node instanceof Element ) ) {
151            return false;
152        }
153
154        $tagName = strtolower( $node->tagName );
155        if ( $tagName === 'br' || $tagName === 'hr' ) {
156            return true;
157        }
158
159        // TemplateStyles followed by any of the others
160        if ( $node->nextSibling &&
161            ( $tagName === 'link' || $tagName === 'style' ) &&
162            self::isCommentSeparator( $node->nextSibling )
163        ) {
164            return true;
165        }
166
167        $classList = DOMCompat::getClassList( $node );
168        if (
169            // Anything marked as not containing comments
170            $classList->contains( 'mw-notalk' ) ||
171            // {{outdent}} templates
172            $classList->contains( 'outdent-template' ) ||
173            // {{tracked}} templates (T313097)
174            $classList->contains( 'mw-trackedTemplate' )
175        ) {
176            return true;
177        }
178
179        // Wikitext definition list term markup (`;`) when used as a fake heading (T265964)
180        if ( $tagName === 'dl' &&
181            count( $node->childNodes ) === 1 &&
182            $node->firstChild instanceof Element &&
183            strtolower( $node->firstChild->nodeName ) === 'dt'
184        ) {
185            return true;
186        }
187
188        return false;
189    }
190
191    /**
192     * Check whether the node is a comment content. It's a little vague what this means…
193     *
194     * @param Node $node Node, should be a leaf node (a node with no children)
195     * @return bool
196     */
197    public static function isCommentContent( Node $node ): bool {
198        return (
199            $node instanceof Text &&
200            static::htmlTrim( $node->nodeValue ?? '' ) !== ''
201        ) ||
202        (
203            static::cantHaveElementChildren( $node )
204        );
205    }
206
207    /**
208     * Get the index of $child in its parent
209     */
210    public static function childIndexOf( Node $child ): int {
211        $i = 0;
212        while ( ( $child = $child->previousSibling ) ) {
213            $i++;
214        }
215        return $i;
216    }
217
218    /**
219     * Check whether a Node contains (is an ancestor of) another Node (or is the same node)
220     */
221    public static function contains( Node $ancestor, Node $descendant ): bool {
222        // TODO can we use Node->compareDocumentPosition() here maybe?
223        $node = $descendant;
224        while ( $node && $node !== $ancestor ) {
225            $node = $node->parentNode;
226        }
227        return $node === $ancestor;
228    }
229
230    /**
231     * Find closest ancestor element using one of the given tag names.
232     *
233     * @param Node $node
234     * @param string[] $tagNames
235     * @return Element|null
236     */
237    public static function closestElement( Node $node, array $tagNames ): ?Element {
238        do {
239            if (
240                $node instanceof Element &&
241                in_array( strtolower( $node->tagName ), $tagNames, true )
242            ) {
243                return $node;
244            }
245            $node = $node->parentNode;
246        } while ( $node );
247        return null;
248    }
249
250    /**
251     * Find closest ancestor element that has sibling nodes
252     *
253     * @param Node $node
254     * @param string $direction Can be 'next', 'previous', or 'either'
255     * @return Element|null
256     */
257    public static function closestElementWithSibling( Node $node, string $direction ): ?Element {
258        do {
259            if (
260                $node instanceof Element && (
261                    ( $node->nextSibling && ( $direction === 'next' || $direction === 'either' ) ) ||
262                    ( $node->previousSibling && ( $direction === 'previous' || $direction === 'either' ) )
263                )
264            ) {
265                return $node;
266            }
267            $node = $node->parentNode;
268        } while ( $node );
269        return null;
270    }
271
272    /**
273     * Find the transclusion node which rendered the current node, if it exists.
274     *
275     * 1. Find the closest ancestor with an 'about' attribute
276     * 2. Find the main node of the about-group (first sibling with the same 'about' attribute)
277     * 3. If this is an mw:Transclusion node, return it; otherwise, go to step 1
278     *
279     * @param Node $node
280     * @return Element|null Transclusion node, null if not found
281     */
282    public static function getTranscludedFromElement( Node $node ): ?Element {
283        while ( $node ) {
284            // 1.
285            if (
286                $node instanceof Element &&
287                $node->getAttribute( 'about' ) &&
288                preg_match( '/^#mwt\d+$/', $node->getAttribute( 'about' ) ?? '' )
289            ) {
290                $about = $node->getAttribute( 'about' );
291
292                // 2.
293                while (
294                    ( $previousSibling = $node->previousSibling ) &&
295                    $previousSibling instanceof Element &&
296                    $previousSibling->getAttribute( 'about' ) === $about
297                ) {
298                    $node = $previousSibling;
299                }
300
301                // 3.
302                if (
303                    $node->getAttribute( 'typeof' ) &&
304                    in_array( 'mw:Transclusion', explode( ' ', $node->getAttribute( 'typeof' ) ?? '' ), true )
305                ) {
306                    break;
307                }
308            }
309
310            $node = $node->parentNode;
311        }
312        return $node;
313    }
314
315    /**
316     * Given a heading node, return the node on which the ID attribute is set.
317     *
318     * @param Element $heading Heading node (`<h1>`-`<h6>`)
319     * @return Element Headline node, normally also a `<h1>`-`<h6>` element.
320     *   In integration tests and in JS, it can be a `<span class="mw-headline">` (see T363031).
321     */
322    public static function getHeadlineNode( Element $heading ): Element {
323        // This code assumes that $wgFragmentMode is [ 'html5', 'legacy' ] or [ 'html5' ]
324        $headline = $heading;
325
326        if ( $headline->hasAttribute( 'data-mw-comment-start' ) ) {
327            // HACK: For contaminated integration tests only (see T363031)
328            $headline = $headline->parentNode;
329            Assert::precondition( $headline !== null, 'data-mw-comment-start was attached to a heading' );
330        }
331
332        if ( !$headline->getAttribute( 'id' ) && !$headline->getAttribute( 'data-mw-anchor' ) ) {
333            // HACK: For outdated integration tests only (see T363031)
334            $headline = DOMCompat::querySelector( $headline, '.mw-headline' );
335            if ( !$headline ) {
336                $headline = $heading;
337            }
338        }
339
340        return $headline;
341    }
342
343    /**
344     * Trim ASCII whitespace, as defined in the HTML spec.
345     */
346    public static function htmlTrim( string $str ): string {
347        // https://infra.spec.whatwg.org/#ascii-whitespace
348        return trim( $str, "\t\n\f\r " );
349    }
350
351    /**
352     * Get the indent level of $node, relative to $rootNode.
353     *
354     * The indent level is the number of lists inside of which it is nested.
355     */
356    public static function getIndentLevel( Node $node, Element $rootNode ): int {
357        $indent = 0;
358        while ( $node ) {
359            if ( $node === $rootNode ) {
360                break;
361            }
362            $tagName = $node instanceof Element ? strtolower( $node->tagName ) : null;
363            if ( $tagName === 'li' || $tagName === 'dd' ) {
364                $indent++;
365            }
366            $node = $node->parentNode;
367        }
368        return $indent;
369    }
370
371    /**
372     * Get an array of sibling nodes that contain parts of the given range.
373     *
374     * @param ImmutableRange $range
375     * @return Node[]
376     */
377    public static function getCoveredSiblings( ImmutableRange $range ): array {
378        $ancestor = $range->commonAncestorContainer;
379
380        // Convert to array early because apparently NodeList acts like a linked list
381        // and accessing items by index is slow
382        $siblings = iterator_to_array( $ancestor->childNodes );
383        $start = 0;
384        $end = count( $siblings ) - 1;
385
386        // Find first of the siblings that contains the item
387        if ( $ancestor === $range->startContainer ) {
388            $start = $range->startOffset;
389        } else {
390            while ( !static::contains( $siblings[ $start ], $range->startContainer ) ) {
391                $start++;
392            }
393        }
394
395        // Find last of the siblings that contains the item
396        if ( $ancestor === $range->endContainer ) {
397            $end = $range->endOffset - 1;
398        } else {
399            while ( !static::contains( $siblings[ $end ], $range->endContainer ) ) {
400                $end--;
401            }
402        }
403
404        return array_slice( $siblings, $start, $end - $start + 1 );
405    }
406
407    /**
408     * Get the nodes (if any) that contain the given thread item, and nothing else.
409     *
410     * @param ContentThreadItem $item
411     * @param ?Node $excludedAncestorNode Node that shouldn't be included in the result, even if it
412     *     contains the item and nothing else. This is intended to avoid traversing outside of a node
413     *     which is a container for all the thread items.
414     * @return Node[]|null
415     */
416    public static function getFullyCoveredSiblings(
417        ContentThreadItem $item, ?Node $excludedAncestorNode = null
418    ): ?array {
419        $siblings = static::getCoveredSiblings( $item->getRange() );
420
421        $makeRange = static function ( $siblings ) {
422            return new ImmutableRange(
423                $siblings[0]->parentNode,
424                CommentUtils::childIndexOf( $siblings[0] ),
425                end( $siblings )->parentNode,
426                CommentUtils::childIndexOf( end( $siblings ) ) + 1
427            );
428        };
429
430        $matches = static::compareRanges( $makeRange( $siblings ), $item->getRange() ) === 'equal';
431
432        if ( $matches ) {
433            // If these are all of the children (or the only child), go up one more level
434            while (
435                ( $parent = $siblings[ 0 ]->parentNode ) &&
436                $parent !== $excludedAncestorNode &&
437                static::compareRanges( $makeRange( [ $parent ] ), $item->getRange() ) === 'equal'
438            ) {
439                $siblings = [ $parent ];
440            }
441            return $siblings;
442        }
443        return null;
444    }
445
446    /**
447     * Unwrap Parsoid sections
448     *
449     * @param Element $element Parent element, e.g. document body
450     */
451    public static function unwrapParsoidSections( Element $element ): void {
452        $sections = DOMCompat::querySelectorAll( $element, 'section[data-mw-section-id]' );
453        foreach ( $sections as $section ) {
454            $parent = $section->parentNode;
455            while ( $section->firstChild ) {
456                $parent->insertBefore( $section->firstChild, $section );
457            }
458            $parent->removeChild( $section );
459        }
460    }
461
462    /**
463     * Get a MediaWiki page title from a URL
464     *
465     * @param string $url Relative URL (from a `href` attribute)
466     * @param Config $config Config settings needed to resolve the relative URL
467     * @return string|null
468     */
469    public static function getTitleFromUrl( string $url, Config $config ): ?string {
470        // Protocol-relative URLs are handled really badly by parse_url()
471        if ( str_starts_with( $url, '//' ) ) {
472            $url = "http:$url";
473        }
474
475        $bits = parse_url( $url );
476        $query = wfCgiToArray( $bits['query'] ?? '' );
477        if ( isset( $query['title'] ) ) {
478            return $query['title'];
479        }
480
481        // TODO: Set the correct base in the document?
482        $articlePath = $config->get( MainConfigNames::ArticlePath );
483        if ( str_starts_with( $url, './' ) ) {
484            // Assume this is URL in the format used by Parsoid documents
485            $url = substr( $url, 2 );
486            $path = str_replace( '$1', $url, $articlePath );
487        } elseif ( !str_contains( $url, '://' ) ) {
488            // Assume this is URL in the format used by legacy parser documents
489            $path = $url;
490        } else {
491            // External link
492            $path = $bits['path'] ?? '';
493        }
494
495        $articlePathRegexp = '/^' . str_replace(
496            '\\$1',
497            '([^?]*)',
498            preg_quote( $articlePath, '/' )
499        ) . '/';
500        $matches = null;
501        if ( preg_match( $articlePathRegexp, $path, $matches ) ) {
502            return rawurldecode( $matches[1] );
503        }
504        return null;
505    }
506
507    /**
508     * Traverse the document in depth-first order, calling the callback whenever entering and leaving
509     * a node. The walk starts before the given node and ends when callback returns a truthy value, or
510     * after reaching the end of the document.
511     *
512     * You might also think about this as processing XML token stream linearly (rather than XML
513     * nodes), as if we were parsing the document.
514     *
515     * @param Node $node Node to start at
516     * @param callable $callback Function accepting two arguments: $event ('enter' or 'leave') and
517     *     $node (Node)
518     * @return mixed Final return value of the callback
519     */
520    public static function linearWalk( Node $node, callable $callback ) {
521        $result = null;
522        [ $withinNode, $beforeNode ] = [ $node->parentNode, $node ];
523
524        while ( $beforeNode || $withinNode ) {
525            if ( $beforeNode ) {
526                $result = $callback( 'enter', $beforeNode );
527                [ $withinNode, $beforeNode ] = [ $beforeNode, $beforeNode->firstChild ];
528            } else {
529                $result = $callback( 'leave', $withinNode );
530                [ $withinNode, $beforeNode ] = [ $withinNode->parentNode, $withinNode->nextSibling ];
531            }
532
533            if ( $result ) {
534                return $result;
535            }
536        }
537        return $result;
538    }
539
540    /**
541     * Like #linearWalk, but it goes backwards.
542     *
543     * @inheritDoc ::linearWalk()
544     */
545    public static function linearWalkBackwards( Node $node, callable $callback ) {
546        $result = null;
547        [ $withinNode, $beforeNode ] = [ $node->parentNode, $node ];
548
549        while ( $beforeNode || $withinNode ) {
550            if ( $beforeNode ) {
551                $result = $callback( 'enter', $beforeNode );
552                [ $withinNode, $beforeNode ] = [ $beforeNode, $beforeNode->lastChild ];
553            } else {
554                $result = $callback( 'leave', $withinNode );
555                [ $withinNode, $beforeNode ] = [ $withinNode->parentNode, $withinNode->previousSibling ];
556            }
557
558            if ( $result ) {
559                return $result;
560            }
561        }
562        return $result;
563    }
564
565    /**
566     * @param ImmutableRange $range (must not be collapsed)
567     * @return Node
568     */
569    public static function getRangeFirstNode( ImmutableRange $range ): Node {
570        Assert::precondition( !$range->collapsed, 'Range is not collapsed' );
571        // PHP bug: childNodes can be null
572        return $range->startContainer->childNodes && $range->startContainer->childNodes->length ?
573            $range->startContainer->childNodes[ $range->startOffset ] :
574            $range->startContainer;
575    }
576
577    /**
578     * @param ImmutableRange $range (must not be collapsed)
579     * @return Node
580     */
581    public static function getRangeLastNode( ImmutableRange $range ): Node {
582        Assert::precondition( !$range->collapsed, 'Range is not collapsed' );
583        // PHP bug: childNodes can be null
584        return $range->endContainer->childNodes && $range->endContainer->childNodes->length ?
585            $range->endContainer->childNodes[ $range->endOffset - 1 ] :
586            $range->endContainer;
587    }
588
589    /**
590     * Check whether two ranges overlap, and how.
591     *
592     * Includes a hack to check for "almost equal" ranges (whose start/end boundaries only differ by
593     * "uninteresting" nodes that we ignore when detecting comments), and treat them as equal.
594     *
595     * Illustration of return values:
596     *          [    equal    ]
597     *          |[ contained ]|
598     *        [ |  contains   | ]
599     *  [overlap|start]       |
600     *          |     [overlap|end]
601     * [before] |             |
602     *          |             | [after]
603     *
604     * @param ImmutableRange $a
605     * @param ImmutableRange $b
606     * @return string One of:
607     *     - 'equal': Ranges A and B are equal
608     *     - 'contains': Range A contains range B
609     *     - 'contained': Range A is contained within range B
610     *     - 'after': Range A is before range B
611     *     - 'before': Range A is after range B
612     *     - 'overlapstart': Start of range A overlaps range B
613     *     - 'overlapend': End of range A overlaps range B
614     */
615    public static function compareRanges( ImmutableRange $a, ImmutableRange $b ): string {
616        // Compare the positions of: start of A to start of B, start of A to end of B, and so on.
617        // Watch out, the constant names are the opposite of what they should be.
618        $startToStart = $a->compareBoundaryPoints( ImmutableRange::START_TO_START, $b );
619        $startToEnd = $a->compareBoundaryPoints( ImmutableRange::END_TO_START, $b );
620        $endToStart = $a->compareBoundaryPoints( ImmutableRange::START_TO_END, $b );
621        $endToEnd = $a->compareBoundaryPoints( ImmutableRange::END_TO_END, $b );
622
623        // Handle almost equal ranges: When start or end boundary points of the two ranges are different,
624        // but only differ by "uninteresting" nodes, treat them as equal instead.
625        if (
626            ( $startToStart < 0 && static::compareRangesAlmostEqualBoundaries( $a, $b, 'start' ) ) ||
627            ( $startToStart > 0 && static::compareRangesAlmostEqualBoundaries( $b, $a, 'start' ) )
628        ) {
629            $startToStart = 0;
630        }
631        if (
632            ( $endToEnd < 0 && static::compareRangesAlmostEqualBoundaries( $a, $b, 'end' ) ) ||
633            ( $endToEnd > 0 && static::compareRangesAlmostEqualBoundaries( $b, $a, 'end' ) )
634        ) {
635            $endToEnd = 0;
636        }
637
638        if ( $startToStart === 0 && $endToEnd === 0 ) {
639            return 'equal';
640        }
641        if ( $startToStart <= 0 && $endToEnd >= 0 ) {
642            return 'contains';
643        }
644        if ( $startToStart >= 0 && $endToEnd <= 0 ) {
645            return 'contained';
646        }
647        if ( $startToEnd >= 0 ) {
648            return 'after';
649        }
650        if ( $endToStart <= 0 ) {
651            return 'before';
652        }
653        if ( $startToStart > 0 && $startToEnd < 0 && $endToEnd >= 0 ) {
654            return 'overlapstart';
655        }
656        if ( $endToEnd < 0 && $endToStart > 0 && $startToStart <= 0 ) {
657            return 'overlapend';
658        }
659
660        throw new LogicException( 'Unreachable' );
661    }
662
663    /**
664     * Check if the given boundary points of ranges A and B are almost equal (only differing by
665     * uninteresting nodes).
666     *
667     * Boundary of A must be before the boundary of B in the tree.
668     *
669     * @param ImmutableRange $a
670     * @param ImmutableRange $b
671     * @param string $boundary 'start' or 'end'
672     * @return bool
673     */
674    private static function compareRangesAlmostEqualBoundaries(
675        ImmutableRange $a, ImmutableRange $b, string $boundary
676    ): bool {
677        // This code is awful, but several attempts to rewrite it made it even worse.
678        // You're welcome to give it a try.
679
680        $from = $boundary === 'end' ? static::getRangeLastNode( $a ) : static::getRangeFirstNode( $a );
681        $to = $boundary === 'end' ? static::getRangeLastNode( $b ) : static::getRangeFirstNode( $b );
682
683        $skipNode = null;
684        if ( $boundary === 'end' ) {
685            $skipNode = $from;
686        }
687
688        $foundContent = false;
689        static::linearWalk(
690            $from,
691            static function ( string $event, Node $n ) use (
692                $from, $to, $boundary, &$skipNode, &$foundContent
693            ) {
694                if ( $n === $to && $event === ( $boundary === 'end' ? 'leave' : 'enter' ) ) {
695                    return true;
696                }
697                if ( $skipNode ) {
698                    if ( $n === $skipNode && $event === 'leave' ) {
699                        $skipNode = null;
700                    }
701                    return;
702                }
703
704                if ( $event === 'enter' ) {
705                    if (
706                        CommentUtils::isCommentSeparator( $n ) ||
707                        CommentUtils::isRenderingTransparentNode( $n ) ||
708                        CommentUtils::isOurGeneratedNode( $n )
709                    ) {
710                        $skipNode = $n;
711
712                    } elseif (
713                        CommentUtils::isCommentContent( $n )
714                    ) {
715                        $foundContent = true;
716                        return true;
717                    }
718                }
719            }
720        );
721
722        return !$foundContent;
723    }
724
725    /**
726     * Check whether the last item in the thread item set is a properly signed comment by
727     * the expected author (that is: there is a signature, and either there's nothing following the
728     * signature, or there's some text within the same paragraph that was detected as part of the same
729     * comment).
730     */
731    public static function isSingleCommentSignedBy(
732        ContentThreadItemSet $itemSet,
733        string $author,
734        Element $rootNode
735    ): bool {
736        $items = $itemSet->getThreadItems();
737
738        if ( $items ) {
739            $lastItem = end( $items );
740            // Check that we've detected a comment first, not just headings (T304377)
741            if ( !( $lastItem instanceof ContentCommentItem && $lastItem->getAuthor() === $author ) ) {
742                return false;
743            }
744
745            $commentRange = $lastItem->getRange();
746            $bodyRange = new ImmutableRange(
747                $rootNode, 0, $rootNode, count( $rootNode->childNodes )
748            );
749
750            // Only check that the end of the comment range is at the end of the body range.
751            // We don't care about preceding headings, comments, or other content (T363285).
752            // This is a simplified fragment of static::compareRanges().
753            $cmp = $commentRange->compareBoundaryPoints( ImmutableRange::END_TO_END, $bodyRange );
754            if (
755                $cmp === 0 ||
756                ( $cmp < 0 && static::compareRangesAlmostEqualBoundaries( $commentRange, $bodyRange, 'end' ) ) ||
757                ( $cmp > 0 && static::compareRangesAlmostEqualBoundaries( $bodyRange, $commentRange, 'end' ) )
758            ) {
759                // New comment includes a signature in the proper place
760                return true;
761            }
762        }
763
764        return false;
765    }
766
767    /**
768     * Get the ID for a new topics subscription from a page title
769     *
770     * @param Title $title Page title
771     * @return string ID for a new topics subscription
772     */
773    public static function getNewTopicsSubscriptionId( Title $title ) {
774        return "p-topics-{$title->getNamespace()}:{$title->getDBkey()}";
775    }
776}