Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.86% covered (success)
94.86%
277 / 292
81.48% covered (warning)
81.48%
22 / 27
CRAP
0.00% covered (danger)
0.00%
0 / 1
CommentUtils
94.86% covered (success)
94.86%
277 / 292
81.48% covered (warning)
81.48%
22 / 27
163.47
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
 getHeadlineNodeAndOffset
76.92% covered (warning)
76.92%
10 / 13
0.00% covered (danger)
0.00%
0 / 1
5.31
 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%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 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     * Also returns the offset within that node where the heading text starts.
319     *
320     * @param Element $heading Heading node (`<h1>`-`<h6>`)
321     * @return array Array containing a 'node' (Element) and offset (int)
322     */
323    public static function getHeadlineNodeAndOffset( Element $heading ): array {
324        // This code assumes that $wgFragmentMode is [ 'html5', 'legacy' ] or [ 'html5' ]
325        $headline = $heading;
326        $offset = 0;
327
328        if ( $headline->hasAttribute( 'data-mw-comment-start' ) ) {
329            $headline = $headline->parentNode;
330            Assert::precondition( $headline !== null, 'data-mw-comment-start was attached to a heading' );
331        }
332
333        if ( !$headline->getAttribute( 'id' ) && !$headline->getAttribute( 'data-mw-anchor' ) ) {
334            // PHP HTML: Find the child with .mw-headline
335            $headline = DOMCompat::querySelector( $headline, '.mw-headline' );
336            if ( !$headline ) {
337                $headline = $heading;
338            }
339        }
340
341        return [
342            'node' => $headline,
343            'offset' => $offset,
344        ];
345    }
346
347    /**
348     * Trim ASCII whitespace, as defined in the HTML spec.
349     */
350    public static function htmlTrim( string $str ): string {
351        // https://infra.spec.whatwg.org/#ascii-whitespace
352        return trim( $str, "\t\n\f\r " );
353    }
354
355    /**
356     * Get the indent level of $node, relative to $rootNode.
357     *
358     * The indent level is the number of lists inside of which it is nested.
359     */
360    public static function getIndentLevel( Node $node, Element $rootNode ): int {
361        $indent = 0;
362        while ( $node ) {
363            if ( $node === $rootNode ) {
364                break;
365            }
366            $tagName = $node instanceof Element ? strtolower( $node->tagName ) : null;
367            if ( $tagName === 'li' || $tagName === 'dd' ) {
368                $indent++;
369            }
370            $node = $node->parentNode;
371        }
372        return $indent;
373    }
374
375    /**
376     * Get an array of sibling nodes that contain parts of the given range.
377     *
378     * @param ImmutableRange $range
379     * @return Node[]
380     */
381    public static function getCoveredSiblings( ImmutableRange $range ): array {
382        $ancestor = $range->commonAncestorContainer;
383
384        // Convert to array early because apparently NodeList acts like a linked list
385        // and accessing items by index is slow
386        $siblings = iterator_to_array( $ancestor->childNodes );
387        $start = 0;
388        $end = count( $siblings ) - 1;
389
390        // Find first of the siblings that contains the item
391        if ( $ancestor === $range->startContainer ) {
392            $start = $range->startOffset;
393        } else {
394            while ( !static::contains( $siblings[ $start ], $range->startContainer ) ) {
395                $start++;
396            }
397        }
398
399        // Find last of the siblings that contains the item
400        if ( $ancestor === $range->endContainer ) {
401            $end = $range->endOffset - 1;
402        } else {
403            while ( !static::contains( $siblings[ $end ], $range->endContainer ) ) {
404                $end--;
405            }
406        }
407
408        return array_slice( $siblings, $start, $end - $start + 1 );
409    }
410
411    /**
412     * Get the nodes (if any) that contain the given thread item, and nothing else.
413     *
414     * @param ContentThreadItem $item
415     * @param ?Node $excludedAncestorNode Node that shouldn't be included in the result, even if it
416     *     contains the item and nothing else. This is intended to avoid traversing outside of a node
417     *     which is a container for all the thread items.
418     * @return Node[]|null
419     */
420    public static function getFullyCoveredSiblings(
421        ContentThreadItem $item, ?Node $excludedAncestorNode = null
422    ): ?array {
423        $siblings = static::getCoveredSiblings( $item->getRange() );
424
425        $makeRange = static function ( $siblings ) {
426            return new ImmutableRange(
427                $siblings[0]->parentNode,
428                CommentUtils::childIndexOf( $siblings[0] ),
429                end( $siblings )->parentNode,
430                CommentUtils::childIndexOf( end( $siblings ) ) + 1
431            );
432        };
433
434        $matches = static::compareRanges( $makeRange( $siblings ), $item->getRange() ) === 'equal';
435
436        if ( $matches ) {
437            // If these are all of the children (or the only child), go up one more level
438            while (
439                ( $parent = $siblings[ 0 ]->parentNode ) &&
440                $parent !== $excludedAncestorNode &&
441                static::compareRanges( $makeRange( [ $parent ] ), $item->getRange() ) === 'equal'
442            ) {
443                $siblings = [ $parent ];
444            }
445            return $siblings;
446        }
447        return null;
448    }
449
450    /**
451     * Unwrap Parsoid sections
452     *
453     * @param Element $element Parent element, e.g. document body
454     */
455    public static function unwrapParsoidSections( Element $element ): void {
456        $sections = DOMCompat::querySelectorAll( $element, 'section[data-mw-section-id]' );
457        foreach ( $sections as $section ) {
458            $parent = $section->parentNode;
459            while ( $section->firstChild ) {
460                $parent->insertBefore( $section->firstChild, $section );
461            }
462            $parent->removeChild( $section );
463        }
464    }
465
466    /**
467     * Get a MediaWiki page title from a URL
468     *
469     * @param string $url Relative URL (from a `href` attribute)
470     * @param Config $config Config settings needed to resolve the relative URL
471     * @return string|null
472     */
473    public static function getTitleFromUrl( string $url, Config $config ): ?string {
474        // Protocol-relative URLs are handled really badly by parse_url()
475        if ( str_starts_with( $url, '//' ) ) {
476            $url = "http:$url";
477        }
478
479        $bits = parse_url( $url );
480        $query = wfCgiToArray( $bits['query'] ?? '' );
481        if ( isset( $query['title'] ) ) {
482            return $query['title'];
483        }
484
485        // TODO: Set the correct base in the document?
486        $articlePath = $config->get( MainConfigNames::ArticlePath );
487        if ( str_starts_with( $url, './' ) ) {
488            // Assume this is URL in the format used by Parsoid documents
489            $url = substr( $url, 2 );
490            $path = str_replace( '$1', $url, $articlePath );
491        } elseif ( !str_contains( $url, '://' ) ) {
492            // Assume this is URL in the format used by legacy parser documents
493            $path = $url;
494        } else {
495            // External link
496            $path = $bits['path'] ?? '';
497        }
498
499        $articlePathRegexp = '/^' . str_replace(
500            '\\$1',
501            '([^?]*)',
502            preg_quote( $articlePath, '/' )
503        ) . '/';
504        $matches = null;
505        if ( preg_match( $articlePathRegexp, $path, $matches ) ) {
506            return urldecode( $matches[1] );
507        }
508        return null;
509    }
510
511    /**
512     * Traverse the document in depth-first order, calling the callback whenever entering and leaving
513     * a node. The walk starts before the given node and ends when callback returns a truthy value, or
514     * after reaching the end of the document.
515     *
516     * You might also think about this as processing XML token stream linearly (rather than XML
517     * nodes), as if we were parsing the document.
518     *
519     * @param Node $node Node to start at
520     * @param callable $callback Function accepting two arguments: $event ('enter' or 'leave') and
521     *     $node (Node)
522     * @return mixed Final return value of the callback
523     */
524    public static function linearWalk( Node $node, callable $callback ) {
525        $result = null;
526        [ $withinNode, $beforeNode ] = [ $node->parentNode, $node ];
527
528        while ( $beforeNode || $withinNode ) {
529            if ( $beforeNode ) {
530                $result = $callback( 'enter', $beforeNode );
531                [ $withinNode, $beforeNode ] = [ $beforeNode, $beforeNode->firstChild ];
532            } else {
533                $result = $callback( 'leave', $withinNode );
534                [ $withinNode, $beforeNode ] = [ $withinNode->parentNode, $withinNode->nextSibling ];
535            }
536
537            if ( $result ) {
538                return $result;
539            }
540        }
541        return $result;
542    }
543
544    /**
545     * Like #linearWalk, but it goes backwards.
546     *
547     * @inheritDoc ::linearWalk()
548     */
549    public static function linearWalkBackwards( Node $node, callable $callback ) {
550        $result = null;
551        [ $withinNode, $beforeNode ] = [ $node->parentNode, $node ];
552
553        while ( $beforeNode || $withinNode ) {
554            if ( $beforeNode ) {
555                $result = $callback( 'enter', $beforeNode );
556                [ $withinNode, $beforeNode ] = [ $beforeNode, $beforeNode->lastChild ];
557            } else {
558                $result = $callback( 'leave', $withinNode );
559                [ $withinNode, $beforeNode ] = [ $withinNode->parentNode, $withinNode->previousSibling ];
560            }
561
562            if ( $result ) {
563                return $result;
564            }
565        }
566        return $result;
567    }
568
569    /**
570     * @param ImmutableRange $range (must not be collapsed)
571     * @return Node
572     */
573    public static function getRangeFirstNode( ImmutableRange $range ): Node {
574        Assert::precondition( !$range->collapsed, 'Range is not collapsed' );
575        // PHP bug: childNodes can be null
576        return $range->startContainer->childNodes && $range->startContainer->childNodes->length ?
577            $range->startContainer->childNodes[ $range->startOffset ] :
578            $range->startContainer;
579    }
580
581    /**
582     * @param ImmutableRange $range (must not be collapsed)
583     * @return Node
584     */
585    public static function getRangeLastNode( ImmutableRange $range ): Node {
586        Assert::precondition( !$range->collapsed, 'Range is not collapsed' );
587        // PHP bug: childNodes can be null
588        return $range->endContainer->childNodes && $range->endContainer->childNodes->length ?
589            $range->endContainer->childNodes[ $range->endOffset - 1 ] :
590            $range->endContainer;
591    }
592
593    /**
594     * Check whether two ranges overlap, and how.
595     *
596     * Includes a hack to check for "almost equal" ranges (whose start/end boundaries only differ by
597     * "uninteresting" nodes that we ignore when detecting comments), and treat them as equal.
598     *
599     * Illustration of return values:
600     *          [    equal    ]
601     *          |[ contained ]|
602     *        [ |  contains   | ]
603     *  [overlap|start]       |
604     *          |     [overlap|end]
605     * [before] |             |
606     *          |             | [after]
607     *
608     * @param ImmutableRange $a
609     * @param ImmutableRange $b
610     * @return string One of:
611     *     - 'equal': Ranges A and B are equal
612     *     - 'contains': Range A contains range B
613     *     - 'contained': Range A is contained within range B
614     *     - 'after': Range A is before range B
615     *     - 'before': Range A is after range B
616     *     - 'overlapstart': Start of range A overlaps range B
617     *     - 'overlapend': End of range A overlaps range B
618     */
619    public static function compareRanges( ImmutableRange $a, ImmutableRange $b ): string {
620        // Compare the positions of: start of A to start of B, start of A to end of B, and so on.
621        // Watch out, the constant names are the opposite of what they should be.
622        $startToStart = $a->compareBoundaryPoints( ImmutableRange::START_TO_START, $b );
623        $startToEnd = $a->compareBoundaryPoints( ImmutableRange::END_TO_START, $b );
624        $endToStart = $a->compareBoundaryPoints( ImmutableRange::START_TO_END, $b );
625        $endToEnd = $a->compareBoundaryPoints( ImmutableRange::END_TO_END, $b );
626
627        // Handle almost equal ranges: When start or end boundary points of the two ranges are different,
628        // but only differ by "uninteresting" nodes, treat them as equal instead.
629        if (
630            ( $startToStart < 0 && static::compareRangesAlmostEqualBoundaries( $a, $b, 'start' ) ) ||
631            ( $startToStart > 0 && static::compareRangesAlmostEqualBoundaries( $b, $a, 'start' ) )
632        ) {
633            $startToStart = 0;
634        }
635        if (
636            ( $endToEnd < 0 && static::compareRangesAlmostEqualBoundaries( $a, $b, 'end' ) ) ||
637            ( $endToEnd > 0 && static::compareRangesAlmostEqualBoundaries( $b, $a, 'end' ) )
638        ) {
639            $endToEnd = 0;
640        }
641
642        if ( $startToStart === 0 && $endToEnd === 0 ) {
643            return 'equal';
644        }
645        if ( $startToStart <= 0 && $endToEnd >= 0 ) {
646            return 'contains';
647        }
648        if ( $startToStart >= 0 && $endToEnd <= 0 ) {
649            return 'contained';
650        }
651        if ( $startToEnd >= 0 ) {
652            return 'after';
653        }
654        if ( $endToStart <= 0 ) {
655            return 'before';
656        }
657        if ( $startToStart > 0 && $startToEnd < 0 && $endToEnd >= 0 ) {
658            return 'overlapstart';
659        }
660        if ( $endToEnd < 0 && $endToStart > 0 && $startToStart <= 0 ) {
661            return 'overlapend';
662        }
663
664        throw new LogicException( 'Unreachable' );
665    }
666
667    /**
668     * Check if the given boundary points of ranges A and B are almost equal (only differing by
669     * uninteresting nodes).
670     *
671     * Boundary of A must be before the boundary of B in the tree.
672     *
673     * @param ImmutableRange $a
674     * @param ImmutableRange $b
675     * @param string $boundary 'start' or 'end'
676     * @return bool
677     */
678    private static function compareRangesAlmostEqualBoundaries(
679        ImmutableRange $a, ImmutableRange $b, string $boundary
680    ): bool {
681        // This code is awful, but several attempts to rewrite it made it even worse.
682        // You're welcome to give it a try.
683
684        $from = $boundary === 'end' ? static::getRangeLastNode( $a ) : static::getRangeFirstNode( $a );
685        $to = $boundary === 'end' ? static::getRangeLastNode( $b ) : static::getRangeFirstNode( $b );
686
687        $skipNode = null;
688        if ( $boundary === 'end' ) {
689            $skipNode = $from;
690        }
691
692        $foundContent = false;
693        static::linearWalk(
694            $from,
695            static function ( string $event, Node $n ) use (
696                $from, $to, $boundary, &$skipNode, &$foundContent
697            ) {
698                if ( $n === $to && $event === ( $boundary === 'end' ? 'leave' : 'enter' ) ) {
699                    return true;
700                }
701                if ( $skipNode ) {
702                    if ( $n === $skipNode && $event === 'leave' ) {
703                        $skipNode = null;
704                    }
705                    return;
706                }
707
708                if ( $event === 'enter' ) {
709                    if (
710                        CommentUtils::isCommentSeparator( $n ) ||
711                        CommentUtils::isRenderingTransparentNode( $n ) ||
712                        CommentUtils::isOurGeneratedNode( $n )
713                    ) {
714                        $skipNode = $n;
715
716                    } elseif (
717                        CommentUtils::isCommentContent( $n )
718                    ) {
719                        $foundContent = true;
720                        return true;
721                    }
722                }
723            }
724        );
725
726        return !$foundContent;
727    }
728
729    /**
730     * Assuming that the thread item set contains exactly one comment (or multiple comments with
731     * identical signatures, plus optional heading), check whether that comment is properly signed by
732     * the expected author (that is: there is a signature, and either there's nothing following the
733     * signature, or there's some text within the same paragraph that was detected as part of the same
734     * comment).
735     */
736    public static function isSingleCommentSignedBy(
737        ContentThreadItemSet $itemSet,
738        string $author,
739        Element $rootNode
740    ): bool {
741        $items = $itemSet->getThreadItems();
742
743        if ( $items ) {
744            $lastItem = end( $items );
745            // Check that we've detected a comment first, not just headings (T304377)
746            if ( !( $lastItem instanceof ContentCommentItem && $lastItem->getAuthor() === $author ) ) {
747                return false;
748            }
749
750            // Range covering all of the detected items (to account for a heading, and for multiple
751            // signatures resulting in multiple comments)
752            $commentsRange = new ImmutableRange(
753                $items[0]->getRange()->startContainer,
754                $items[0]->getRange()->startOffset,
755                $lastItem->getRange()->endContainer,
756                $lastItem->getRange()->endOffset
757            );
758            $bodyRange = new ImmutableRange(
759                $rootNode, 0, $rootNode, count( $rootNode->childNodes )
760            );
761
762            if ( static::compareRanges( $commentsRange, $bodyRange ) === 'equal' ) {
763                // New comment includes a signature in the proper place
764                return true;
765            }
766        }
767
768        return false;
769    }
770
771    /**
772     * Get the ID for a new topics subscription from a page title
773     *
774     * @param Title $title Page title
775     * @return string ID for a new topics subscription
776     */
777    public static function getNewTopicsSubscriptionId( Title $title ) {
778        return "p-topics-{$title->getNamespace()}:{$title->getDBkey()}";
779    }
780}