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