Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.06% covered (success)
94.06%
649 / 690
65.38% covered (warning)
65.38%
17 / 26
CRAP
0.00% covered (danger)
0.00%
0 / 1
CommentParser
94.06% covered (success)
94.06%
649 / 690
65.38% covered (warning)
65.38%
17 / 26
259.80
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 parse
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 nextInterestingLeafNode
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
8
 regexpAlternateGroup
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getMessages
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getTimestampRegexp
88.54% covered (warning)
88.54%
85 / 96
0.00% covered (danger)
0.00%
0 / 1
32.45
 getTimestampParser
93.70% covered (success)
93.70%
119 / 127
0.00% covered (danger)
0.00%
0 / 1
52.68
 getLocalTimestampRegexps
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 getLocalTimestampParsers
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 getUsernameFromLink
97.06% covered (success)
97.06%
33 / 34
0.00% covered (danger)
0.00%
0 / 1
17
 findSignature
100.00% covered (success)
100.00%
43 / 43
100.00% covered (success)
100.00%
1 / 1
15
 acceptOnlyNodesAllowingComments
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
11
 getCodepointOffset
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 findTimestamp
100.00% covered (success)
100.00%
44 / 44
100.00% covered (success)
100.00%
1 / 1
10
 adjustSigRange
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 buildThreadItems
98.96% covered (success)
98.96%
95 / 96
0.00% covered (danger)
0.00%
0 / 1
22
 computeTranscludedFrom
69.23% covered (warning)
69.23%
36 / 52
0.00% covered (danger)
0.00%
0 / 1
45.69
 titleCanExist
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 parseTitle
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getTransclusionTitles
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 getTransclusionRange
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 truncateForId
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 computeId
96.30% covered (success)
96.30%
26 / 27
0.00% covered (danger)
0.00%
0 / 1
13
 computeName
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
4.01
 buildThreads
95.24% covered (success)
95.24%
20 / 21
0.00% covered (danger)
0.00%
0 / 1
9
 computeIdsAndNames
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3namespace MediaWiki\Extension\DiscussionTools;
4
5use DateInterval;
6use DateTime;
7use DateTimeImmutable;
8use DateTimeZone;
9use InvalidArgumentException;
10use LogicException;
11use MediaWiki\Config\Config;
12use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentCommentItem;
13use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentHeadingItem;
14use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentThreadItem;
15use MediaWiki\Language\Language;
16use MediaWiki\Language\LanguageConverterFactory;
17use MediaWiki\Title\MalformedTitleException;
18use MediaWiki\Title\TitleParser;
19use MediaWiki\Title\TitleValue;
20use MediaWiki\Utils\MWTimestamp;
21use RuntimeException;
22use Wikimedia\Assert\Assert;
23use Wikimedia\IPUtils;
24use Wikimedia\Parsoid\Core\DOMCompat;
25use Wikimedia\Parsoid\DOM\Element;
26use Wikimedia\Parsoid\DOM\Node;
27use Wikimedia\Parsoid\DOM\Text;
28use Wikimedia\Parsoid\Ext\DOMUtils;
29use Wikimedia\Timestamp\TimestampException;
30
31// TODO consider making timestamp parsing not a returned function
32
33class CommentParser {
34
35    /**
36     * How far backwards we look for a signature associated with a timestamp before giving up.
37     * Note that this is not a hard limit on the length of signatures we detect.
38     */
39    private const SIGNATURE_SCAN_LIMIT = 100;
40
41    /** @var string[] */
42    private array $dateFormat;
43    /** @var string[][] */
44    private array $digits;
45    /** @var string[][] */
46    private $contLangMessages;
47    private string $localTimezone;
48    /** @var string[][] */
49    private array $timezones;
50    private string $specialContributionsName;
51
52    private Element $rootNode;
53    private TitleValue $title;
54
55    public function __construct(
56        private readonly Config $config,
57        private readonly Language $language,
58        private readonly LanguageConverterFactory $languageConverterFactory,
59        LanguageData $languageData,
60        private readonly TitleParser $titleParser,
61    ) {
62        $data = $languageData->getLocalData();
63        $this->dateFormat = $data['dateFormat'];
64        $this->digits = $data['digits'];
65        $this->contLangMessages = $data['contLangMessages'];
66        $this->localTimezone = $data['localTimezone'];
67        $this->timezones = $data['timezones'];
68        $this->specialContributionsName = $data['specialContributionsName'];
69    }
70
71    /**
72     * Parse a discussion page.
73     *
74     * @param Element $rootNode Root node of content to parse
75     * @param TitleValue $title Title of the page being parsed
76     */
77    public function parse( Element $rootNode, TitleValue $title ): ContentThreadItemSet {
78        $this->rootNode = $rootNode;
79        $this->title = $title;
80
81        $result = $this->buildThreadItems();
82        $this->buildThreads( $result );
83        $this->computeIdsAndNames( $result );
84
85        return $result;
86    }
87
88    /**
89     * Return the next leaf node in the tree order that is likely a part of a discussion comment,
90     * rather than some boring "separator" element.
91     *
92     * Currently, this can return a Text node with content other than whitespace, or an Element node
93     * that is a "void element" or "text element", except some special cases that we treat as comment
94     * separators (isCommentSeparator()).
95     *
96     * @param ?Node $node Node after which to start searching
97     *   (if null, start at the beginning of the document).
98     */
99    private function nextInterestingLeafNode( ?Node $node ): Node {
100        $rootNode = $this->rootNode;
101        $treeWalker = new TreeWalker(
102            $rootNode,
103            NodeFilter::SHOW_ELEMENT | NodeFilter::SHOW_TEXT,
104            static function ( $n ) use ( $node ) {
105                // Skip past the starting node and its descendants
106                if ( $n === $node || $n->parentNode === $node ) {
107                    return NodeFilter::FILTER_REJECT;
108                }
109                // Ignore some elements usually used as separators or headers (and their descendants)
110                if ( CommentUtils::isCommentSeparator( $n ) ) {
111                    return NodeFilter::FILTER_REJECT;
112                }
113                // Ignore nodes with no rendering that mess up our indentation detection
114                if ( CommentUtils::isRenderingTransparentNode( $n ) ) {
115                    return NodeFilter::FILTER_REJECT;
116                }
117                if ( CommentUtils::isCommentContent( $n ) ) {
118                    return NodeFilter::FILTER_ACCEPT;
119                }
120                return NodeFilter::FILTER_SKIP;
121            }
122        );
123        if ( $node ) {
124            $treeWalker->currentNode = $node;
125        }
126        $treeWalker->nextNode();
127        if ( !$treeWalker->currentNode ) {
128            throw new RuntimeException( 'nextInterestingLeafNode not found' );
129        }
130        return $treeWalker->currentNode;
131    }
132
133    /**
134     * @param string[] $values Values to match
135     * @return string Regular expression
136     */
137    private static function regexpAlternateGroup( array $values ): string {
138        return '(' . implode( '|', array_map(
139            static fn ( string $val ) => preg_quote( $val, '/' ),
140            $values
141        ) ) . ')';
142    }
143
144    /**
145     * Get text of localisation messages in content language.
146     *
147     * @param string $contLangVariant Content language variant
148     * @param string[] $messages Message keys
149     * @return string[] Message values
150     */
151    private function getMessages( string $contLangVariant, array $messages ): array {
152        return array_map(
153            fn ( string $key ) => $this->contLangMessages[$contLangVariant][$key],
154            $messages
155        );
156    }
157
158    /**
159     * Get a regexp that matches timestamps generated using the given date format.
160     *
161     * This only supports format characters that are used by the default date format in any of
162     * MediaWiki's languages, namely: D, d, F, G, H, i, j, l, M, n, Y, xg, xkY (and escape characters),
163     * and only dates when MediaWiki existed, let's say 2000 onwards (Thai dates before 1941 are
164     * complicated).
165     *
166     * @param string $contLangVariant Content language variant
167     * @param string $format Date format
168     * @param string $digitsRegexp Regular expression matching a single localised digit, e.g. '[0-9]'
169     * @param array $tzAbbrs Associative array mapping localised timezone abbreviations to
170     *   IANA abbreviations, for the local timezone, e.g. [ 'EDT' => 'EDT', 'EST' => 'EST' ]
171     * @return string Regular expression
172     */
173    private function getTimestampRegexp(
174        string $contLangVariant, string $format, string $digitsRegexp, array $tzAbbrs
175    ): string {
176        $formatLength = strlen( $format );
177        $s = '';
178        $raw = false;
179        // Adapted from Language::sprintfDate()
180        for ( $p = 0; $p < $formatLength; $p++ ) {
181            $num = false;
182            $code = $format[ $p ];
183            if ( $code === 'x' && $p < $formatLength - 1 ) {
184                $code .= $format[++$p];
185            }
186            if ( $code === 'xk' && $p < $formatLength - 1 ) {
187                $code .= $format[++$p];
188            }
189
190            switch ( $code ) {
191                case 'xx':
192                    $s .= 'x';
193                    break;
194                case 'xg':
195                    $s .= static::regexpAlternateGroup(
196                        $this->getMessages( $contLangVariant, Language::MONTH_GENITIVE_MESSAGES )
197                    );
198                    break;
199                case 'xn':
200                    $raw = true;
201                    break;
202                case 'd':
203                    $num = '2';
204                    break;
205                case 'D':
206                    $s .= static::regexpAlternateGroup(
207                        $this->getMessages( $contLangVariant, Language::WEEKDAY_ABBREVIATED_MESSAGES )
208                    );
209                    break;
210                case 'j':
211                    $num = '1,2';
212                    break;
213                case 'l':
214                    $s .= static::regexpAlternateGroup(
215                        $this->getMessages( $contLangVariant, Language::WEEKDAY_MESSAGES )
216                    );
217                    break;
218                case 'F':
219                    $s .= static::regexpAlternateGroup(
220                        $this->getMessages( $contLangVariant, Language::MONTH_MESSAGES )
221                    );
222                    break;
223                case 'M':
224                    $s .= static::regexpAlternateGroup(
225                        $this->getMessages( $contLangVariant, Language::MONTH_ABBREVIATED_MESSAGES )
226                    );
227                    break;
228                case 'm':
229                    $num = '2';
230                    break;
231                case 'n':
232                    $num = '1,2';
233                    break;
234                case 'Y':
235                    $num = '4';
236                    break;
237                case 'xkY':
238                    $num = '4';
239                    break;
240                case 'G':
241                    $num = '1,2';
242                    break;
243                case 'H':
244                    $num = '2';
245                    break;
246                case 'i':
247                    $num = '2';
248                    break;
249                case 's':
250                    $num = '2';
251                    break;
252                case '\\':
253                    // Backslash escaping
254                    if ( $p < $formatLength - 1 ) {
255                        $s .= preg_quote( $format[++$p], '/' );
256                    } else {
257                        $s .= preg_quote( '\\', '/' );
258                    }
259                    break;
260                case '"':
261                    // Quoted literal
262                    if ( $p < $formatLength - 1 ) {
263                        $endQuote = strpos( $format, '"', $p + 1 );
264                        if ( $endQuote === false ) {
265                            // No terminating quote, assume literal "
266                            $s .= '"';
267                        } else {
268                            $s .= preg_quote( substr( $format, $p + 1, $endQuote - $p - 1 ), '/' );
269                            $p = $endQuote;
270                        }
271                    } else {
272                        // Quote at end of string, assume literal "
273                        $s .= '"';
274                    }
275                    break;
276                default:
277                    // Copy whole characters together, instead of single bytes
278                    $char = mb_substr( mb_strcut( $format, $p, 4 ), 0, 1 );
279                    $s .= preg_quote( $char, '/' );
280                    $p += strlen( $char ) - 1;
281            }
282            if ( $num !== false ) {
283                if ( $raw ) {
284                    $s .= '([0-9]{' . $num . '})';
285                    $raw = false;
286                } else {
287                    $s .= '(' . $digitsRegexp . '{' . $num . '})';
288                }
289            }
290            // Ignore some invisible Unicode characters that often sneak into copy-pasted timestamps (T308448)
291            $s .= '[\\x{200E}\\x{200F}]?';
292        }
293
294        $tzRegexp = static::regexpAlternateGroup( array_keys( $tzAbbrs ) );
295
296        // Hard-coded parentheses and space like in Parser::pstPass2
297        // Ignore some invisible Unicode characters that often sneak into copy-pasted timestamps (T245784)
298        // \uNNNN syntax can only be used from PHP 7.3
299        return '/' . $s . ' [\\x{200E}\\x{200F}]?\\(' . $tzRegexp . '\\)/u';
300    }
301
302    /**
303     * Get a function that parses timestamps generated using the given date format, based on the result
304     * of matching the regexp returned by getTimestampRegexp()
305     *
306     * @param string $contLangVariant Content language variant
307     * @param string $format Date format, as used by MediaWiki
308     * @param array<int,string>|null $digits Localised digits from 0 to 9, e.g. `[ '0', '1', ..., '9' ]`
309     * @param string $localTimezone Local timezone IANA name, e.g. `America/New_York`
310     * @param array $tzAbbrs Map of localised timezone abbreviations to IANA abbreviations
311     *   for the local timezone, e.g. [ 'EDT' => 'EDT', 'EST' => 'EST' ]
312     * @return callable Parser function
313     */
314    private function getTimestampParser(
315        string $contLangVariant, string $format, ?array $digits, string $localTimezone, array $tzAbbrs
316    ): callable {
317        $untransformDigits = static function ( string $text ) use ( $digits ): int {
318            return (int)( $digits ? strtr( $text, array_flip( $digits ) ) : $text );
319        };
320
321        $formatLength = strlen( $format );
322        $matchingGroups = [];
323        for ( $p = 0; $p < $formatLength; $p++ ) {
324            $code = $format[$p];
325            if ( $code === 'x' && $p < $formatLength - 1 ) {
326                $code .= $format[++$p];
327            }
328            if ( $code === 'xk' && $p < $formatLength - 1 ) {
329                $code .= $format[++$p];
330            }
331
332            switch ( $code ) {
333                case 'xx':
334                case 'xn':
335                    break;
336                case 'xg':
337                case 'd':
338                case 'j':
339                case 'D':
340                case 'l':
341                case 'F':
342                case 'M':
343                case 'm':
344                case 'n':
345                case 'Y':
346                case 'xkY':
347                case 'G':
348                case 'H':
349                case 'i':
350                case 's':
351                    $matchingGroups[] = $code;
352                    break;
353                case '\\':
354                    // Backslash escaping
355                    if ( $p < $formatLength - 1 ) {
356                        $p++;
357                    }
358                    break;
359                case '"':
360                    // Quoted literal
361                    if ( $p < $formatLength - 1 ) {
362                        $endQuote = strpos( $format, '"', $p + 1 );
363                        if ( $endQuote !== false ) {
364                            $p = $endQuote;
365                        }
366                    }
367                    break;
368                default:
369                    break;
370            }
371        }
372
373        return function ( array $match ) use (
374            $matchingGroups, $untransformDigits, $localTimezone, $tzAbbrs, $contLangVariant
375        ) {
376            if ( is_array( $match[0] ) ) {
377                /** Undo the effect of PREG_OFFSET_CAPTURE from {@link findTimestamp} */
378                $match = array_column( $match, 0 );
379            }
380            $year = 0;
381            $monthIdx = 0;
382            $day = 0;
383            $hour = 0;
384            $minute = 0;
385            foreach ( $matchingGroups as $i => $code ) {
386                $text = $match[$i + 1];
387                switch ( $code ) {
388                    case 'xg':
389                        $monthIdx = array_search(
390                            $text,
391                            $this->getMessages( $contLangVariant, Language::MONTH_GENITIVE_MESSAGES ),
392                            true
393                        );
394                        break;
395                    case 'd':
396                    case 'j':
397                        $day = $untransformDigits( $text );
398                        break;
399                    case 'D':
400                    case 'l':
401                        // Day of the week - unused
402                        break;
403                    case 'F':
404                        $monthIdx = array_search(
405                            $text,
406                            $this->getMessages( $contLangVariant, Language::MONTH_MESSAGES ),
407                            true
408                        );
409                        break;
410                    case 'M':
411                        $monthIdx = array_search(
412                            $text,
413                            $this->getMessages( $contLangVariant, Language::MONTH_ABBREVIATED_MESSAGES ),
414                            true
415                        );
416                        break;
417                    case 'm':
418                    case 'n':
419                        $monthIdx = $untransformDigits( $text ) - 1;
420                        break;
421                    case 'Y':
422                        $year = $untransformDigits( $text );
423                        break;
424                    case 'xkY':
425                        // Thai year
426                        $year = $untransformDigits( $text ) - 543;
427                        break;
428                    case 'G':
429                    case 'H':
430                        $hour = $untransformDigits( $text );
431                        break;
432                    case 'i':
433                        $minute = $untransformDigits( $text );
434                        break;
435                    case 's':
436                        // Seconds - unused, because most timestamp formats omit them
437                        break;
438                    default:
439                        throw new LogicException( 'Not implemented' );
440                }
441            }
442
443            // The last matching group is the timezone abbreviation
444            $tzAbbr = $tzAbbrs[ end( $match ) ];
445
446            // Most of the time, the timezone abbreviation is not necessary to parse the date, since we
447            // can assume all times are in the wiki's local timezone.
448            $date = new DateTime();
449            // setTimezone must be called before setDate/setTime
450            $date->setTimezone( new DateTimeZone( $localTimezone ) );
451            $date->setDate( $year, $monthIdx + 1, $day );
452            $date->setTime( $hour, $minute, 0 );
453
454            // But during the "fall back" at the end of DST, some times will happen twice.
455            // Since the timezone abbreviation disambiguates the DST/non-DST times, we can detect
456            // when PHP chose the wrong one, and then try the other one. It appears that PHP always
457            // uses the later (non-DST) hour, but that behavior isn't documented, so we account for both.
458            $dateWarning = null;
459            if ( $date->format( 'T' ) !== $tzAbbr ) {
460                $altDate = clone $date;
461                if ( $date->format( 'I' ) ) {
462                    // Parsed time is DST, try non-DST by advancing one hour
463                    $altDate->add( new DateInterval( 'PT1H' ) );
464                } else {
465                    // Parsed time is non-DST, try DST by going back one hour
466                    $altDate->sub( new DateInterval( 'PT1H' ) );
467                }
468                if ( $altDate->format( 'T' ) === $tzAbbr ) {
469                    $date = $altDate;
470                    $dateWarning = 'Timestamp has timezone abbreviation for the wrong time';
471                } else {
472                    $dateWarning = 'Ambiguous time at DST switchover was parsed';
473                }
474            }
475
476            // Now set the timezone back to UTC for formatting
477            $date->setTimezone( new DateTimeZone( 'UTC' ) );
478            $date = DateTimeImmutable::createFromMutable( $date );
479
480            // We require the date to be compatible with our libraries, for example zero or negative years (T352455)
481            // In PHP we need to check with MWTimestamp.
482            // In JS we need to check with Moment.
483            try {
484                // @phan-suppress-next-line PhanNoopNew
485                new MWTimestamp( $date->format( 'c' ) );
486            } catch ( TimestampException ) {
487                return null;
488            }
489
490            return [
491                'date' => $date,
492                'warning' => $dateWarning,
493            ];
494        };
495    }
496
497    /**
498     * Get a regexp that matches timestamps in the local date format, for each language variant.
499     *
500     * This calls getTimestampRegexp() with predefined data for the current wiki.
501     *
502     * @return string[] Regular expressions
503     */
504    public function getLocalTimestampRegexps(): array {
505        $langConv = $this->languageConverterFactory->getLanguageConverter( $this->language );
506        return array_map(
507            fn ( $contLangVariant ) => $this->getTimestampRegexp(
508                $contLangVariant,
509                $this->dateFormat[$contLangVariant],
510                '[' . implode( '', $this->digits[$contLangVariant] ) . ']',
511                $this->timezones[$contLangVariant]
512            ),
513            $langConv->getVariants()
514        );
515    }
516
517    /**
518     * Get a function that parses timestamps in the local date format, for each language variant,
519     * based on the result of matching the regexp returned by getLocalTimestampRegexp().
520     *
521     * This calls getTimestampParser() with predefined data for the current wiki.
522     *
523     * @return callable[] Parser functions
524     */
525    private function getLocalTimestampParsers(): array {
526        $langConv = $this->languageConverterFactory->getLanguageConverter( $this->language );
527        return array_map(
528            fn ( $contLangVariant ) => $this->getTimestampParser(
529                $contLangVariant,
530                $this->dateFormat[$contLangVariant],
531                $this->digits[$contLangVariant],
532                $this->localTimezone,
533                $this->timezones[$contLangVariant]
534            ),
535            $langConv->getVariants()
536        );
537    }
538
539    /**
540     * Given a link node (`<a>`), if it's a link to a user-related page, return their username.
541     *
542     * @return array|null Array, or null:
543     * - string 'username' Username
544     * - string|null 'displayName' Display name (link text if link target was in the user namespace)
545     */
546    private function getUsernameFromLink( Element $link ): ?array {
547        // Selflink: use title of current page
548        if ( DOMUtils::hasClass( $link, 'mw-selflink' ) ) {
549            $title = $this->title;
550        } else {
551            $titleString = CommentUtils::getTitleFromUrl( $link->getAttribute( 'href' ) ?? '', $this->config ) ?? '';
552            // Performance optimization, skip strings that obviously don't contain a namespace
553            if ( $titleString === '' || !str_contains( $titleString, ':' ) ) {
554                return null;
555            }
556            $title = $this->parseTitle( $titleString );
557            if ( !$title ) {
558                return null;
559            }
560        }
561
562        $username = null;
563        $displayName = null;
564        $mainText = $title->getText();
565
566        if ( $title->inNamespace( NS_USER ) || $title->inNamespace( NS_USER_TALK ) ) {
567            $username = $mainText;
568            if ( str_contains( $username, '/' ) ) {
569                return null;
570            }
571            if ( $title->inNamespace( NS_USER ) ) {
572                // Use regex trim for consistency with JS implementation
573                $text = preg_replace( [ '/^[\s]+/u', '/[\s]+$/u' ], '', $link->textContent ?? '' );
574                // Record the display name if it has been customised beyond changing case
575                if ( $text && mb_strtolower( $text ) !== mb_strtolower( $username ) ) {
576                    $displayName = $text;
577                }
578            }
579        } elseif ( $title->inNamespace( NS_SPECIAL ) ) {
580            $parts = explode( '/', $mainText );
581            if ( count( $parts ) === 2 && $parts[0] === $this->specialContributionsName ) {
582                // Normalize the username: users may link to their contributions with an unnormalized name
583                $userpage = $this->titleParser->makeTitleValueSafe( NS_USER, $parts[1] );
584                if ( !$userpage ) {
585                    return null;
586                }
587                $username = $userpage->getText();
588            }
589        }
590        if ( $username === null ) {
591            return null;
592        }
593        if ( IPUtils::isIPv6( $username ) ) {
594            // Bot-generated links "Preceding unsigned comment added by" have non-standard case
595            $username = strtoupper( $username );
596        }
597        return [
598            'username' => $username,
599            'displayName' => $displayName,
600        ];
601    }
602
603    /**
604     * Find a user signature preceding a timestamp.
605     *
606     * The signature includes the timestamp node.
607     *
608     * A signature must contain at least one link to the user's userpage, discussion page or
609     * contributions (and may contain other links). The link may be nested in other elements.
610     *
611     * @param Text $timestampNode
612     * @param Node|null $until Node to stop searching at
613     * @return array Result, an associative array with the following keys:
614     *   - Node[] `nodes` Sibling nodes comprising the signature, in reverse order (with
615     *     $timestampNode or its parent node as the first element)
616     *   - string|null `username` Username, null for unsigned comments
617     */
618    private function findSignature( Text $timestampNode, ?Node $until = null ): array {
619        $sigUsername = null;
620        $sigDisplayName = null;
621        $length = 0;
622        $lastLinkNode = $timestampNode;
623
624        CommentUtils::linearWalkBackwards(
625            $timestampNode,
626            function ( string $event, Node $node ) use (
627                &$sigUsername, &$sigDisplayName, &$lastLinkNode, &$length,
628                $until, $timestampNode
629            ) {
630                if ( $event === 'enter' && $node === $until ) {
631                    return true;
632                }
633                if ( $length >= static::SIGNATURE_SCAN_LIMIT ) {
634                    return true;
635                }
636                if ( CommentUtils::isBlockElement( $node ) ) {
637                    // Don't allow reaching into preceding paragraphs
638                    return true;
639                }
640
641                if ( $event === 'leave' && $node !== $timestampNode ) {
642                    $length += $node instanceof Text ?
643                        mb_strlen( CommentUtils::htmlTrim( $node->textContent ?? '' ) ) : 0;
644                }
645
646                // Find the closest link before timestamp that links to the user's user page.
647                //
648                // Support timestamps being linked to the diff introducing the comment:
649                // if the timestamp node is the only child of a link node, use the link node instead
650                //
651                // Handle links nested in formatting elements.
652                if ( $event === 'leave' && $node instanceof Element && strtolower( $node->tagName ) === 'a' ) {
653                    $classList = DOMCompat::getClassList( $node );
654                    // Generated timestamp links sometimes look like username links (e.g. on user talk pages)
655                    // so ignore these.
656                    if ( !$classList->contains( 'ext-discussiontools-init-timestamplink' ) ) {
657                        $user = $this->getUsernameFromLink( $node );
658                        if ( $user ) {
659                            // Accept the first link to the user namespace, then only accept links to that user
660                            $sigUsername ??= $user['username'];
661                            if ( $user['username'] === $sigUsername ) {
662                                $lastLinkNode = $node;
663                                if ( $user['displayName'] ) {
664                                    $sigDisplayName = $user['displayName'];
665                                }
666                            }
667                        }
668                        // Keep looking if a node with links wasn't a link to a user page
669                        // "Doc James (talk Â· contribs Â· email)"
670                    }
671                }
672            }
673        );
674
675        $range = new ImmutableRange(
676            $lastLinkNode->parentNode,
677            CommentUtils::childIndexOf( $lastLinkNode ),
678            $timestampNode->parentNode,
679            CommentUtils::childIndexOf( $timestampNode ) + 1
680        );
681
682        // Expand the range so that it covers sibling nodes.
683        // This will include any wrapping formatting elements as part of the signature.
684        //
685        // Helpful accidental feature: users whose signature is not detected in full (due to
686        // text formatting) can just wrap it in a <span> to fix that.
687        // "Ten Pound Hammer â€¢ (What did I screw up now?)"
688        // "« Saper // dyskusja Â»"
689        //
690        // TODO Not sure if this is actually good, might be better to just use the range...
691        $sigNodes = array_reverse( CommentUtils::getCoveredSiblings( $range ) );
692
693        return [
694            'nodes' => $sigNodes,
695            'username' => $sigUsername,
696            'displayName' => $sigDisplayName,
697        ];
698    }
699
700    /**
701     * Callback for TreeWalker that will skip over nodes where we don't want to detect
702     * comments (or section headings).
703     *
704     * @return int Appropriate NodeFilter constant
705     */
706    public static function acceptOnlyNodesAllowingComments( Node $node ): int {
707        if ( $node instanceof Element ) {
708            $tagName = strtolower( $node->tagName );
709            // The table of contents has a heading that gets erroneously detected as a section
710            if ( $node->getAttribute( 'id' ) === 'toc' ) {
711                return NodeFilter::FILTER_REJECT;
712            }
713            // Don't detect comments within quotes (T275881)
714            if (
715                $tagName === 'blockquote' ||
716                $tagName === 'cite' ||
717                $tagName === 'q'
718            ) {
719                return NodeFilter::FILTER_REJECT;
720            }
721            // Don't attempt to parse blocks marked 'mw-notalk'
722            if ( DOMUtils::hasClass( $node, 'mw-notalk' ) ) {
723                return NodeFilter::FILTER_REJECT;
724            }
725            // Don't detect comments within references. We can't add replies to them without bungling up
726            // the structure in some cases (T301213), and you're not supposed to do that anyway…
727            if (
728                // <ol class="references"> is the only reliably consistent thing between the two parsers
729                $tagName === 'ol' &&
730                DOMUtils::hasClass( $node, 'references' )
731            ) {
732                return NodeFilter::FILTER_REJECT;
733            }
734        }
735        $parentNode = $node->parentNode;
736        // Don't detect comments within headings (but don't reject the headings themselves)
737        if ( $parentNode instanceof Element && preg_match( '/^h([1-6])$/i', $parentNode->tagName ) ) {
738            return NodeFilter::FILTER_REJECT;
739        }
740        return NodeFilter::FILTER_ACCEPT;
741    }
742
743    /**
744     * Convert a byte offset within a text node to a unicode codepoint offset
745     *
746     * @param Text $node Text node
747     * @param int $byteOffset Byte offset
748     * @return int Codepoint offset
749     */
750    private static function getCodepointOffset( Text $node, int $byteOffset ): int {
751        return mb_strlen( substr( $node->nodeValue ?? '', 0, $byteOffset ) );
752    }
753
754    /**
755     * Find a timestamps in a given text node
756     *
757     * @param Text $node
758     * @param string[] $timestampRegexps
759     * @return array|null Array with the following keys:
760     *   - int 'offset' Length of extra text preceding the node that was used for matching (in bytes)
761     *   - int 'parserIndex' Which of the regexps matched
762     *   - array 'matchData' Regexp match data, which specifies the location of the match,
763     *     and which can be parsed using getLocalTimestampParsers() (offsets are in bytes)
764     *   - ImmutableRange 'range' Range covering the timestamp
765     */
766    public function findTimestamp( Text $node, array $timestampRegexps ): ?array {
767        $nodeText = '';
768        $offset = 0;
769        // Searched nodes (reverse order)
770        $nodes = [];
771
772        while ( $node ) {
773            $nodeText = $node->nodeValue . $nodeText;
774            $nodes[] = $node;
775
776            // In Parsoid HTML, entities are represented as a 'mw:Entity' node, rather than normal HTML
777            // entities. On Arabic Wikipedia, the "UTC" timezone name contains some non-breaking spaces,
778            // which apparently are often turned into &nbsp; entities by buggy editing tools. To handle
779            // this, we must piece together the text, so that our regexp can match those timestamps.
780            if (
781                ( $previousSibling = $node->previousSibling ) &&
782                $previousSibling instanceof Element &&
783                $previousSibling->getAttribute( 'typeof' ) === 'mw:Entity'
784            ) {
785                $nodeText = $previousSibling->firstChild->nodeValue . $nodeText;
786                $offset += strlen( $previousSibling->firstChild->nodeValue ?? '' );
787                $nodes[] = $previousSibling->firstChild;
788
789                // If the entity is preceded by more text, do this again
790                if ( $previousSibling->previousSibling instanceof Text ) {
791                    $offset += strlen( $previousSibling->previousSibling->nodeValue ?? '' );
792                    $node = $previousSibling->previousSibling;
793                } else {
794                    $node = null;
795                }
796            } else {
797                $node = null;
798            }
799        }
800
801        foreach ( $timestampRegexps as $i => $timestampRegexp ) {
802            $matchData = null;
803            // Allows us to mimic match.index in #getComments
804            if ( preg_match( $timestampRegexp, $nodeText, $matchData, PREG_OFFSET_CAPTURE ) ) {
805                $timestampLength = strlen( $matchData[0][0] );
806                // Bytes at the end of the last node which aren't part of the match
807                $tailLength = strlen( $nodeText ) - $timestampLength - $matchData[0][1];
808                // We are moving right to left, but we start to the right of the end of
809                // the timestamp if there is trailing garbage, so that is a negative offset.
810                $count = -$tailLength;
811                $endNode = $nodes[0];
812                $endOffset = strlen( $endNode->nodeValue ?? '' ) - $tailLength;
813
814                foreach ( $nodes as $n ) {
815                    $count += strlen( $n->nodeValue ?? '' );
816                    // If we have counted to beyond the start of the timestamp, we are in the
817                    // start node of the timestamp
818                    if ( $count >= $timestampLength ) {
819                        $startNode = $n;
820                        // Offset is how much we overshot the start by
821                        $startOffset = $count - $timestampLength;
822                        break;
823                    }
824                }
825                Assert::precondition( $endNode instanceof Node, 'endNode of timestamp is a Node' );
826                Assert::precondition( $startNode instanceof Node, 'startNode of timestamp range found' );
827                Assert::precondition( is_int( $startOffset ), 'startOffset of timestamp range found' );
828
829                $startOffset = static::getCodepointOffset( $startNode, $startOffset );
830                $endOffset = static::getCodepointOffset( $endNode, $endOffset );
831
832                $range = new ImmutableRange( $startNode, $startOffset, $endNode, $endOffset );
833
834                return [
835                    'matchData' => $matchData,
836                    // Bytes at the start of the first node which aren't part of the match
837                    // TODO: Remove this and use 'range' instead
838                    'offset' => $offset,
839                    'range' => $range,
840                    'parserIndex' => $i,
841                ];
842            }
843        }
844        return null;
845    }
846
847    /**
848     * @param Node[] $sigNodes
849     * @param array $match
850     * @param Text $node
851     */
852    private function adjustSigRange( array $sigNodes, array $match, Text $node ): ImmutableRange {
853        $firstSigNode = end( $sigNodes );
854        $lastSigNode = $sigNodes[0];
855
856        // TODO Document why this needs to be so complicated
857        $lastSigNodeOffsetByteOffset =
858            $match['matchData'][0][1] + strlen( $match['matchData'][0][0] ) - $match['offset'];
859        $lastSigNodeOffset = $lastSigNode === $node ?
860            static::getCodepointOffset( $node, $lastSigNodeOffsetByteOffset ) :
861            CommentUtils::childIndexOf( $lastSigNode ) + 1;
862        $sigRange = new ImmutableRange(
863            $firstSigNode->parentNode,
864            CommentUtils::childIndexOf( $firstSigNode ),
865            $lastSigNode === $node ? $node : $lastSigNode->parentNode,
866            $lastSigNodeOffset
867        );
868
869        return $sigRange;
870    }
871
872    private function buildThreadItems(): ContentThreadItemSet {
873        $result = new ContentThreadItemSet();
874
875        $timestampRegexps = $this->getLocalTimestampRegexps();
876        $dfParsers = $this->getLocalTimestampParsers();
877
878        $curCommentEnd = null;
879
880        $treeWalker = new TreeWalker(
881            $this->rootNode,
882            NodeFilter::SHOW_ELEMENT | NodeFilter::SHOW_TEXT,
883            static::acceptOnlyNodesAllowingComments( ... )
884        );
885        while ( $node = $treeWalker->nextNode() ) {
886            if ( $node instanceof Element && preg_match( '/^h([1-6])$/i', $node->tagName, $match ) ) {
887                $headingNode = CommentUtils::getHeadlineNode( $node );
888                $range = new ImmutableRange(
889                    $headingNode, 0, $headingNode, $headingNode->childNodes->length
890                );
891                $transcludedFrom = $this->computeTranscludedFrom( $range );
892                $curComment = new ContentHeadingItem( $range, $transcludedFrom, (int)( $match[ 1 ] ) );
893                $curComment->setRootNode( $this->rootNode );
894                $result->addThreadItem( $curComment );
895                $curCommentEnd = $node;
896            } elseif ( $node instanceof Text && ( $match = $this->findTimestamp( $node, $timestampRegexps ) ) ) {
897                $warnings = [];
898                $foundSignature = $this->findSignature( $node, $curCommentEnd );
899                $author = $foundSignature['username'];
900
901                if ( $author === null ) {
902                    // Ignore timestamps for which we couldn't find a signature. It's probably not a real
903                    // comment, but just a false match due to a copypasted timestamp.
904                    continue;
905                }
906
907                $sigRanges = [];
908                $timestampRanges = [];
909
910                $sigRanges[] = $this->adjustSigRange( $foundSignature['nodes'], $match, $node );
911                $timestampRanges[] = $match['range'];
912
913                // Everything from the last comment up to here is the next comment
914                $startNode = $this->nextInterestingLeafNode( $curCommentEnd );
915                $endNode = $foundSignature['nodes'][0];
916
917                // Skip to the end of the "paragraph". This only looks at tag names and can be fooled by CSS, but
918                // avoiding that would be more difficult and slower.
919                //
920                // If this skips over another potential signature, also skip it in the main TreeWalker loop, to
921                // avoid generating multiple comments when there is more than one signature on a single "line".
922                // Often this is done when someone edits their comment later and wants to add a note about that.
923                // (Or when another person corrects a typo, or strikes out a comment, etc.) Multiple comments
924                // within one paragraph/list-item result in a confusing double "Reply" button, and we also have
925                // no way to indicate which one you're replying to (this might matter in the future for
926                // notifications or something).
927                CommentUtils::linearWalk(
928                    $endNode,
929                    function ( string $event, Node $n ) use (
930                        &$endNode, &$sigRanges, &$timestampRanges,
931                        $treeWalker, $timestampRegexps, $node
932                    ) {
933                        if ( CommentUtils::isBlockElement( $n ) || CommentUtils::isCommentSeparator( $n ) ) {
934                            // Stop when entering or leaving a block node
935                            return true;
936                        }
937                        if (
938                            $event === 'leave' &&
939                            $n instanceof Text && $n !== $node &&
940                            ( $match2 = $this->findTimestamp( $n, $timestampRegexps ) )
941                        ) {
942                            // If this skips over another potential signature, also skip it in the main TreeWalker loop
943                            $treeWalker->currentNode = $n;
944                            // â€¦and add it as another signature to this comment (regardless of the author and timestamp)
945                            $foundSignature2 = $this->findSignature( $n, $node );
946                            if ( $foundSignature2['username'] !== null ) {
947                                $sigRanges[] = $this->adjustSigRange( $foundSignature2['nodes'], $match2, $n );
948                                $timestampRanges[] = $match2['range'];
949                            }
950                        }
951                        if ( $event === 'leave' ) {
952                            // Take the last complete node which we skipped past
953                            $endNode = $n;
954                        }
955                    }
956                );
957
958                $length = ( $endNode instanceof Text ) ?
959                    mb_strlen( rtrim( $endNode->nodeValue ?? '', "\t\n\f\r " ) ) :
960                    // PHP bug: childNodes can be null for comment nodes
961                    // (it should always be a NodeList, even if the node can't have children)
962                    ( $endNode->childNodes ? $endNode->childNodes->length : 0 );
963                $range = new ImmutableRange(
964                    $startNode->parentNode,
965                    CommentUtils::childIndexOf( $startNode ),
966                    $endNode,
967                    $length
968                );
969                $transcludedFrom = $this->computeTranscludedFrom( $range );
970
971                $startLevel = CommentUtils::getIndentLevel( $startNode, $this->rootNode ) + 1;
972                $endLevel = CommentUtils::getIndentLevel( $node, $this->rootNode ) + 1;
973                if ( $startLevel !== $endLevel ) {
974                    $warnings[] = 'Comment starts and ends with different indentation';
975                }
976                // Should this use the indent level of $startNode or $node?
977                $level = min( $startLevel, $endLevel );
978
979                $parserResult = $dfParsers[ $match['parserIndex'] ]( $match['matchData'] );
980                if ( !$parserResult ) {
981                    continue;
982                }
983                [ 'date' => $dateTime, 'warning' => $dateWarning ] = $parserResult;
984
985                if ( $dateWarning ) {
986                    $warnings[] = $dateWarning;
987                }
988
989                $curComment = new ContentCommentItem(
990                    $level,
991                    $range,
992                    $transcludedFrom,
993                    $sigRanges,
994                    $timestampRanges,
995                    $dateTime,
996                    $author,
997                    $foundSignature['displayName']
998                );
999                $curComment->setRootNode( $this->rootNode );
1000                if ( $warnings ) {
1001                    $curComment->addWarnings( $warnings );
1002                }
1003                if ( $result->isEmpty() ) {
1004                    // Add a fake placeholder heading if there are any comments in the 0th section
1005                    // (before the first real heading)
1006                    $range = new ImmutableRange( $this->rootNode, 0, $this->rootNode, 0 );
1007                    $fakeHeading = new ContentHeadingItem( $range, false, null );
1008                    $fakeHeading->setRootNode( $this->rootNode );
1009                    $result->addThreadItem( $fakeHeading );
1010                }
1011                $result->addThreadItem( $curComment );
1012                $curCommentEnd = $curComment->getRange()->endContainer;
1013            }
1014        }
1015
1016        return $result;
1017    }
1018
1019    /**
1020     * Get the name of the page from which this thread item is transcluded (if any). Replies to
1021     * transcluded items must be posted on that page, instead of the current one.
1022     *
1023     * This is tricky, because we don't want to mark items as transcluded when they're just using a
1024     * template (e.g. {{ping|…}} or a non-substituted signature template). Sometimes the whole comment
1025     * can be template-generated (e.g. when using some wrapper templates), but as long as a reply can
1026     * be added outside of that template, we should not treat it as transcluded.
1027     *
1028     * The start/end boundary points of comment ranges and Parsoid transclusion ranges don't line up
1029     * exactly, even when to a human it's obvious that they cover the same content, making this more
1030     * complicated.
1031     *
1032     * @return string|bool `false` if this item is not transcluded. A string if it's transcluded
1033     *   from a single page (the page title, in text form with spaces). `true` if it's transcluded, but
1034     *   we can't determine the source.
1035     */
1036    public function computeTranscludedFrom( ImmutableRange $commentRange ) {
1037        // Collapsed ranges should otherwise be impossible, but they're not (T299583)
1038        // TODO: See if we can fix the root cause, and remove this?
1039        if ( $commentRange->collapsed ) {
1040            return false;
1041        }
1042
1043        // General approach:
1044        //
1045        // Compare the comment range to each transclusion range on the page, and if it overlaps any of
1046        // them, examine the overlap. There are a few cases:
1047        //
1048        // * Comment and transclusion do not overlap:
1049        //   â†’ Not transcluded.
1050        // * Comment contains the transclusion:
1051        //   â†’ Not transcluded (just a template).
1052        // * Comment is contained within the transclusion:
1053        //   â†’ Transcluded, we can determine the source page (unless it's a complex transclusion).
1054        // * Comment and transclusion overlap partially:
1055        //   â†’ Transcluded, but we can't determine the source page.
1056        // * Comment (almost) exactly matches the transclusion:
1057        //   â†’ Maybe transcluded (it could be that the source page only contains that single comment),
1058        //     maybe not transcluded (it could be a wrapper template that covers a single comment).
1059        //     This is very sad, and we decide based on the namespace.
1060        //
1061        // Most transclusion ranges on the page trivially fall in the "do not overlap" or "contains"
1062        // cases, and we only have to carefully examine the two transclusion ranges that contain the
1063        // first and last node of the comment range.
1064        //
1065        // To check for almost exact matches, we walk between the relevant boundary points, and if we
1066        // only find uninteresting nodes (that would be ignored when detecting comments), we treat them
1067        // like exact matches.
1068
1069        $startTransclNode = CommentUtils::getTranscludedFromElement(
1070            CommentUtils::getRangeFirstNode( $commentRange )
1071        );
1072        $endTransclNode = CommentUtils::getTranscludedFromElement(
1073            CommentUtils::getRangeLastNode( $commentRange )
1074        );
1075
1076        // We only have to examine the two transclusion ranges that contain the first/last node of the
1077        // comment range (if they exist). Ignore ranges outside the comment or in the middle of it.
1078        $transclNodes = [];
1079        if ( $startTransclNode ) {
1080            $transclNodes[] = $startTransclNode;
1081        }
1082        if ( $endTransclNode && $endTransclNode !== $startTransclNode ) {
1083            $transclNodes[] = $endTransclNode;
1084        }
1085
1086        foreach ( $transclNodes as $transclNode ) {
1087            $transclRange = static::getTransclusionRange( $transclNode );
1088            $compared = CommentUtils::compareRanges( $commentRange, $transclRange );
1089            $transclTitles = $this->getTransclusionTitles( $transclNode );
1090            $simpleTransclTitle = count( $transclTitles ) === 1 && $transclTitles[0] !== null ?
1091                $this->parseTitle( $transclTitles[0] ) : null;
1092
1093            switch ( $compared ) {
1094                case 'equal':
1095                    // Comment (almost) exactly matches the transclusion
1096                    if ( $simpleTransclTitle === null ) {
1097                        // Allow replying to some accidental complex transclusions consisting of only templates
1098                        // and wikitext (T313093)
1099                        if ( count( $transclTitles ) > 1 ) {
1100                            foreach ( $transclTitles as $transclTitleString ) {
1101                                if ( $transclTitleString !== null ) {
1102                                    $transclTitle = $this->parseTitle( $transclTitleString );
1103                                    if ( $transclTitle && !$transclTitle->inNamespace( NS_TEMPLATE ) ) {
1104                                        return true;
1105                                    }
1106                                }
1107                            }
1108                            // Continue examining the other ranges.
1109                            break;
1110                        }
1111                        // Multi-template transclusion, or a parser function call, or template-affected wikitext outside
1112                        // of a template call, or a mix of the above
1113                        return true;
1114
1115                    } elseif ( $simpleTransclTitle->inNamespace( NS_TEMPLATE ) ) {
1116                        // Is that a subpage transclusion with a single comment, or a wrapper template
1117                        // transclusion on this page? We don't know, but let's guess based on the namespace.
1118                        // (T289873)
1119                        // Continue examining the other ranges.
1120                        break;
1121                    } elseif ( !$this->titleCanExist( $simpleTransclTitle ) ) {
1122                        // Special page transclusion (T344622) or something else weird. Don't return the title,
1123                        // since it's useless for replying, and can't be stored in the permalink database.
1124                        return true;
1125                    } else {
1126                        Assert::precondition( $transclTitles[0] !== null, "Simple transclusion found" );
1127                        return strtr( $transclTitles[0], '_', ' ' );
1128                    }
1129
1130                case 'contains':
1131                    // Comment contains the transclusion
1132
1133                    // If the entire transclusion is contained within the comment range, that's just a
1134                    // template. This is the same as a transclusion in the middle of the comment, which we
1135                    // ignored earlier, it just takes us longer to get here in this case.
1136
1137                    // Continue examining the other ranges.
1138                    break;
1139
1140                case 'contained':
1141                    // Comment is contained within the transclusion
1142                    if ( $simpleTransclTitle === null ) {
1143                        return true;
1144                    } elseif ( !$this->titleCanExist( $simpleTransclTitle ) ) {
1145                        // Special page transclusion (T344622) or something else weird. Don't return the title,
1146                        // since it's useless for replying, and can't be stored in the permalink database.
1147                        return true;
1148                    } else {
1149                        Assert::precondition( $transclTitles[0] !== null, "Simple transclusion found" );
1150                        return strtr( $transclTitles[0], '_', ' ' );
1151                    }
1152
1153                case 'after':
1154                case 'before':
1155                    // Comment and transclusion do not overlap
1156
1157                    // This should be impossible, because we ignored these ranges earlier.
1158                    throw new LogicException( 'Unexpected transclusion or comment range' );
1159
1160                case 'overlapstart':
1161                case 'overlapend':
1162                    // Comment and transclusion overlap partially
1163                    return true;
1164
1165                default:
1166                    throw new LogicException( 'Unexpected return value from compareRanges()' );
1167            }
1168        }
1169
1170        // If we got here, the comment range was not contained by or overlapping any of the transclusion
1171        // ranges. Comment is not transcluded.
1172        return false;
1173    }
1174
1175    private function titleCanExist( TitleValue $title ): bool {
1176        return $title->getNamespace() >= NS_MAIN &&
1177            !$title->isExternal() &&
1178            $title->getText() !== '';
1179    }
1180
1181    private function parseTitle( string $titleString ): ?TitleValue {
1182        try {
1183            return $this->titleParser->parseTitle( $titleString );
1184        } catch ( MalformedTitleException ) {
1185            return null;
1186        }
1187    }
1188
1189    /**
1190     * Return the page titles for each part of the transclusion, or nulls for each part that isn't
1191     * transcluded from another page.
1192     *
1193     * If the node represents a single-page transclusion, this will return an array containing a
1194     * single string.
1195     *
1196     * @return array<string|null>
1197     */
1198    private function getTransclusionTitles( Element $node ): array {
1199        $dataMw = json_decode( $node->getAttribute( 'data-mw' ) ?? '', true );
1200        $out = [];
1201
1202        foreach ( $dataMw['parts'] ?? [] as $part ) {
1203            if (
1204                !is_string( $part ) &&
1205                // 'href' will be unset if this is a parser function rather than a template
1206                isset( $part['template']['target']['href'] )
1207            ) {
1208                $parsoidHref = $part['template']['target']['href'];
1209                Assert::precondition( str_starts_with( $parsoidHref, './' ), 'href has valid format' );
1210                $out[] = rawurldecode( substr( $parsoidHref, 2 ) );
1211            } else {
1212                $out[] = null;
1213            }
1214        }
1215
1216        return $out;
1217    }
1218
1219    /**
1220     * Given a transclusion's first node (e.g. returned by CommentUtils::getTranscludedFromElement()),
1221     * return a range starting before the node and ending after the transclusion's last node.
1222     */
1223    private function getTransclusionRange( Element $startNode ): ImmutableRange {
1224        $endNode = $startNode;
1225        while (
1226            // Phan doesn't realize that the conditions on $nextSibling can terminate the loop
1227            // @phan-suppress-next-line PhanInfiniteLoop
1228            $endNode &&
1229            ( $nextSibling = $endNode->nextSibling ) &&
1230            $nextSibling instanceof Element &&
1231            $nextSibling->getAttribute( 'about' ) === $endNode->getAttribute( 'about' )
1232        ) {
1233            $endNode = $nextSibling;
1234        }
1235
1236        $range = new ImmutableRange(
1237            $startNode->parentNode,
1238            CommentUtils::childIndexOf( $startNode ),
1239            $endNode->parentNode,
1240            CommentUtils::childIndexOf( $endNode ) + 1
1241        );
1242
1243        return $range;
1244    }
1245
1246    /**
1247     * Truncate user generated parts of IDs so full ID always fits within a database field of length 255
1248     *
1249     * nb: Text should already have had spaces replaced with underscores by this point.
1250     *
1251     * @param string $text Text
1252     * @param bool $legacy Generate legacy ID, not needed in JS implementation
1253     * @return string Truncated text
1254     */
1255    private function truncateForId( string $text, bool $legacy = false ): string {
1256        $truncated = $this->language->truncateForDatabase( $text, 80, '' );
1257        if ( !$legacy ) {
1258            $truncated = trim( $truncated, '_' );
1259        }
1260        return $truncated;
1261    }
1262
1263    /**
1264     * Given a thread item, return an identifier for it that is unique within the page.
1265     *
1266     * @param ContentThreadItem $threadItem
1267     * @param ContentThreadItemSet $previousItems
1268     * @param bool $legacy Generate legacy ID, not needed in JS implementation
1269     */
1270    private function computeId(
1271        ContentThreadItem $threadItem, ContentThreadItemSet $previousItems, bool $legacy = false
1272    ): string {
1273        $id = null;
1274
1275        if ( $threadItem instanceof ContentHeadingItem && $threadItem->isPlaceholderHeading() ) {
1276            // The range points to the root note, using it like below results in silly values
1277            $id = 'h-';
1278        } elseif ( $threadItem instanceof ContentHeadingItem ) {
1279            $id = 'h-' . $this->truncateForId( $threadItem->getLinkableId(), $legacy );
1280        } elseif ( $threadItem instanceof ContentCommentItem ) {
1281            $id = 'c-' . $this->truncateForId( str_replace( ' ', '_', $threadItem->getAuthor() ), $legacy ) .
1282                '-' . $threadItem->getTimestampString();
1283        } else {
1284            throw new InvalidArgumentException( 'Unknown ThreadItem type' );
1285        }
1286
1287        // If there would be multiple comments with the same ID (i.e. the user left multiple comments
1288        // in one edit, or within a minute), add the parent ID to disambiguate them.
1289        $threadItemParent = $threadItem->getParent();
1290        if ( $threadItemParent instanceof ContentHeadingItem && !$threadItemParent->isPlaceholderHeading() ) {
1291            $id .= '-' . $this->truncateForId( $threadItemParent->getLinkableId(), $legacy );
1292        } elseif ( $threadItemParent instanceof ContentCommentItem ) {
1293            $id .= '-' . $this->truncateForId( str_replace( ' ', '_', $threadItemParent->getAuthor() ), $legacy ) .
1294                '-' . $threadItemParent->getTimestampString();
1295        }
1296
1297        if ( $threadItem instanceof ContentHeadingItem ) {
1298            // To avoid old threads re-appearing on popular pages when someone uses a vague title
1299            // (e.g. dozens of threads titled "question" on [[Wikipedia:Help desk]]: https://w.wiki/fbN),
1300            // include the oldest timestamp in the thread (i.e. date the thread was started) in the
1301            // heading ID.
1302            $oldestComment = $threadItem->getOldestReply();
1303            if ( $oldestComment ) {
1304                $id .= '-' . $oldestComment->getTimestampString();
1305            }
1306        }
1307
1308        if ( $previousItems->findCommentById( $id ) ) {
1309            // Well, that's tough
1310            if ( !$legacy ) {
1311                $threadItem->addWarning( 'Duplicate comment ID' );
1312            }
1313            // Finally, disambiguate by adding sequential numbers, to allow replying to both comments
1314            $number = 1;
1315            while ( $previousItems->findCommentById( "$id-$number" ) ) {
1316                $number++;
1317            }
1318            $id = "$id-$number";
1319        }
1320
1321        return $id;
1322    }
1323
1324    /**
1325     * Given a thread item, return an identifier for it that is consistent across all pages and
1326     * revisions where this comment might appear.
1327     *
1328     * Multiple comments on a page can have the same name; use ID to distinguish them.
1329     */
1330    private function computeName( ContentThreadItem $threadItem ): string {
1331        $name = null;
1332
1333        if ( $threadItem instanceof ContentHeadingItem ) {
1334            $name = 'h-';
1335            $mainComment = $threadItem->getOldestReply();
1336        } elseif ( $threadItem instanceof ContentCommentItem ) {
1337            $name = 'c-';
1338            $mainComment = $threadItem;
1339        } else {
1340            throw new InvalidArgumentException( 'Unknown ThreadItem type' );
1341        }
1342
1343        if ( $mainComment ) {
1344            $name .= $this->truncateForId( str_replace( ' ', '_', $mainComment->getAuthor() ) ) .
1345                '-' . $mainComment->getTimestampString();
1346        }
1347
1348        return $name;
1349    }
1350
1351    private function buildThreads( ContentThreadItemSet $result ): void {
1352        $lastHeading = null;
1353        $replies = [];
1354
1355        foreach ( $result->getThreadItems() as $threadItem ) {
1356            if ( count( $replies ) < $threadItem->getLevel() ) {
1357                // Someone skipped an indentation level (or several). Pretend that the previous reply
1358                // covers multiple indentation levels, so that following comments get connected to it.
1359                $threadItem->addWarning( 'Comment skips indentation level' );
1360                while ( count( $replies ) < $threadItem->getLevel() ) {
1361                    $replies[] = end( $replies );
1362                }
1363            }
1364
1365            if ( $threadItem instanceof ContentHeadingItem ) {
1366                // New root (thread)
1367                // Attach as a sub-thread to preceding higher-level heading.
1368                // Any replies will appear in the tree twice, under the main-thread and the sub-thread.
1369                $maybeParent = $lastHeading;
1370                while ( $maybeParent && $maybeParent->getHeadingLevel() >= $threadItem->getHeadingLevel() ) {
1371                    $maybeParent = $maybeParent->getParent();
1372                }
1373                if ( $maybeParent ) {
1374                    $threadItem->setParent( $maybeParent );
1375                    $maybeParent->addReply( $threadItem );
1376                }
1377                $lastHeading = $threadItem;
1378            } elseif ( isset( $replies[ $threadItem->getLevel() - 1 ] ) ) {
1379                // Add as a reply to the closest less-nested comment
1380                $threadItem->setParent( $replies[ $threadItem->getLevel() - 1 ] );
1381                $threadItem->getParent()->addReply( $threadItem );
1382            } else {
1383                $threadItem->addWarning( 'Comment could not be connected to a thread' );
1384            }
1385
1386            $replies[ $threadItem->getLevel() ] = $threadItem;
1387            // Cut off more deeply nested replies
1388            array_splice( $replies, $threadItem->getLevel() + 1 );
1389        }
1390    }
1391
1392    /**
1393     * Set the IDs and names used to refer to comments and headings.
1394     * This has to be a separate pass because we don't have the list of replies before
1395     * this point.
1396     */
1397    private function computeIdsAndNames( ContentThreadItemSet $result ): void {
1398        foreach ( $result->getThreadItems() as $threadItem ) {
1399            $name = $this->computeName( $threadItem );
1400            $threadItem->setName( $name );
1401
1402            $id = $this->computeId( $threadItem, $result );
1403            $threadItem->setId( $id );
1404            $legacyId = $this->computeId( $threadItem, $result, true );
1405            if ( $legacyId !== $id ) {
1406                $threadItem->setLegacyId( $legacyId );
1407            }
1408
1409            $result->updateIdAndNameMaps( $threadItem );
1410        }
1411    }
1412}