Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 224
0.00% covered (danger)
0.00%
0 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
HookUtils
0.00% covered (danger)
0.00%
0 / 224
0.00% covered (danger)
0.00%
0 / 12
10712
0.00% covered (danger)
0.00%
0 / 1
 hasPageProp
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 parseRevisionParsoidHtml
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
42
 featureConflictsWithGadget
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
42
 isFeatureAvailableToUser
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
110
 isFeatureEnabledForUser
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
56
 isAvailableForTitle
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
210
 isFeatureEnabledForOutput
0.00% covered (danger)
0.00%
0 / 42
0.00% covered (danger)
0.00%
0 / 1
506
 shouldShowNewSectionTab
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
30
 shouldOpenNewTopicTool
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
110
 shouldDisplayEmptyState
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
132
 pageSubjectExists
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
 shouldAddAutoSubscription
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2/**
3 * DiscussionTools extension hooks
4 *
5 * @file
6 * @ingroup Extensions
7 * @license MIT
8 */
9
10namespace MediaWiki\Extension\DiscussionTools\Hooks;
11
12use LqtDispatch;
13use MediaWiki\Context\IContextSource;
14use MediaWiki\Context\RequestContext;
15use MediaWiki\Extension\DiscussionTools\CommentParser;
16use MediaWiki\Extension\DiscussionTools\CommentUtils;
17use MediaWiki\Extension\DiscussionTools\ContentThreadItemSetStatus;
18use MediaWiki\Linker\LinkTarget;
19use MediaWiki\MediaWikiServices;
20use MediaWiki\Output\OutputPage;
21use MediaWiki\Page\ParserOutputAccess;
22use MediaWiki\Parser\ParserOptions;
23use MediaWiki\Registration\ExtensionRegistry;
24use MediaWiki\Revision\RevisionRecord;
25use MediaWiki\Status\Status;
26use MediaWiki\Title\Title;
27use MediaWiki\Title\TitleValue;
28use MediaWiki\User\UserIdentity;
29use Wikimedia\Assert\Assert;
30use Wikimedia\NormalizedException\NormalizedException;
31use Wikimedia\Parsoid\Core\DOMCompat;
32use Wikimedia\Parsoid\Ext\DOMUtils;
33use Wikimedia\Rdbms\IDBAccessObject;
34
35class HookUtils {
36
37    public const REPLYTOOL = 'replytool';
38    public const NEWTOPICTOOL = 'newtopictool';
39    public const SOURCEMODETOOLBAR = 'sourcemodetoolbar';
40    public const TOPICSUBSCRIPTION = 'topicsubscription';
41    public const AUTOTOPICSUB = 'autotopicsub';
42    public const VISUALENHANCEMENTS = 'visualenhancements';
43
44    /**
45     * @var string[] List of all sub-features. Will be used to generate:
46     *  - Body class: ext-discussiontools-FEATURE-enabled
47     *  - User option: discussiontools-FEATURE
48     */
49    public const FEATURES = [
50        // Can't use static:: in compile-time constants
51        self::REPLYTOOL,
52        self::NEWTOPICTOOL,
53        self::SOURCEMODETOOLBAR,
54        self::TOPICSUBSCRIPTION,
55        self::AUTOTOPICSUB,
56        self::VISUALENHANCEMENTS
57    ];
58
59    /**
60     * @var string[] List of configurable sub-features, used to generate:
61     *  - Feature override global: $wgDiscussionTools_FEATURE
62     *
63     * Feature setting can be 'available', 'unavailable' or 'default'. If set
64     * to 'default' and $wgDiscussionToolsBeta is true, the feature will be
65     * available only to users who have enabled the beta feature.
66     */
67    public const CONFIGS = [];
68
69    public const FEATURES_CONFLICT_WITH_GADGET = [
70        self::REPLYTOOL,
71        self::TOPICSUBSCRIPTION,
72    ];
73
74    public const FEATURES_DEPENDENCIES = [
75        self::SOURCEMODETOOLBAR => [
76            self::REPLYTOOL,
77            self::NEWTOPICTOOL,
78        ],
79        self::AUTOTOPICSUB => [
80            self::TOPICSUBSCRIPTION,
81        ]
82    ];
83
84    private const CACHED_PAGE_PROPS = [
85        'newsectionlink',
86        'nonewsectionlink',
87        'notalk',
88        'archivedtalk',
89    ];
90
91    /**
92     * Check if a title has a page prop.
93     *
94     * @param Title $title Title
95     * @param string $prop Page property
96     * @return bool Title has page property
97     */
98    private static function hasPageProp( Title $title, string $prop ): bool {
99        Assert::parameter(
100            in_array( $prop, self::CACHED_PAGE_PROPS, true ),
101            '$prop',
102            'must be one of the cached properties'
103        );
104        $id = $title->getArticleId();
105
106        // Optimization: Always load our props together to warm their cache at once (T347123)
107        $services = MediaWikiServices::getInstance();
108        $pagePropsPerId = $services->getPageProps()->getProperties( $title, self::CACHED_PAGE_PROPS );
109        return isset( $pagePropsPerId[ $id ][ $prop ] );
110    }
111
112    /**
113     * Parse a revision by using the discussion parser on the HTML provided by Parsoid.
114     *
115     * @param RevisionRecord $revRecord
116     * @param string|false $updateParserCacheFor Whether the parser cache should be updated on cache miss.
117     *        May be set to false for batch operations to avoid flooding the cache.
118     *        Otherwise, it should be set to the name of the calling method (__METHOD__),
119     *        so we can track what is causing parser cache writes.
120     */
121    public static function parseRevisionParsoidHtml(
122        RevisionRecord $revRecord,
123        $updateParserCacheFor
124    ): ContentThreadItemSetStatus {
125        $services = MediaWikiServices::getInstance();
126        $mainConfig = $services->getMainConfig();
127        $parserOutputAccess = $services->getParserOutputAccess();
128
129        // Look up the page by ID in master. If we just used $revRecord->getPage(),
130        // ParserOutputAccess would look it up by namespace+title in replica.
131        $pageRecord = $services->getPageStore()->getPageById( $revRecord->getPageId() ) ?:
132            $services->getPageStore()->getPageById( $revRecord->getPageId(), IDBAccessObject::READ_LATEST );
133        if ( !$pageRecord ) {
134            throw new NormalizedException(
135                "PageRecord for page {page} revision {revision} not found",
136                [
137                    'page' => $revRecord->getPageId(),
138                    'revision' => $revRecord->getId(),
139                ]
140            );
141        }
142
143        $parserOptions = ParserOptions::newFromAnon();
144        $parserOptions->setUseParsoid();
145
146        if ( $updateParserCacheFor ) {
147            // $updateParserCache contains the name of the calling method
148            $parserOptions->setRenderReason( $updateParserCacheFor );
149        }
150
151        $status = $parserOutputAccess->getParserOutput(
152            $pageRecord,
153            $parserOptions,
154            $revRecord,
155            // Don't flood the parser cache
156            [ ParserOutputAccess::OPT_NO_UPDATE_CACHE => !$updateParserCacheFor ],
157        );
158
159        if ( !$status->isOK() ) {
160            // This is currently the only expected failure, make the caller handle it
161            if ( $status->hasMessage( 'parsoid-resource-limit-exceeded' ) ) {
162                return ContentThreadItemSetStatus::wrap( $status );
163            }
164            // Any other failures indicate a software bug, so throw an exception
165            throw new NormalizedException( ...Status::wrap( $status )->getPsr3MessageAndContext() );
166        }
167
168        $parserOutput = $status->getValue();
169        $html = $parserOutput->getContentHolderText();
170
171        // Run the discussion parser on it
172        $doc = DOMUtils::parseHTML( $html );
173        $container = DOMCompat::getBody( $doc );
174
175        // Unwrap sections, so that transclusions overlapping section boundaries don't cause all
176        // comments in the sections to be treated as transcluded from another page.
177        CommentUtils::unwrapParsoidSections( $container );
178
179        /** @var CommentParser $parser */
180        $parser = $services->getService( 'DiscussionTools.CommentParser' );
181        $title = TitleValue::newFromPage( $revRecord->getPage() );
182        return ContentThreadItemSetStatus::newGood( $parser->parse( $container, $title ) );
183    }
184
185    /**
186     * @param UserIdentity $user
187     * @param string $feature Feature to check for
188     * @return bool
189     */
190    public static function featureConflictsWithGadget( UserIdentity $user, string $feature ) {
191        $dtConfig = MediaWikiServices::getInstance()->getConfigFactory()
192            ->makeConfig( 'discussiontools' );
193        $gadgetName = $dtConfig->get( 'DiscussionToolsConflictingGadgetName' );
194        if ( !$gadgetName ) {
195            return false;
196        }
197
198        if ( !in_array( $feature, static::FEATURES_CONFLICT_WITH_GADGET, true ) ) {
199            return false;
200        }
201
202        $extensionRegistry = ExtensionRegistry::getInstance();
203        if ( $extensionRegistry->isLoaded( 'Gadgets' ) ) {
204            $gadgetsRepo = MediaWikiServices::getInstance()->getService( 'GadgetsRepo' );
205            $match = array_search( $gadgetName, $gadgetsRepo->getGadgetIds(), true );
206            if ( $match !== false ) {
207                try {
208                    return $gadgetsRepo->getGadget( $gadgetName )
209                        ->isEnabled( $user );
210                } catch ( \InvalidArgumentException ) {
211                    return false;
212                }
213            }
214        }
215        return false;
216    }
217
218    /**
219     * Check if a DiscussionTools feature is available to this user
220     *
221     * @param UserIdentity $user
222     * @param string|null $feature Feature to check for (one of static::FEATURES)
223     *  Null will check for any DT feature.
224     */
225    public static function isFeatureAvailableToUser( UserIdentity $user, ?string $feature = null ): bool {
226        $services = MediaWikiServices::getInstance();
227        $dtConfig = $services->getConfigFactory()->makeConfig( 'discussiontools' );
228
229        $userIdentityUtils = $services->getUserIdentityUtils();
230        if (
231            ( $feature === static::TOPICSUBSCRIPTION || $feature === static::AUTOTOPICSUB ) &&
232            // Users must be logged in to use topic subscription, and Echo must be installed (T322498)
233            ( !$user->isRegistered() || $userIdentityUtils->isTemp( $user ) ||
234                !ExtensionRegistry::getInstance()->isLoaded( 'Echo' ) )
235        ) {
236            return false;
237        }
238
239        $optionsLookup = $services->getUserOptionsLookup();
240
241        if ( $feature ) {
242            // Feature-specific override
243            if ( !in_array( $feature, static::CONFIGS, true ) ) {
244                // Feature is not configurable, always available
245                return true;
246            }
247            if ( $dtConfig->get( 'DiscussionTools_' . $feature ) !== 'default' ) {
248                // Feature setting can be 'available' or 'unavailable', overriding any BetaFeatures settings
249                return $dtConfig->get( 'DiscussionTools_' . $feature ) === 'available';
250            }
251        } else {
252            // Some features are always available, so if no feature is
253            // specified (i.e. checking for any feature), always return true.
254            return true;
255        }
256
257        // No feature-specific override found.
258
259        if ( $dtConfig->get( 'DiscussionToolsBeta' ) ) {
260            $betaenabled = $optionsLookup->getOption( $user, 'discussiontools-betaenable', 0 );
261            return (bool)$betaenabled;
262        }
263
264        return true;
265    }
266
267    /**
268     * Check if a DiscussionTools feature is enabled by this user
269     *
270     * @param UserIdentity $user
271     * @param string|null $feature Feature to check for (one of static::FEATURES)
272     *  Null will check for any DT feature.
273     */
274    public static function isFeatureEnabledForUser( UserIdentity $user, ?string $feature = null ): bool {
275        if ( !static::isFeatureAvailableToUser( $user, $feature ) ) {
276            return false;
277        }
278        $services = MediaWikiServices::getInstance();
279        $optionsLookup = $services->getUserOptionsLookup();
280        if ( $feature ) {
281            if ( static::featureConflictsWithGadget( $user, $feature ) ) {
282                return false;
283            }
284            // Check for a specific feature
285            $enabled = $optionsLookup->getOption( $user, 'discussiontools-' . $feature );
286            // `null` means there is no user option for this feature, so it must be enabled
287            return $enabled === null ? true : $enabled;
288        } else {
289            // Check for any feature
290            foreach ( static::FEATURES as $feat ) {
291                if ( $optionsLookup->getOption( $user, 'discussiontools-' . $feat ) ) {
292                    return true;
293                }
294            }
295            return false;
296        }
297    }
298
299    /**
300     * Check if the tools are available for a given title
301     *
302     * Keep in sync with SQL conditions in persistRevisionThreadItems.php.
303     *
304     * @param Title $title
305     * @param string|null $feature Feature to check for (one of static::FEATURES)
306     *  Null will check for any DT feature.
307     */
308    public static function isAvailableForTitle( Title $title, ?string $feature = null ): bool {
309        // Only wikitext pages (e.g. not Flow boards, special pages)
310        if ( $title->getContentModel() !== CONTENT_MODEL_WIKITEXT ) {
311            return false;
312        }
313        // LiquidThreads needs a separate check, since it predates content models other than wikitext (T329423)
314        // @phan-suppress-next-line PhanUndeclaredClassMethod
315        if ( ExtensionRegistry::getInstance()->isLoaded( 'Liquid Threads' ) && LqtDispatch::isLqtPage( $title ) ) {
316            return false;
317        }
318        if ( !$title->canExist() ) {
319            return false;
320        }
321
322        // ARCHIVEDTALK/NOTALK magic words
323        if ( static::hasPageProp( $title, 'notalk' ) ) {
324            return false;
325        }
326        if (
327            $feature === static::REPLYTOOL &&
328            static::hasPageProp( $title, 'archivedtalk' )
329        ) {
330            return false;
331        }
332
333        $services = MediaWikiServices::getInstance();
334
335        if ( $feature === static::VISUALENHANCEMENTS ) {
336            $dtConfig = MediaWikiServices::getInstance()->getConfigFactory()->makeConfig( 'discussiontools' );
337            // Visual enhancements are only enabled on talk namespaces (T325417) ...
338            return $title->isTalkPage() || (
339                // ... or __NEWSECTIONLINK__ (T331635) or __ARCHIVEDTALK__ (T374198) pages
340                (
341                    static::hasPageProp( $title, 'newsectionlink' ) ||
342                    static::hasPageProp( $title, 'archivedtalk' )
343                ) &&
344                // excluding the main namespace, unless it has been configured for signatures
345                (
346                    !$title->inNamespace( NS_MAIN ) ||
347                    $services->getNamespaceInfo()->wantSignatures( $title->getNamespace() )
348                )
349            );
350        }
351
352        // Check that the page supports discussions.
353        return (
354            // Talk namespaces, and other namespaces where the signature button is shown in wikitext
355            // editor using $wgExtraSignatureNamespaces (T249036)
356            $services->getNamespaceInfo()->wantSignatures( $title->getNamespace() ) ||
357            // Treat pages with __NEWSECTIONLINK__ as talk pages (T245890)
358            static::hasPageProp( $title, 'newsectionlink' )
359        );
360    }
361
362    /**
363     * Check if the tool is available on a given page
364     *
365     * @param OutputPage $output
366     * @param string|null $feature Feature to check for (one of static::FEATURES)
367     *  Null will check for any DT feature.
368     */
369    public static function isFeatureEnabledForOutput( OutputPage $output, ?string $feature = null ): bool {
370        // Only show on normal page views (not history etc.), and in edit mode for previews
371        if (
372            // Don't try to call $output->getActionName if testing for NEWTOPICTOOL as we use
373            // the hook onGetActionName to override the action for the tool on empty pages.
374            // If we tried to call it here it would set up infinite recursion (T312689)
375            $feature !== static::NEWTOPICTOOL && !(
376                in_array( $output->getActionName(), [ 'view', 'edit', 'submit' ], true ) ||
377                // Subscriptions (specifically page-level subscriptions) are available on history pages (T345096)
378                (
379                    $output->getActionName() === 'history' &&
380                    $feature === static::TOPICSUBSCRIPTION
381                )
382            )
383        ) {
384            return false;
385        }
386
387        $title = $output->getTitle();
388        // Don't show on pages without a Title
389        if ( !$title ) {
390            return false;
391        }
392
393        // Topic subscription is not available on your own talk page, as you will
394        // get 'edit-user-talk' notifications already. (T276996)
395        if (
396            ( $feature === static::TOPICSUBSCRIPTION || $feature === static::AUTOTOPICSUB ) &&
397            $title->equals( $output->getUser()->getTalkPage() )
398        ) {
399            return false;
400        }
401
402        // ?dtenable=1 overrides all user and title checks
403        $queryEnable = $output->getRequest()->getRawVal( 'dtenable' ) ?:
404            // Extra hack for parses from API, where this parameter isn't passed to derivative requests
405            RequestContext::getMain()->getRequest()->getRawVal( 'dtenable' );
406
407        if ( $queryEnable ) {
408            return true;
409        }
410
411        if ( $queryEnable === '0' ) {
412            // ?dtenable=0 forcibly disables the feature regardless of any other checks (T285578)
413            return false;
414        }
415
416        if ( !static::isAvailableForTitle( $title, $feature ) ) {
417            return false;
418        }
419
420        $isMobile = false;
421        if ( ExtensionRegistry::getInstance()->isLoaded( 'MobileFrontend' ) ) {
422            $mobFrontContext = MediaWikiServices::getInstance()->getService( 'MobileFrontend.Context' );
423            $isMobile = $mobFrontContext->shouldDisplayMobileView();
424        }
425        $dtConfig = MediaWikiServices::getInstance()->getConfigFactory()->makeConfig( 'discussiontools' );
426
427        if ( $isMobile ) {
428            return $feature === null ||
429                $feature === static::REPLYTOOL ||
430                $feature === static::NEWTOPICTOOL ||
431                $feature === static::SOURCEMODETOOLBAR ||
432                // Even though mobile ignores user preferences, TOPICSUBSCRIPTION must
433                // still be disabled if the user isn't registered, or
434                // if Echo is disabled
435                (
436                    $feature === static::TOPICSUBSCRIPTION &&
437                    $output->getUser()->isNamed() &&
438                    ExtensionRegistry::getInstance()->isLoaded( 'Echo' )
439                ) ||
440                $feature === static::VISUALENHANCEMENTS;
441        }
442
443        return static::isFeatureEnabledForUser( $output->getUser(), $feature );
444    }
445
446    /**
447     * Check if the "New section" tab would be shown in a normal skin.
448     */
449    public static function shouldShowNewSectionTab( IContextSource $context ): bool {
450        $title = $context->getTitle();
451        $output = $context->getOutput();
452
453        // Match the logic in MediaWiki core (as defined in SkinTemplate::buildContentNavigationUrlsInternal):
454        // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/core/+/add6d0a0e38167a710fb47fac97ff3004451494c/includes/skins/SkinTemplate.php#1317
455        // * __NONEWSECTIONLINK__ is not present (OutputPage::forceHideNewSectionLink) and...
456        //   - This is the current revision of a non-redirect in a talk namespace or...
457        //   - __NEWSECTIONLINK__ is present (OutputPage::showNewSectionLink)
458        return (
459            !static::hasPageProp( $title, 'nonewsectionlink' ) &&
460            ( ( $title->isTalkPage() && !$title->isRedirect() && $output->isRevisionCurrent() ) ||
461                static::hasPageProp( $title, 'newsectionlink' ) )
462        );
463    }
464
465    /**
466     * Check if this page view should open the new topic tool on page load.
467     */
468    public static function shouldOpenNewTopicTool( IContextSource $context ): bool {
469        $req = $context->getRequest();
470        $out = $context->getOutput();
471        $hasPreload = $req->getCheck( 'editintro' ) || $req->getCheck( 'preload' ) ||
472            $req->getCheck( 'preloadparams' ) || $req->getCheck( 'preloadtitle' ) ||
473            // Switching or previewing from an external tool (T316333)
474            $req->getCheck( 'wpTextbox1' );
475
476        return (
477            // ?title=...&action=edit&section=new
478            // ?title=...&veaction=editsource&section=new
479            ( $req->getRawVal( 'action' ) === 'edit' || $req->getRawVal( 'veaction' ) === 'editsource' ) &&
480            $req->getRawVal( 'section' ) === 'new' &&
481            // Handle new topic with preloaded text only when requested (T269310)
482            ( $req->getCheck( 'dtpreload' ) || !$hasPreload ) &&
483            // User has new topic tool enabled (and not using &dtenable=0)
484            static::isFeatureEnabledForOutput( $out, static::NEWTOPICTOOL )
485        );
486    }
487
488    /**
489     * Check if this page view should display the "empty state" message for empty talk pages.
490     */
491    public static function shouldDisplayEmptyState( IContextSource $context ): bool {
492        $req = $context->getRequest();
493        $out = $context->getOutput();
494        $user = $context->getUser();
495        $title = $context->getTitle();
496
497        $optionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
498
499        return (
500            (
501                // When following a red link from another page (but not when clicking the 'Edit' tab)
502                (
503                    $req->getRawVal( 'action' ) === 'edit' && $req->getRawVal( 'redlink' ) === '1' &&
504                    // …if not disabled by the user
505                    $optionsLookup->getOption( $user, 'discussiontools-newtopictool-createpage' )
506                ) ||
507                // When the new topic tool will be opened (usually when clicking the 'Add topic' tab)
508                static::shouldOpenNewTopicTool( $context ) ||
509                // In read mode (accessible for non-existent pages by clicking 'Cancel' in editor)
510                ( $req->getRawVal( 'action' ) ?? 'view' ) === 'view'
511            ) &&
512            // Only in talk namespaces, not including other namespaces that isAvailableForTitle() allows
513            $title->isTalkPage() &&
514            // Only if the subject page or the user exists (T288319, T312560)
515            ( $title->exists() || static::pageSubjectExists( $title ) ) &&
516            // The default display will probably be more useful for links to old revisions of deleted
517            // pages (existing pages are already excluded in shouldShowNewSectionTab())
518            $req->getIntOrNull( 'oldid' ) === null &&
519            // Only if "New section" tab would be shown by the skin.
520            // If the page doesn't exist, this only happens in talk namespaces.
521            // If the page exists, it also considers magic words on the page.
522            static::shouldShowNewSectionTab( $context ) &&
523            // User has new topic tool enabled (and not using &dtenable=0)
524            static::isFeatureEnabledForOutput( $out, static::NEWTOPICTOOL )
525        );
526    }
527
528    /**
529     * Return whether the corresponding subject page exists, or (if the page is a user talk page,
530     * excluding subpages) whether the user is registered or a valid IP address.
531     */
532    private static function pageSubjectExists( LinkTarget $talkPage ): bool {
533        $services = MediaWikiServices::getInstance();
534        $namespaceInfo = $services->getNamespaceInfo();
535        Assert::precondition( $namespaceInfo->isTalk( $talkPage->getNamespace() ), "Page is a talk page" );
536
537        if ( $talkPage->inNamespace( NS_USER_TALK ) && !str_contains( $talkPage->getText(), '/' ) ) {
538            if ( $services->getUserNameUtils()->isIP( $talkPage->getText() ) ) {
539                return true;
540            }
541            $subjectUser = $services->getUserFactory()->newFromName( $talkPage->getText() );
542            if ( $subjectUser && $subjectUser->isRegistered() ) {
543                return true;
544            }
545            return false;
546        } else {
547            $subjectPage = $namespaceInfo->getSubjectPage( $talkPage );
548            return $services->getPageStore()->getPageForLink( $subjectPage )->exists();
549        }
550    }
551
552    /**
553     * Check if we should be adding automatic topic subscriptions for this user on this page.
554     */
555    public static function shouldAddAutoSubscription( UserIdentity $user, Title $title ): bool {
556        // This duplicates the logic from isFeatureEnabledForOutput(),
557        // because we don't have access to the request or the output here.
558
559        // Topic subscription is not available on your own talk page, as you will
560        // get 'edit-user-talk' notifications already. (T276996)
561        // (can't use User::getTalkPage() to check because this is a UserIdentity)
562        if ( $title->inNamespace( NS_USER_TALK ) && $title->getText() === $user->getName() ) {
563            return false;
564        }
565
566        // Users flagged as bots shouldn't be autosubscribed. They can
567        // manually subscribe if it becomes relevant. (T301933)
568        $user = MediaWikiServices::getInstance()
569            ->getUserFactory()
570            ->newFromUserIdentity( $user );
571        if ( $user->isBot() ) {
572            return false;
573        }
574
575        // Check if the user has automatic subscriptions enabled, and the tools are enabled on the page.
576        return static::isAvailableForTitle( $title ) &&
577            static::isFeatureEnabledForUser( $user, static::AUTOTOPICSUB );
578    }
579}