Debian Codegraph @

extensions/DiscussionTools/includes/Hooks/PageHooks.php

raw symbols SCIP
1 <?php
2 /**
3 * DiscussionTools page hooks
4 *
5 * @file
6 * @ingroup Extensions
7 * @license MIT
8 */
9
10 namespace MediaWiki\Extension\DiscussionTools\Hooks;
11
12 use Article;
13 use MediaWiki\Actions\Hook\GetActionNameHook;
14 use MediaWiki\Context\IContextSource;
15 use MediaWiki\Context\RequestContext;
16 use MediaWiki\Extension\DiscussionTools\BatchModifyElements;
17 use MediaWiki\Extension\DiscussionTools\CommentFormatter;
18 use MediaWiki\Extension\DiscussionTools\CommentUtils;
19 use MediaWiki\Extension\DiscussionTools\SubscriptionStore;
20 use MediaWiki\Extension\VisualEditor\Hooks as VisualEditorHooks;
21 use MediaWiki\Hook\SidebarBeforeOutputHook;
22 use MediaWiki\Hook\SkinTemplateNavigation__UniversalHook;
23 use MediaWiki\Html\Html;
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Output\Hook\BeforePageDisplayHook;
26 use MediaWiki\Output\Hook\OutputPageBeforeHTMLHook;
27 use MediaWiki\Output\Hook\OutputPageParserOutputHook;
28 use MediaWiki\Output\OutputPage;
29 use MediaWiki\Page\Hook\BeforeDisplayNoArticleTextHook;
30 use MediaWiki\Parser\ParserOutput;
31 use MediaWiki\Registration\ExtensionRegistry;
32 use MediaWiki\SpecialPage\SpecialPage;
33 use MediaWiki\Title\Title;
34 use MediaWiki\User\Options\UserOptionsLookup;
35 use MediaWiki\User\UserIdentity;
36 use MediaWiki\User\UserNameUtils;
37 use OOUI\ButtonWidget;
38 use Skin;
39 use SkinTemplate;
40
41 class PageHooks implements
42 BeforeDisplayNoArticleTextHook,
43 BeforePageDisplayHook,
44 GetActionNameHook,
45 OutputPageBeforeHTMLHook,
46 OutputPageParserOutputHook,
47 SidebarBeforeOutputHook,
48 SkinTemplateNavigation__UniversalHook
49 {
50
51 private SubscriptionStore $subscriptionStore;
52 private UserNameUtils $userNameUtils;
53 private UserOptionsLookup $userOptionsLookup;
54
55 public function __construct(
56 SubscriptionStore $subscriptionStore,
57 UserNameUtils $userNameUtils,
58 UserOptionsLookup $userOptionsLookup
59 ) {
60 $this->subscriptionStore = $subscriptionStore;
61 $this->userNameUtils = $userNameUtils;
62 $this->userOptionsLookup = $userOptionsLookup;
63 }
64
65 private function isMobile(): bool {
66 if ( ExtensionRegistry::getInstance()->isLoaded( 'MobileFrontend' ) ) {
67 /** @var \MobileContext $mobFrontContext */
68 $mobFrontContext = MediaWikiServices::getInstance()->getService( 'MobileFrontend.Context' );
69 return $mobFrontContext->shouldDisplayMobileView();
70 }
71 return false;
72 }
73
74 /**
75 * Adds DiscussionTools JS to the output.
76 *
77 * This is attached to the MediaWiki 'BeforePageDisplay' hook.
78 *
79 * @param OutputPage $output
80 * @param Skin $skin
81 * @return void This hook must not abort, it must return no value
82 */
83 public function onBeforePageDisplay( $output, $skin ): void {
84 $user = $output->getUser();
85 $req = $output->getRequest();
86 $title = $output->getTitle();
87
88 foreach ( HookUtils::FEATURES as $feature ) {
89 // Add a CSS class for each enabled feature
90 if ( HookUtils::isFeatureEnabledForOutput( $output, $feature ) ) {
91 // The following CSS classes are generated here:
92 // * ext-discussiontools-replytool-enabled
93 // * ext-discussiontools-newtopictool-enabled
94 // * ext-discussiontools-sourcemodetoolbar-enabled
95 // * ext-discussiontools-topicsubscription-enabled
96 // * ext-discussiontools-autotopicsub-enabled
97 // * ext-discussiontools-visualenhancements-enabled
98 // * ext-discussiontools-visualenhancements_reply-enabled
99 // * ext-discussiontools-visualenhancements_pageframe-enabled
100 $output->addBodyClasses( "ext-discussiontools-$feature-enabled" );
101 }
102 }
103
104 $isMobile = $this->isMobile();
105
106 if ( $isMobile && HookUtils::isFeatureEnabledForOutput( $output, HookUtils::VISUALENHANCEMENTS ) ) {
107 $output->addBodyClasses( 'collapsible-headings-collapsed' );
108 }
109
110 // Load style modules if the tools can be available for the title
111 // to selectively hide DT features, depending on the body classes added above.
112 if ( HookUtils::isAvailableForTitle( $title ) ) {
113 $output->addModuleStyles( 'ext.discussionTools.init.styles' );
114 }
115
116 // Load modules if any DT feature is enabled for this user
117 if ( HookUtils::isFeatureEnabledForOutput( $output ) ) {
118 $output->addModules( 'ext.discussionTools.init' );
119
120 $enabledVars = [];
121 foreach ( HookUtils::FEATURES as $feature ) {
122 $enabledVars[$feature] = HookUtils::isFeatureEnabledForOutput( $output, $feature );
123 }
124 $output->addJsConfigVars( 'wgDiscussionToolsFeaturesEnabled', $enabledVars );
125
126 $editor = $this->userOptionsLookup->getOption( $user, 'discussiontools-editmode' );
127 // User has no preferred editor yet
128 // If the user has a preferred editor, this will be evaluated in the client
129 if ( !$editor ) {
130 // Check which editor we would use for articles
131 // VE pref is 'visualeditor'/'wikitext'. Here we describe the mode,
132 // not the editor, so 'visual'/'source'
133 $editor = VisualEditorHooks::getPreferredEditor( $user, $req ) === 'visualeditor' ?
134 'visual' : 'source';
135 $output->addJsConfigVars(
136 'wgDiscussionToolsFallbackEditMode',
137 $editor
138 );
139 }
140 }
141
142 // Replace the action=edit&section=new form with the new topic tool.
143 if ( HookUtils::shouldOpenNewTopicTool( $output->getContext() ) ) {
144 $output->addJsConfigVars( 'wgDiscussionToolsStartNewTopicTool', true );
145
146 // For no-JS compatibility, redirect to the old new section editor if JS is unavailable.
147 // This isn't great, because the user has to load the page twice. But making a page that is
148 // both a view mode and an edit mode seems difficult, so I'm cutting some corners here.
149 // (Code below adapted from VisualEditor.)
150 $params = $output->getRequest()->getValues();
151 $params['dtenable'] = '0';
152 $url = wfScript() . '?' . wfArrayToCgi( $params );
153 $escapedUrl = htmlspecialchars( $url );
154
155 // Redirect if the user has no JS (<noscript>)
156 $output->addHeadItem(
157 'dt-noscript-fallback',
158 "<noscript><meta http-equiv=\"refresh\" content=\"0; url=$escapedUrl\"></noscript>"
159 );
160 // Redirect if the user has no ResourceLoader
161 $output->addScript( Html::inlineScript(
162 "(window.NORLQ=window.NORLQ||[]).push(" .
163 "function(){" .
164 "location.href=\"$url\";" .
165 "}" .
166 ");"
167 ) );
168 }
169
170 if ( $isMobile ) {
171 if (
172 $title->isTalkPage() &&
173 HookUtils::isFeatureEnabledForOutput( $output, HookUtils::REPLYTOOL ) && (
174 // 'DiscussionTools-ledeButton' property may be already set to true or false.
175 // Examine the other conditions only if it's unset.
176 $output->getProperty( 'DiscussionTools-ledeButton' ) ?? (
177 // Header shown on all talk pages, see Article::showNamespaceHeader
178 !$output->getContext()->msg( 'talkpageheader' )->isDisabled() &&
179 // Check if it isn't empty since it may use parser functions to only show itself on some pages
180 trim( $output->getContext()->msg( 'talkpageheader' )->text() ) !== ''
181 )
182 )
183 ) {
184 $output->addBodyClasses( 'ext-discussiontools-init-lede-hidden' );
185 $output->enableOOUI();
186 $output->prependHTML(
187 Html::rawElement( 'div',
188 [ 'class' => 'ext-discussiontools-init-lede-button-container' ],
189 ( new ButtonWidget( [
190 'label' => $output->getContext()->msg( 'discussiontools-ledesection-button' )->text(),
191 'classes' => [ 'ext-discussiontools-init-lede-button' ],
192 'framed' => false,
193 'icon' => 'info',
194 'infusable' => true,
195 ] ) )
196 )
197 );
198 }
199 }
200
201 if ( $output->getSkin()->getSkinName() === 'minerva' ) {
202 if (
203 ( $req->getRawVal( 'action' ) ?? 'view' ) === 'view' &&
204 HookUtils::isFeatureEnabledForOutput( $output, HookUtils::NEWTOPICTOOL ) &&
205 // Only add the button if "New section" tab would be shown in a normal skin.
206 HookUtils::shouldShowNewSectionTab( $output->getContext() )
207 ) {
208 $output->enableOOUI();
209 // For speechBubbleAdd
210 $output->addModuleStyles( 'oojs-ui.styles.icons-alerts' );
211 $output->addBodyClasses( 'ext-discussiontools-init-new-topic-opened' );
212
213 // Minerva doesn't show a new topic button.
214 $output->addHTML( Html::rawElement( 'div',
215 [ 'class' => 'ext-discussiontools-init-new-topic' ],
216 ( new ButtonWidget( [
217 'classes' => [ 'ext-discussiontools-init-new-topic-button' ],
218 'href' => $title->getLinkURL( [ 'action' => 'edit', 'section' => 'new' ] ),
219 'icon' => 'speechBubbleAdd',
220 'label' => $output->getContext()->msg( 'skin-action-addsection' )->text(),
221 'flags' => [ 'progressive', 'primary' ],
222 'infusable' => true,
223 ] ) )
224 // For compatibility with MobileWebUIActionsTracking logging (T295490)
225 ->setAttributes( [ 'data-event-name' => 'talkpage.add-topic' ] )
226 ) );
227 }
228
229 if ( HookUtils::isFeatureEnabledForOutput( $output, HookUtils::TOPICSUBSCRIPTION ) ) {
230 $output->addModuleStyles( 'ext.discussionTools.minervaicons' );
231 }
232 }
233 }
234
235 /**
236 * OutputPageBeforeHTML hook handler
237 * @see https://www.mediawiki.org/wiki/Manual:Hooks/OutputPageBeforeHTML
238 *
239 * @param OutputPage $output OutputPage object that corresponds to the page
240 * @param string &$text Text that will be displayed, in HTML
241 * @return bool|void This hook must not abort, it must return true or null.
242 */
243 public function onOutputPageBeforeHTML( $output, &$text ) {
244 // ParserOutputPostCacheTransform hook would be a better place to do this,
245 // so that when the ParserOutput is used directly without using this hook,
246 // we don't leave half-baked interface elements in it (see e.g. T292345, T294168).
247 // But that hook doesn't provide parameters that we need to render correctly
248 // (including the page title, interface language, and current user).
249
250 // This hook can be executed more than once per page view if the page content is composed from
251 // multiple sources!
252
253 $batchModifyElements = new BatchModifyElements();
254
255 // Match the check in ParserHooks::transformHtml which adds the timestamp link placeholders
256 if ( HookUtils::isAvailableForTitle( $output->getTitle() ) ) {
257 CommentFormatter::postprocessTimestampLinks( $text, $batchModifyElements, $output );
258 }
259
260 $isMobile = $this->isMobile();
261 $visualEnhancementsEnabled =
262 HookUtils::isFeatureEnabledForOutput( $output, HookUtils::VISUALENHANCEMENTS );
263 $visualEnhancementsReplyEnabled =
264 HookUtils::isFeatureEnabledForOutput( $output, HookUtils::VISUALENHANCEMENTS_REPLY );
265
266 if ( HookUtils::isFeatureEnabledForOutput( $output, HookUtils::TOPICSUBSCRIPTION ) ) {
267 // Just enable OOUI PHP - the OOUI subscribe button isn't infused unless VISUALENHANCEMENTS are enabled
268 $output->setupOOUI();
269 CommentFormatter::postprocessTopicSubscription(
270 $text, $batchModifyElements, $output, $this->subscriptionStore, $isMobile, $visualEnhancementsEnabled
271 );
272 } else {
273 CommentFormatter::removeTopicSubscription( $batchModifyElements );
274 }
275
276 if ( HookUtils::isFeatureEnabledForOutput( $output, HookUtils::REPLYTOOL ) ) {
277 $output->enableOOUI();
278 CommentFormatter::postprocessReplyTool(
279 $text, $batchModifyElements, $output, $isMobile, $visualEnhancementsReplyEnabled
280 );
281 } else {
282 CommentFormatter::removeReplyTool( $batchModifyElements );
283 }
284
285 if ( $visualEnhancementsEnabled ) {
286 $output->enableOOUI();
287 if ( HookUtils::isFeatureEnabledForOutput( $output, HookUtils::TOPICSUBSCRIPTION ) ) {
288 // Visually enhanced topic subscriptions: bell, bellOutline
289 $output->addModuleStyles( 'oojs-ui.styles.icons-alerts' );
290 }
291 if (
292 $isMobile ||
293 (
294 $visualEnhancementsReplyEnabled &&
295 CommentFormatter::isLanguageRequiringReplyIcon( $output->getLanguage() )
296 )
297 ) {
298 // Reply button: share
299 $output->addModuleStyles( 'oojs-ui.styles.icons-content' );
300 }
301 $output->addModuleStyles( [
302 // Overflow menu ('ellipsis' icon)
303 'oojs-ui.styles.icons-interactions',
304 ] );
305 if ( $isMobile ) {
306 $output->addModuleStyles( [
307 // Edit button in overflow menu ('edit' icon)
308 'oojs-ui.styles.icons-editing-core',
309 ] );
310 }
311 CommentFormatter::postprocessVisualEnhancements( $text, $batchModifyElements, $output, $isMobile );
312 } else {
313 CommentFormatter::removeVisualEnhancements( $batchModifyElements );
314 }
315
316 $text = $batchModifyElements->apply( $text );
317
318 // Append empty state if the OutputPageParserOutput hook decided that we should.
319 // This depends on the order in which the hooks run. Hopefully it doesn't change.
320 if ( $output->getProperty( 'DiscussionTools-emptyStateHtml' ) ) {
321 // Insert before the last </div> tag, which should belong to <div class="mw-parser-output">
322 $idx = strrpos( $text, '</div>' );
323 $text = substr_replace(
324 $text,
325 $output->getProperty( 'DiscussionTools-emptyStateHtml' ),
326 $idx === false ? strlen( $text ) : $idx,
327 0
328 );
329 }
330 }
331
332 /**
333 * OutputPageParserOutput hook handler
334 * @see https://www.mediawiki.org/wiki/Manual:Hooks/OutputPageParserOutput
335 *
336 * @param OutputPage $output
337 * @param ParserOutput $pout ParserOutput instance being added in $output
338 * @return void This hook must not abort, it must return no value
339 */
340 public function onOutputPageParserOutput( $output, $pout ): void {
341 // ParserOutputPostCacheTransform hook would be a better place to do this,
342 // so that when the ParserOutput is used directly without using this hook,
343 // we don't leave half-baked interface elements in it (see e.g. T292345, T294168).
344 // But that hook doesn't provide parameters that we need to render correctly
345 // (including the page title, interface language, and current user).
346
347 // This hook can be executed more than once per page view if the page content is composed from
348 // multiple sources!
349
350 CommentFormatter::postprocessTableOfContents( $pout, $output );
351
352 if (
353 CommentFormatter::isEmptyTalkPage( $pout ) &&
354 HookUtils::shouldDisplayEmptyState( $output->getContext() )
355 ) {
356 $output->enableOOUI();
357 // This must be appended after the content of the page, which wasn't added to OutputPage yet.
358 // Pass it to the OutputPageBeforeHTML hook, so that it may add it at the right time.
359 // This depends on the order in which the hooks run. Hopefully it doesn't change.
360 $output->setProperty( 'DiscussionTools-emptyStateHtml',
361 $this->getEmptyStateHtml( $output->getContext() ) );
362 $output->addBodyClasses( 'ext-discussiontools-emptystate-shown' );
363 }
364
365 if ( HookUtils::isFeatureEnabledForOutput( $output, HookUtils::VISUALENHANCEMENTS ) ) {
366 $subtitle = CommentFormatter::postprocessVisualEnhancementsSubtitle( $pout, $output );
367
368 if ( $subtitle ) {
369 $output->addSubtitle( $subtitle );
370 }
371 }
372
373 if ( $output->getSkin()->getSkinName() === 'minerva' ) {
374 $title = $output->getTitle();
375
376 if (
377 $title->isTalkPage() &&
378 HookUtils::isFeatureEnabledForOutput( $output, HookUtils::REPLYTOOL )
379 ) {
380 if (
381 CommentFormatter::hasCommentsInLedeContent( $pout )
382 ) {
383 // If there are comments in the lede section, we can't really separate them from other lede
384 // content, so keep the whole section visible.
385 $output->setProperty( 'DiscussionTools-ledeButton', false );
386
387 } elseif (
388 CommentFormatter::hasLedeContent( $pout ) &&
389 $output->getProperty( 'DiscussionTools-ledeButton' ) === null
390 ) {
391 // If there is lede content and the lede button hasn't been disabled above, enable it.
392 $output->setProperty( 'DiscussionTools-ledeButton', true );
393 }
394 }
395 }
396 }
397
398 /**
399 * GetActionName hook handler
400 *
401 * @param IContextSource $context Request context
402 * @param string &$action Default action name, reassign to change it
403 * @return void This hook must not abort, it must return no value
404 */
405 public function onGetActionName( IContextSource $context, string &$action ): void {
406 if ( $action === 'edit' && (
407 HookUtils::shouldOpenNewTopicTool( $context ) ||
408 HookUtils::shouldDisplayEmptyState( $context )
409 ) ) {
410 $action = 'view';
411 }
412 }
413
414 /**
415 * BeforeDisplayNoArticleText hook handler
416 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeDisplayNoArticleText
417 *
418 * @param Article $article The (empty) article
419 * @return bool|void This hook can abort
420 */
421 public function onBeforeDisplayNoArticleText( $article ) {
422 // We want to override the empty state for articles on which we would be enabled
423 $context = $article->getContext();
424 if ( !HookUtils::shouldDisplayEmptyState( $context ) ) {
425 // Our empty states are all about using the new topic tool, but
426 // expect to be on a talk page, so fall back if it's not
427 // available or if we're in a non-talk namespace that still has
428 // DT features enabled
429 return true;
430 }
431
432 $output = $context->getOutput();
433 $output->enableOOUI();
434 $output->disableClientCache();
435
436 $html = $this->getEmptyStateHtml( $context );
437
438 $output->addHTML(
439 // This being mw-parser-output is a lie, but makes the reply controller cope much better with everything
440 Html::rawElement( 'div', [ 'class' => 'mw-parser-output noarticletext' ], $html )
441 );
442 $output->addBodyClasses( 'ext-discussiontools-emptystate-shown' );
443
444 return false;
445 }
446
447 /**
448 * Generate HTML markup for the new topic tool's empty state, shown on talk pages that don't exist
449 * or have no topics.
450 *
451 * @param IContextSource $context
452 * @return string HTML
453 */
454 private function getEmptyStateHtml( IContextSource $context ): string {
455 $coreConfig = RequestContext::getMain()->getConfig();
456 $iconpath = $coreConfig->get( 'ExtensionAssetsPath' ) . '/DiscussionTools/images';
457
458 $descParams = [];
459 $buttonMsg = 'discussiontools-emptystate-button';
460 $title = $context->getTitle();
461 if ( $title->inNamespace( NS_USER_TALK ) && !$title->isSubpage() ) {
462 // This is a user talk page
463 $isIP = $this->userNameUtils->isIP( $title->getText() );
464 $isTemp = $this->userNameUtils->isTemp( $title->getText() );
465 if ( $title->equals( $context->getUser()->getTalkPage() ) ) {
466 // This is your own user talk page
467 if ( $isIP || $isTemp ) {
468 if ( $isIP ) {
469 // You're an IP editor, so this is only *sort of* your talk page
470 $titleMsg = 'discussiontools-emptystate-title-self-anon';
471 $descMsg = 'discussiontools-emptystate-desc-self-anon';
472 } else {
473 // You're a temporary user, so you don't get some of the good stuff
474 $titleMsg = 'discussiontools-emptystate-title-self-temp';
475 $descMsg = 'discussiontools-emptystate-desc-self-temp';
476 }
477 $query = $context->getRequest()->getValues();
478 unset( $query['title'] );
479 $descParams = [
480 SpecialPage::getTitleFor( 'CreateAccount' )->getFullURL( [
481 'returnto' => $context->getTitle()->getFullText(),
482 'returntoquery' => wfArrayToCgi( $query ),
483 ] ),
484 SpecialPage::getTitleFor( 'Userlogin' )->getFullURL( [
485 'returnto' => $context->getTitle()->getFullText(),
486 'returntoquery' => wfArrayToCgi( $query ),
487 ] ),
488 ];
489 } else {
490 // You're logged in, this is very much your talk page
491 $titleMsg = 'discussiontools-emptystate-title-self';
492 $descMsg = 'discussiontools-emptystate-desc-self';
493 }
494 $buttonMsg = false;
495 } elseif ( $isIP ) {
496 // This is an IP editor
497 $titleMsg = 'discussiontools-emptystate-title-user-anon';
498 $descMsg = 'discussiontools-emptystate-desc-user-anon';
499 } elseif ( $isTemp ) {
500 // This is a temporary user
501 $titleMsg = 'discussiontools-emptystate-title-user-temp';
502 $descMsg = 'discussiontools-emptystate-desc-user-temp';
503 } else {
504 // This is any other user
505 $titleMsg = 'discussiontools-emptystate-title-user';
506 $descMsg = 'discussiontools-emptystate-desc-user';
507 }
508 } else {
509 // This is any other page on which DT is enabled
510 $titleMsg = 'discussiontools-emptystate-title';
511 $descMsg = 'discussiontools-emptystate-desc';
512 }
513
514 $text =
515 Html::rawElement( 'h3', [],
516 $context->msg( $titleMsg )->parse()
517 ) .
518 Html::rawElement( 'div', [ 'class' => 'plainlinks' ],
519 $context->msg( $descMsg, $descParams )->parseAsBlock()
520 );
521
522 if ( $buttonMsg ) {
523 $text .= new ButtonWidget( [
524 'label' => $context->msg( $buttonMsg )->text(),
525 'href' => $title->getLocalURL( 'action=edit&section=new' ),
526 'flags' => [ 'primary', 'progressive' ]
527 ] );
528 }
529
530 $wrapped =
531 Html::rawElement( 'div', [ 'class' => 'ext-discussiontools-emptystate' ],
532 Html::rawElement( 'div', [ 'class' => 'ext-discussiontools-emptystate-text' ], $text ) .
533 Html::element( 'img', [
534 'src' => $iconpath . '/emptystate.svg',
535 'class' => 'ext-discussiontools-emptystate-logo',
536 // This is a purely decorative element
537 'alt' => '',
538 ] )
539 );
540
541 return $wrapped;
542 }
543
544 /**
545 * @param Skin $skin
546 * @param array &$sidebar
547 */
548 public function onSidebarBeforeOutput( $skin, &$sidebar ): void {
549 $output = $skin->getOutput();
550 if (
551 $skin->getSkinName() === 'minerva' &&
552 HookUtils::isFeatureEnabledForOutput( $output, HookUtils::TOPICSUBSCRIPTION )
553 ) {
554 $button = $this->getNewTopicsSubscriptionButton(
555 $skin->getUser(),
556 $skin->getTitle(),
557 $skin->getContext()
558 );
559 $sidebar['TOOLBOX']['t-page-subscribe'] = [
560 'icon' => $button['icon'],
561 'text' => $button['label'],
562 'href' => $button['href'],
563 ];
564 }
565 }
566
567 /**
568 * @param SkinTemplate $sktemplate
569 * @param array &$links
570 * @return void
571 * @phpcs:disable MediaWiki.NamingConventions.LowerCamelFunctionsName.FunctionName
572 */
573 public function onSkinTemplateNavigation__Universal( $sktemplate, &$links ): void {
574 $output = $sktemplate->getOutput();
575 if ( HookUtils::isFeatureEnabledForOutput( $output, HookUtils::TOPICSUBSCRIPTION ) ) {
576 $button = $this->getNewTopicsSubscriptionButton(
577 $sktemplate->getUser(),
578 $sktemplate->getTitle(),
579 $sktemplate->getContext()
580 );
581
582 $links['actions']['dt-page-subscribe'] = [
583 'text' => $button['label'],
584 'title' => $button['tooltip'],
585 'data-mw-subscribed' => $button['isSubscribed'] ? '1' : '0',
586 'href' => $button['href'],
587 ];
588
589 $output->addModules( [ 'ext.discussionTools.init' ] );
590 }
591 }
592
593 /**
594 * Get data from a new topics subcription button
595 *
596 * @param UserIdentity $user User
597 * @param Title $title Title
598 * @param IContextSource $context Context
599 * @return array Array containing label, tooltip, icon, isSubscribed and href.
600 */
601 private function getNewTopicsSubscriptionButton(
602 UserIdentity $user, Title $title, IContextSource $context
603 ): array {
604 $items = $this->subscriptionStore->getSubscriptionItemsForUser(
605 $user,
606 [ CommentUtils::getNewTopicsSubscriptionId( $title ) ]
607 );
608 $subscriptionItem = count( $items ) ? $items[ 0 ] : null;
609 $isSubscribed = $subscriptionItem && !$subscriptionItem->isMuted();
610
611 return [
612 'label' => $context->msg( $isSubscribed ?
613 'discussiontools-newtopicssubscription-button-unsubscribe-label' :
614 'discussiontools-newtopicssubscription-button-subscribe-label'
615 )->text(),
616 'tooltip' => $context->msg( $isSubscribed ?
617 'discussiontools-newtopicssubscription-button-unsubscribe-tooltip' :
618 'discussiontools-newtopicssubscription-button-subscribe-tooltip'
619 )->text(),
620 'icon' => $isSubscribed ? 'bell' : 'bellOutline',
621 'isSubscribed' => $isSubscribed,
622 'href' => $title->getLinkURL( [
623 'action' => $isSubscribed ? 'dtunsubscribe' : 'dtsubscribe',
624 'commentname' => CommentUtils::getNewTopicsSubscriptionId( $title ),
625 ] ),
626 ];
627 }
628 }