Debian Codegraph @

extensions/DiscussionTools/includes/CommentFormatter.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\DiscussionTools;
4
5 use MediaWiki\Config\ConfigException;
6 use MediaWiki\Context\IContextSource;
7 use MediaWiki\Extension\DiscussionTools\Hooks\HookRunner;
8 use MediaWiki\Extension\DiscussionTools\Hooks\HookUtils;
9 use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentCommentItem;
10 use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentHeadingItem;
11 use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentThreadItem;
12 use MediaWiki\Extension\DiscussionTools\ThreadItem\ThreadItem;
13 use MediaWiki\Html\Html;
14 use MediaWiki\Html\HtmlHelper;
15 use MediaWiki\Language\Language;
16 use MediaWiki\MediaWikiServices;
17 use MediaWiki\Parser\ParserOutput;
18 use MediaWiki\Parser\Sanitizer;
19 use MediaWiki\Request\WebRequest;
20 use MediaWiki\Title\Title;
21 use MediaWiki\User\UserIdentity;
22 use MediaWiki\Utils\MWTimestamp;
23 use MWExceptionHandler;
24 use Throwable;
25 use Wikimedia\Parsoid\DOM\Document;
26 use Wikimedia\Parsoid\DOM\Element;
27 use Wikimedia\Parsoid\Utils\DOMCompat;
28 use Wikimedia\Parsoid\Utils\DOMUtils;
29 use Wikimedia\Parsoid\Wt2Html\XMLSerializer;
30 use Wikimedia\RemexHtml\Serializer\SerializerNode;
31 use Wikimedia\Timestamp\TimestampException;
32
33 class CommentFormatter {
34 // List of features which, when enabled, cause the comment formatter to run
35 public const USE_WITH_FEATURES = [
36 HookUtils::REPLYTOOL,
37 HookUtils::TOPICSUBSCRIPTION,
38 HookUtils::VISUALENHANCEMENTS
39 ];
40
41 /**
42 * Get a comment parser object for a DOM element
43 *
44 * This method exists so it can mocked in tests.
45 */
46 protected static function getParser(): CommentParser {
47 return MediaWikiServices::getInstance()->getService( 'DiscussionTools.CommentParser' );
48 }
49
50 protected static function getHookRunner(): HookRunner {
51 return new HookRunner( MediaWikiServices::getInstance()->getHookContainer() );
52 }
53
54 /**
55 * Add discussion tools to some HTML
56 *
57 * @param string &$text Parser text output (modified by reference)
58 * @param ParserOutput $pout ParserOutput object for metadata, e.g. parser limit report
59 * @param Title $title
60 */
61 public static function addDiscussionTools( string &$text, ParserOutput $pout, Title $title ): void {
62 $start = microtime( true );
63 $requestId = null;
64
65 try {
66 $text = static::addDiscussionToolsInternal( $text, $pout, $title );
67
68 } catch ( Throwable $e ) {
69 // Catch errors, so that they don't cause the entire page to not display.
70 // Log it and report the request ID to make it easier to find in the logs.
71 MWExceptionHandler::logException( $e );
72 $requestId = WebRequest::getRequestId();
73 }
74
75 $duration = microtime( true ) - $start;
76
77 MediaWikiServices::getInstance()->getStatsFactory()
78 ->getTiming( 'discussiontools_addreplylinks_seconds' )
79 ->copyToStatsdAt( 'discussiontools.addReplyLinks' )
80 ->observe( $duration * 1000 );
81
82 // How long this method took, in seconds
83 $pout->setLimitReportData(
84 // The following messages can be generated upstream
85 // * discussiontools-limitreport-timeusage-value
86 // * discussiontools-limitreport-timeusage-value-text
87 // * discussiontools-limitreport-timeusage-value-html
88 'discussiontools-limitreport-timeusage',
89 sprintf( '%.3f', $duration )
90 );
91 if ( $requestId ) {
92 // Request ID where errors were logged (only if an error occurred)
93 $pout->setLimitReportData(
94 'discussiontools-limitreport-errorreqid',
95 $requestId
96 );
97 }
98 }
99
100 /**
101 * Add a wrapper, topic container, and subscribe link around a heading element
102 *
103 * @param Element $headingElement Heading element
104 * @param ContentHeadingItem|null $headingItem Heading item
105 * @param array|null &$tocInfo TOC info
106 * @return Element Wrapper element (either found or newly added)
107 */
108 protected static function handleHeading(
109 Element $headingElement,
110 ?ContentHeadingItem $headingItem = null,
111 ?array &$tocInfo = null
112 ): Element {
113 $doc = $headingElement->ownerDocument;
114 $wrapperNode = $headingElement->parentNode;
115 if ( !(
116 $wrapperNode instanceof Element &&
117 DOMCompat::getClassList( $wrapperNode )->contains( 'mw-heading' )
118 ) ) {
119 // Do not add the wrapper if the heading has attributes generated from wikitext (T353489).
120 // Only allow reserved attributes (e.g. 'data-mw', which can't be used in wikitext, but which
121 // are used internally by our own code and by Parsoid) and the 'id', 'about', and 'typeof'
122 // attributes used by Parsoid.
123 foreach ( $headingElement->attributes as $attr ) {
124 if (
125 !in_array( $attr->name, [ 'id', 'about', 'typeof' ], true ) &&
126 !Sanitizer::isReservedDataAttribute( $attr->name )
127 ) {
128 return $headingElement;
129 }
130 }
131
132 $wrapperNode = $doc->createElement( 'div' );
133 $headingElement->parentNode->insertBefore( $wrapperNode, $headingElement );
134 $wrapperNode->appendChild( $headingElement );
135 }
136
137 if ( !$headingItem ) {
138 return $wrapperNode;
139 }
140
141 $uneditable = DOMCompat::querySelector( $wrapperNode, 'mw\\:editsection' ) === null;
142 $headingItem->setUneditableSection( $uneditable );
143 self::addOverflowMenuButton( $headingItem, $doc, $wrapperNode );
144
145 $latestReplyItem = $headingItem->getLatestReply();
146
147 $bar = null;
148 if ( $latestReplyItem ) {
149 $bar = $doc->createElement( 'div' );
150 $bar->setAttribute(
151 'class',
152 'ext-discussiontools-init-section-bar'
153 );
154 }
155
156 self::addTopicContainer(
157 $wrapperNode, $latestReplyItem, $doc, $headingItem, $bar, $tocInfo
158 );
159
160 self::addSubscribeLink(
161 $headingItem, $doc, $wrapperNode, $latestReplyItem, $bar
162 );
163
164 if ( $latestReplyItem ) {
165 // The check for if ( $latestReplyItem ) prevents $bar from being null
166 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
167 $wrapperNode->appendChild( $bar );
168 }
169
170 return $wrapperNode;
171 }
172
173 /**
174 * Add a topic container around a heading element.
175 *
176 * A topic container is the information displayed when the "Show discusion activity" user
177 * preference is selected. This displays information such as the latest comment time, number
178 * of comments, and number of editors in the discussion.
179 */
180 protected static function addTopicContainer(
181 Element $wrapperNode,
182 ?ContentCommentItem $latestReplyItem,
183 Document $doc,
184 ContentHeadingItem $headingItem,
185 ?Element $bar,
186 array &$tocInfo
187 ) {
188 if ( !DOMCompat::getClassList( $wrapperNode )->contains( 'mw-heading' ) ) {
189 DOMCompat::getClassList( $wrapperNode )->add( 'mw-heading' );
190 DOMCompat::getClassList( $wrapperNode )->add( 'mw-heading2' );
191 }
192 DOMCompat::getClassList( $wrapperNode )->add( 'ext-discussiontools-init-section' );
193
194 if ( !$latestReplyItem ) {
195 return;
196 }
197
198 $latestReplyJSON = json_encode( static::getJsonArrayForCommentMarker( $latestReplyItem ) );
199 // Timestamp output varies by user timezone, so is formatted later
200 $latestReply = $doc->createElement( 'mw:dt-latestcommentthread' );
201 $latestReply->setAttribute( 'data', $latestReplyJSON );
202
203 $commentCount = $doc->createElement( 'mw:dt-commentcount' );
204 $commentCount->setAttribute( 'data', (string)$headingItem->getCommentCount() );
205
206 $authorCount = $doc->createElement( 'mw:dt-authorcount' );
207 $authorCount->setAttribute( 'data', (string)count( $headingItem->getAuthorsBelow() ) );
208
209 $metadata = $doc->createElement( 'div' );
210 $metadata->setAttribute(
211 'class',
212 'ext-discussiontools-init-section-metadata'
213 );
214 $metadata->appendChild( $latestReply );
215 $metadata->appendChild( $commentCount );
216 $metadata->appendChild( $authorCount );
217 $bar->appendChild( $metadata );
218
219 $tocInfo[ $headingItem->getLinkableTitle() ] = [
220 'commentCount' => $headingItem->getCommentCount(),
221 ];
222 }
223
224 /**
225 * Add a subscribe/unsubscribe link to the right of a heading element
226 */
227 protected static function addSubscribeLink(
228 ContentHeadingItem $headingItem,
229 Document $doc,
230 Element $wrapperNode,
231 ?ContentCommentItem $latestReplyItem,
232 ?Element $bar
233 ) {
234 $headingJSON = json_encode( static::getJsonForHeadingMarker( $headingItem ) );
235
236 // Replaced in ::postprocessTopicSubscription() as the text depends on user state
237 if ( $headingItem->isSubscribable() ) {
238 $subscribeButton = $doc->createElement( 'mw:dt-subscribebutton' );
239 $subscribeButton->setAttribute( 'data', $headingJSON );
240 $wrapperNode->insertBefore( $subscribeButton, $wrapperNode->firstChild );
241 }
242
243 if ( !$latestReplyItem ) {
244 return;
245 }
246
247 $actions = $doc->createElement( 'div' );
248 $actions->setAttribute(
249 'class',
250 'ext-discussiontools-init-section-actions'
251 );
252 if ( $headingItem->isSubscribable() ) {
253 $subscribeButton = $doc->createElement( 'mw:dt-subscribebutton' );
254 $subscribeButton->setAttribute( 'mobile', '' );
255 $subscribeButton->setAttribute( 'data', $headingJSON );
256 $actions->appendChild( $subscribeButton );
257 }
258 $bar->appendChild( $actions );
259 }
260
261 /**
262 * Add discussion tools to some HTML
263 *
264 * @param string $html HTML
265 * @param ParserOutput $pout
266 * @param Title $title
267 * @return string HTML with discussion tools
268 */
269 protected static function addDiscussionToolsInternal( string $html, ParserOutput $pout, Title $title ): string {
270 // The output of this method can end up in the HTTP cache (Varnish). Avoid changing it;
271 // and when doing so, ensure that frontend code can handle both the old and new outputs.
272 // See controller#init in JS.
273
274 $doc = DOMUtils::parseHTML( $html );
275 $container = DOMCompat::getBody( $doc );
276
277 $threadItemSet = static::getParser()->parse( $container, $title->getTitleValue() );
278 $threadItems = $threadItemSet->getThreadItems();
279
280 $tocInfo = [];
281
282 $newestComment = null;
283 $newestCommentData = null;
284
285 $url = $title->getCanonicalURL();
286 $dtConfig = MediaWikiServices::getInstance()->getConfigFactory()->makeConfig( 'discussiontools' );
287 $enablePermalinksFrontend = $dtConfig->get( 'DiscussionToolsEnablePermalinksFrontend' );
288
289 // Iterate in reverse order, because adding the range markers for a thread item
290 // can invalidate the ranges of subsequent thread items (T298096)
291 foreach ( array_reverse( $threadItems ) as $threadItem ) {
292 // Create a dummy node to attach data to.
293 if ( $threadItem instanceof ContentHeadingItem && $threadItem->isPlaceholderHeading() ) {
294 $node = $doc->createElement( 'span' );
295 $container->insertBefore( $node, $container->firstChild );
296 $threadItem->setRange( new ImmutableRange( $node, 0, $node, 0 ) );
297 }
298
299 // Add start and end markers to range
300 $id = $threadItem->getId();
301 $range = $threadItem->getRange();
302 $startMarker = $doc->createElement( 'span' );
303 $startMarker->setAttribute( 'data-mw-comment-start', '' );
304 $startMarker->setAttribute( 'id', $id );
305 $endMarker = $doc->createElement( 'span' );
306 $endMarker->setAttribute( 'data-mw-comment-end', $id );
307
308 // Extend the range if the start or end is inside an element which can't have element children.
309 // (There may be other problematic elements... but this seems like a good start.)
310 while ( CommentUtils::cantHaveElementChildren( $range->startContainer ) ) {
311 $range = $range->setStart(
312 $range->startContainer->parentNode,
313 CommentUtils::childIndexOf( $range->startContainer )
314 );
315 }
316 while ( CommentUtils::cantHaveElementChildren( $range->endContainer ) ) {
317 $range = $range->setEnd(
318 $range->endContainer->parentNode,
319 CommentUtils::childIndexOf( $range->endContainer ) + 1
320 );
321 }
322
323 $range->setStart( $range->endContainer, $range->endOffset )->insertNode( $endMarker );
324 // Start marker is added after reply link to keep reverse DOM order
325
326 if ( $threadItem instanceof ContentHeadingItem ) {
327 $headline = $threadItem->getHeadlineNode();
328 $headline->setAttribute( 'data-mw-thread-id', $threadItem->getId() );
329 if ( $threadItem->getHeadingLevel() === 2 ) {
330 // Hack for tests (T363031), $headline should already be a <h2>
331 $headingElement = CommentUtils::closestElement( $headline, [ 'h2' ] );
332
333 if ( $headingElement ) {
334 static::handleHeading( $headingElement, $threadItem, $tocInfo );
335 }
336 }
337 } elseif ( $threadItem instanceof ContentCommentItem ) {
338 $replyButtons = $doc->createElement( 'span' );
339 $replyButtons->setAttribute( 'class', 'ext-discussiontools-init-replylink-buttons' );
340 $replyButtons->setAttribute( 'data-mw-thread-id', $threadItem->getId() );
341 $replyButtons->appendChild( $doc->createElement( 'mw:dt-replybuttonscontent' ) );
342
343 if ( !$newestComment || $threadItem->getTimestamp() > $newestComment->getTimestamp() ) {
344 $newestComment = $threadItem;
345 // Needs to calculated before DOM modifications change ranges
346 $newestCommentData = static::getJsonArrayForCommentMarker( $threadItem, true );
347 }
348
349 CommentModifier::addReplyLink( $threadItem, $replyButtons );
350
351 if ( $enablePermalinksFrontend ) {
352 $timestampRanges = $threadItem->getTimestampRanges();
353 $lastTimestamp = end( $timestampRanges );
354 $existingLink = CommentUtils::closestElement( $lastTimestamp->startContainer, [ 'a' ] ) ??
355 CommentUtils::closestElement( $lastTimestamp->endContainer, [ 'a' ] );
356
357 if ( !$existingLink ) {
358 $link = $doc->createElement( 'a' );
359 $link->setAttribute( 'href', $url . '#' . Sanitizer::escapeIdForLink( $threadItem->getId() ) );
360 $link->setAttribute( 'class', 'ext-discussiontools-init-timestamplink' );
361 $lastTimestamp->surroundContents( $link );
362 }
363 }
364 self::addOverflowMenuButton( $threadItem, $doc, $replyButtons );
365
366 $sigMarker = $doc->createElement( 'span' );
367 $sigMarker->setAttribute( 'data-mw-comment-sig', $id );
368 $signatureRanges = $threadItem->getSignatureRanges();
369 $lastSignature = end( $signatureRanges );
370 $lastSignature->insertNode( $sigMarker );
371 }
372
373 $range->insertNode( $startMarker );
374 }
375
376 $pout->setExtensionData( 'DiscussionTools-tocInfo', $tocInfo );
377
378 if ( $newestCommentData ) {
379 $pout->setExtensionData( 'DiscussionTools-newestComment', $newestCommentData );
380 }
381
382 $startOfSections = DOMCompat::querySelector( $container, 'meta[property="mw:PageProp/toc"]' );
383
384 // Enhance other <h2>'s which aren't part of a thread
385 $headings = DOMCompat::querySelectorAll( $container, 'h2' );
386 foreach ( $headings as $headingElement ) {
387 $wrapper = $headingElement->parentNode;
388 if ( $wrapper instanceof Element && DOMCompat::getClassList( $wrapper )->contains( 'toctitle' ) ) {
389 continue;
390 }
391 $headingElement = static::handleHeading( $headingElement );
392 if ( !$startOfSections ) {
393 $startOfSections = $headingElement;
394 }
395 }
396
397 if (
398 // Page has no headings but some content
399 ( !$startOfSections && $container->childNodes->length ) ||
400 // Page has content before the first heading / TOC
401 ( $startOfSections && $startOfSections->previousSibling !== null )
402 ) {
403 $pout->setExtensionData( 'DiscussionTools-hasLedeContent', true );
404 }
405 if (
406 // Placeholder heading indicates that there are comments in the lede section (T324139).
407 // We can't really separate them from the lede content.
408 isset( $threadItems[0] ) &&
409 $threadItems[0] instanceof ContentHeadingItem &&
410 $threadItems[0]->isPlaceholderHeading()
411 ) {
412 $pout->setExtensionData( 'DiscussionTools-hasCommentsInLedeContent', true );
413 MediaWikiServices::getInstance()->getTrackingCategories()
414 // The following messages are generated upstream:
415 // * discussiontools-comments-before-first-heading-category-desc
416 ->addTrackingCategory( $pout, 'discussiontools-comments-before-first-heading-category', $title );
417 }
418
419 // FIXME: Similar to `setJsConfigVar` below, this will eventually throw
420 // from Parsoid's calls to the legacy parser for extension content parsing
421 $pout->setExtensionData(
422 'DiscussionTools-isEmptyTalkPage',
423 count( $threadItems ) === 0
424 );
425
426 $threadsJSON = array_map( static function ( ContentThreadItem $item ) {
427 return $item->jsonSerialize( true );
428 }, $threadItemSet->getThreadsStructured() );
429
430 // Temporary hack to deal with T351461#9358034: this should be a
431 // call to `setJsConfigVar` but Parsoid is currently reprocessing
432 // content from extensions. (T372592)
433 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
434 @$pout->addJsConfigVars( 'wgDiscussionToolsPageThreads', $threadsJSON );
435
436 // Like DOMCompat::getInnerHTML(), but disable 'smartQuote' for compatibility with
437 // ParserOutput::EDITSECTION_REGEX matching 'mw:editsection' tags (T274709)
438 $html = XMLSerializer::serialize( $container, [ 'innerXML' => true, 'smartQuote' => false ] )['html'];
439
440 return $html;
441 }
442
443 /**
444 * Add an overflow menu button to an element.
445 *
446 * @param ThreadItem $threadItem The heading or comment item
447 * @param Document $document Retrieved by parsing page HTML
448 * @param Element $element The element to add the overflow menu button to
449 * @return void
450 */
451 protected static function addOverflowMenuButton(
452 ThreadItem $threadItem, Document $document, Element $element
453 ): void {
454 $overflowMenuDataJSON = json_encode( [ 'threadItem' => $threadItem ] );
455
456 $overflowMenuButton = $document->createElement( 'mw:dt-ellipsisbutton' );
457 $overflowMenuButton->setAttribute( 'data', $overflowMenuDataJSON );
458 $element->appendChild( $overflowMenuButton );
459 }
460
461 /**
462 * Replace placeholders for all interactive tools with nothing. This is intended for cases where
463 * interaction is unexpected, e.g. reply links while previewing an edit.
464 */
465 public static function removeInteractiveTools( string $text ): string {
466 $text = HtmlHelper::modifyElements(
467 $text,
468 static fn ( SerializerNode $node ): bool => in_array( $node->name, [
469 'mw:dt-replybuttonscontent',
470 'mw:dt-ellipsisbutton',
471 'mw:dt-subscribebutton',
472 // HACK: MobileFrontend's HtmlFormatter strips the mw: namespace
473 'dt-replybuttonscontent',
474 'dt-ellipsisbutton',
475 'dt-subscribebutton'
476 ] ),
477 static fn () => ''
478 );
479 return $text;
480 }
481
482 /**
483 * Replace placeholders for topic subscription buttons with the real thing.
484 */
485 public static function postprocessTopicSubscription(
486 string $text, BatchModifyElements &$batchModifyElements, IContextSource $contextSource,
487 SubscriptionStore $subscriptionStore, bool $isMobile, bool $useButtons
488 ): void {
489 $doc = DOMCompat::newDocument( true );
490
491 $itemDataByName = [];
492 HtmlHelper::modifyElements(
493 $text,
494 static function ( SerializerNode $node ) use ( &$itemDataByName ): bool {
495 if ( $node->name === 'mw:dt-subscribebutton' || $node->name === 'dt-subscribebutton' ) {
496 $data = $node->attrs['data'];
497 $itemDataByName[ $data ] = json_decode( $data, true );
498 }
499 // This is non-replacing - we are just using this as
500 // a convenient way to traverse the DOM tree.
501 return false;
502 },
503 static fn ( $n ) => $n
504 );
505
506 $itemNames = array_column( $itemDataByName, 'name' );
507
508 $user = $contextSource->getUser();
509 $items = $subscriptionStore->getSubscriptionItemsForUser(
510 $user,
511 $itemNames
512 );
513 $itemsByName = [];
514 foreach ( $items as $item ) {
515 $itemsByName[ $item->getItemName() ] = $item;
516 }
517
518 $lang = $contextSource->getLanguage();
519 $title = $contextSource->getTitle();
520 $batchModifyElements->add(
521 static fn ( SerializerNode $node ): bool => $node->name === 'mw:dt-subscribebutton' ||
522 $node->name === 'dt-subscribebutton',
523 static function ( SerializerNode $node ) use (
524 $doc, $itemsByName, $itemDataByName, $lang, $title, $isMobile, $useButtons
525 ) {
526 $buttonIsMobile = $node->attrs->offsetExists( 'mobile' );
527 $itemData = $itemDataByName[ $node->attrs['data'] ];
528 '@phan-var array $itemData';
529 $itemName = $itemData['name'];
530
531 $isSubscribed = isset( $itemsByName[ $itemName ] ) && !$itemsByName[ $itemName ]->isMuted();
532 $subscribedState = isset( $itemsByName[ $itemName ] ) ? $itemsByName[ $itemName ]->getState() : null;
533
534 $href = $title->getLinkURL( [
535 'action' => $isSubscribed ? 'dtunsubscribe' : 'dtsubscribe',
536 'commentname' => $itemName,
537 'section' => $isSubscribed ? null : $itemData['linkableTitle'],
538 ] );
539
540 if ( $buttonIsMobile !== $isMobile ) {
541 return '';
542 }
543
544 if ( !$useButtons ) {
545 $subscribe = $doc->createElement( 'span' );
546 $subscribe->setAttribute(
547 'class',
548 'ext-discussiontools-init-section-subscribe mw-editsection-like'
549 );
550
551 $subscribeLink = $doc->createElement( 'a' );
552 $subscribeLink->setAttribute( 'href', $href );
553 $subscribeLink->setAttribute( 'class', 'ext-discussiontools-init-section-subscribe-link' );
554 $subscribeLink->setAttribute( 'role', 'button' );
555 $subscribeLink->setAttribute( 'tabindex', '0' );
556 $subscribeLink->setAttribute( 'title', wfMessage(
557 $isSubscribed ?
558 'discussiontools-topicsubscription-button-unsubscribe-tooltip' :
559 'discussiontools-topicsubscription-button-subscribe-tooltip'
560 )->inLanguage( $lang )->text() );
561 $subscribeLink->nodeValue = wfMessage(
562 $isSubscribed ?
563 'discussiontools-topicsubscription-button-unsubscribe' :
564 'discussiontools-topicsubscription-button-subscribe'
565 )->inLanguage( $lang )->text();
566
567 if ( $subscribedState !== null ) {
568 $subscribeLink->setAttribute( 'data-mw-subscribed', (string)$subscribedState );
569 }
570
571 $bracket = $doc->createElement( 'span' );
572 $bracket->setAttribute( 'class', 'ext-discussiontools-init-section-subscribe-bracket' );
573 $bracketOpen = $bracket->cloneNode( false );
574 $bracketOpen->nodeValue = '[';
575 $bracketClose = $bracket->cloneNode( false );
576 $bracketClose->nodeValue = ']';
577
578 $subscribe->appendChild( $bracketOpen );
579 $subscribe->appendChild( $subscribeLink );
580 $subscribe->appendChild( $bracketClose );
581
582 return DOMCompat::getOuterHTML( $subscribe );
583 } else {
584 $subscribe = new \OOUI\ButtonWidget( [
585 'classes' => [ 'ext-discussiontools-init-section-subscribeButton' ],
586 'framed' => false,
587 'icon' => $isSubscribed ? 'bell' : 'bellOutline',
588 'flags' => [ 'progressive' ],
589 'href' => $href,
590 'label' => wfMessage( $isSubscribed ?
591 'discussiontools-topicsubscription-button-unsubscribe-label' :
592 'discussiontools-topicsubscription-button-subscribe-label'
593 )->inLanguage( $lang )->text(),
594 'title' => wfMessage( $isSubscribed ?
595 'discussiontools-topicsubscription-button-unsubscribe-tooltip' :
596 'discussiontools-topicsubscription-button-subscribe-tooltip'
597 )->inLanguage( $lang )->text(),
598 'infusable' => true,
599 ] );
600
601 if ( $subscribedState !== null ) {
602 $subscribe->setAttributes( [ 'data-mw-subscribed' => (string)$subscribedState ] );
603 }
604
605 return $subscribe->toString();
606 }
607 }
608 );
609 }
610
611 /**
612 * Remove placeholders for topic subscription buttons (e.g. if the feature is disabled)
613 */
614 public static function removeTopicSubscription( BatchModifyElements &$batchModifyElements ): void {
615 $batchModifyElements->add(
616 static fn ( SerializerNode $node ): bool => $node->name === 'mw:dt-subscribebutton' ||
617 $node->name === 'dt-subscribebutton',
618 static fn () => ''
619 );
620 }
621
622 /**
623 * Replace placeholders for reply links with the real thing.
624 */
625 public static function postprocessReplyTool(
626 string $text, BatchModifyElements &$batchModifyElements,
627 IContextSource $contextSource, bool $isMobile, bool $useButtons
628 ): void {
629 $doc = DOMCompat::newDocument( true );
630
631 $lang = $contextSource->getLanguage();
632 $replyLinkText = wfMessage( 'discussiontools-replylink' )->inLanguage( $lang )->escaped();
633 $replyButtonText = wfMessage( 'discussiontools-replybutton' )->inLanguage( $lang )->escaped();
634
635 $batchModifyElements->add(
636 static fn ( SerializerNode $node ): bool => $node->name === 'mw:dt-replybuttonscontent' ||
637 $node->name === 'dt-replybuttonscontent',
638 static function ( SerializerNode $node ) use(
639 $doc, $replyLinkText, $replyButtonText, $isMobile, $useButtons, $lang
640 ) {
641 $replyLinkButtons = $doc->createElement( 'span' );
642
643 if ( $useButtons ) {
644 // Visual enhancements button
645 $useIcon = $isMobile || static::isLanguageRequiringReplyIcon( $lang );
646 $replyLinkButton = new \OOUI\ButtonWidget( [
647 'classes' => [ 'ext-discussiontools-init-replybutton' ],
648 'framed' => false,
649 'label' => $replyButtonText,
650 'icon' => $useIcon ? 'share' : null,
651 'flags' => [ 'progressive' ],
652 'infusable' => true,
653 ] );
654
655 DOMCompat::setInnerHTML( $replyLinkButtons, $replyLinkButton->toString() );
656 } else {
657 // Reply link
658 $replyLink = $doc->createElement( 'a' );
659 $replyLink->setAttribute( 'class', 'ext-discussiontools-init-replylink-reply' );
660 $replyLink->setAttribute( 'role', 'button' );
661 $replyLink->setAttribute( 'tabindex', '0' );
662 // Set empty 'href' to avoid a:not([href]) selector in MobileFrontend
663 $replyLink->setAttribute( 'href', '' );
664 $replyLink->textContent = $replyLinkText;
665
666 $bracket = $doc->createElement( 'span' );
667 $bracket->setAttribute( 'class', 'ext-discussiontools-init-replylink-bracket' );
668 $bracketOpen = $bracket->cloneNode( false );
669 $bracketClose = $bracket->cloneNode( false );
670 $bracketOpen->textContent = '[';
671 $bracketClose->textContent = ']';
672
673 $replyLinkButtons->appendChild( $bracketOpen );
674 $replyLinkButtons->appendChild( $replyLink );
675 $replyLinkButtons->appendChild( $bracketClose );
676 }
677
678 return DOMCompat::getInnerHTML( $replyLinkButtons );
679 }
680 );
681 }
682
683 /**
684 * Remove placeholders for reply links (e.g. if the feature is disabled)
685 */
686 public static function removeReplyTool( BatchModifyElements &$batchModifyElements ): void {
687 $batchModifyElements->add(
688 static fn ( SerializerNode $node ): bool => $node->name === 'mw:dt-replybuttonscontent' ||
689 $node->name === 'dt-replybuttonscontent',
690 static fn () => ''
691 );
692 }
693
694 /**
695 * Replace placeholders for timestamp links.
696 */
697 public static function postprocessTimestampLinks(
698 string $text, BatchModifyElements &$batchModifyElements, IContextSource $contextSource
699 ): void {
700 $lang = $contextSource->getLanguage();
701 $user = $contextSource->getUser();
702
703 $batchModifyElements->add(
704 static fn ( SerializerNode $node ): bool => $node->name === 'mw:dt-timestamplink' ||
705 $node->name === 'dt-timestamplink',
706 static function ( SerializerNode $node ) use ( $lang, $user ): SerializerNode {
707 $node->name = 'a';
708 $relativeTime = static::getSignatureRelativeTime(
709 new MWTimestamp( $node->attrs['title'] ),
710 $lang,
711 $user
712 );
713 $node->attrs['title'] = $relativeTime;
714 return $node;
715 }
716 );
717 }
718
719 /**
720 * Create a meta item label
721 *
722 * @param string $className
723 * @param string|\OOUI\HtmlSnippet $label Label
724 * @return \OOUI\Tag
725 */
726 private static function metaLabel( string $className, $label ): \OOUI\Tag {
727 return ( new \OOUI\Tag( 'span' ) )
728 ->addClasses( [ 'ext-discussiontools-init-section-metaitem', $className ] )
729 ->appendContent( $label );
730 }
731
732 /**
733 * Get JSON data for a commentItem that can be inserted into a comment marker
734 *
735 * @param ContentCommentItem $commentItem Comment item
736 * @param bool $includeTopicAndAuthor Include metadata about topic and author
737 * @return array
738 */
739 private static function getJsonArrayForCommentMarker(
740 ContentCommentItem $commentItem,
741 bool $includeTopicAndAuthor = false
742 ): array {
743 $JSON = [
744 'id' => $commentItem->getId(),
745 'timestamp' => $commentItem->getTimestampString()
746 ];
747 if ( $includeTopicAndAuthor ) {
748 $JSON['author'] = $commentItem->getAuthor();
749 $heading = $commentItem->getSubscribableHeading();
750 if ( $heading ) {
751 $JSON['heading'] = static::getJsonForHeadingMarker( $heading );
752 }
753 }
754 return $JSON;
755 }
756
757 private static function getJsonForHeadingMarker( ContentHeadingItem $heading ): array {
758 $JSON = $heading->jsonSerialize();
759 $JSON['text'] = $heading->getText();
760 $JSON['linkableTitle'] = $heading->getLinkableTitle();
761 return $JSON;
762 }
763
764 /**
765 * Get a relative timestamp from a signature timestamp.
766 *
767 * Signature timestamps don't have seconds-level accuracy, so any
768 * time difference of less than 120 seconds is treated as being
769 * posted "just now".
770 */
771 public static function getSignatureRelativeTime(
772 MWTimestamp $timestamp, Language $lang, UserIdentity $user
773 ): string {
774 try {
775 $diff = time() - intval( $timestamp->getTimestamp() );
776 } catch ( TimestampException $ex ) {
777 // Can't happen
778 $diff = 0;
779 }
780 if ( $diff < 120 ) {
781 $timestamp = new MWTimestamp();
782 }
783 return $lang->getHumanTimestamp( $timestamp, null, $user );
784 }
785
786 /**
787 * Post-process visual enhancements features (topic containers)
788 */
789 public static function postprocessVisualEnhancements(
790 string $text, BatchModifyElements &$batchModifyElements,
791 IContextSource $contextSource, bool $isMobile
792 ): void {
793 $lang = $contextSource->getLanguage();
794 $user = $contextSource->getUser();
795 $batchModifyElements->add(
796 static fn ( SerializerNode $node ): bool => $node->name === 'mw:dt-latestcommentthread' ||
797 $node->name === 'dt-latestcommentthread',
798 static function ( SerializerNode $node ) use ( $lang, $user ) {
799 $itemData = json_decode( $node->attrs['data'], true );
800 if ( $itemData && $itemData['timestamp'] && $itemData['id'] ) {
801 $relativeTime = static::getSignatureRelativeTime(
802 new MWTimestamp( $itemData['timestamp'] ),
803 $lang,
804 $user
805 );
806 $commentLink = Html::element( 'a', [
807 'href' => '#' . Sanitizer::escapeIdForLink( $itemData['id'] )
808 ], $relativeTime );
809
810 $label = wfMessage( 'discussiontools-topicheader-latestcomment' )
811 ->rawParams( $commentLink )
812 ->inLanguage( $lang )->escaped();
813
814 return CommentFormatter::metaLabel(
815 'ext-discussiontools-init-section-timestampLabel',
816 new \OOUI\HtmlSnippet( $label )
817 )->toString();
818 }
819 }
820 );
821 $batchModifyElements->add(
822 static fn ( SerializerNode $node ): bool => $node->name === 'mw:dt-commentcount' ||
823 $node->name === 'dt-commentcount',
824 static function ( SerializerNode $node ) use ( $lang, $user ) {
825 $count = $lang->formatNum( $node->attrs['data'] );
826 $label = wfMessage(
827 'discussiontools-topicheader-commentcount',
828 $count
829 )->inLanguage( $lang )->text();
830 return CommentFormatter::metaLabel(
831 'ext-discussiontools-init-section-commentCountLabel',
832 $label
833 )->toString();
834 }
835 );
836 $batchModifyElements->add(
837 static fn ( SerializerNode $node ): bool => $node->name === 'mw:dt-authorcount' ||
838 $node->name === 'dt-authorcount',
839 static function ( SerializerNode $node ) use ( $lang, $user ) {
840 $count = $lang->formatNum( $node->attrs['data'] );
841 $label = wfMessage(
842 'discussiontools-topicheader-authorcount',
843 $count
844 )->inLanguage( $lang )->text();
845 return CommentFormatter::metaLabel(
846 'ext-discussiontools-init-section-authorCountLabel',
847 $label
848 )->toString();
849 }
850 );
851 $batchModifyElements->add(
852 static fn ( SerializerNode $node ): bool => $node->name === 'mw:dt-ellipsisbutton' ||
853 $node->name === 'dt-ellipsisbutton',
854 static function ( SerializerNode $node ) use ( $contextSource, $isMobile ) {
855 $overflowMenuData = json_decode( $node->attrs['data'], true );
856
857 '@phan-var array $overflowMenuData';
858 $threadItem = $overflowMenuData['threadItem'];
859 $threadItemType = $threadItem['type'] ?? null;
860 if ( !$isMobile && $threadItemType === 'heading' ) {
861 // Displaying the overflow menu next to a topic heading is a bit more
862 // complicated on desktop, so leaving it out for now.
863 return '';
864 }
865 $overflowMenuItems = [];
866 $resourceLoaderModules = [];
867
868 self::getHookRunner()->onDiscussionToolsAddOverflowMenuItems(
869 $overflowMenuItems,
870 $resourceLoaderModules,
871 $threadItem,
872 $contextSource
873 );
874
875 if ( $overflowMenuItems ) {
876 usort(
877 $overflowMenuItems,
878 static function ( OverflowMenuItem $itemA, OverflowMenuItem $itemB ): int {
879 return $itemB->getWeight() - $itemA->getWeight();
880 }
881 );
882
883 $overflowButton = new ButtonMenuSelectWidget( [
884 'classes' => [
885 'ext-discussiontools-init-section-overflowMenuButton'
886 ],
887 'framed' => false,
888 'icon' => 'ellipsis',
889 'infusable' => true,
890 'data' => [
891 'itemConfigs' => $overflowMenuItems,
892 'resourceLoaderModules' => $resourceLoaderModules
893 ]
894 ] );
895 return $overflowButton->toString();
896 } else {
897 return '';
898 }
899 }
900 );
901 }
902
903 /**
904 * Remove visual enhancements features (e.g. if the feature is disabled)
905 */
906 public static function removeVisualEnhancements( BatchModifyElements &$batchModifyElements ): void {
907 $batchModifyElements->add(
908 static fn ( SerializerNode $node ): bool => in_array( $node->name, [
909 'mw:dt-latestcommentthread',
910 'mw:dt-commentcount',
911 'mw:dt-authorcount',
912 'mw:dt-ellipsisbutton',
913 // HACK: MobileFrontend's HtmlFormatter strips the mw: namespace
914 'dt-latestcommentthread',
915 'dt-commentcount',
916 'dt-authorcount',
917 'dt-ellipsisbutton',
918 ] ),
919 static fn () => ''
920 );
921 }
922
923 /**
924 * Post-process visual enhancements features for page subtitle
925 *
926 * @return string|null HTML for page subtitle, null if nothing to show
927 */
928 public static function postprocessVisualEnhancementsSubtitle(
929 ParserOutput $pout, IContextSource $contextSource
930 ): ?string {
931 $itemData = $pout->getExtensionData( 'DiscussionTools-newestComment' );
932 if ( $itemData && $itemData['timestamp'] && $itemData['id'] ) {
933 $lang = $contextSource->getLanguage();
934 $user = $contextSource->getUser();
935 $relativeTime = static::getSignatureRelativeTime(
936 new MWTimestamp( $itemData['timestamp'] ),
937 $lang,
938 $user
939 );
940 $commentLink = Html::element( 'a', [
941 'href' => '#' . Sanitizer::escapeIdForLink( $itemData['id'] )
942 ], $relativeTime );
943
944 if ( isset( $itemData['heading'] ) ) {
945 $headingLink = Html::element( 'a', [
946 'href' => '#' . Sanitizer::escapeIdForLink( $itemData['heading']['linkableTitle'] )
947 ], $itemData['heading']['text'] );
948 $label = wfMessage( 'discussiontools-pageframe-latestcomment' )
949 ->rawParams( $commentLink )
950 ->params( $itemData['author'] )
951 ->rawParams( $headingLink )
952 ->inLanguage( $lang )->escaped();
953 } else {
954 $label = wfMessage( 'discussiontools-pageframe-latestcomment-notopic' )
955 ->rawParams( $commentLink )
956 ->params( $itemData['author'] )
957 ->inLanguage( $lang )->escaped();
958 }
959
960 return Html::rawElement(
961 'div',
962 [ 'class' => 'ext-discussiontools-init-pageframe-latestcomment' ],
963 $label
964 );
965 }
966 return null;
967 }
968
969 /**
970 * Post-process visual enhancements features for table of contents
971 */
972 public static function postprocessTableOfContents(
973 ParserOutput $pout, IContextSource $contextSource
974 ): void {
975 $tocInfo = $pout->getExtensionData( 'DiscussionTools-tocInfo' );
976
977 if ( $tocInfo && $pout->getTOCData() ) {
978 $sections = $pout->getTOCData()->getSections();
979 foreach ( $sections as $item ) {
980 $key = str_replace( '_', ' ', $item->anchor );
981 // Unset if we did not format this section as a topic container
982 if ( isset( $tocInfo[$key] ) ) {
983 $lang = $contextSource->getLanguage();
984 $count = $lang->formatNum( $tocInfo[$key]['commentCount'] );
985 $commentCount = wfMessage(
986 'discussiontools-topicheader-commentcount',
987 $count
988 )->inLanguage( $lang )->text();
989
990 $summary = Html::element( 'span', [
991 'class' => 'ext-discussiontools-init-sidebar-meta'
992 ], $commentCount );
993 } else {
994 $summary = '';
995 }
996
997 // This also shows up in API action=parse&prop=sections output.
998 $item->setExtensionData( 'DiscussionTools-html-summary', $summary );
999 }
1000 }
1001 }
1002
1003 /**
1004 * Check if the talk page had no comments or headings.
1005 */
1006 public static function isEmptyTalkPage( ParserOutput $pout ): bool {
1007 return $pout->getExtensionData( 'DiscussionTools-isEmptyTalkPage' ) === true;
1008 }
1009
1010 /**
1011 * Check if the talk page has content above the first heading, in the lede section.
1012 */
1013 public static function hasLedeContent( ParserOutput $pout ): bool {
1014 return $pout->getExtensionData( 'DiscussionTools-hasLedeContent' ) === true;
1015 }
1016
1017 /**
1018 * Check if the talk page has comments above the first heading, in the lede section.
1019 */
1020 public static function hasCommentsInLedeContent( ParserOutput $pout ): bool {
1021 return $pout->getExtensionData( 'DiscussionTools-hasCommentsInLedeContent' ) === true;
1022 }
1023
1024 /**
1025 * Check if the language requires an icon for the reply button
1026 *
1027 * @param Language $userLang Language
1028 * @return bool
1029 */
1030 public static function isLanguageRequiringReplyIcon( Language $userLang ): bool {
1031 $services = MediaWikiServices::getInstance();
1032
1033 $dtConfig = $services->getConfigFactory()->makeConfig( 'discussiontools' );
1034 $languages = $dtConfig->get( 'DiscussionTools_visualenhancements_reply_icon_languages' );
1035
1036 if ( array_is_list( $languages ) ) {
1037 // Detect legacy list format
1038 throw new ConfigException(
1039 'DiscussionTools_visualenhancements_reply_icon_languages must be an associative array'
1040 );
1041 }
1042
1043 // User language matched exactly and is explicitly set to true or false
1044 if ( isset( $languages[ $userLang->getCode() ] ) ) {
1045 return (bool)$languages[ $userLang->getCode() ];
1046 }
1047
1048 // Check fallback languages
1049 $fallbackLanguages = $userLang->getFallbackLanguages();
1050 foreach ( $fallbackLanguages as $fallbackLanguage ) {
1051 if ( isset( $languages[ $fallbackLanguage ] ) ) {
1052 return (bool)$languages[ $fallbackLanguage ];
1053 }
1054 }
1055
1056 // Language not listed, default is to show no icon
1057 return false;
1058 }
1059
1060 }