Debian Codegraph @

includes/skins/Skin.php

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