Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
49.86% covered (danger)
49.86%
532 / 1067
44.29% covered (danger)
44.29%
31 / 70
CRAP
0.00% covered (danger)
0.00%
0 / 1
Skin
49.86% covered (danger)
49.86%
532 / 1067
44.29% covered (danger)
44.29%
31 / 70
10234.61
0.00% covered (danger)
0.00%
0 / 1
 getVersion
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getComponent
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getTemplateData
65.96% covered (warning)
65.96%
31 / 47
0.00% covered (danger)
0.00%
0 / 1
13.95
 normalizeKey
50.00% covered (danger)
50.00%
12 / 24
0.00% covered (danger)
0.00%
0 / 1
13.12
 __construct
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
4.01
 getSkinName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isResponsive
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 initPage
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
20
 getDefaultModules
81.25% covered (warning)
81.25%
39 / 48
0.00% covered (danger)
0.00%
0 / 1
16.48
 preloadExistence
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
90
 setRelevantTitle
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRelevantTitle
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setRelevantUser
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRelevantUser
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
11
 outputPage
n/a
0 / 0
n/a
0 / 0
0
 getPageClasses
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
5
 getHtmlElementAttributes
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 getCategoryLinks
16.28% covered (danger)
16.28%
7 / 43
0.00% covered (danger)
0.00%
0 / 1
35.75
 getCategories
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 afterContentHook
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 getCanonicalUrl
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 printSource
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getUndeleteLink
18.18% covered (danger)
18.18%
6 / 33
0.00% covered (danger)
0.00%
0 / 1
43.05
 subPageSubtitleInternal
27.27% covered (danger)
27.27%
9 / 33
0.00% covered (danger)
0.00%
0 / 1
40.16
 getFooterTemplateDataItem
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 getCopyright
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 logoText
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 getFooterIcons
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 makeFooterIcon
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 footerLink
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 editUrlOptions
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 showEmailUser
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 makeMainPageUrl
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 makeSpecialUrl
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 makeSpecialUrlSubpage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 makeInternalOrExternalUrl
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
 makeUrlDetails
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 makeKnownUrlDetails
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 mapInterwikiToLanguage
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getLanguages
15.52% covered (danger)
15.52%
9 / 58
0.00% covered (danger)
0.00%
0 / 1
83.96
 buildNavUrls
37.84% covered (danger)
37.84%
42 / 111
0.00% covered (danger)
0.00%
0 / 1
126.93
 buildFeedUrls
44.44% covered (danger)
44.44%
4 / 9
0.00% covered (danger)
0.00%
0 / 1
4.54
 buildSidebar
100.00% covered (success)
100.00%
36 / 36
100.00% covered (success)
100.00%
1 / 1
4
 addToSidebar
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 addToSidebarPlain
100.00% covered (success)
100.00%
51 / 51
100.00% covered (success)
100.00%
1 / 1
16
 getSidebarIcon
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
7
 hideNewTalkMessagesForCurrentSession
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getNewtalks
2.50% covered (danger)
2.50%
2 / 80
0.00% covered (danger)
0.00%
0 / 1
223.54
 getCachedNotice
32.26% covered (danger)
32.26%
10 / 31
0.00% covered (danger)
0.00%
0 / 1
12.77
 getSiteNotice
78.95% covered (warning)
78.95%
15 / 19
0.00% covered (danger)
0.00%
0 / 1
9.76
 doEditSectionLink
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
6
 doEditSectionLinksHTML
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
 makeToolbox
61.11% covered (warning)
61.11%
22 / 36
0.00% covered (danger)
0.00%
0 / 1
15.88
 getIndicatorsData
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 getPersonalToolsForMakeListItem
96.67% covered (success)
96.67%
29 / 30
0.00% covered (danger)
0.00%
0 / 1
9
 makeLink
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 makeListItem
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 makeSearchInput
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 makeSearchButton
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 getAfterPortlet
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 prepareSubtitle
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 getJsConfigVars
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getUserLanguageAttributes
63.64% covered (warning)
63.64%
7 / 11
0.00% covered (danger)
0.00%
0 / 1
3.43
 prepareUserLanguageAttributes
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 prepareUndeleteLink
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 getAction
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 wrapHTML
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 getOptions
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
1
 supportsMenu
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getPortletLinkOptions
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 getPortletData
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21use MediaWiki\Context\ContextSource;
22use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
23use MediaWiki\Html\Html;
24use MediaWiki\MainConfigNames;
25use MediaWiki\MediaWikiServices;
26use MediaWiki\Output\OutputPage;
27use MediaWiki\Parser\Sanitizer;
28use MediaWiki\ResourceLoader as RL;
29use MediaWiki\Revision\RevisionStore;
30use MediaWiki\Skin\SkinComponent;
31use MediaWiki\Skin\SkinComponentFooter;
32use MediaWiki\Skin\SkinComponentLink;
33use MediaWiki\Skin\SkinComponentListItem;
34use MediaWiki\Skin\SkinComponentMenu;
35use MediaWiki\Skin\SkinComponentRegistry;
36use MediaWiki\Skin\SkinComponentRegistryContext;
37use MediaWiki\Skin\SkinComponentUtils;
38use MediaWiki\SpecialPage\SpecialPage;
39use MediaWiki\Specials\SpecialUserRights;
40use MediaWiki\Title\Title;
41use MediaWiki\User\User;
42use MediaWiki\User\UserIdentity;
43use MediaWiki\User\UserIdentityValue;
44use MediaWiki\WikiMap\WikiMap;
45
46/**
47 * @defgroup Skins Skins
48 */
49
50/**
51 * The base class for all skins.
52 *
53 * See docs/Skin.md for more information.
54 *
55 * @stable to extend
56 * @ingroup Skins
57 */
58abstract class Skin extends ContextSource {
59    use ProtectedHookAccessorTrait;
60
61    /**
62     * @var array link options used in Skin::makeLink. Can be set by skin option `link`.
63     */
64    private $defaultLinkOptions;
65
66    /**
67     * @var string|null
68     */
69    protected $skinname = null;
70
71    /**
72     * @var array Skin options passed into constructor
73     */
74    protected $options = [];
75    protected $mRelevantTitle = null;
76
77    /**
78     * @var UserIdentity|null|false
79     */
80    private $mRelevantUser = false;
81
82    /** The current major version of the skin specification. */
83    protected const VERSION_MAJOR = 1;
84
85    /** @var array|null Cache for getLanguages() */
86    private $languageLinks;
87
88    /** @var array|null Cache for buildSidebar() */
89    private $sidebar;
90
91    /**
92     * @var SkinComponentRegistry Initialised in constructor.
93     */
94    private $componentRegistry = null;
95
96    /**
97     * Get the current major version of Skin. This is used to manage changes
98     * to underlying data and for providing support for older and new versions of code.
99     *
100     * @since 1.36
101     * @return int
102     */
103    public static function getVersion() {
104        return self::VERSION_MAJOR;
105    }
106
107    /**
108     * @internal use in Skin.php, SkinTemplate.php or SkinMustache.php
109     * @param string $name
110     * @return SkinComponent
111     */
112    final protected function getComponent( string $name ): SkinComponent {
113        return $this->componentRegistry->getComponent( $name );
114    }
115
116    /**
117     * @stable to extend. Subclasses may extend this method to add additional
118     * template data.
119     * @internal this method should never be called outside Skin and its subclasses
120     * as it can be computationally expensive and typically has side effects on the Skin
121     * instance, through execution of hooks.
122     *
123     * The data keys should be valid English words. Compound words should
124     * be hyphenated except if they are normally written as one word. Each
125     * key should be prefixed with a type hint, this may be enforced by the
126     * class PHPUnit test.
127     *
128     * Plain strings are prefixed with 'html-', plain arrays with 'array-'
129     * and complex array data with 'data-'. 'is-' and 'has-' prefixes can
130     * be used for boolean variables.
131     * Messages are prefixed with 'msg-', followed by their message key.
132     * All messages specified in the skin option 'messages' will be available
133     * under 'msg-MESSAGE-NAME'.
134     *
135     * @return array Data for a mustache template
136     */
137    public function getTemplateData() {
138        $title = $this->getTitle();
139        $out = $this->getOutput();
140        $user = $this->getUser();
141        $isMainPage = $title->isMainPage();
142        $blankedHeading = false;
143        // Heading can only be blanked on "views". It should
144        // still show on action=edit, diff pages and action=history
145        $isHeadingOverridable = $this->getContext()->getActionName() === 'view' &&
146            !$this->getRequest()->getRawVal( 'diff' );
147
148        if ( $isMainPage && $isHeadingOverridable ) {
149            // Special casing for the main page to allow more freedom to editors, to
150            // design their home page differently. This came up in T290480.
151            // The parameter for logged in users is optional and may
152            // or may not be used.
153            $titleMsg = $user->isAnon() ?
154                $this->msg( 'mainpage-title' ) :
155                $this->msg( 'mainpage-title-loggedin', $user->getName() );
156
157            // T298715: Use content language rather than user language so that
158            // the custom page heading is shown to all users, not just those that have
159            // their interface set to the site content language.
160            //
161            // T331095: Avoid Message::inContentLanuguage and, just like Parser,
162            // pick the language variant based on the current URL and/or user
163            // preference if their variant relates to the content language.
164            $forceUIMsgAsContentMsg = $this->getConfig()
165                ->get( MainConfigNames::ForceUIMsgAsContentMsg );
166            if ( !in_array( $titleMsg->getKey(), (array)$forceUIMsgAsContentMsg ) ) {
167                $services = MediaWikiServices::getInstance();
168                $contLangVariant = $services->getLanguageConverterFactory()
169                    ->getLanguageConverter( $services->getContentLanguage() )
170                    ->getPreferredVariant();
171                $titleMsg->inLanguage( $contLangVariant );
172            }
173            $titleMsg->setInterfaceMessageFlag( true );
174            $blankedHeading = $titleMsg->isBlank();
175            if ( !$titleMsg->isDisabled() ) {
176                $htmlTitle = $titleMsg->parse();
177            } else {
178                $htmlTitle = $out->getPageTitle();
179            }
180        } else {
181            $htmlTitle = $out->getPageTitle();
182        }
183
184        $data = [
185            // raw HTML
186            'html-title-heading' => Html::rawElement(
187                'h1',
188                [
189                    'id' => 'firstHeading',
190                    'class' => 'firstHeading mw-first-heading',
191                    'style' => $blankedHeading ? 'display: none' : null
192                ] + $this->getUserLanguageAttributes(),
193                $htmlTitle
194            ),
195            'html-title' => $htmlTitle ?: null,
196            // Boolean values
197            'is-title-blank' => $blankedHeading, // @since 1.38
198            'is-anon' => $user->isAnon(),
199            'is-article' => $out->isArticle(),
200            'is-mainpage' => $isMainPage,
201            'is-specialpage' => $title->isSpecialPage(),
202            'canonical-url' => $this->getCanonicalUrl(),
203        ];
204
205        $components = $this->componentRegistry->getComponents();
206        foreach ( $components as $componentName => $component ) {
207            $data['data-' . $componentName] = $component->getTemplateData();
208        }
209        return $data;
210    }
211
212    /**
213     * Normalize a skin preference value to a form that can be loaded.
214     *
215     * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
216     * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
217     *
218     * @param string $key 'monobook', 'vector', etc.
219     * @return string
220     */
221    public static function normalizeKey( string $key ) {
222        $config = MediaWikiServices::getInstance()->getMainConfig();
223        $defaultSkin = $config->get( MainConfigNames::DefaultSkin );
224        $fallbackSkin = $config->get( MainConfigNames::FallbackSkin );
225        $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
226        $skinNames = $skinFactory->getInstalledSkins();
227
228        // Make keys lowercase for case-insensitive matching.
229        $skinNames = array_change_key_case( $skinNames, CASE_LOWER );
230        $key = strtolower( $key );
231        $defaultSkin = strtolower( $defaultSkin );
232        $fallbackSkin = strtolower( $fallbackSkin );
233
234        if ( $key == '' || $key == 'default' ) {
235            // Don't return the default immediately;
236            // in a misconfiguration we need to fall back.
237            $key = $defaultSkin;
238        }
239
240        if ( isset( $skinNames[$key] ) ) {
241            return $key;
242        }
243
244        // Older versions of the software used a numeric setting
245        // in the user preferences.
246        $fallback = [
247            0 => $defaultSkin,
248            2 => 'cologneblue'
249        ];
250
251        if ( isset( $fallback[$key] ) ) {
252            // @phan-suppress-next-line PhanTypeMismatchDimFetch False positive
253            $key = $fallback[$key];
254        }
255
256        if ( isset( $skinNames[$key] ) ) {
257            return $key;
258        } elseif ( isset( $skinNames[$defaultSkin] ) ) {
259            return $defaultSkin;
260        } else {
261            return $fallbackSkin;
262        }
263    }
264
265    /**
266     * @since 1.31
267     * @param string|array|null $options Options for the skin can be an array (since 1.35).
268     *  When a string is passed, it's the skinname.
269     *  When an array is passed:
270     *
271     *  - `name`: Required. Internal skin name, generally in lowercase to comply with conventions
272     *     for interface message keys and CSS class names which embed this value.
273     *
274     *  - `styles`: ResourceLoader style modules to load on all pages. Default: `[]`
275     *
276     *  - `scripts`: ResourceLoader script modules to load on all pages. Default: `[]`
277     *
278     *  - `toc`: Whether a table of contents is included in the main article content
279     *     area. If your skin has place a table of contents elsewhere (for example, the sidebar),
280     *     set this to `false`.
281     *
282     *     See ParserOutput::getText() for the implementation logic.
283     *
284     *     Default: `true`
285     *
286     *  - `bodyClasses`: An array of extra class names to add to the HTML `<body>` element.
287     *     Default: `[]`
288     *
289     *  - `bodyOnly`: Whether the skin is takes control of generating the `<html>`, `<head>` and
290     *    `<body>` elements. This is for SkinTemplate subclasses only. For SkinMustache, this is
291     *     always true and ignored.
292     *
293     *     Default: `false`
294     *
295     *  - `clientPrefEnabled`: Enable support for mw.user.clientPrefs.
296     *     This instructs OutputPage and ResourceLoader\ClientHtml to include an inline script
297     *     in web responses for unregistered users to switch HTML classes as needed.
298     *
299     *     Since: MW 1.41
300     *     Default: `false`
301     *
302     *  - `responsive`: Whether the skin supports responsive behaviour and wants a viewport meta
303     *     tag to be added to the HTML head. Note, users can disable this feature via a user
304     *     preference.
305     *
306     *     Default: `false`
307     *
308     *  - `link`: An array of link option overriddes. See Skin::makeLink for the available options.
309     *
310     *     Default: `[]`
311     *
312     *  - `tempUserBanner`: Whether to display a banner on page views by in temporary user sessions.
313     *     This will prepend SkinComponentTempUserBanner to the `<body>` above everything else.
314     *     See also MediaWiki\MainConfigSchema::AutoCreateTempUser and User::isTemp.
315     *
316     *     Default: `false`
317     *
318     *  - `menus`: Which menus the skin supports, to allow features like SpecialWatchlist
319     *     and SpecialContribute to render their own navigation in the skins that don't
320     *     support certain menus.
321     *
322     *     Default: `['namespaces', 'views', 'actions', 'variants']`
323     *
324     *     Opt-in menus:
325     *     - `associated-page`
326     *     - `notification`
327     *     - `user-interface-preferences`
328     *     - `user-page`
329     *     - `user-menu`
330     */
331    public function __construct( $options = null ) {
332        if ( is_string( $options ) ) {
333            $this->skinname = $options;
334        } elseif ( $options ) {
335            $name = $options['name'] ?? null;
336
337            if ( !$name ) {
338                throw new SkinException( 'Skin name must be specified' );
339            }
340
341            // Defaults are set in Skin::getOptions()
342            $this->options = $options;
343            $this->skinname = $name;
344        }
345        $this->defaultLinkOptions = $this->getOptions()['link'];
346        $this->componentRegistry = new SkinComponentRegistry(
347            new SkinComponentRegistryContext( $this )
348        );
349    }
350
351    /**
352     * @return string|null Skin name
353     */
354    public function getSkinName() {
355        return $this->skinname;
356    }
357
358    /**
359     * Indicates if this skin is responsive.
360     * Responsive skins have skin--responsive added to <body> by OutputPage,
361     * and a viewport <meta> tag set by Skin::initPage.
362     *
363     * @since 1.36
364     * @stable to override
365     * @return bool
366     */
367    public function isResponsive() {
368        $isSkinResponsiveCapable = $this->getOptions()['responsive'];
369        $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
370
371        return $isSkinResponsiveCapable &&
372            $userOptionsLookup->getBoolOption( $this->getUser(), 'skin-responsive' );
373    }
374
375    /**
376     * @stable to override
377     * @param OutputPage $out
378     */
379    public function initPage( OutputPage $out ) {
380        $skinMetaTags = $this->getConfig()->get( MainConfigNames::SkinMetaTags );
381        $siteName = $this->getConfig()->get( MainConfigNames::Sitename );
382        $this->preloadExistence();
383
384        if ( $this->isResponsive() ) {
385            $out->addMeta(
386                'viewport',
387                'width=device-width, initial-scale=1.0, ' .
388                'user-scalable=yes, minimum-scale=0.25, maximum-scale=5.0'
389            );
390        } else {
391            // Width is based on the value of @width-breakpoint-desktop
392            // This is as @width-breakpoint-desktop-wide usually tends to optimize
393            // for larger screens with max-widths and margins.
394            // The initial-scale SHOULD NOT be set here as defining it will impact zoom
395            // on mobile devices. To allow font-size adjustment in iOS devices (see T311795)
396            // we will define a zoom in JavaScript on certain devices (see resources/src/mediawiki.page.ready/ready.js)
397            $out->addMeta(
398                'viewport',
399                'width=1000'
400            );
401        }
402
403        $tags = [
404            'og:site_name' => $siteName,
405            'og:title' => $out->getHTMLTitle(),
406            'twitter:card' => 'summary_large_image',
407            'og:type' => 'website',
408        ];
409
410        // Support sharing on platforms such as Facebook and Twitter
411        foreach ( $tags as $key => $value ) {
412            if ( in_array( $key, $skinMetaTags ) ) {
413                $out->addMeta( $key, $value );
414            }
415        }
416    }
417
418    /**
419     * Defines the ResourceLoader modules that should be added to the skin
420     * It is recommended that skins wishing to override call parent::getDefaultModules()
421     * and substitute out any modules they wish to change by using a key to look them up
422     *
423     * Any modules defined with the 'styles' key will be added as render blocking CSS via
424     * Output::addModuleStyles. Similarly, each key should refer to a list of modules
425     *
426     * @stable to override
427     * @return array Array of modules with helper keys for easy overriding
428     */
429    public function getDefaultModules() {
430        $out = $this->getOutput();
431        $user = $this->getUser();
432
433        // Modules declared in the $modules literal are loaded
434        // for ALL users, on ALL pages, in ALL skins.
435        // Keep this list as small as possible!
436        $modules = [
437            // The 'styles' key sets render-blocking style modules
438            // Unlike other keys in $modules, this is an associative array
439            // where each key is its own group pointing to a list of modules
440            'styles' => [
441                'skin' => $this->getOptions()['styles'],
442                'core' => [],
443                'content' => [],
444                'syndicate' => [],
445                'user' => []
446            ],
447            'core' => [
448                'site',
449                'mediawiki.page.ready',
450            ],
451            // modules that enhance the content in some way
452            'content' => [],
453            // modules relating to search functionality
454            'search' => [],
455            // Skins can register their own scripts
456            'skin' => $this->getOptions()['scripts'],
457            // modules relating to functionality relating to watching an article
458            'watch' => [],
459            // modules which relate to the current users preferences
460            'user' => [],
461            // modules relating to RSS/Atom Feeds
462            'syndicate' => [],
463        ];
464
465        // Preload jquery.tablesorter for mediawiki.page.ready
466        if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
467            $modules['content'][] = 'jquery.tablesorter';
468            $modules['styles']['content'][] = 'jquery.tablesorter.styles';
469        }
470
471        // Preload jquery.makeCollapsible for mediawiki.page.ready
472        if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
473            $modules['content'][] = 'jquery.makeCollapsible';
474            $modules['styles']['content'][] = 'jquery.makeCollapsible.styles';
475        }
476
477        // Load relevant styles on wiki pages that use mw-ui-button.
478        // Since 1.26, this no longer loads unconditionally. Special pages
479        // and extensions should load this via addModuleStyles() instead.
480        if ( strpos( $out->getHTML(), 'mw-ui-button' ) !== false ) {
481            $modules['styles']['content'][] = 'mediawiki.ui.button';
482        }
483
484        if ( $out->isTOCEnabled() ) {
485            $modules['content'][] = 'mediawiki.toc';
486        }
487
488        $authority = $this->getAuthority();
489        if ( $authority->getUser()->isRegistered()
490            && $authority->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
491            && $this->getRelevantTitle()->canExist()
492        ) {
493            $modules['watch'][] = 'mediawiki.page.watch.ajax';
494        }
495
496        $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
497        if ( $userOptionsLookup->getBoolOption( $user, 'editsectiononrightclick' )
498            || ( $out->isArticle() && $userOptionsLookup->getOption( $user, 'editondblclick' ) )
499        ) {
500            $modules['user'][] = 'mediawiki.misc-authed-pref';
501        }
502
503        if ( $out->isSyndicated() ) {
504            $modules['styles']['syndicate'][] = 'mediawiki.feedlink';
505        }
506
507        if ( $user->isTemp() ) {
508            $modules['user'][] = 'mediawiki.tempUserBanner';
509            $modules['styles']['user'][] = 'mediawiki.tempUserBanner.styles';
510        }
511
512        if ( $this->getTitle() && $this->getTitle()->getNamespace() === NS_FILE ) {
513            $modules['styles']['core'][] = 'filepage'; // local Filepage.css, T31277, T356505
514        }
515
516        return $modules;
517    }
518
519    /**
520     * Preload the existence of three commonly-requested pages in a single query
521     */
522    private function preloadExistence() {
523        $titles = [];
524
525        // User/talk link
526        $user = $this->getUser();
527        if ( $user->isRegistered() ) {
528            $titles[] = $user->getUserPage();
529            $titles[] = $user->getTalkPage();
530        }
531
532        // Check, if the page can hold some kind of content, otherwise do nothing
533        $title = $this->getRelevantTitle();
534        if ( $title->canExist() && $title->canHaveTalkPage() ) {
535            $namespaceInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
536            if ( $title->isTalkPage() ) {
537                $titles[] = $namespaceInfo->getSubjectPage( $title );
538            } else {
539                $titles[] = $namespaceInfo->getTalkPage( $title );
540            }
541        }
542
543        // Preload for self::getCategoryLinks
544        $allCats = $this->getOutput()->getCategoryLinks();
545        if ( isset( $allCats['normal'] ) && $allCats['normal'] !== [] ) {
546            $catLink = Title::newFromText( $this->msg( 'pagecategorieslink' )->inContentLanguage()->text() );
547            if ( $catLink ) {
548                // If this is a special page, the LinkBatch would skip it
549                $titles[] = $catLink;
550            }
551        }
552
553        $this->getHookRunner()->onSkinPreloadExistence( $titles, $this );
554
555        if ( $titles ) {
556            $linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
557            $lb = $linkBatchFactory->newLinkBatch( $titles );
558            $lb->setCaller( __METHOD__ );
559            $lb->execute();
560        }
561    }
562
563    /**
564     * @see self::getRelevantTitle()
565     * @param Title $t
566     */
567    public function setRelevantTitle( $t ) {
568        $this->mRelevantTitle = $t;
569    }
570
571    /**
572     * Return the "relevant" title.
573     * A "relevant" title is not necessarily the actual title of the page.
574     * Special pages like Special:MovePage use set the page they are acting on
575     * as their "relevant" title, this allows the skin system to display things
576     * such as content tabs which belong to that page instead of displaying
577     * a basic special page tab which has almost no meaning.
578     *
579     * @return Title|null the title is null when no relevant title was set, as this
580     *   falls back to ContextSource::getTitle
581     */
582    public function getRelevantTitle() {
583        return $this->mRelevantTitle ?? $this->getTitle();
584    }
585
586    /**
587     * @see self::getRelevantUser()
588     * @param UserIdentity|null $u
589     */
590    public function setRelevantUser( ?UserIdentity $u ) {
591        $this->mRelevantUser = $u;
592    }
593
594    /**
595     * Return the "relevant" user.
596     * A "relevant" user is similar to a relevant title. Special pages like
597     * Special:Contributions mark the user which they are relevant to so that
598     * things like the toolbox can display the information they usually are only
599     * able to display on a user's userpage and talkpage.
600     *
601     * @return UserIdentity|null Null if there's no relevant user or the viewer cannot view it.
602     */
603    public function getRelevantUser(): ?UserIdentity {
604        if ( $this->mRelevantUser === false ) {
605            $this->mRelevantUser = null; // false indicates we never attempted to load it.
606            $title = $this->getRelevantTitle();
607            if ( $title->hasSubjectNamespace( NS_USER ) ) {
608                $services = MediaWikiServices::getInstance();
609                $rootUser = $title->getRootText();
610                $userNameUtils = $services->getUserNameUtils();
611                if ( $userNameUtils->isIP( $rootUser ) ) {
612                    $this->mRelevantUser = UserIdentityValue::newAnonymous( $rootUser );
613                } else {
614                    $user = $services->getUserIdentityLookup()->getUserIdentityByName( $rootUser );
615                    $this->mRelevantUser = $user && $user->isRegistered() ? $user : null;
616                }
617            }
618        }
619
620        // The relevant user should only be set if it exists. However, if it exists but is hidden,
621        // and the viewer cannot see hidden users, this exposes the fact that the user exists;
622        // pretend like the user does not exist in such cases, by setting it to null. T120883
623        if ( $this->mRelevantUser && $this->mRelevantUser->isRegistered() ) {
624            $userBlock = MediaWikiServices::getInstance()
625                ->getBlockManager()
626                ->getBlock( $this->mRelevantUser, null );
627            if ( $userBlock && $userBlock->getHideName() &&
628                !$this->getAuthority()->isAllowed( 'hideuser' )
629            ) {
630                $this->mRelevantUser = null;
631            }
632        }
633
634        return $this->mRelevantUser;
635    }
636
637    /**
638     * Outputs the HTML generated by other functions.
639     */
640    abstract public function outputPage();
641
642    /**
643     * TODO: document
644     * @param Title $title
645     * @return string
646     */
647    public function getPageClasses( $title ) {
648        $services = MediaWikiServices::getInstance();
649        $ns = $title->getNamespace();
650        $numeric = 'ns-' . $ns;
651
652        if ( $title->isSpecialPage() ) {
653            $type = 'ns-special';
654            // T25315: provide a class based on the canonical special page name without subpages
655            [ $canonicalName ] = $services->getSpecialPageFactory()->resolveAlias( $title->getDBkey() );
656            if ( $canonicalName ) {
657                $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" );
658            } else {
659                $type .= ' mw-invalidspecialpage';
660            }
661        } else {
662            if ( $title->isTalkPage() ) {
663                $type = 'ns-talk';
664            } else {
665                $type = 'ns-subject';
666            }
667            // T208315: add HTML class when the user can edit the page
668            if ( $this->getAuthority()->probablyCan( 'edit', $title ) ) {
669                $type .= ' mw-editable';
670            }
671        }
672
673        $titleFormatter = $services->getTitleFormatter();
674        $name = Sanitizer::escapeClass( 'page-' . $titleFormatter->getPrefixedText( $title ) );
675        $root = Sanitizer::escapeClass( 'rootpage-' . $titleFormatter->formatTitle( $ns, $title->getRootText() ) );
676
677        return "$numeric $type $name $root";
678    }
679
680    /**
681     * Return values for <html> element
682     * @return array Array of associative name-to-value elements for <html> element
683     */
684    public function getHtmlElementAttributes() {
685        $lang = $this->getLanguage();
686        return [
687            'lang' => $lang->getHtmlCode(),
688            'dir' => $lang->getDir(),
689            'class' => 'client-nojs',
690        ];
691    }
692
693    /**
694     * @return string HTML
695     */
696    public function getCategoryLinks() {
697        $out = $this->getOutput();
698        $allCats = $out->getCategoryLinks();
699        $title = $this->getTitle();
700        $services = MediaWikiServices::getInstance();
701        $linkRenderer = $services->getLinkRenderer();
702
703        if ( $allCats === [] ) {
704            return '';
705        }
706
707        $embed = "<li>";
708        $pop = "</li>";
709
710        $s = '';
711        $colon = $this->msg( 'colon-separator' )->escaped();
712
713        if ( !empty( $allCats['normal'] ) ) {
714            $t = $embed . implode( $pop . $embed, $allCats['normal'] ) . $pop;
715
716            $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) );
717            $linkPage = $this->msg( 'pagecategorieslink' )->inContentLanguage()->text();
718            $pageCategoriesLinkTitle = Title::newFromText( $linkPage );
719            if ( $pageCategoriesLinkTitle ) {
720                $link = $linkRenderer->makeLink( $pageCategoriesLinkTitle, $msg->text() );
721            } else {
722                $link = $msg->escaped();
723            }
724            $s .= Html::rawElement(
725                'div',
726                [ 'id' => 'mw-normal-catlinks', 'class' => 'mw-normal-catlinks' ],
727                $link . $colon . Html::rawElement( 'ul', [], $t )
728            );
729        }
730
731        # Hidden categories
732        if ( isset( $allCats['hidden'] ) ) {
733            $userOptionsLookup = $services->getUserOptionsLookup();
734
735            if ( $userOptionsLookup->getBoolOption( $this->getUser(), 'showhiddencats' ) ) {
736                $class = ' mw-hidden-cats-user-shown';
737            } elseif ( $title->inNamespace( NS_CATEGORY ) ) {
738                $class = ' mw-hidden-cats-ns-shown';
739            } else {
740                $class = ' mw-hidden-cats-hidden';
741            }
742
743            $s .= Html::rawElement(
744                'div',
745                [ 'id' => 'mw-hidden-catlinks', 'class' => "mw-hidden-catlinks$class" ],
746                $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
747                    $colon .
748                    Html::rawElement(
749                        'ul',
750                        [],
751                        $embed . implode( $pop . $embed, $allCats['hidden'] ) . $pop
752                    )
753            );
754        }
755
756        return $s;
757    }
758
759    /**
760     * @return string HTML
761     */
762    public function getCategories() {
763        $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
764        $showHiddenCats = $userOptionsLookup->getBoolOption( $this->getUser(), 'showhiddencats' );
765
766        $catlinks = $this->getCategoryLinks();
767        // Check what we're showing
768        $allCats = $this->getOutput()->getCategoryLinks();
769        $showHidden = $showHiddenCats || $this->getTitle()->inNamespace( NS_CATEGORY );
770
771        $classes = [ 'catlinks' ];
772        if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
773            $classes[] = 'catlinks-allhidden';
774        }
775
776        return Html::rawElement(
777            'div',
778            [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
779            $catlinks
780        );
781    }
782
783    /**
784     * This runs a hook to allow extensions placing their stuff after content
785     * and article metadata (e.g. categories).
786     * Note: This function has nothing to do with afterContent().
787     *
788     * This hook is placed here in order to allow using the same hook for all
789     * skins, both the SkinTemplate based ones and the older ones, which directly
790     * use this class to get their data.
791     *
792     * The output of this function gets processed in SkinTemplate::outputPage() for
793     * the SkinTemplate based skins, all other skins should directly echo it.
794     *
795     * @return string Empty by default, if not changed by any hook function.
796     */
797    protected function afterContentHook() {
798        $data = '';
799
800        if ( $this->getHookRunner()->onSkinAfterContent( $data, $this ) ) {
801            // adding just some spaces shouldn't toggle the output
802            // of the whole <div/>, so we use trim() here
803            if ( trim( $data ) != '' ) {
804                // Doing this here instead of in the skins to
805                // ensure that the div has the same ID in all
806                // skins
807                $data = "<div id='mw-data-after-content'>\n" .
808                    "\t$data\n" .
809                    "</div>\n";
810            }
811        } else {
812            wfDebug( "Hook SkinAfterContent changed output processing." );
813        }
814
815        return $data;
816    }
817
818    /**
819     * Get the canonical URL (permalink) for the page including oldid if present.
820     *
821     * @return string
822     */
823    private function getCanonicalUrl() {
824        $title = $this->getTitle();
825        $oldid = $this->getOutput()->getRevisionId();
826        if ( $oldid ) {
827            return $title->getCanonicalURL( 'oldid=' . $oldid );
828        } else {
829            // oldid not available for non existing pages
830            return $title->getCanonicalURL();
831        }
832    }
833
834    /**
835     * Text with the permalink to the source page,
836     * usually shown on the footer of a printed page
837     *
838     * @stable to override
839     * @return string HTML text with an URL
840     */
841    public function printSource() {
842        $url = htmlspecialchars( wfExpandIRI( $this->getCanonicalUrl() ) );
843
844        return $this->msg( 'retrievedfrom' )
845            ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
846            ->parse();
847    }
848
849    /**
850     * @return string HTML
851     */
852    public function getUndeleteLink() {
853        $action = $this->getRequest()->getRawVal( 'action', 'view' );
854        $title = $this->getTitle();
855        $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
856
857        if ( ( !$title->exists() || $action == 'history' ) &&
858            $this->getAuthority()->probablyCan( 'deletedhistory', $title )
859        ) {
860            $n = $title->getDeletedEditsCount();
861
862            if ( $n ) {
863                if ( $this->getAuthority()->probablyCan( 'undelete', $title ) ) {
864                    $msg = 'thisisdeleted';
865                } else {
866                    $msg = 'viewdeleted';
867                }
868
869                $subtitle = $this->msg( $msg )->rawParams(
870                    $linkRenderer->makeKnownLink(
871                        SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedDBkey() ),
872                        $this->msg( 'restorelink' )->numParams( $n )->text() )
873                    )->escaped();
874
875                $links = [];
876                // Add link to page logs, unless we're on the history page (which
877                // already has one)
878                if ( $action !== 'history' ) {
879                    $links[] = $linkRenderer->makeKnownLink(
880                        SpecialPage::getTitleFor( 'Log' ),
881                        $this->msg( 'viewpagelogs-lowercase' )->text(),
882                        [],
883                        [ 'page' => $title->getPrefixedText() ]
884                    );
885                }
886
887                // Allow extensions to add more links
888                $this->getHookRunner()->onUndeletePageToolLinks(
889                    $this->getContext(), $linkRenderer, $links );
890
891                if ( $links ) {
892                    $subtitle .= ''
893                        . $this->msg( 'word-separator' )->escaped()
894                        . $this->msg( 'parentheses' )
895                            ->rawParams( $this->getLanguage()->pipeList( $links ) )
896                            ->escaped();
897                }
898
899                return Html::rawElement( 'div', [ 'class' => 'mw-undelete-subtitle' ], $subtitle );
900            }
901        }
902
903        return '';
904    }
905
906    /**
907     * @return string
908     */
909    private function subPageSubtitleInternal() {
910        $services = MediaWikiServices::getInstance();
911        $linkRenderer = $services->getLinkRenderer();
912        $out = $this->getOutput();
913        $title = $out->getTitle();
914        $subpages = '';
915
916        if ( !$this->getHookRunner()->onSkinSubPageSubtitle( $subpages, $this, $out ) ) {
917            return $subpages;
918        }
919
920        $hasSubpages = $services->getNamespaceInfo()->hasSubpages( $title->getNamespace() );
921        if ( !$out->isArticle() || !$hasSubpages ) {
922            return $subpages;
923        }
924
925        $ptext = $title->getPrefixedText();
926        if ( strpos( $ptext, '/' ) !== false ) {
927            $links = explode( '/', $ptext );
928            array_pop( $links );
929            $count = 0;
930            $growingLink = '';
931            $display = '';
932            $lang = $this->getLanguage();
933
934            foreach ( $links as $link ) {
935                $growingLink .= $link;
936                $display .= $link;
937                $linkObj = Title::newFromText( $growingLink );
938
939                if ( $linkObj && $linkObj->isKnown() ) {
940                    $getlink = $linkRenderer->makeKnownLink( $linkObj, $display );
941
942                    $count++;
943
944                    if ( $count > 1 ) {
945                        $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
946                    } else {
947                        $subpages .= '&lt; ';
948                    }
949
950                    $subpages .= $getlink;
951                    $display = '';
952                } else {
953                    $display .= '/';
954                }
955                $growingLink .= '/';
956            }
957        }
958
959        return $subpages;
960    }
961
962    /**
963     * Helper function for mapping template data for use in legacy function
964     *
965     * @param string $dataKey
966     * @param string $name
967     * @return string
968     */
969    private function getFooterTemplateDataItem( string $dataKey, string $name ) {
970        $footerData = $this->getComponent( 'footer' )->getTemplateData();
971        $items = $footerData[ $dataKey ]['array-items'] ?? [];
972        foreach ( $items as $item ) {
973            if ( $item['name'] === $name ) {
974                return $item['html'];
975            }
976        }
977        return '';
978    }
979
980    /**
981     * @param string $type
982     * @return string
983     */
984    final public function getCopyright( $type = 'detect' ) {
985        if ( $type !== 'detect' ) {
986            wfDeprecated( __METHOD__ . ' with detect parameter', '1.40' );
987        }
988        return $this->getFooterTemplateDataItem( 'data-info', 'copyright' );
989    }
990
991    /**
992     * @param string $align
993     * @return string
994     */
995    public function logoText( $align = '' ) {
996        if ( $align != '' ) {
997            $a = " style='float: {$align};'";
998        } else {
999            $a = '';
1000        }
1001
1002        $mp = $this->msg( 'mainpage' )->escaped();
1003        $url = htmlspecialchars( Title::newMainPage()->getLocalURL() );
1004
1005        $logourl = RL\SkinModule::getAvailableLogos( $this->getConfig() )[ '1x' ];
1006        return "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
1007    }
1008
1009    /**
1010     * Get template representation of the footer.
1011     *
1012     * Stable to use since 1.40 but should not be overridden.
1013     *
1014     * @since 1.35
1015     * @internal for use inside SkinComponentRegistryContext
1016     * @return array
1017     */
1018    public function getFooterIcons() {
1019        MWDebug::detectDeprecatedOverride( $this, __CLASS__, 'getFooterIcons', '1.40' );
1020        return SkinComponentFooter::getFooterIconsData(
1021            $this->getConfig()
1022        );
1023    }
1024
1025    /**
1026     * Renders a $wgFooterIcons icon according to the method's arguments
1027     *
1028     * Stable to use since 1.40 but should not be overridden.
1029     *
1030     * @param array $icon The icon to build the html for, see $wgFooterIcons
1031     *   for the format of this array.
1032     * @param bool|string $withImage Whether to use the icon's image or output
1033     *   a text-only footericon.
1034     * @return string HTML
1035     */
1036    public function makeFooterIcon( $icon, $withImage = 'withImage' ) {
1037        MWDebug::detectDeprecatedOverride( $this, __CLASS__, 'makeFooterIcon', '1.40' );
1038        return SkinComponentFooter::makeFooterIconHTML(
1039            $this->getConfig(), $icon, $withImage
1040        );
1041    }
1042
1043    /**
1044     * Given a pair of message keys for link and text label,
1045     * return an HTML link for use in the footer.
1046     *
1047     * @param string $desc The i18n message key for the link text.
1048     *         The content of this message will be the visible text label.
1049     *         If this is set to nonexisting message key or the message is
1050     *         disabled, the link will not be generated, empty string will
1051     *         be returned in the stead.
1052     * @param string $page The i18n message key for the page to link to.
1053     *         The content of this message will be the destination page for
1054     *         the footer link. Given a message key 'Privacypage' with content
1055     *         'Project:Privacy policy', the link will lead to the wiki page with
1056     *         the title of the content.
1057     *
1058     * @return string HTML anchor
1059     * @deprecated since 1.40
1060     */
1061    public function footerLink( $desc, $page ) {
1062        wfDeprecated( __METHOD__, '1.40' );
1063
1064        // If the link description has been disabled in the default language,
1065        if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
1066            // then it is disabled, for all languages.
1067            $title = null;
1068        } else {
1069            // Otherwise, we display the link for the user, described in their
1070            // language (which may or may not be the same as the default language),
1071            // but we make the link target be the one site-wide page.
1072            $title = Title::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1073        }
1074
1075        if ( !$title ) {
1076            return '';
1077        }
1078
1079        // Similar to Skin::addToSidebarPlain
1080        // Optimization: Avoid LinkRenderer here as it requires extra DB info
1081        // to add unneeded classes even for makeKnownLink (T313462).
1082        return Html::element( 'a',
1083            [ 'href' => $title->fixSpecialName()->getLinkURL() ],
1084            $this->msg( $desc )->text()
1085        );
1086    }
1087
1088    /**
1089     * Return URL options for the 'edit page' link.
1090     * This may include an 'oldid' specifier, if the current page view is such.
1091     *
1092     * @return array
1093     * @internal
1094     */
1095    public function editUrlOptions() {
1096        $options = [ 'action' => 'edit' ];
1097        $out = $this->getOutput();
1098
1099        if ( !$out->isRevisionCurrent() ) {
1100            $options['oldid'] = intval( $out->getRevisionId() );
1101        }
1102
1103        return $options;
1104    }
1105
1106    /**
1107     * @param UserIdentity|int $id
1108     * @return bool
1109     */
1110    public function showEmailUser( $id ) {
1111        if ( $id instanceof UserIdentity ) {
1112            $targetUser = User::newFromIdentity( $id );
1113        } else {
1114            $targetUser = User::newFromId( $id );
1115        }
1116
1117        # The sending user must have a confirmed email address and the receiving
1118        # user must accept emails from the sender.
1119        $emailUser = MediaWikiServices::getInstance()->getEmailUserFactory()
1120            ->newEmailUser( $this->getUser() );
1121
1122        return $emailUser->canSend()->isOK()
1123            && $emailUser->validateTarget( $targetUser )->isOK();
1124    }
1125
1126    /* these are used extensively in SkinTemplate, but also some other places */
1127
1128    /**
1129     * @param string|array $urlaction
1130     * @return string
1131     */
1132    public static function makeMainPageUrl( $urlaction = '' ) {
1133        $title = Title::newMainPage();
1134
1135        return $title->getLinkURL( $urlaction );
1136    }
1137
1138    /**
1139     * Make a URL for a Special Page using the given query and protocol.
1140     *
1141     * If $proto is set to null, make a local URL. Otherwise, make a full
1142     * URL with the protocol specified.
1143     *
1144     * @deprecated since 1.39 - Moved to SkinComponentUtils::makeSpecialUrl
1145     * @param string $name Name of the Special page
1146     * @param string|array $urlaction Query to append
1147     * @param string|null $proto Protocol to use or null for a local URL
1148     * @return string
1149     */
1150    public static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1151        return SkinComponentUtils::makeSpecialUrl( $name, $urlaction, $proto );
1152    }
1153
1154    /**
1155     * @deprecated since 1.39 - Moved to SkinComponentUtils::makeSpecialUrlSubpage
1156     * @param string $name
1157     * @param string|bool $subpage false for no subpage
1158     * @param string|array $urlaction
1159     * @return string
1160     */
1161    public static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1162        return SkinComponentUtils::makeSpecialUrlSubpage( $name, $subpage, $urlaction );
1163    }
1164
1165    /**
1166     * If url string starts with http, consider as external URL, else
1167     * internal
1168     * @param string $name
1169     * @return string URL
1170     */
1171    public static function makeInternalOrExternalUrl( $name ) {
1172        if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1173            return $name;
1174        } else {
1175            $title = $name instanceof Title ? $name : Title::newFromText( $name );
1176            return $title ? $title->getLocalURL() : '';
1177        }
1178    }
1179
1180    /**
1181     * these return an array with the 'href' and boolean 'exists'
1182     * @param string|Title $name
1183     * @param string|array $urlaction
1184     * @return array
1185     */
1186    protected static function makeUrlDetails( $name, $urlaction = '' ) {
1187        $title = $name instanceof Title ? $name : Title::newFromText( $name );
1188        return [
1189            'href' => $title ? $title->getLocalURL( $urlaction ) : '',
1190            'exists' => $title && $title->isKnown(),
1191        ];
1192    }
1193
1194    /**
1195     * Make URL details where the article exists (or at least it's convenient to think so)
1196     * @param string|Title $name Article name
1197     * @param string|array $urlaction
1198     * @return array
1199     */
1200    protected static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1201        $title = $name instanceof Title ? $name : Title::newFromText( $name );
1202        return [
1203            'href' => $title ? $title->getLocalURL( $urlaction ) : '',
1204            'exists' => (bool)$title,
1205        ];
1206    }
1207
1208    /**
1209     * Allows correcting the language of interlanguage links which, mostly due to
1210     * legacy reasons, do not always match the standards compliant language tag.
1211     *
1212     * @param string $code
1213     * @return string
1214     * @since 1.35
1215     */
1216    public function mapInterwikiToLanguage( $code ) {
1217        $map = $this->getConfig()->get( MainConfigNames::InterlanguageLinkCodeMap );
1218        return $map[ $code ] ?? $code;
1219    }
1220
1221    /**
1222     * Generates array of language links for the current page.
1223     * This may includes items added to this section by the SidebarBeforeOutput hook
1224     * (which may not necessarily be language links)
1225     *
1226     * @since 1.35
1227     * @return array
1228     */
1229    public function getLanguages() {
1230        if ( $this->getConfig()->get( MainConfigNames::HideInterlanguageLinks ) ) {
1231            return [];
1232        }
1233        if ( $this->languageLinks === null ) {
1234            $hookRunner = $this->getHookRunner();
1235
1236            $userLang = $this->getLanguage();
1237            $languageLinks = [];
1238            $langNameUtils = MediaWikiServices::getInstance()->getLanguageNameUtils();
1239
1240            foreach ( $this->getOutput()->getLanguageLinks() as $languageLinkText ) {
1241                $class = 'interlanguage-link interwiki-' . explode( ':', $languageLinkText, 2 )[0];
1242
1243                $languageLinkTitle = Title::newFromText( $languageLinkText );
1244                if ( !$languageLinkTitle ) {
1245                    continue;
1246                }
1247
1248                $ilInterwikiCode =
1249                    $this->mapInterwikiToLanguage( $languageLinkTitle->getInterwiki() );
1250
1251                $ilLangName = $langNameUtils->getLanguageName( $ilInterwikiCode );
1252
1253                if ( strval( $ilLangName ) === '' ) {
1254                    $ilDisplayTextMsg = $this->msg( "interlanguage-link-$ilInterwikiCode" );
1255                    if ( !$ilDisplayTextMsg->isDisabled() ) {
1256                        // Use custom MW message for the display text
1257                        $ilLangName = $ilDisplayTextMsg->text();
1258                    } else {
1259                        // Last resort: fallback to the language link target
1260                        $ilLangName = $languageLinkText;
1261                    }
1262                } else {
1263                    // Use the language autonym as display text
1264                    $ilLangName = $this->getLanguage()->ucfirst( $ilLangName );
1265                }
1266
1267                // CLDR extension or similar is required to localize the language name;
1268                // otherwise we'll end up with the autonym again.
1269                $ilLangLocalName =
1270                    $langNameUtils->getLanguageName( $ilInterwikiCode, $userLang->getCode() );
1271
1272                $languageLinkTitleText = $languageLinkTitle->getText();
1273                if ( $ilLangLocalName === '' ) {
1274                    $ilFriendlySiteName =
1275                        $this->msg( "interlanguage-link-sitename-$ilInterwikiCode" );
1276                    if ( !$ilFriendlySiteName->isDisabled() ) {
1277                        if ( $languageLinkTitleText === '' ) {
1278                            $ilTitle =
1279                                $this->msg( 'interlanguage-link-title-nonlangonly',
1280                                    $ilFriendlySiteName->text() )->text();
1281                        } else {
1282                            $ilTitle =
1283                                $this->msg( 'interlanguage-link-title-nonlang',
1284                                    $languageLinkTitleText, $ilFriendlySiteName->text() )->text();
1285                        }
1286                    } else {
1287                        // we have nothing friendly to put in the title, so fall back to
1288                        // displaying the interlanguage link itself in the title text
1289                        // (similar to what is done in page content)
1290                        $ilTitle = $languageLinkTitle->getInterwiki() . ":$languageLinkTitleText";
1291                    }
1292                } elseif ( $languageLinkTitleText === '' ) {
1293                    $ilTitle =
1294                        $this->msg( 'interlanguage-link-title-langonly', $ilLangLocalName )->text();
1295                } else {
1296                    $ilTitle =
1297                        $this->msg( 'interlanguage-link-title', $languageLinkTitleText,
1298                            $ilLangLocalName )->text();
1299                }
1300
1301                $ilInterwikiCodeBCP47 = LanguageCode::bcp47( $ilInterwikiCode );
1302                $languageLink = [
1303                    'href' => $languageLinkTitle->getFullURL(),
1304                    'text' => $ilLangName,
1305                    'title' => $ilTitle,
1306                    'class' => $class,
1307                    'link-class' => 'interlanguage-link-target',
1308                    'lang' => $ilInterwikiCodeBCP47,
1309                    'hreflang' => $ilInterwikiCodeBCP47,
1310                ];
1311                $hookRunner->onSkinTemplateGetLanguageLink(
1312                    $languageLink, $languageLinkTitle, $this->getTitle(), $this->getOutput()
1313                );
1314                $languageLinks[] = $languageLink;
1315            }
1316            $this->languageLinks = $languageLinks;
1317        }
1318
1319        return $this->languageLinks;
1320    }
1321
1322    /**
1323     * Build array of common navigation links.
1324     * Assumes thispage property has been set before execution.
1325     * @since 1.35
1326     * @return array
1327     */
1328    protected function buildNavUrls() {
1329        $out = $this->getOutput();
1330        $title = $this->getTitle();
1331        $thispage = $title->getPrefixedDBkey();
1332        $uploadNavigationUrl = $this->getConfig()->get( MainConfigNames::UploadNavigationUrl );
1333
1334        $nav_urls = [];
1335        $nav_urls['mainpage'] = [ 'href' => self::makeMainPageUrl() ];
1336        if ( $uploadNavigationUrl ) {
1337            $nav_urls['upload'] = [ 'href' => $uploadNavigationUrl ];
1338        } elseif ( UploadBase::isEnabled() && UploadBase::isAllowed( $this->getAuthority() ) === true ) {
1339            $nav_urls['upload'] = [ 'href' => SkinComponentUtils::makeSpecialUrl( 'Upload' ) ];
1340        } else {
1341            $nav_urls['upload'] = false;
1342        }
1343        $nav_urls['specialpages'] = [ 'href' => SkinComponentUtils::makeSpecialUrl( 'Specialpages' ) ];
1344
1345        $nav_urls['print'] = false;
1346        $nav_urls['permalink'] = false;
1347        $nav_urls['info'] = false;
1348        $nav_urls['whatlinkshere'] = false;
1349        $nav_urls['recentchangeslinked'] = false;
1350        $nav_urls['contributions'] = false;
1351        $nav_urls['log'] = false;
1352        $nav_urls['blockip'] = false;
1353        $nav_urls['changeblockip'] = false;
1354        $nav_urls['unblockip'] = false;
1355        $nav_urls['mute'] = false;
1356        $nav_urls['emailuser'] = false;
1357        $nav_urls['userrights'] = false;
1358
1359        // A print stylesheet is attached to all pages, but nobody ever
1360        // figures that out. :)  Add a link...
1361        if ( !$out->isPrintable() && ( $out->isArticle() || $title->isSpecialPage() ) ) {
1362            $nav_urls['print'] = [
1363                'text' => $this->msg( 'printableversion' )->text(),
1364                'href' => 'javascript:print();'
1365            ];
1366        }
1367
1368        if ( $out->isArticle() ) {
1369            // Also add a "permalink" while we're at it
1370            $revid = $out->getRevisionId();
1371            if ( $revid ) {
1372                $nav_urls['permalink'] = [
1373                    'icon' => 'link',
1374                    'text' => $this->msg( 'permalink' )->text(),
1375                    'href' => $title->getLocalURL( "oldid=$revid" )
1376                ];
1377            }
1378        }
1379
1380        if ( $out->isArticleRelated() ) {
1381            $nav_urls['whatlinkshere'] = [
1382                'href' => SpecialPage::getTitleFor( 'Whatlinkshere', $thispage )->getLocalURL()
1383            ];
1384
1385            $nav_urls['info'] = [
1386                'icon' => 'infoFilled',
1387                'text' => $this->msg( 'pageinfo-toolboxlink' )->text(),
1388                'href' => $title->getLocalURL( "action=info" )
1389            ];
1390
1391            if ( $title->exists() || $title->inNamespace( NS_CATEGORY ) ) {
1392                $nav_urls['recentchangeslinked'] = [
1393                    'href' => SpecialPage::getTitleFor( 'Recentchangeslinked', $thispage )->getLocalURL()
1394                ];
1395            }
1396        }
1397
1398        $user = $this->getRelevantUser();
1399
1400        if ( $user ) {
1401            $rootUser = $user->getName();
1402
1403            $nav_urls['contributions'] = [
1404                'text' => $this->msg( 'tool-link-contributions', $rootUser )->text(),
1405                'href' => SkinComponentUtils::makeSpecialUrlSubpage( 'Contributions', $rootUser ),
1406                'tooltip-params' => [ $rootUser ],
1407            ];
1408
1409            $nav_urls['log'] = [
1410                'icon' => 'listBullet',
1411                'href' => SkinComponentUtils::makeSpecialUrlSubpage( 'Log', $rootUser )
1412            ];
1413
1414            if ( $this->getAuthority()->isAllowed( 'block' ) ) {
1415                // Check if the user is already blocked
1416                $userBlock = MediaWikiServices::getInstance()
1417                ->getBlockManager()
1418                ->getBlock( $user, null );
1419                if ( $userBlock ) {
1420                    $nav_urls['changeblockip'] = [
1421                        'icon' => 'block',
1422                        'href' => SkinComponentUtils::makeSpecialUrlSubpage( 'Block', $rootUser )
1423                    ];
1424                    $nav_urls['unblockip'] = [
1425                        'icon' => 'unBlock',
1426                        'href' => SkinComponentUtils::makeSpecialUrlSubpage( 'Unblock', $rootUser )
1427                    ];
1428                } else {
1429                    $nav_urls['blockip'] = [
1430                        'icon' => 'block',
1431                        'text' => $this->msg( 'blockip', $rootUser )->text(),
1432                        'href' => SkinComponentUtils::makeSpecialUrlSubpage( 'Block', $rootUser )
1433                    ];
1434                }
1435            }
1436
1437            if ( $this->showEmailUser( $user ) ) {
1438                $nav_urls['emailuser'] = [
1439                    'text' => $this->msg( 'tool-link-emailuser', $rootUser )->text(),
1440                    'href' => SkinComponentUtils::makeSpecialUrlSubpage( 'Emailuser', $rootUser ),
1441                    'tooltip-params' => [ $rootUser ],
1442                ];
1443            }
1444
1445            if ( $user->isRegistered() ) {
1446                if ( $this->getConfig()->get( MainConfigNames::EnableSpecialMute ) &&
1447                    $this->getUser()->isNamed()
1448                ) {
1449                    $nav_urls['mute'] = [
1450                        'text' => $this->msg( 'mute-preferences' )->text(),
1451                        'href' => SkinComponentUtils::makeSpecialUrlSubpage( 'Mute', $rootUser )
1452                    ];
1453                }
1454
1455                $sur = new SpecialUserRights;
1456                $sur->setContext( $this->getContext() );
1457                $canChange = $sur->userCanChangeRights( $user );
1458                $delimiter = $this->getConfig()->get(
1459                    MainConfigNames::UserrightsInterwikiDelimiter );
1460                if ( str_contains( $rootUser, $delimiter ) ) {
1461                    // Username contains interwiki delimiter, link it via the
1462                    // #{userid} syntax. (T260222)
1463                    $linkArgs = [ false, [ 'user' => '#' . $user->getId() ] ];
1464                } else {
1465                    $linkArgs = [ $rootUser ];
1466                }
1467                $nav_urls['userrights'] = [
1468                    'icon' => 'userGroup',
1469                    'text' => $this->msg(
1470                        $canChange ? 'tool-link-userrights' : 'tool-link-userrights-readonly',
1471                        $rootUser
1472                    )->text(),
1473                    'href' => SkinComponentUtils::makeSpecialUrlSubpage( 'Userrights', ...$linkArgs )
1474                ];
1475            }
1476        }
1477
1478        return $nav_urls;
1479    }
1480
1481    /**
1482     * Build data structure representing syndication links.
1483     * @since 1.35
1484     * @return array
1485     */
1486    final protected function buildFeedUrls() {
1487        $feeds = [];
1488        $out = $this->getOutput();
1489        if ( $out->isSyndicated() ) {
1490            foreach ( $out->getSyndicationLinks() as $format => $link ) {
1491                $feeds[$format] = [
1492                    // Messages: feed-atom, feed-rss
1493                    'text' => $this->msg( "feed-$format" )->text(),
1494                    'href' => $link
1495                ];
1496            }
1497        }
1498        return $feeds;
1499    }
1500
1501    /**
1502     * Build an array that represents the sidebar(s), the navigation bar among them.
1503     *
1504     * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1505     *
1506     * The format of the returned array is [ heading => content, ... ], where:
1507     * - heading is the heading of a navigation portlet. It is either:
1508     *   - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1509     *     - Note that 'SEARCH' unlike others is not supported out-of-the-box by the skins.
1510     *     - For it to work, a skin must add custom support for it.
1511     *   - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1512     *   - plain text, which should be HTML-escaped by the skin
1513     * - content is the contents of the portlet. This must be array of link data in a format
1514     *         accepted by self::makeListItem().
1515     *   - (for a magic string as a key, any value)
1516     *
1517     * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1518     * and can technically insert anything in here; skin creators are expected to handle
1519     * values described above.
1520     *
1521     * @return array
1522     */
1523    public function buildSidebar() {
1524        if ( $this->sidebar === null ) {
1525            $services = MediaWikiServices::getInstance();
1526            $callback = function ( $old = null, &$ttl = null ) {
1527                $bar = [];
1528                $this->addToSidebar( $bar, 'sidebar' );
1529
1530                // This hook may vary its behaviour by skin.
1531                $this->getHookRunner()->onSkinBuildSidebar( $this, $bar );
1532                $msgCache = MediaWikiServices::getInstance()->getMessageCache();
1533                if ( $msgCache->isDisabled() ) {
1534                    // Don't cache the fallback if DB query failed. T133069
1535                    $ttl = WANObjectCache::TTL_UNCACHEABLE;
1536                }
1537
1538                return $bar;
1539            };
1540
1541            $msgCache = $services->getMessageCache();
1542            $wanCache = $services->getMainWANObjectCache();
1543            $config = $this->getConfig();
1544            $languageCode = $this->getLanguage()->getCode();
1545
1546            $sidebar = $config->get( MainConfigNames::EnableSidebarCache )
1547                ? $wanCache->getWithSetCallback(
1548                    $wanCache->makeKey( 'sidebar', $languageCode, $this->getSkinName() ?? '' ),
1549                    $config->get( MainConfigNames::SidebarCacheExpiry ),
1550                    $callback,
1551                    [
1552                        'checkKeys' => [
1553                            // Unless there is both no exact $code override nor an i18n definition
1554                            // in the software, the only MediaWiki page to check is for $code.
1555                            $msgCache->getCheckKey( $languageCode )
1556                        ],
1557                        'lockTSE' => 30
1558                    ]
1559                )
1560                : $callback();
1561
1562            $sidebar['TOOLBOX'] = $this->makeToolbox(
1563                $this->buildNavUrls(),
1564                $this->buildFeedUrls()
1565            );
1566            $sidebar['LANGUAGES'] = $this->getLanguages();
1567            // Apply post-processing to the cached value
1568            $this->getHookRunner()->onSidebarBeforeOutput( $this, $sidebar );
1569            $this->sidebar = $sidebar;
1570        }
1571
1572        return $this->sidebar;
1573    }
1574
1575    /**
1576     * Add content from a sidebar system message
1577     * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1578     *
1579     * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1580     *
1581     * @param array &$bar
1582     * @param string $message
1583     */
1584    public function addToSidebar( &$bar, $message ) {
1585        $this->addToSidebarPlain( $bar, $this->msg( $message )->inContentLanguage()->plain() );
1586    }
1587
1588    /**
1589     * Add content from plain text
1590     * @since 1.17
1591     * @param array &$bar
1592     * @param string $text
1593     * @return array
1594     */
1595    public function addToSidebarPlain( &$bar, $text ) {
1596        $lines = explode( "\n", $text );
1597
1598        $heading = '';
1599        $config = $this->getConfig();
1600        $messageTitle = $config->get( MainConfigNames::EnableSidebarCache )
1601            ? Title::newMainPage() : $this->getTitle();
1602        $messageCache = MediaWikiServices::getInstance()->getMessageCache();
1603
1604        foreach ( $lines as $line ) {
1605            if ( strpos( $line, '*' ) !== 0 ) {
1606                continue;
1607            }
1608            $line = rtrim( $line, "\r" ); // for Windows compat
1609
1610            if ( strpos( $line, '**' ) !== 0 ) {
1611                $heading = trim( $line, '* ' );
1612                if ( !array_key_exists( $heading, $bar ) ) {
1613                    $bar[$heading] = [];
1614                }
1615            } else {
1616                $line = trim( $line, '* ' );
1617
1618                if ( strpos( $line, '|' ) !== false ) {
1619                    $line = $messageCache->transform( $line, false, null, $messageTitle );
1620                    $line = array_map( 'trim', explode( '|', $line, 2 ) );
1621                    if ( count( $line ) !== 2 ) {
1622                        // Second check, could be hit by people doing
1623                        // funky stuff with parserfuncs... (T35321)
1624                        continue;
1625                    }
1626
1627                    $extraAttribs = [];
1628
1629                    $msgLink = $this->msg( $line[0] )->page( $messageTitle )->inContentLanguage();
1630                    if ( $msgLink->exists() ) {
1631                        $link = $msgLink->text();
1632                        if ( $link == '-' ) {
1633                            continue;
1634                        }
1635                    } else {
1636                        $link = $line[0];
1637                    }
1638                    $msgText = $this->msg( $line[1] )->page( $messageTitle );
1639                    if ( $msgText->exists() ) {
1640                        $text = $msgText->text();
1641                    } else {
1642                        $text = $line[1];
1643                    }
1644
1645                    if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1646                        $href = $link;
1647
1648                        // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1649                        if ( $config->get( MainConfigNames::NoFollowLinks ) &&
1650                            !wfMatchesDomainList( $href,
1651                                $config->get( MainConfigNames::NoFollowDomainExceptions ) )
1652                        ) {
1653                            $extraAttribs['rel'] = 'nofollow';
1654                        }
1655
1656                        if ( $config->get( MainConfigNames::ExternalLinkTarget ) ) {
1657                            $extraAttribs['target'] =
1658                                $config->get( MainConfigNames::ExternalLinkTarget );
1659                        }
1660                    } else {
1661                        $title = Title::newFromText( $link );
1662                        $href = $title ? $title->fixSpecialName()->getLinkURL() : '';
1663                    }
1664
1665                    $id = strtr( $line[1], ' ', '-' );
1666                    $bar[$heading][] = array_merge( [
1667                        'text' => $text,
1668                        'href' => $href,
1669                        'icon' => $this->getSidebarIcon( $id ),
1670                        'id' => Sanitizer::escapeIdForAttribute( 'n-' . $id ),
1671                        'active' => false,
1672                    ], $extraAttribs );
1673                }
1674            }
1675        }
1676
1677        return $bar;
1678    }
1679
1680    /**
1681     * @param string $id the id of the menu
1682     * @return string|null the icon glyph name to associate with this menu
1683     */
1684    private function getSidebarIcon( string $id ) {
1685        switch ( $id ) {
1686            case 'mainpage-description':
1687                return 'home';
1688            case 'randompage':
1689                return 'die';
1690            case 'recentchanges':
1691                return 'recentChanges';
1692            // These menu items are commonly added in MediaWiki:Sidebar. We should
1693            // reconsider the location of this logic in future.
1694            case 'help':
1695            case 'help-mediawiki':
1696                return 'help';
1697            default:
1698                return null;
1699        }
1700    }
1701
1702    /**
1703     * Check whether to allow new talk page notifications for the current request.
1704     *
1705     * The client might be reading without a session cookie from an IP that matches
1706     * a previous IP editor. When clients without a session visit a page with a CDN miss,
1707     * we must not embed personal notifications, as doing so might leak personal details
1708     * (if Cache-Control is public), or risk an outage per T350861 (if max-age=0).
1709     *
1710     * From an end-user perspective, this has the added benefit of not randomly showing
1711     * notifications to readers (on page views that happen to be a CDN miss) when
1712     * sharing an IP with an editor. Notifying clients without a session is not reliably
1713     * possible, as their requests are usually CDN hits.
1714     *
1715     * @see https://phabricator.wikimedia.org/T350861
1716     * @return bool
1717     */
1718    private function hideNewTalkMessagesForCurrentSession() {
1719        // Only show new talk page notification if there is a session,
1720        // (the client edited a page from this browser, or is logged-in).
1721        return !$this->getRequest()->getSession()->isPersistent();
1722    }
1723
1724    /**
1725     * Gets new talk page messages for the current user and returns an
1726     * appropriate alert message (or an empty string if there are no messages)
1727     * @return string
1728     */
1729    public function getNewtalks() {
1730        if ( $this->hideNewTalkMessagesForCurrentSession() ) {
1731            return '';
1732        }
1733
1734        $newMessagesAlert = '';
1735        $user = $this->getUser();
1736        $services = MediaWikiServices::getInstance();
1737        $linkRenderer = $services->getLinkRenderer();
1738        $userHasNewMessages = $services->getTalkPageNotificationManager()
1739            ->userHasNewMessages( $user );
1740        $timestamp = $services->getTalkPageNotificationManager()
1741            ->getLatestSeenMessageTimestamp( $user );
1742        $newtalks = !$userHasNewMessages ? [] : [
1743            [
1744            // TODO: Deprecate adding wiki and link to array and redesign GetNewMessagesAlert hook
1745            'wiki' => WikiMap::getCurrentWikiId(),
1746            'link' => $user->getTalkPage()->getLocalURL(),
1747            'rev' => $timestamp ? $services->getRevisionLookup()
1748                ->getRevisionByTimestamp( $user->getTalkPage(), $timestamp ) : null
1749            ]
1750        ];
1751        $out = $this->getOutput();
1752
1753        // Allow extensions to disable or modify the new messages alert
1754        if ( !$this->getHookRunner()->onGetNewMessagesAlert(
1755            $newMessagesAlert, $newtalks, $user, $out )
1756        ) {
1757            return '';
1758        }
1759        if ( $newMessagesAlert ) {
1760            return $newMessagesAlert;
1761        }
1762
1763        if ( $newtalks !== [] ) {
1764            $uTalkTitle = $user->getTalkPage();
1765            $lastSeenRev = $newtalks[0]['rev'];
1766            $numAuthors = 0;
1767            if ( $lastSeenRev !== null ) {
1768                $plural = true; // Default if we have a last seen revision: if unknown, use plural
1769                $revStore = $services->getRevisionStore();
1770                $latestRev = $revStore->getRevisionByTitle(
1771                    $uTalkTitle,
1772                    0,
1773                    IDBAccessObject::READ_NORMAL
1774                );
1775                if ( $latestRev !== null ) {
1776                    // Singular if only 1 unseen revision, plural if several unseen revisions.
1777                    $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1778                    $numAuthors = $revStore->countAuthorsBetween(
1779                        $uTalkTitle->getArticleID(),
1780                        $lastSeenRev,
1781                        $latestRev,
1782                        null,
1783                        10,
1784                        RevisionStore::INCLUDE_NEW
1785                    );
1786                }
1787            } else {
1788                // Singular if no revision -> diff link will show latest change only in any case
1789                $plural = false;
1790            }
1791            $plural = $plural ? 999 : 1;
1792            // 999 signifies "more than one revision". We don't know how many, and even if we did,
1793            // the number of revisions or authors is not necessarily the same as the number of
1794            // "messages".
1795            $newMessagesLink = $linkRenderer->makeKnownLink(
1796                $uTalkTitle,
1797                $this->msg( 'new-messages-link-plural' )->params( $plural )->text(),
1798                [],
1799                $uTalkTitle->isRedirect() ? [ 'redirect' => 'no' ] : []
1800            );
1801
1802            $newMessagesDiffLink = $linkRenderer->makeKnownLink(
1803                $uTalkTitle,
1804                $this->msg( 'new-messages-diff-link-plural' )->params( $plural )->text(),
1805                [],
1806                $lastSeenRev !== null
1807                    ? [ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1808                    : [ 'diff' => 'cur' ]
1809            );
1810
1811            if ( $numAuthors >= 1 && $numAuthors <= 10 ) {
1812                $newMessagesAlert = $this->msg(
1813                    'new-messages-from-users'
1814                )->rawParams(
1815                    $newMessagesLink,
1816                    $newMessagesDiffLink
1817                )->numParams(
1818                    $numAuthors,
1819                    $plural
1820                );
1821            } else {
1822                // $numAuthors === 11 signifies "11 or more" ("more than 10")
1823                $newMessagesAlert = $this->msg(
1824                    $numAuthors > 10 ? 'new-messages-from-many-users' : 'new-messages'
1825                )->rawParams(
1826                    $newMessagesLink,
1827                    $newMessagesDiffLink
1828                )->numParams( $plural );
1829            }
1830            $newMessagesAlert = $newMessagesAlert->parse();
1831        }
1832
1833        return $newMessagesAlert;
1834    }
1835
1836    /**
1837     * Get a cached notice
1838     *
1839     * @param string $name Message name, or 'default' for $wgSiteNotice
1840     * @return string|false HTML fragment, or false to indicate that the caller
1841     *   should fall back to the next notice in its sequence
1842     */
1843    private function getCachedNotice( $name ) {
1844        $config = $this->getConfig();
1845
1846        if ( $name === 'default' ) {
1847            // special case
1848            $notice = $config->get( MainConfigNames::SiteNotice );
1849            if ( !$notice ) {
1850                return false;
1851            }
1852        } else {
1853            $msg = $this->msg( $name )->inContentLanguage();
1854            if ( $msg->isBlank() ) {
1855                return '';
1856            } elseif ( $msg->isDisabled() ) {
1857                return false;
1858            }
1859            $notice = $msg->plain();
1860        }
1861
1862        $services = MediaWikiServices::getInstance();
1863        $cache = $services->getMainWANObjectCache();
1864        $parsed = $cache->getWithSetCallback(
1865            // Use the extra hash appender to let eg SSL variants separately cache
1866            // Key is verified with md5 hash of unparsed wikitext
1867            $cache->makeKey(
1868                $name, $config->get( MainConfigNames::RenderHashAppend ), md5( $notice ) ),
1869            // TTL in seconds
1870            600,
1871            function () use ( $notice ) {
1872                return $this->getOutput()->parseAsInterface( $notice );
1873            }
1874        );
1875
1876        $contLang = $services->getContentLanguage();
1877        return Html::rawElement(
1878            'div',
1879            [
1880                'class' => $name,
1881                'lang' => $contLang->getHtmlCode(),
1882                'dir' => $contLang->getDir()
1883            ],
1884            $parsed
1885        );
1886    }
1887
1888    /**
1889     * @return string HTML fragment
1890     */
1891    public function getSiteNotice() {
1892        $siteNotice = '';
1893
1894        if ( $this->getHookRunner()->onSiteNoticeBefore( $siteNotice, $this ) ) {
1895            if ( $this->getUser()->isRegistered() ) {
1896                $siteNotice = $this->getCachedNotice( 'sitenotice' );
1897            } else {
1898                $anonNotice = $this->getCachedNotice( 'anonnotice' );
1899                if ( $anonNotice === false ) {
1900                    $siteNotice = $this->getCachedNotice( 'sitenotice' );
1901                } else {
1902                    $siteNotice = $anonNotice;
1903                }
1904            }
1905            if ( $siteNotice === false ) {
1906                $siteNotice = $this->getCachedNotice( 'default' ) ?: '';
1907            }
1908            if ( $this->canUseWikiPage() ) {
1909                $ns = $this->getWikiPage()->getNamespace();
1910                $nsNotice = $this->getCachedNotice( "namespacenotice-$ns" );
1911                if ( $nsNotice ) {
1912                    $siteNotice .= $nsNotice;
1913                }
1914            }
1915            if ( $siteNotice !== '' ) {
1916                $siteNotice = Html::rawElement( 'div', [ 'id' => 'localNotice', 'data-nosnippet' => '' ], $siteNotice );
1917            }
1918        }
1919
1920        $this->getHookRunner()->onSiteNoticeAfter( $siteNotice, $this );
1921        return $siteNotice;
1922    }
1923
1924    /**
1925     * Create a section edit link.
1926     *
1927     * @param Title $nt The title being linked to (may not be the same as
1928     *   the current page, if the section is included from a template)
1929     * @param string $section The designation of the section being pointed to,
1930     *   to be included in the link, like "&section=$section"
1931     * @param string $sectionTitle Section title. It is used in the link tooltip, escaped and
1932     *   wrapped in the 'editsectionhint' message
1933     * @param Language $lang
1934     * @return string HTML to use for edit link
1935     */
1936    public function doEditSectionLink( Title $nt, $section, $sectionTitle, Language $lang ) {
1937        // HTML generated here should probably have userlangattributes
1938        // added to it for LTR text on RTL pages
1939
1940        $attribs = [];
1941        $attribs['title'] = $this->msg( 'editsectionhint' )->plaintextParams( $sectionTitle )
1942            ->inLanguage( $lang )->text();
1943
1944        $links = [
1945            'editsection' => [
1946                'icon' => 'edit',
1947                'text' => $this->msg( 'editsection' )->inLanguage( $lang )->text(),
1948                'targetTitle' => $nt,
1949                'attribs' => $attribs,
1950                'query' => [ 'action' => 'edit', 'section' => $section ]
1951            ]
1952        ];
1953
1954        $this->getHookRunner()->onSkinEditSectionLinks( $this, $nt, $section, $sectionTitle, $links, $lang );
1955
1956        $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1957        $newLinks = [];
1958        $options = $this->defaultLinkOptions + [
1959            'class-as-property' => true,
1960        ];
1961        $ctx = $this->getContext();
1962        foreach ( $links as $key => $linkDetails ) {
1963            $targetTitle = $linkDetails['targetTitle'];
1964            $attrs = $linkDetails['attribs'];
1965            $query = $linkDetails['query'];
1966            unset( $linkDetails['targetTitle'] );
1967            unset( $linkDetails['query'] );
1968            unset( $linkDetails['attribs'] );
1969            unset( $linkDetails['options' ] );
1970            $component = new SkinComponentLink(
1971                $key, $linkDetails + [
1972                    'href' => Title::newFromLinkTarget( $targetTitle )->getLinkURL( $query, false ),
1973                ] + $attrs, $ctx, $options
1974            );
1975            $newLinks[] = $component->getTemplateData();
1976        }
1977        return $this->doEditSectionLinksHTML( $newLinks, $lang );
1978    }
1979
1980    /**
1981     * @stable to override by skins
1982     *
1983     * @param array $links
1984     * @param Language $lang
1985     * @return string
1986     */
1987    protected function doEditSectionLinksHTML( array $links, Language $lang ) {
1988        $result = Html::openElement( 'span', [ 'class' => 'mw-editsection' ] );
1989        $result .= Html::rawElement( 'span', [ 'class' => 'mw-editsection-bracket' ], '[' );
1990
1991        $linksHtml = [];
1992        foreach ( $links as $linkDetails ) {
1993            $linksHtml[] = $linkDetails['html'];
1994        }
1995
1996        $result .= implode(
1997            Html::rawElement(
1998                'span',
1999                [ 'class' => 'mw-editsection-divider' ],
2000                $this->msg( 'pipe-separator' )->inLanguage( $lang )->escaped()
2001            ),
2002            $linksHtml
2003        );
2004
2005        $result .= Html::rawElement( 'span', [ 'class' => 'mw-editsection-bracket' ], ']' );
2006        $result .= Html::closeElement( 'span' );
2007        return $result;
2008    }
2009
2010    /**
2011     * Create an array of common toolbox items from the data in the quicktemplate
2012     * stored by SkinTemplate.
2013     * The resulting array is built according to a format intended to be passed
2014     * through makeListItem to generate the html.
2015     * @param array $navUrls
2016     * @param array $feedUrls
2017     * @return array
2018     */
2019    public function makeToolbox( $navUrls, $feedUrls ) {
2020        $toolbox = [];
2021        if ( $navUrls['whatlinkshere'] ?? null ) {
2022            $toolbox['whatlinkshere'] = $navUrls['whatlinkshere'];
2023            $toolbox['whatlinkshere']['id'] = 't-whatlinkshere';
2024            $toolbox['whatlinkshere']['icon'] = 'articleRedirect';
2025        }
2026        if ( $navUrls['recentchangeslinked'] ?? null ) {
2027            $toolbox['recentchangeslinked'] = $navUrls['recentchangeslinked'];
2028            $toolbox['recentchangeslinked']['msg'] = 'recentchangeslinked-toolbox';
2029            $toolbox['recentchangeslinked']['id'] = 't-recentchangeslinked';
2030            $toolbox['recentchangeslinked']['rel'] = 'nofollow';
2031        }
2032        if ( $feedUrls ) {
2033            $toolbox['feeds']['id'] = 'feedlinks';
2034            $toolbox['feeds']['links'] = [];
2035            foreach ( $feedUrls as $key => $feed ) {
2036                $toolbox['feeds']['links'][$key] = $feed;
2037                $toolbox['feeds']['links'][$key]['id'] = "feed-$key";
2038                $toolbox['feeds']['links'][$key]['rel'] = 'alternate';
2039                $toolbox['feeds']['links'][$key]['type'] = "application/{$key}+xml";
2040                $toolbox['feeds']['links'][$key]['class'] = 'feedlink';
2041            }
2042        }
2043        foreach ( [ 'contributions', 'log', 'blockip', 'changeblockip', 'unblockip',
2044            'emailuser', 'mute', 'userrights', 'upload', 'specialpages' ] as $special
2045        ) {
2046            if ( $navUrls[$special] ?? null ) {
2047                $toolbox[$special] = $navUrls[$special];
2048                $toolbox[$special]['id'] = "t-$special";
2049            }
2050        }
2051        if ( $navUrls['print'] ?? null ) {
2052            $toolbox['print'] = $navUrls['print'];
2053            $toolbox['print']['id'] = 't-print';
2054            $toolbox['print']['rel'] = 'alternate';
2055            $toolbox['print']['msg'] = 'printableversion';
2056        }
2057        if ( $navUrls['permalink'] ?? null ) {
2058            $toolbox['permalink'] = $navUrls['permalink'];
2059            $toolbox['permalink']['id'] = 't-permalink';
2060        }
2061        if ( $navUrls['info'] ?? null ) {
2062            $toolbox['info'] = $navUrls['info'];
2063            $toolbox['info']['id'] = 't-info';
2064        }
2065
2066        return $toolbox;
2067    }
2068
2069    /**
2070     * Return an array of indicator data.
2071     * Can be used by subclasses but should not be extended.
2072     * @param array $indicators return value of OutputPage::getIndicators
2073     * @return array
2074     */
2075    protected function getIndicatorsData( $indicators ) {
2076        $indicatorData = [];
2077        foreach ( $indicators as $id => $content ) {
2078            $indicatorData[] = [
2079                'id' => Sanitizer::escapeIdForAttribute( "mw-indicator-$id" ),
2080                'class' => 'mw-indicator',
2081                'html' => $content,
2082            ];
2083        }
2084        return $indicatorData;
2085    }
2086
2087    /**
2088     * Create an array of personal tools items from the data in the quicktemplate
2089     * stored by SkinTemplate.
2090     * The resulting array is built according to a format intended to be passed
2091     * through makeListItem to generate the html.
2092     * This is in reality the same list as already stored in personal_urls
2093     * however it is reformatted so that you can just pass the individual items
2094     * to makeListItem instead of hardcoding the element creation boilerplate.
2095     * @since 1.35
2096     * @param array $urls
2097     * @param bool $applyClassesToListItems (optional) when set behaves consistently with other menus,
2098     *   applying the `class` property applies to list items. When not set will move the class to child links.
2099     * @return array[]
2100     */
2101    final public function getPersonalToolsForMakeListItem( $urls, $applyClassesToListItems = false ) {
2102        $personal_tools = [];
2103        foreach ( $urls as $key => $plink ) {
2104            # The class on a personal_urls item is meant to go on the <a> instead
2105            # of the <li> so we have to use a single item "links" array instead
2106            # of using most of the personal_url's keys directly.
2107            $ptool = [
2108                'links' => [
2109                    [ 'single-id' => "pt-$key" ],
2110                ],
2111                'id' => "pt-$key",
2112            ];
2113            if ( $applyClassesToListItems && isset( $plink['class'] ) ) {
2114                $ptool['class'] = $plink['class'];
2115            }
2116            if ( isset( $plink['active'] ) ) {
2117                $ptool['active'] = $plink['active'];
2118            }
2119            // Set class for the link to link-class, when defined.
2120            // This allows newer notifications content navigation to retain their classes
2121            // when merged back into the personal tools.
2122            // Doing this here allows the loop below to overwrite the class if defined directly.
2123            if ( isset( $plink['link-class'] ) ) {
2124                $ptool['links'][0]['class'] = $plink['link-class'];
2125            }
2126            $props = [
2127                'href',
2128                'text',
2129                'dir',
2130                'data',
2131                'exists',
2132                'data-mw',
2133                'link-html',
2134            ];
2135            if ( !$applyClassesToListItems ) {
2136                $props[] = 'class';
2137            }
2138            foreach ( $props as $k ) {
2139                if ( isset( $plink[$k] ) ) {
2140                    $ptool['links'][0][$k] = $plink[$k];
2141                }
2142            }
2143            $personal_tools[$key] = $ptool;
2144        }
2145        return $personal_tools;
2146    }
2147
2148    /**
2149     * Makes a link, usually used by makeListItem to generate a link for an item
2150     * in a list used in navigation lists, portlets, portals, sidebars, etc...
2151     *
2152     * @since 1.35
2153     * @param string $key Usually a key from the list you are generating this
2154     * link from.
2155     * @param array $item Contains some of a specific set of keys.
2156     *
2157     * If "html" key is present, this will be returned. All other keys will be ignored.
2158     *
2159     * The text of the link will be generated either from the contents of the
2160     * "text" key in the $item array, if a "msg" key is present a message by
2161     * that name will be used, and if neither of those are set the $key will be
2162     * used as a message name.
2163     *
2164     * If a "href" key is not present makeLink will just output htmlescaped text.
2165     * The "href", "id", "class", "rel", and "type" keys are used as attributes
2166     * for the link if present.
2167     *
2168     * If an "id" or "single-id" (if you don't want the actual id to be output
2169     * on the link) is present it will be used to generate a tooltip and
2170     * accesskey for the link.
2171     *
2172     * The 'link-html' key can be used to prepend additional HTML inside the link HTML.
2173     * For example to prepend an icon.
2174     *
2175     * The keys "context" and "primary" are ignored; these keys are used
2176     * internally by skins and are not supposed to be included in the HTML
2177     * output.
2178     *
2179     * If you don't want an accesskey, set $item['tooltiponly'] = true;
2180     *
2181     * If a "data" key is present, it must be an array, where the keys represent
2182     * the data-xxx properties with their provided values. For example,
2183     *     $item['data'] = [
2184     *       'foo' => 1,
2185     *       'bar' => 'baz',
2186     *     ];
2187     * will render as element properties:
2188     *     data-foo='1' data-bar='baz'
2189     *
2190     * The "class" key currently accepts both a string and an array of classes, but this will be
2191     * changed to only accept an array in the future.
2192     *
2193     * @param array $linkOptions Can be used to affect the output of a link.
2194     * Possible options are:
2195     *   - 'text-wrapper' key to specify a list of elements to wrap the text of
2196     *   a link in. This should be an array of arrays containing a 'tag' and
2197     *   optionally an 'attributes' key. If you only have one element you don't
2198     *   need to wrap it in another array. eg: To use <a><span>...</span></a>
2199     *   in all links use [ 'text-wrapper' => [ 'tag' => 'span' ] ]
2200     *   for your options.
2201     *   - 'link-class' key can be used to specify additional classes to apply
2202     *   to all links.
2203     *   - 'link-fallback' can be used to specify a tag to use instead of "<a>"
2204     *   if there is no link. eg: If you specify 'link-fallback' => 'span' than
2205     *   any non-link will output a "<span>" instead of just text.
2206     *
2207     * @return string
2208     */
2209    final public function makeLink( $key, $item, $linkOptions = [] ) {
2210        $options = $linkOptions + $this->defaultLinkOptions;
2211        $component = new SkinComponentLink(
2212            $key, $item, $this->getContext(), $options
2213        );
2214        return $component->getTemplateData()[ 'html' ];
2215    }
2216
2217    /**
2218     * Generates a list item for a navigation, portlet, portal, sidebar... list
2219     *
2220     * @since 1.35
2221     * @param string $key Usually a key from the list you are generating this link from.
2222     * @param array $item Array of list item data containing some of a specific set of keys.
2223     * The "id", "class" and "itemtitle" keys will be used as attributes for the list item,
2224     * if "active" contains a value of true a "active" class will also be appended to class.
2225     * The "class" key currently accepts both a string and an array of classes, but this will be
2226     * changed to only accept an array in the future.
2227     * @phan-param array{id?:string,html?:string,class?:string|string[],itemtitle?:string,active?:bool} $item
2228     *
2229     * @param array $options
2230     * @phan-param array{tag?:string} $options
2231     *
2232     * If you want something other than a "<li>" you can pass a tag name such as
2233     * "tag" => "span" in the $options array to change the tag used.
2234     * link/content data for the list item may come in one of two forms
2235     * A "links" key may be used, in which case it should contain an array with
2236     * a list of links to include inside the list item, see makeLink for the
2237     * format of individual links array items.
2238     *
2239     * Otherwise the relevant keys from the list item $item array will be passed
2240     * to makeLink instead. Note however that "id" and "class" are used by the
2241     * list item directly so they will not be passed to makeLink
2242     * (however the link will still support a tooltip and accesskey from it)
2243     * If you need an id or class on a single link you should include a "links"
2244     * array with just one link item inside of it. You can also set "link-class" in
2245     * $item to set a class on the link itself. If you want to add a title
2246     * to the list item itself, you can set "itemtitle" to the value.
2247     * $options is also passed on to makeLink calls
2248     *
2249     * @return string
2250     */
2251    final public function makeListItem( $key, $item, $options = [] ) {
2252        $component = new SkinComponentListItem(
2253            $key, $item, $this->getContext(), $options, $this->defaultLinkOptions
2254        );
2255        return $component->getTemplateData()[ 'html-item' ];
2256    }
2257
2258    /**
2259     * @since 1.35
2260     * @param array $attrs (optional) will be passed to tooltipAndAccesskeyAttribs
2261     *  and decorate the resulting input
2262     * @deprecated 1.39 use $this->getTemplateData()['data-search-box'] instead.
2263     * @return string of HTML input
2264     */
2265    public function makeSearchInput( $attrs = [] ) {
2266        wfDeprecated( __METHOD__,
2267            '[1.39] use $this->getTemplateData()["data-search-box"] or SkinTemplate::makeSearchInput'
2268        );
2269
2270        // It's possible that getTemplateData might be calling
2271        // Skin::makeSearchInput. To avoid infinite recursion create a
2272        // new instance of the search component here.
2273        $searchBox = $this->getComponent( 'search-box' );
2274        $data = $searchBox->getTemplateData();
2275
2276        return Html::element( 'input',
2277            $data[ 'array-input-attributes' ] + $attrs
2278        );
2279    }
2280
2281    /**
2282     * @param string $mode representing the type of button wanted
2283     *  either `go`, `fulltext` or `image`
2284     * @param array $attrs (optional)
2285     * @deprecated 1.39 use $this->getTemplateData()['data-search-box'] instead.
2286     *   Note: When removing this function please merge SkinTemplate::makeSearchButtonInternal
2287     *   with SkinTemplate::makeSearchButton.
2288     * @return string of HTML button
2289     */
2290    public function makeSearchButton( $mode, $attrs = [] ) {
2291        wfDeprecated( __METHOD__,
2292            '[1.39] use $this->getTemplateData()["data-search-box"] or SkinTemplate::makeSearchButton'
2293        );
2294
2295        // It's possible that getTemplateData might be calling
2296        // Skin::makeSearchInput. To avoid infinite recursion create a
2297        // new instance of the search component here.
2298        $searchBox = $this->getComponent( 'search-box' );
2299        $data = $searchBox->getTemplateData();
2300
2301        return SkinTemplate::makeSearchButtonInternal(
2302            $mode, $data, $attrs
2303        );
2304    }
2305
2306    /**
2307     * Allows extensions to hook into known portlets and add stuff to them.
2308     * Unlike its BaseTemplate counterpart, this method does not wrap the html
2309     * provided by the hook in a div.
2310     *
2311     * @param string $name
2312     *
2313     * @return string html
2314     * @since 1.35
2315     */
2316    public function getAfterPortlet( string $name ): string {
2317        $html = '';
2318
2319        $this->getHookRunner()->onSkinAfterPortlet( $this, $name, $html );
2320
2321        return $html;
2322    }
2323
2324    /**
2325     * Prepare the subtitle of the page for output in the skin if one has been set.
2326     * @since 1.35
2327     * @param bool $withContainer since 1.40, when provided the mw-content-subtitle element will be output too.
2328     * @return string HTML
2329     */
2330    final public function prepareSubtitle( bool $withContainer = true ) {
2331        $out = $this->getOutput();
2332        $subpagestr = $this->subPageSubtitleInternal();
2333        if ( $subpagestr !== '' ) {
2334            $subpagestr = Html::rawElement( 'div', [ 'class' => 'subpages' ], $subpagestr );
2335        }
2336        $html = $subpagestr . $out->getSubtitle();
2337        return $withContainer ? Html::rawElement( 'div', [
2338            'id' => 'mw-content-subtitle',
2339        ] + $this->getUserLanguageAttributes(), $html ) : $html;
2340    }
2341
2342    /**
2343     * Returns array of config variables that should be added only to this skin
2344     * for use in JavaScript.
2345     * Skins can override this to add variables to the page.
2346     * @since 1.38 or 1.35 if extending SkinTemplate.
2347     * @return array
2348     */
2349    protected function getJsConfigVars(): array {
2350        return [];
2351    }
2352
2353    /**
2354     * Get user language attribute links array
2355     *
2356     * @return array HTML attributes
2357     */
2358    final protected function getUserLanguageAttributes() {
2359        $userLang = $this->getLanguage();
2360        $userLangCode = $userLang->getHtmlCode();
2361        $userLangDir = $userLang->getDir();
2362        $contLang = MediaWikiServices::getInstance()->getContentLanguage();
2363        if (
2364            $userLangCode !== $contLang->getHtmlCode() ||
2365            $userLangDir !== $contLang->getDir()
2366        ) {
2367            return [
2368                'lang' => $userLangCode,
2369                'dir' => $userLangDir,
2370            ];
2371        }
2372        return [];
2373    }
2374
2375    /**
2376     * Prepare user language attribute links
2377     * @since 1.38 on Skin and 1.35 on classes extending SkinTemplate
2378     * @return string HTML attributes
2379     */
2380    final protected function prepareUserLanguageAttributes() {
2381        return Html::expandAttributes(
2382            $this->getUserLanguageAttributes()
2383        );
2384    }
2385
2386    /**
2387     * Prepare undelete link for output in page.
2388     * @since 1.38 on Skin and 1.35 on classes extending SkinTemplate
2389     * @return null|string HTML, or null if there is no undelete link.
2390     */
2391    final protected function prepareUndeleteLink() {
2392        $undelete = $this->getUndeleteLink();
2393        return $undelete === '' ? null : '<div class="subpages">' . $undelete . '</div>';
2394    }
2395
2396    /**
2397     * @return string
2398     * @deprecated since 1.39
2399     */
2400    final protected function getAction(): string {
2401        wfDeprecated( __METHOD__, '1.39' );
2402        return $this->getContext()->getActionName();
2403    }
2404
2405    /**
2406     * Wrap the body text with language information and identifiable element
2407     *
2408     * @since 1.38 in Skin, previously was a method of SkinTemplate
2409     * @param Title $title
2410     * @param string $html body text
2411     * @return string html
2412     */
2413    protected function wrapHTML( $title, $html ) {
2414        // This wraps the "real" body content (i.e. parser output or special page).
2415        // On page views, elements like categories and contentSub are outside of this.
2416        return Html::rawElement( 'div', [
2417            'id' => 'mw-content-text',
2418            'class' => [
2419                'mw-body-content',
2420            ],
2421        ], $html );
2422    }
2423
2424    /**
2425     * Get current skin's options
2426     *
2427     * For documentation about supported options, refer to the Skin constructor.
2428     *
2429     * @internal Please call SkinFactory::getSkinOptions instead
2430     * @return array
2431     */
2432    final public function getOptions(): array {
2433        return $this->options + [
2434            'styles' => [],
2435            'scripts' => [],
2436            'toc' => true,
2437            'bodyClasses' => [],
2438            'bodyOnly' => false,
2439            'clientPrefEnabled' => false,
2440            'responsive' => false,
2441            'link' => [],
2442            'tempUserBanner' => false,
2443            'menus' => [
2444                // Legacy keys that are enabled by default for backwards compatibility
2445                'namespaces',
2446                'views',
2447                'actions',
2448                'variants',
2449                // Opt-in menus
2450                // * 'associated-pages'
2451                // * 'notifications'
2452                // * 'user-interface-preferences',
2453                // * 'user-page',
2454                // * 'user-menu',
2455            ]
2456        ];
2457    }
2458
2459    /**
2460     * Does the skin support the named menu?
2461     *
2462     * @since 1.39
2463     * @param string $menu See Skin::__construct for menu names.
2464     * @return bool
2465     */
2466    public function supportsMenu( string $menu ): bool {
2467        $options = $this->getOptions();
2468        return in_array( $menu, $options['menus'] );
2469    }
2470
2471    /**
2472     * Returns skin options for portlet links, used by addPortletLink
2473     *
2474     * @internal
2475     * @param RL\Context $context
2476     * @return array $linkOptions
2477     *   - 'text-wrapper' key to specify a list of elements to wrap the text of
2478     *   a link in. This should be an array of arrays containing a 'tag' and
2479     *   optionally an 'attributes' key. If you only have one element you don't
2480     *   need to wrap it in another array. eg: To use <a><span>...</span></a>
2481     *   in all links use [ 'text-wrapper' => [ 'tag' => 'span' ] ]
2482     *   for your options. If text-wrapper contains multiple entries they are
2483     *   interpreted as going from the outer wrapper to the inner wrapper.
2484     */
2485    public static function getPortletLinkOptions( RL\Context $context ): array {
2486        $skinName = $context->getSkin();
2487        $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
2488        $options = $skinFactory->getSkinOptions( $skinName );
2489        $portletLinkOptions = $options['link'] ?? [];
2490        // Normalize link options to always have this key
2491        $portletLinkOptions += [ 'text-wrapper' => [] ];
2492        // Normalize text-wrapper to always be an array of arrays
2493        if ( isset( $portletLinkOptions['text-wrapper']['tag'] ) ) {
2494            $portletLinkOptions['text-wrapper'] = [ $portletLinkOptions['text-wrapper'] ];
2495        }
2496        return $portletLinkOptions;
2497    }
2498
2499    /**
2500     * @param string $name of the portal e.g. p-personal the name is personal.
2501     * @param array $items that are accepted input to Skin::makeListItem
2502     *
2503     * @return array data that can be passed to a Mustache template that
2504     *   represents a single menu.
2505     */
2506    final protected function getPortletData( string $name, array $items ): array {
2507        $portletComponent = new SkinComponentMenu(
2508            $name,
2509            $items,
2510            $this->getContext(),
2511            '',
2512            $this->defaultLinkOptions,
2513            $this->getAfterPortlet( $name )
2514        );
2515        return $portletComponent->getTemplateData();
2516    }
2517}