Debian Codegraph @

extensions/DiscussionTools/modules/Parser.js

raw symbols SCIP
1 'use strict';
2 /* global $:off */
3
4 const
5 utils = require( './utils.js' ),
6 charAt = require( 'mediawiki.String' ).charAt,
7 codePointLength = require( 'mediawiki.String' ).codePointLength,
8 trimByteLength = require( 'mediawiki.String' ).trimByteLength,
9 CommentItem = require( './CommentItem.js' ),
10 HeadingItem = require( './HeadingItem.js' ),
11 ThreadItem = require( './ThreadItem.js' ),
12 ThreadItemSet = require( './ThreadItemSet.js' ),
13 moment = require( './lib/moment-timezone/moment-timezone-with-data-1970-2030.js' );
14
15 /**
16 * Utilities for detecting and parsing components of discussion pages: signatures, timestamps,
17 * comments and threads.
18 *
19 * @class mw.dt.Parser
20 * @param {Array} data Language-specific data to be used for parsing
21 * @constructor
22 */
23 function Parser( data ) {
24 this.data = data;
25 }
26
27 /**
28 * How far backwards we look for a signature associated with a timestamp before giving up.
29 * Note that this is not a hard limit on the length of signatures we detect.
30 *
31 * @constant {number}
32 */
33 const SIGNATURE_SCAN_LIMIT = 100;
34
35 /**
36 * Parse a discussion page.
37 *
38 * @param {HTMLElement} rootNode Root node of content to parse
39 * @param {mw.Title} title Title of the page being parsed
40 * @chainable
41 * @return {Parser}
42 */
43 Parser.prototype.parse = function ( rootNode, title ) {
44 this.rootNode = rootNode;
45 this.title = title;
46
47 const result = this.buildThreadItems();
48 this.buildThreads( result );
49 this.computeIdsAndNames( result );
50
51 return result;
52 };
53
54 OO.initClass( Parser );
55
56 /**
57 * Get text of localisation messages in content language.
58 *
59 * @private
60 * @param {string} contLangVariant Content language variant
61 * @param {string[]} messages Message keys
62 * @return {string[]} Message values
63 */
64 Parser.prototype.getMessages = function ( contLangVariant, messages ) {
65 return messages.map( ( code ) => this.data.contLangMessages[ contLangVariant ][ code ] );
66 };
67
68 /**
69 * Get a regexp that matches timestamps generated using the given date format.
70 *
71 * This only supports format characters that are used by the default date format in any of
72 * MediaWiki's languages, namely: D, d, F, G, H, i, j, l, M, n, Y, xg, xkY (and escape characters),
73 * and only dates when MediaWiki existed, let's say 2000 onwards (Thai dates before 1941 are
74 * complicated).
75 *
76 * @private
77 * @param {string} contLangVariant Content language variant
78 * @param {string} format Date format, as used by MediaWiki
79 * @param {string} digitsRegexp Regular expression matching a single localised digit, e.g. `[0-9]`
80 * @param {Object.<string,string>} tzAbbrs Map of localised timezone abbreviations to IANA abbreviations
81 * for the local timezone, e.g. `{EDT: "EDT", EST: "EST"}`
82 * @return {string} Regular expression
83 */
84 Parser.prototype.getTimestampRegexp = function ( contLangVariant, format, digitsRegexp, tzAbbrs ) {
85 function regexpGroup( r ) {
86 return '(' + r + ')';
87 }
88
89 function regexpAlternateGroup( array ) {
90 return '(' + array.map( mw.util.escapeRegExp ).join( '|' ) + ')';
91 }
92
93 let s = '';
94 let raw = false;
95 // Adapted from Language::sprintfDate()
96 for ( let p = 0; p < format.length; p++ ) {
97 let num = false;
98 let code = format[ p ];
99 if ( code === 'x' && p < format.length - 1 ) {
100 code += format[ ++p ];
101 }
102 if ( code === 'xk' && p < format.length - 1 ) {
103 code += format[ ++p ];
104 }
105
106 switch ( code ) {
107 case 'xx':
108 s += 'x';
109 break;
110 case 'xg':
111 s += regexpAlternateGroup( this.getMessages( contLangVariant, [
112 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
113 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
114 'december-gen'
115 ] ) );
116 break;
117 case 'xn':
118 raw = true;
119 break;
120 case 'd':
121 num = '2';
122 break;
123 case 'D':
124 s += regexpAlternateGroup( this.getMessages( contLangVariant, [
125 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
126 ] ) );
127 break;
128 case 'j':
129 num = '1,2';
130 break;
131 case 'l':
132 s += regexpAlternateGroup( this.getMessages( contLangVariant, [
133 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
134 'friday', 'saturday'
135 ] ) );
136 break;
137 case 'F':
138 s += regexpAlternateGroup( this.getMessages( contLangVariant, [
139 'january', 'february', 'march', 'april', 'may_long', 'june',
140 'july', 'august', 'september', 'october', 'november',
141 'december'
142 ] ) );
143 break;
144 case 'M':
145 s += regexpAlternateGroup( this.getMessages( contLangVariant, [
146 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
147 'sep', 'oct', 'nov', 'dec'
148 ] ) );
149 break;
150 case 'm':
151 num = '2';
152 break;
153 case 'n':
154 num = '1,2';
155 break;
156 case 'Y':
157 num = '4';
158 break;
159 case 'xkY':
160 num = '4';
161 break;
162 case 'G':
163 num = '1,2';
164 break;
165 case 'H':
166 num = '2';
167 break;
168 case 'i':
169 num = '2';
170 break;
171 case 's':
172 num = '2';
173 break;
174 case '\\':
175 // Backslash escaping
176 if ( p < format.length - 1 ) {
177 s += mw.util.escapeRegExp( format[ ++p ] );
178 } else {
179 s += mw.util.escapeRegExp( '\\' );
180 }
181 break;
182 case '"':
183 // Quoted literal
184 if ( p < format.length - 1 ) {
185 const endQuote = format.indexOf( '"', p + 1 );
186 if ( endQuote === -1 ) {
187 // No terminating quote, assume literal "
188 s += '"';
189 } else {
190 s += mw.util.escapeRegExp( format.slice( p + 1, endQuote ) );
191 p = endQuote;
192 }
193 } else {
194 // Quote at end of string, assume literal "
195 s += '"';
196 }
197 break;
198 default: {
199 // Copy whole characters together, instead of single UTF-16 surrogates
200 const char = charAt( format, p );
201 s += mw.util.escapeRegExp( char );
202 p += char.length - 1;
203 }
204 }
205 if ( num !== false ) {
206 if ( raw ) {
207 s += regexpGroup( '[0-9]{' + num + '}' );
208 raw = false;
209 } else {
210 s += regexpGroup( digitsRegexp + '{' + num + '}' );
211 }
212 }
213 // Ignore some invisible Unicode characters that often sneak into copy-pasted timestamps (T308448)
214 s += '[\\u200E\\u200F]?';
215 }
216
217 const tzRegexp = regexpAlternateGroup( Object.keys( tzAbbrs ) );
218 // Hard-coded parentheses and space like in Parser::pstPass2
219 // Ignore some invisible Unicode characters that often sneak into copy-pasted timestamps (T245784)
220 const regexp = s + ' [\\u200E\\u200F]?\\(' + tzRegexp + '\\)';
221
222 return regexp;
223 };
224
225 /**
226 * Get a function that parses timestamps generated using the given date format, based on the result
227 * of matching the regexp returned by #getTimestampRegexp.
228 *
229 * @private
230 * @param {string} contLangVariant Content language variant
231 * @param {string} format Date format, as used by MediaWiki
232 * @param {string[]|null} digits Localised digits from 0 to 9, e.g. `[ '0', '1', ..., '9' ]`
233 * @param {string} localTimezone Local timezone IANA name, e.g. `America/New_York`
234 * @param {Object.<string,string>} tzAbbrs Map of localised timezone abbreviations to IANA abbreviations
235 * for the local timezone, e.g. `{EDT: "EDT", EST: "EST"}`
236 * @return {TimestampParser} Timestamp parser function
237 */
238 Parser.prototype.getTimestampParser = function ( contLangVariant, format, digits, localTimezone, tzAbbrs ) {
239 const matchingGroups = [];
240 for ( let p = 0; p < format.length; p++ ) {
241 let code = format[ p ];
242 if ( code === 'x' && p < format.length - 1 ) {
243 code += format[ ++p ];
244 }
245 if ( code === 'xk' && p < format.length - 1 ) {
246 code += format[ ++p ];
247 }
248
249 switch ( code ) {
250 case 'xx':
251 case 'xn':
252 break;
253 case 'xg':
254 case 'd':
255 case 'j':
256 case 'D':
257 case 'l':
258 case 'F':
259 case 'M':
260 case 'm':
261 case 'n':
262 case 'Y':
263 case 'xkY':
264 case 'G':
265 case 'H':
266 case 'i':
267 case 's':
268 matchingGroups.push( code );
269 break;
270 case '\\':
271 // Backslash escaping
272 if ( p < format.length - 1 ) {
273 ++p;
274 }
275 break;
276 case '"':
277 // Quoted literal
278 if ( p < format.length - 1 ) {
279 const endQuote = format.indexOf( '"', p + 1 );
280 if ( endQuote !== -1 ) {
281 p = endQuote;
282 }
283 }
284 break;
285 default:
286 break;
287 }
288 }
289
290 /**
291 * @param {string} text
292 * @return {number}
293 */
294 function untransformDigits( text ) {
295 return Number( digits ? text.replace(
296 // digits list comes from site config so is trusted
297 new RegExp( '[' + digits.join( '' ) + ']', 'g' ),
298 ( m ) => digits.indexOf( m )
299 ) : text );
300 }
301
302 /**
303 * @typedef {function(Array):moment} TimestampParser
304 */
305
306 /**
307 * Timestamp parser
308 *
309 * @param {Array} match RegExp match data
310 * @return {Object} Result, an object with the following keys (or null if the date is invalid):
311 * - {moment} date Moment date object
312 * - {string|null} warning Warning message if the input wasn't correctly formed
313 */
314 return ( match ) => {
315 let
316 year = 0,
317 monthIdx = 0,
318 day = 0,
319 hour = 0,
320 minute = 0;
321
322 for ( let i = 0; i < matchingGroups.length; i++ ) {
323 const code2 = matchingGroups[ i ];
324 const text = match[ i + 1 ];
325
326 switch ( code2 ) {
327 case 'xg':
328 monthIdx = this.getMessages( contLangVariant, [
329 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
330 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
331 'december-gen'
332 ] ).indexOf( text );
333 break;
334 case 'd':
335 case 'j':
336 day = untransformDigits( text );
337 break;
338 case 'D':
339 case 'l':
340 // Day of the week - unused
341 break;
342 case 'F':
343 monthIdx = this.getMessages( contLangVariant, [
344 'january', 'february', 'march', 'april', 'may_long', 'june',
345 'july', 'august', 'september', 'october', 'november',
346 'december'
347 ] ).indexOf( text );
348 break;
349 case 'M':
350 monthIdx = this.getMessages( contLangVariant, [
351 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
352 'sep', 'oct', 'nov', 'dec'
353 ] ).indexOf( text );
354 break;
355 case 'm':
356 case 'n':
357 monthIdx = untransformDigits( text ) - 1;
358 break;
359 case 'Y':
360 year = untransformDigits( text );
361 break;
362 case 'xkY':
363 // Thai year
364 year = untransformDigits( text ) - 543;
365 break;
366 case 'G':
367 case 'H':
368 hour = untransformDigits( text );
369 break;
370 case 'i':
371 minute = untransformDigits( text );
372 break;
373 case 's':
374 // Seconds - unused, because most timestamp formats omit them
375 break;
376 default:
377 throw new Error( 'Not implemented' );
378 }
379 }
380 // The last matching group is the timezone abbreviation
381 const tzAbbr = tzAbbrs[ match[ match.length - 1 ] ];
382
383 // Most of the time, the timezone abbreviation is not necessary to parse the date, since we
384 // can assume all times are in the wiki's local timezone.
385 let date = moment.tz( [ year, monthIdx, day, hour, minute ], localTimezone );
386
387 // But during the "fall back" at the end of DST, some times will happen twice. Per the docs,
388 // "Moment Timezone handles this by always using the earlier instance of a duplicated hour."
389 // https://momentjs.com/timezone/docs/#/using-timezones/parsing-ambiguous-inputs/
390
391 // Since the timezone abbreviation disambiguates the DST/non-DST times, we can detect when
392 // that behavior was incorrect...
393 let dateWarning = null;
394 if ( date.zoneAbbr() !== tzAbbr ) {
395 // ...and force the correct parsing. I can't find proper documentation for this feature,
396 // but this pull request explains it: https://github.com/moment/moment-timezone/pull/101
397 moment.tz.moveAmbiguousForward = true;
398 date = moment.tz( [ year, monthIdx, day, hour, minute ], localTimezone );
399 moment.tz.moveAmbiguousForward = false;
400 if ( date.zoneAbbr() !== tzAbbr ) {
401 // This should not be possible for "genuine" timestamps generated by MediaWiki.
402 // But bots and humans get it wrong when marking up unsigned comments…
403 // https://pl.wikipedia.org/w/index.php?title=Wikipedia:Kawiarenka/Artykuły&diff=prev&oldid=54772606
404 dateWarning = 'Timestamp has timezone abbreviation for the wrong time';
405 } else {
406 dateWarning = 'Ambiguous time at DST switchover was parsed';
407 }
408 }
409
410 // We require the date to be compatible with our libraries, for example zero or negative years (T352455)
411 // In PHP we need to check with MWTimestamp.
412 // In JS we need to check with Moment.
413 if ( !date.isValid() ) {
414 return null;
415 }
416
417 return {
418 date: date,
419 warning: dateWarning
420 };
421 };
422 };
423
424 /**
425 * Get a regexp that matches timestamps in the local date format, for each language variant.
426 *
427 * This calls #getTimestampRegexp with predefined data for the current wiki.
428 *
429 * @private
430 * @return {string[]} Regular expressions
431 */
432 Parser.prototype.getLocalTimestampRegexps = function () {
433 return Object.keys( this.data.dateFormat ).map( ( contLangVariant ) => this.getTimestampRegexp(
434 contLangVariant,
435 this.data.dateFormat[ contLangVariant ],
436 '[' + this.data.digits[ contLangVariant ].join( '' ) + ']',
437 this.data.timezones[ contLangVariant ]
438 ) );
439 };
440
441 /**
442 * Get a function that parses timestamps in the local date format, for each language variant,
443 * based on the result of matching the regexps returned by #getLocalTimestampRegexps.
444 *
445 * This calls #getTimestampParser with predefined data for the current wiki.
446 *
447 * @private
448 * @return {TimestampParser[]} Timestamp parser functions
449 */
450 Parser.prototype.getLocalTimestampParsers = function () {
451 return Object.keys( this.data.dateFormat ).map( ( contLangVariant ) => this.getTimestampParser(
452 contLangVariant,
453 this.data.dateFormat[ contLangVariant ],
454 this.data.digits[ contLangVariant ],
455 this.data.localTimezone,
456 this.data.timezones[ contLangVariant ]
457 ) );
458 };
459
460 /**
461 * Callback for document.createTreeWalker that will skip over nodes where we don't want to detect
462 * comments (or section headings).
463 *
464 * @param {Node} node
465 * @return {number} Appropriate NodeFilter constant
466 */
467 function acceptOnlyNodesAllowingComments( node ) {
468 if ( node instanceof HTMLElement ) {
469 const tagName = node.tagName.toLowerCase();
470 // The table of contents has a heading that gets erroneously detected as a section
471 if ( node.id === 'toc' ) {
472 return NodeFilter.FILTER_REJECT;
473 }
474 // Don't detect comments within quotes (T275881)
475 if (
476 tagName === 'blockquote' ||
477 tagName === 'cite' ||
478 tagName === 'q'
479 ) {
480 return NodeFilter.FILTER_REJECT;
481 }
482 // Don't attempt to parse blocks marked 'mw-notalk'
483 if ( node.classList.contains( 'mw-notalk' ) ) {
484 return NodeFilter.FILTER_REJECT;
485 }
486 // Don't detect comments within references. We can't add replies to them without bungling up
487 // the structure in some cases (T301213), and you're not supposed to do that anyway…
488 if (
489 // <ol class="references"> is the only reliably consistent thing between the two parsers
490 tagName === 'ol' &&
491 node.classList.contains( 'references' )
492 ) {
493 return NodeFilter.FILTER_REJECT;
494 }
495 }
496 const parentNode = node.parentNode;
497 // Don't detect comments within headings (but don't reject the headings themselves)
498 if ( parentNode instanceof HTMLElement && parentNode.tagName.match( /^h([1-6])$/i ) ) {
499 return NodeFilter.FILTER_REJECT;
500 }
501 return NodeFilter.FILTER_ACCEPT;
502 }
503
504 /**
505 * Find a timestamp in a given text node
506 *
507 * @private
508 * @param {Text} node Text node
509 * @param {string[]} timestampRegexps Timestamp regexps
510 * @return {Object|null} Object with the following keys:
511 * - {number} offset Length of extra text preceding the node that was used for matching
512 * - {number} parserIndex Which of the regexps matched
513 * - {Array} matchData Regexp match data, which specifies the location of the match,
514 * and which can be parsed using #getLocalTimestampParsers
515 * - {Object} range Range-like object covering the timestamp
516 */
517 Parser.prototype.findTimestamp = function ( node, timestampRegexps ) {
518 let nodeText = '';
519 let offset = 0;
520 // Searched nodes (reverse order)
521 const nodes = [];
522
523 while ( node ) {
524 nodeText = node.nodeValue + nodeText;
525 nodes.push( node );
526
527 // In Parsoid HTML, entities are represented as a 'mw:Entity' node, rather than normal HTML
528 // entities. On Arabic Wikipedia, the "UTC" timezone name contains some non-breaking spaces,
529 // which apparently are often turned into &nbsp; entities by buggy editing tools. To handle
530 // this, we must piece together the text, so that our regexp can match those timestamps.
531 if (
532 node.previousSibling &&
533 node.previousSibling.nodeType === Node.ELEMENT_NODE &&
534 node.previousSibling.getAttribute( 'typeof' ) === 'mw:Entity'
535 ) {
536 nodeText = node.previousSibling.firstChild.nodeValue + nodeText;
537 offset += node.previousSibling.firstChild.nodeValue.length;
538 nodes.push( node.previousSibling.firstChild );
539
540 // If the entity is followed by more text, do this again
541 if (
542 node.previousSibling.previousSibling &&
543 node.previousSibling.previousSibling.nodeType === Node.TEXT_NODE
544 ) {
545 offset += node.previousSibling.previousSibling.nodeValue.length;
546 node = node.previousSibling.previousSibling;
547 } else {
548 node = null;
549 }
550 } else {
551 node = null;
552 }
553 }
554
555 for ( let i = 0; i < timestampRegexps.length; i++ ) {
556 // Technically, there could be multiple matches in a single text node. However, the ultimate
557 // point of this is to find the signatures which precede the timestamps, and any later
558 // timestamps in the text node can't be directly preceded by a signature (as we require them to
559 // have links), so we only concern ourselves with the first match.
560 const matchData = nodeText.match( timestampRegexps[ i ] );
561 if ( matchData ) {
562 const timestampLength = matchData[ 0 ].length;
563 // Bytes at the end of the last node which aren't part of the match
564 const tailLength = nodeText.length - timestampLength - matchData.index;
565 // We are moving right to left, but we start to the right of the end of
566 // the timestamp if there is trailing garbage, so that is a negative offset.
567 let count = -tailLength;
568 const endContainer = nodes[ 0 ];
569 const endOffset = endContainer.nodeValue.length - tailLength;
570
571 let startContainer, startOffset;
572 nodes.some( ( n ) => {
573 count += n.nodeValue.length;
574 // If we have counted to beyond the start of the timestamp, we are in the
575 // start node of the timestamp
576 if ( count >= timestampLength ) {
577 startContainer = n;
578 // Offset is how much we overshot the start by
579 startOffset = count - timestampLength;
580 return true;
581 }
582 return false;
583 } );
584
585 const range = {
586 startContainer: startContainer,
587 startOffset: startOffset,
588 endContainer: endContainer,
589 endOffset: endOffset
590 };
591
592 return {
593 matchData: matchData,
594 // Bytes at the start of the first node which aren't part of the match
595 // TODO: Remove this and use 'range' instead
596 offset: offset,
597 range: range,
598 parserIndex: i
599 };
600 }
601 }
602 return null;
603 };
604
605 /**
606 * Given a link node (`<a>`), if it's a link to a user-related page, return their username.
607 *
608 * @param {HTMLElement} link
609 * @return {Object|null} Object, or null:
610 * - {string} username Username
611 * - {string|null} displayName Display name (link text if link target was in the user namespace)
612 */
613 Parser.prototype.getUsernameFromLink = function ( link ) {
614 let title;
615 // Selflink: use title of current page
616 if ( link.classList.contains( 'mw-selflink' ) ) {
617 title = this.title;
618 } else {
619 const titleString = utils.getTitleFromUrl( link.href ) || '';
620 // Performance optimization, skip strings that obviously don't contain a namespace
621 if ( !titleString || titleString.indexOf( ':' ) === -1 ) {
622 return null;
623 }
624 title = mw.Title.newFromText( titleString );
625 }
626 if ( !title ) {
627 return null;
628 }
629
630 let username;
631 let displayName = null;
632 const namespaceId = title.getNamespaceId();
633 const mainText = title.getMainText();
634 const namespaceIds = mw.config.get( 'wgNamespaceIds' );
635
636 if (
637 namespaceId === namespaceIds.user ||
638 namespaceId === namespaceIds.user_talk
639 ) {
640 username = mainText;
641 if ( username.indexOf( '/' ) !== -1 ) {
642 return null;
643 }
644 if ( namespaceId === namespaceIds.user ) {
645 // Use regex trim for consistency with PHP implementation
646 const text = link.textContent.replace( /^[\s]+/, '' ).replace( /[\s]+$/, '' );
647 // Record the display name if it has been customised beyond changing case
648 if ( text && text.toLowerCase() !== username.toLowerCase() ) {
649 displayName = text;
650 }
651 }
652 } else if ( namespaceId === namespaceIds.special ) {
653 const parts = mainText.split( '/' );
654 if ( parts.length === 2 && parts[ 0 ] === this.data.specialContributionsName ) {
655 // Normalize the username: users may link to their contributions with an unnormalized name
656 const userpage = mw.Title.makeTitle( namespaceIds.user, parts[ 1 ] );
657 if ( !userpage ) {
658 return null;
659 }
660 username = userpage.getMainText();
661 }
662 }
663 if ( !username ) {
664 return null;
665 }
666 if ( mw.util.isIPv6Address( username ) ) {
667 // Bot-generated links "Preceding unsigned comment added by" have non-standard case
668 username = username.toUpperCase();
669 }
670 return {
671 username: username,
672 displayName: displayName
673 };
674 };
675
676 /**
677 * Find a user signature preceding a timestamp.
678 *
679 * The signature includes the timestamp node.
680 *
681 * A signature must contain at least one link to the user's userpage, discussion page or
682 * contributions (and may contain other links). The link may be nested in other elements.
683 *
684 * @private
685 * @param {Text} timestampNode Text node
686 * @param {Node} [until] Node to stop searching at
687 * @return {Object} Result, an object with the following keys:
688 * - {Node[]} nodes Sibling nodes comprising the signature, in reverse order (with
689 * `timestampNode` or its parent node as the first element)
690 * - {string|null} username Username, null for unsigned comments
691 */
692 Parser.prototype.findSignature = function ( timestampNode, until ) {
693 let sigUsername = null;
694 let sigDisplayName = null;
695 let length = 0;
696 let lastLinkNode = timestampNode;
697
698 utils.linearWalkBackwards(
699 timestampNode,
700 ( event, node ) => {
701 if ( event === 'enter' && node === until ) {
702 return true;
703 }
704 if ( length >= SIGNATURE_SCAN_LIMIT ) {
705 return true;
706 }
707 if ( utils.isBlockElement( node ) ) {
708 // Don't allow reaching into preceding paragraphs
709 return true;
710 }
711
712 if ( event === 'leave' && node !== timestampNode ) {
713 length += node.nodeType === Node.TEXT_NODE ?
714 codePointLength( utils.htmlTrim( node.textContent ) ) : 0;
715 }
716
717 // Find the closest link before timestamp that links to the user's user page.
718 //
719 // Support timestamps being linked to the diff introducing the comment:
720 // if the timestamp node is the only child of a link node, use the link node instead
721 //
722 // Handle links nested in formatting elements.
723 if ( event === 'leave' && node.nodeType === Node.ELEMENT_NODE && node.tagName.toLowerCase() === 'a' ) {
724 if ( !node.classList.contains( 'ext-discussiontools-init-timestamplink' ) ) {
725 const user = this.getUsernameFromLink( node );
726 if ( user ) {
727 // Accept the first link to the user namespace, then only accept links to that user
728 if ( sigUsername === null ) {
729 sigUsername = user.username;
730 }
731 if ( user.username === sigUsername ) {
732 lastLinkNode = node;
733 if ( user.displayName ) {
734 sigDisplayName = user.displayName;
735 }
736 }
737 }
738 // Keep looking if a node with links wasn't a link to a user page
739 // "Doc James (talk · contribs · email)"
740 }
741 }
742 }
743 );
744
745 const range = {
746 startContainer: lastLinkNode.parentNode,
747 startOffset: utils.childIndexOf( lastLinkNode ),
748 endContainer: timestampNode.parentNode,
749 endOffset: utils.childIndexOf( timestampNode ) + 1
750 };
751 const nativeRange = ThreadItem.prototype.getRange.call( { range: range } );
752
753 // Expand the range so that it covers sibling nodes.
754 // This will include any wrapping formatting elements as part of the signature.
755 //
756 // Helpful accidental feature: users whose signature is not detected in full (due to
757 // text formatting) can just wrap it in a <span> to fix that.
758 // "Ten Pound Hammer • (What did I screw up now?)"
759 // "« Saper // dyskusja »"
760 //
761 // TODO Not sure if this is actually good, might be better to just use the range...
762 const sigNodes = utils.getCoveredSiblings( nativeRange ).reverse();
763
764 return {
765 nodes: sigNodes,
766 username: sigUsername,
767 displayName: sigDisplayName
768 };
769 };
770
771 /**
772 * Return the next leaf node in the tree order that is likely a part of a discussion comment,
773 * rather than some boring "separator" element.
774 *
775 * Currently, this can return a Text node with content other than whitespace, or an Element node
776 * that is a "void element" or "text element", except some special cases that we treat as comment
777 * separators (isCommentSeparator()).
778 *
779 * @private
780 * @param {Node|null} node Node after which to start searching
781 * (if null, start at the beginning of the document).
782 * @return {Node}
783 */
784 Parser.prototype.nextInterestingLeafNode = function ( node ) {
785 const rootNode = this.rootNode;
786
787 const treeWalker = rootNode.ownerDocument.createTreeWalker(
788 rootNode,
789 // eslint-disable-next-line no-bitwise
790 NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
791 ( n ) => {
792 // Skip past the starting node and its descendants
793 if ( n === node || n.parentNode === node ) {
794 return NodeFilter.FILTER_REJECT;
795 }
796 // Ignore some elements usually used as separators or headers (and their descendants)
797 if ( utils.isCommentSeparator( n ) ) {
798 return NodeFilter.FILTER_REJECT;
799 }
800 // Ignore nodes with no rendering that mess up our indentation detection
801 if ( utils.isRenderingTransparentNode( n ) ) {
802 return NodeFilter.FILTER_REJECT;
803 }
804 if ( utils.isCommentContent( n ) ) {
805 return NodeFilter.FILTER_ACCEPT;
806 }
807 return NodeFilter.FILTER_SKIP;
808 },
809 false
810 );
811 if ( node ) {
812 treeWalker.currentNode = node;
813 }
814 treeWalker.nextNode();
815 if ( !treeWalker.currentNode ) {
816 throw new Error( 'nextInterestingLeafNode not found' );
817 }
818 return treeWalker.currentNode;
819 };
820
821 /**
822 * @param {Node[]} sigNodes
823 * @param {Object} match
824 * @param {Text} node
825 * @return {Object} Range-like object
826 */
827 function adjustSigRange( sigNodes, match, node ) {
828 const firstSigNode = sigNodes[ sigNodes.length - 1 ];
829 const lastSigNode = sigNodes[ 0 ];
830
831 // TODO Document why this needs to be so complicated
832 const lastSigNodeOffset = lastSigNode === node ?
833 match.matchData.index + match.matchData[ 0 ].length - match.offset :
834 utils.childIndexOf( lastSigNode ) + 1;
835 const sigRange = {
836 startContainer: firstSigNode.parentNode,
837 startOffset: utils.childIndexOf( firstSigNode ),
838 endContainer: lastSigNode === node ? node : lastSigNode.parentNode,
839 endOffset: lastSigNodeOffset
840 };
841 return sigRange;
842 }
843
844 /**
845 * @return {ThreadItemSet}
846 */
847 Parser.prototype.buildThreadItems = function () {
848 const result = new ThreadItemSet();
849
850 const
851 dfParsers = this.getLocalTimestampParsers(),
852 timestampRegexps = this.getLocalTimestampRegexps();
853
854 const treeWalker = this.rootNode.ownerDocument.createTreeWalker(
855 this.rootNode,
856 // eslint-disable-next-line no-bitwise
857 NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
858 acceptOnlyNodesAllowingComments,
859 false
860 );
861
862 let curComment, range;
863 let curCommentEnd = null;
864
865 let node;
866 while ( ( node = treeWalker.nextNode() ) ) {
867 let match;
868 if ( node.tagName && ( match = node.tagName.match( /^h([1-6])$/i ) ) ) {
869 const headingNode = utils.getHeadlineNode( node );
870 range = {
871 startContainer: headingNode,
872 startOffset: 0,
873 endContainer: headingNode,
874 endOffset: headingNode.childNodes.length
875 };
876 curComment = new HeadingItem( range, +match[ 1 ] );
877 curComment.rootNode = this.rootNode;
878 result.addThreadItem( curComment );
879 curCommentEnd = node;
880 } else if ( node.nodeType === Node.TEXT_NODE && ( match = this.findTimestamp( node, timestampRegexps ) ) ) {
881 const warnings = [];
882 const foundSignature = this.findSignature( node, curCommentEnd );
883 const author = foundSignature.username;
884
885 if ( !author ) {
886 // Ignore timestamps for which we couldn't find a signature. It's probably not a real
887 // comment, but just a false match due to a copypasted timestamp.
888 continue;
889 }
890
891 const sigRanges = [];
892 const timestampRanges = [];
893
894 sigRanges.push( adjustSigRange( foundSignature.nodes, match, node ) );
895 timestampRanges.push( match.range );
896
897 // Everything from the last comment up to here is the next comment
898 const startNode = this.nextInterestingLeafNode( curCommentEnd );
899 let endNode = foundSignature.nodes[ 0 ];
900
901 // Skip to the end of the "paragraph". This only looks at tag names and can be fooled by CSS, but
902 // avoiding that would be more difficult and slower.
903 //
904 // If this skips over another potential signature, also skip it in the main TreeWalker loop, to
905 // avoid generating multiple comments when there is more than one signature on a single "line".
906 // Often this is done when someone edits their comment later and wants to add a note about that.
907 // (Or when another person corrects a typo, or strikes out a comment, etc.) Multiple comments
908 // within one paragraph/list-item result in a confusing double "Reply" button, and we also have
909 // no way to indicate which one you're replying to (this might matter in the future for
910 // notifications or something).
911 utils.linearWalk(
912 endNode,
913 // eslint-disable-next-line no-loop-func
914 ( event, n ) => {
915 let match2, foundSignature2;
916 if ( utils.isBlockElement( n ) || utils.isCommentSeparator( n ) ) {
917 // Stop when entering or leaving a block node
918 return true;
919 }
920 if (
921 event === 'leave' &&
922 n.nodeType === Node.TEXT_NODE && n !== node &&
923 ( match2 = this.findTimestamp( n, timestampRegexps ) )
924 ) {
925 // If this skips over another potential signature, also skip it in the main TreeWalker loop
926 treeWalker.currentNode = n;
927 // …and add it as another signature to this comment (regardless of the author and timestamp)
928 foundSignature2 = this.findSignature( n, node );
929 if ( foundSignature2.username ) {
930 sigRanges.push( adjustSigRange( foundSignature2.nodes, match2, n ) );
931 timestampRanges.push( match2.range );
932 }
933 }
934 if ( event === 'leave' ) {
935 // Take the last complete node which we skipped past
936 endNode = n;
937 }
938 }
939 );
940
941 const length = endNode.nodeType === Node.TEXT_NODE ?
942 endNode.textContent.replace( /[\t\n\f\r ]+$/, '' ).length :
943 endNode.childNodes.length;
944 range = {
945 startContainer: startNode.parentNode,
946 startOffset: utils.childIndexOf( startNode ),
947 endContainer: endNode,
948 endOffset: length
949 };
950
951 const startLevel = utils.getIndentLevel( startNode, this.rootNode ) + 1;
952 const endLevel = utils.getIndentLevel( node, this.rootNode ) + 1;
953 if ( startLevel !== endLevel ) {
954 warnings.push( 'Comment starts and ends with different indentation' );
955 }
956 // Should this use the indent level of `startNode` or `node`?
957 const level = Math.min( startLevel, endLevel );
958
959 const parserResult = dfParsers[ match.parserIndex ]( match.matchData );
960 if ( !parserResult ) {
961 continue;
962 }
963 const dateTime = parserResult.date;
964 if ( parserResult.warning ) {
965 warnings.push( parserResult.warning );
966 }
967
968 curComment = new CommentItem(
969 level,
970 range,
971 sigRanges,
972 timestampRanges,
973 dateTime,
974 author,
975 foundSignature.displayName
976 );
977 curComment.rootNode = this.rootNode;
978 if ( warnings.length ) {
979 curComment.warnings = warnings;
980 }
981 if ( result.isEmpty() ) {
982 // Add a fake placeholder heading if there are any comments in the 0th section
983 // (before the first real heading)
984 range = {
985 startContainer: this.rootNode,
986 startOffset: 0,
987 endContainer: this.rootNode,
988 endOffset: 0
989 };
990 const fakeHeading = new HeadingItem( range, null );
991 fakeHeading.rootNode = this.rootNode;
992 result.addThreadItem( fakeHeading );
993 }
994 result.addThreadItem( curComment );
995 curCommentEnd = curComment.range.endContainer;
996 }
997 }
998
999 return result;
1000 };
1001
1002 /**
1003 * Truncate user generated parts of IDs so full ID always fits within a database field of length 255
1004 *
1005 * nb: Text should already have had spaces replaced with underscores by this point.
1006 *
1007 * @param {string} text Text
1008 * @return {string} Truncated text
1009 */
1010 Parser.prototype.truncateForId = function ( text ) {
1011 return trimByteLength( '', text, 80 ).newVal.replace( /^_+|_+$/g, '' );
1012 };
1013
1014 /**
1015 * Given a thread item, return an identifier for it that is unique within the page.
1016 *
1017 * @param {ThreadItem} threadItem
1018 * @param {ThreadItemSet} previousItems
1019 * @return {string}
1020 */
1021 Parser.prototype.computeId = function ( threadItem, previousItems ) {
1022 let id, headline;
1023
1024 if ( threadItem instanceof HeadingItem && threadItem.placeholderHeading ) {
1025 // The range points to the root note, using it like below results in silly values
1026 id = 'h-';
1027 } else if ( threadItem instanceof HeadingItem ) {
1028 headline = threadItem.range.startContainer;
1029 id = 'h-' + this.truncateForId( headline.getAttribute( 'id' ) || '' );
1030 } else if ( threadItem instanceof CommentItem ) {
1031 id = 'c-' + this.truncateForId( threadItem.author || '' ).replace( / /g, '_' ) + '-' + threadItem.getTimestampString();
1032 } else {
1033 throw new Error( 'Unknown ThreadItem type' );
1034 }
1035
1036 // If there would be multiple comments with the same ID (i.e. the user left multiple comments
1037 // in one edit, or within a minute), append sequential numbers
1038 const threadItemParent = threadItem.parent;
1039 if ( threadItemParent instanceof HeadingItem && !threadItemParent.placeholderHeading ) {
1040 headline = threadItemParent.range.startContainer;
1041 id += '-' + this.truncateForId( headline.getAttribute( 'id' ) || '' );
1042 } else if ( threadItemParent instanceof CommentItem ) {
1043 id += '-' + this.truncateForId( threadItemParent.author || '' ).replace( / /g, '_' ) + '-' + threadItemParent.getTimestampString();
1044 }
1045
1046 if ( threadItem instanceof HeadingItem ) {
1047 // To avoid old threads re-appearing on popular pages when someone uses a vague title
1048 // (e.g. dozens of threads titled "question" on [[Wikipedia:Help desk]]: https://w.wiki/fbN),
1049 // include the oldest timestamp in the thread (i.e. date the thread was started) in the
1050 // heading ID.
1051 const oldestComment = threadItem.getOldestReply();
1052 if ( oldestComment ) {
1053 id += '-' + oldestComment.getTimestampString();
1054 }
1055 }
1056
1057 if ( previousItems.findCommentById( id ) ) {
1058 // Well, that's tough
1059 threadItem.warnings.push( 'Duplicate comment ID' );
1060 // Finally, disambiguate by adding sequential numbers, to allow replying to both comments
1061 let number = 1;
1062 while ( previousItems.findCommentById( id + '-' + number ) ) {
1063 number++;
1064 }
1065 id = id + '-' + number;
1066 }
1067
1068 return id;
1069 };
1070
1071 /**
1072 * Given a thread item, return an identifier for it that is consistent across all pages and
1073 * revisions where this comment might appear.
1074 *
1075 * Multiple comments on a page can have the same name; use ID to distinguish them.
1076 *
1077 * @param {ThreadItem} threadItem
1078 * @return {string}
1079 */
1080 Parser.prototype.computeName = function ( threadItem ) {
1081 let name, mainComment;
1082
1083 if ( threadItem instanceof HeadingItem ) {
1084 name = 'h-';
1085 mainComment = threadItem.getOldestReply();
1086 } else if ( threadItem instanceof CommentItem ) {
1087 name = 'c-';
1088 mainComment = threadItem;
1089 } else {
1090 throw new Error( 'Unknown ThreadItem type' );
1091 }
1092
1093 if ( mainComment ) {
1094 name += this.truncateForId( mainComment.author || '' ).replace( / /g, '_' ) +
1095 '-' + mainComment.getTimestampString();
1096 }
1097
1098 return name;
1099 };
1100
1101 /**
1102 * @param {ThreadItemSet} result
1103 */
1104 Parser.prototype.buildThreads = function ( result ) {
1105 let lastHeading = null;
1106 const replies = [];
1107
1108 for ( let i = 0; i < result.threadItems.length; i++ ) {
1109 const threadItem = result.threadItems[ i ];
1110
1111 if ( replies.length < threadItem.level ) {
1112 // Someone skipped an indentation level (or several). Pretend that the previous reply
1113 // covers multiple indentation levels, so that following comments get connected to it.
1114 threadItem.warnings.push( 'Comment skips indentation level' );
1115 while ( replies.length < threadItem.level ) {
1116 replies[ replies.length ] = replies[ replies.length - 1 ];
1117 }
1118 }
1119
1120 if ( threadItem instanceof HeadingItem ) {
1121 // New root (thread)
1122 // Attach as a sub-thread to preceding higher-level heading.
1123 // Any replies will appear in the tree twice, under the main-thread and the sub-thread.
1124 let maybeParent = lastHeading;
1125 while ( maybeParent && maybeParent.headingLevel >= threadItem.headingLevel ) {
1126 maybeParent = maybeParent.parent;
1127 }
1128 if ( maybeParent ) {
1129 threadItem.parent = maybeParent;
1130 maybeParent.replies.push( threadItem );
1131 }
1132 lastHeading = threadItem;
1133 } else if ( replies[ threadItem.level - 1 ] ) {
1134 // Add as a reply to the closest less-nested comment
1135 threadItem.parent = replies[ threadItem.level - 1 ];
1136 threadItem.parent.replies.push( threadItem );
1137 } else {
1138 threadItem.warnings.push( 'Comment could not be connected to a thread' );
1139 }
1140
1141 replies[ threadItem.level ] = threadItem;
1142 // Cut off more deeply nested replies
1143 replies.length = threadItem.level + 1;
1144 }
1145 };
1146
1147 /**
1148 * Set the IDs and names used to refer to comments and headings.
1149 * This has to be a separate pass because we don't have the list of replies before
1150 * this point.
1151 *
1152 * @param {ThreadItemSet} result
1153 */
1154 Parser.prototype.computeIdsAndNames = function ( result ) {
1155 let i, threadItem;
1156 for ( i = 0; i < result.threadItems.length; i++ ) {
1157 threadItem = result.threadItems[ i ];
1158
1159 const name = this.computeName( threadItem );
1160 threadItem.name = name;
1161
1162 const id = this.computeId( threadItem, result );
1163 threadItem.id = id;
1164
1165 result.updateIdAndNameMaps( threadItem );
1166 }
1167 };
1168
1169 /**
1170 * @param {ThreadItem} threadItem
1171 * @return {CommentItem|null}
1172 */
1173 Parser.prototype.getThreadStartComment = function ( threadItem ) {
1174 let oldest = null;
1175 if ( threadItem instanceof CommentItem ) {
1176 oldest = threadItem;
1177 }
1178 // Check all replies. This can't just use the first comment because threads are often summarized
1179 // at the top when the discussion is closed.
1180 for ( let i = 0; i < threadItem.replies.length; i++ ) {
1181 const comment = threadItem.replies[ i ];
1182 // Don't include sub-threads to avoid changing the ID when threads are "merged".
1183 if ( comment instanceof CommentItem ) {
1184 const oldestInReplies = this.getThreadStartComment( comment );
1185 if ( !oldest || oldestInReplies.timestamp.isBefore( oldest.timestamp ) ) {
1186 oldest = oldestInReplies;
1187 }
1188 }
1189 }
1190 return oldest;
1191 };
1192
1193 module.exports = Parser;