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