3 * Base class for all skins.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
24 use Wikimedia\WrappedString
;
25 use Wikimedia\WrappedStringList
;
28 * @defgroup Skins Skins
32 * The main skin class which provides methods and properties for all other skins.
34 * See docs/skin.txt for more information.
38 abstract class Skin
extends ContextSource
{
42 protected $skinname = null;
44 protected $mRelevantTitle = null;
45 protected $mRelevantUser = null;
48 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
49 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
51 public $stylename = null;
54 * Fetch the set of available skins.
55 * @return array Associative array of strings
57 static function getSkinNames() {
58 return SkinFactory
::getDefaultInstance()->getSkinNames();
62 * Fetch the skinname messages for available skins.
65 static function getSkinNameMessages() {
67 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
68 $messages[] = "skinname-$skinKey";
74 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
75 * Useful for Special:Preferences and other places where you
76 * only want to show skins users _can_ use.
80 public static function getAllowedSkins() {
83 $allowedSkins = self
::getSkinNames();
85 foreach ( $wgSkipSkins as $skip ) {
86 unset( $allowedSkins[$skip] );
93 * Normalize a skin preference value to a form that can be loaded.
95 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
96 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
98 * @param string $key 'monobook', 'vector', etc.
101 static function normalizeKey( $key ) {
102 global $wgDefaultSkin, $wgFallbackSkin;
104 $skinNames = self
::getSkinNames();
106 // Make keys lowercase for case-insensitive matching.
107 $skinNames = array_change_key_case( $skinNames, CASE_LOWER
);
108 $key = strtolower( $key );
109 $defaultSkin = strtolower( $wgDefaultSkin );
110 $fallbackSkin = strtolower( $wgFallbackSkin );
112 if ( $key == '' ||
$key == 'default' ) {
113 // Don't return the default immediately;
114 // in a misconfiguration we need to fall back.
118 if ( isset( $skinNames[$key] ) ) {
122 // Older versions of the software used a numeric setting
123 // in the user preferences.
129 if ( isset( $fallback[$key] ) ) {
130 $key = $fallback[$key];
133 if ( isset( $skinNames[$key] ) ) {
135 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
138 return $fallbackSkin;
144 * @param string|null $skinname
146 public function __construct( $skinname = null ) {
147 if ( is_string( $skinname ) ) {
148 $this->skinname
= $skinname;
153 * @return string|null Skin name
155 public function getSkinName() {
156 return $this->skinname
;
160 * @param OutputPage $out
162 public function initPage( OutputPage
$out ) {
163 $this->preloadExistence();
167 * Defines the ResourceLoader modules that should be added to the skin
168 * It is recommended that skins wishing to override call parent::getDefaultModules()
169 * and substitute out any modules they wish to change by using a key to look them up
171 * Any modules defined with the 'styles' key will be added as render blocking CSS via
172 * Output::addModuleStyles. Similarly, each key should refer to a list of modules
174 * @return array Array of modules with helper keys for easy overriding
176 public function getDefaultModules() {
177 $out = $this->getOutput();
178 $user = $this->getUser();
180 // Modules declared in the $modules literal are loaded
181 // for ALL users, on ALL pages, in ALL skins.
182 // Keep this list as small as possible!
185 // The 'styles' key sets render-blocking style modules
186 // Unlike other keys in $modules, this is an associative array
187 // where each key is its own group pointing to a list of modules
189 'mediawiki.legacy.shared',
190 'mediawiki.legacy.commonPrint',
197 'mediawiki.page.startup',
199 // modules that enhance the content in some way
201 'mediawiki.page.ready',
203 // modules relating to search functionality
205 'mediawiki.searchSuggest',
207 // modules relating to functionality relating to watching an article
209 // modules which relate to the current users preferences
211 // modules relating to RSS/Atom Feeds
215 // Preload jquery.tablesorter for mediawiki.page.ready
216 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
217 $modules['content'][] = 'jquery.tablesorter';
220 // Preload jquery.makeCollapsible for mediawiki.page.ready
221 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
222 $modules['content'][] = 'jquery.makeCollapsible';
223 $modules['styles']['content'][] = 'jquery.makeCollapsible.styles';
226 // Deprecated since 1.26: Unconditional loading of mediawiki.ui.button
227 // on every page is deprecated. Express a dependency instead.
228 if ( strpos( $out->getHTML(), 'mw-ui-button' ) !== false ) {
229 $modules['styles']['content'][] = 'mediawiki.ui.button';
232 if ( $out->isTOCEnabled() ) {
233 $modules['content'][] = 'mediawiki.toc';
234 $modules['styles']['content'][] = 'mediawiki.toc.styles';
237 // Add various resources if required
238 if ( $user->isLoggedIn()
239 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
240 && $this->getRelevantTitle()->canExist()
242 $modules['watch'][] = 'mediawiki.page.watch.ajax';
245 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
246 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
249 // Crazy edit-on-double-click stuff
250 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
251 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
254 if ( $out->isSyndicated() ) {
255 $modules['styles']['syndicate'][] = 'mediawiki.feedlink';
262 * Preload the existence of three commonly-requested pages in a single query
264 protected function preloadExistence() {
268 $user = $this->getUser();
269 if ( $user->isLoggedIn() ) {
270 $titles[] = $user->getUserPage();
271 $titles[] = $user->getTalkPage();
274 // Check, if the page can hold some kind of content, otherwise do nothing
275 $title = $this->getRelevantTitle();
276 if ( $title->canExist() ) {
277 if ( $title->isTalkPage() ) {
278 $titles[] = $title->getSubjectPage();
280 $titles[] = $title->getTalkPage();
284 // Footer links (used by SkinTemplate::prepareQuickTemplate)
286 $this->footerLinkTitle( 'privacy', 'privacypage' ),
287 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
288 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
295 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
298 $lb = new LinkBatch( $titles );
299 $lb->setCaller( __METHOD__
);
305 * Get the current revision ID
309 public function getRevisionId() {
310 return $this->getOutput()->getRevisionId();
314 * Whether the revision displayed is the latest revision of the page
318 public function isRevisionCurrent() {
319 $revID = $this->getRevisionId();
320 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
324 * Set the "relevant" title
325 * @see self::getRelevantTitle()
328 public function setRelevantTitle( $t ) {
329 $this->mRelevantTitle
= $t;
333 * Return the "relevant" title.
334 * A "relevant" title is not necessarily the actual title of the page.
335 * Special pages like Special:MovePage use set the page they are acting on
336 * as their "relevant" title, this allows the skin system to display things
337 * such as content tabs which belong to to that page instead of displaying
338 * a basic special page tab which has almost no meaning.
342 public function getRelevantTitle() {
343 return $this->mRelevantTitle ??
$this->getTitle();
347 * Set the "relevant" user
348 * @see self::getRelevantUser()
351 public function setRelevantUser( $u ) {
352 $this->mRelevantUser
= $u;
356 * Return the "relevant" user.
357 * A "relevant" user is similar to a relevant title. Special pages like
358 * Special:Contributions mark the user which they are relevant to so that
359 * things like the toolbox can display the information they usually are only
360 * able to display on a user's userpage and talkpage.
363 public function getRelevantUser() {
364 if ( isset( $this->mRelevantUser
) ) {
365 return $this->mRelevantUser
;
367 $title = $this->getRelevantTitle();
368 if ( $title->hasSubjectNamespace( NS_USER
) ) {
369 $rootUser = $title->getRootText();
370 if ( User
::isIP( $rootUser ) ) {
371 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
373 $user = User
::newFromName( $rootUser, false );
376 $user->load( User
::READ_NORMAL
);
378 if ( $user->isLoggedIn() ) {
379 $this->mRelevantUser
= $user;
383 return $this->mRelevantUser
;
389 * Outputs the HTML generated by other functions.
390 * @param OutputPage|null $out
392 abstract function outputPage( OutputPage
$out = null );
396 * @param string|null $nonce OutputPage::getCSPNonce()
397 * @return string|WrappedString HTML
399 public static function makeVariablesScript( $data, $nonce = null ) {
401 return ResourceLoader
::makeInlineScript(
402 ResourceLoader
::makeConfigSetScript( $data ),
410 * Get the query to generate a dynamic stylesheet
412 * @deprecated since 1.32 Use action=raw&ctype=text/css directly.
415 public static function getDynamicStylesheetQuery() {
418 'ctype' => 'text/css',
423 * Hook point for adding style modules to OutputPage.
425 * @deprecated since 1.32 Use getDefaultModules() instead.
426 * @param OutputPage $out Legacy parameter, identical to $this->getOutput()
428 public function setupSkinUserCss( OutputPage
$out ) {
434 * @param Title $title
437 function getPageClasses( $title ) {
438 $numeric = 'ns-' . $title->getNamespace();
439 $user = $this->getUser();
441 if ( $title->isSpecialPage() ) {
442 $type = 'ns-special';
443 // T25315: provide a class based on the canonical special page name without subpages
444 list( $canonicalName ) = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
445 resolveAlias( $title->getDBkey() );
446 if ( $canonicalName ) {
447 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
449 $type .= ' mw-invalidspecialpage';
452 if ( $title->isTalkPage() ) {
455 $type = 'ns-subject';
457 // T208315: add HTML class when the user can edit the page
458 if ( $title->quickUserCan( 'edit', $user ) ) {
459 $type .= ' mw-editable';
463 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
464 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
466 return "$numeric $type $name $root";
470 * Return values for <html> element
471 * @return array Array of associative name-to-value elements for <html> element
473 public function getHtmlElementAttributes() {
474 $lang = $this->getLanguage();
476 'lang' => $lang->getHtmlCode(),
477 'dir' => $lang->getDir(),
478 'class' => 'client-nojs',
483 * This will be called by OutputPage::headElement when it is creating the
484 * "<body>" tag, skins can override it if they have a need to add in any
485 * body attributes or classes of their own.
486 * @param OutputPage $out
487 * @param array &$bodyAttrs
489 function addToBodyAttributes( $out, &$bodyAttrs ) {
490 // does nothing by default
498 return $this->getConfig()->get( 'Logo' );
502 * Whether the logo should be preloaded with an HTTP link header or not
504 * @deprecated since 1.32 Redundant. It now happens automatically based on whether
505 * the skin loads a stylesheet based on ResourceLoaderSkinModule, which all
506 * skins that use wgLogo in CSS do, and other's would not.
510 public function shouldPreloadLogo() {
515 * @return string HTML
517 function getCategoryLinks() {
518 $out = $this->getOutput();
519 $allCats = $out->getCategoryLinks();
521 if ( $allCats === [] ) {
529 $colon = $this->msg( 'colon-separator' )->escaped();
531 if ( !empty( $allCats['normal'] ) ) {
532 $t = $embed . implode( $pop . $embed, $allCats['normal'] ) . $pop;
534 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
535 $linkPage = $this->msg( 'pagecategorieslink' )->inContentLanguage()->text();
536 $title = Title
::newFromText( $linkPage );
537 $link = $title ? Linker
::link( $title, $msg ) : $msg;
538 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
539 $link . $colon . '<ul>' . $t . '</ul></div>';
543 if ( isset( $allCats['hidden'] ) ) {
544 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
545 $class = ' mw-hidden-cats-user-shown';
546 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
547 $class = ' mw-hidden-cats-ns-shown';
549 $class = ' mw-hidden-cats-hidden';
552 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
553 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
554 $colon . '<ul>' . $embed . implode( $pop . $embed, $allCats['hidden'] ) . $pop . '</ul>' .
558 # optional 'dmoz-like' category browser. Will be shown under the list
559 # of categories an article belong to
560 if ( $this->getConfig()->get( 'UseCategoryBrowser' ) ) {
561 $s .= '<br /><hr />';
563 # get a big array of the parents tree
564 $parenttree = $this->getTitle()->getParentCategoryTree();
565 # Skin object passed by reference cause it can not be
566 # accessed under the method subfunction drawCategoryBrowser
567 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
568 # Clean out bogus first entry and sort them
569 unset( $tempout[0] );
571 # Output one per line
572 $s .= implode( "<br />\n", $tempout );
579 * Render the array as a series of links.
580 * @param array $tree Categories tree returned by Title::getParentCategoryTree
581 * @return string Separated by >, terminate with "\n"
583 function drawCategoryBrowser( $tree ) {
586 foreach ( $tree as $element => $parent ) {
587 if ( empty( $parent ) ) {
588 # element start a new list
591 # grab the others elements
592 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
595 # add our current element to the list
596 $eltitle = Title
::newFromText( $element );
597 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
604 * @return string HTML
606 function getCategories() {
607 $out = $this->getOutput();
608 $catlinks = $this->getCategoryLinks();
610 // Check what we're showing
611 $allCats = $out->getCategoryLinks();
612 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
613 $this->getTitle()->getNamespace() == NS_CATEGORY
;
615 $classes = [ 'catlinks' ];
616 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
617 $classes[] = 'catlinks-allhidden';
620 return Html
::rawElement(
622 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
628 * This runs a hook to allow extensions placing their stuff after content
629 * and article metadata (e.g. categories).
630 * Note: This function has nothing to do with afterContent().
632 * This hook is placed here in order to allow using the same hook for all
633 * skins, both the SkinTemplate based ones and the older ones, which directly
634 * use this class to get their data.
636 * The output of this function gets processed in SkinTemplate::outputPage() for
637 * the SkinTemplate based skins, all other skins should directly echo it.
639 * @return string Empty by default, if not changed by any hook function.
641 protected function afterContentHook() {
644 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
645 // adding just some spaces shouldn't toggle the output
646 // of the whole <div/>, so we use trim() here
647 if ( trim( $data ) != '' ) {
648 // Doing this here instead of in the skins to
649 // ensure that the div has the same ID in all
651 $data = "<div id='mw-data-after-content'>\n" .
656 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
663 * Generate debug data HTML for displaying at the bottom of the main content
665 * @return string HTML containing debug data, if enabled (otherwise empty).
667 protected function generateDebugHTML() {
668 return MWDebug
::getHTMLDebugLog();
672 * This gets called shortly before the "</body>" tag.
674 * @return string|WrappedStringList HTML containing scripts to put before `</body>`
676 function bottomScripts() {
677 // TODO and the suckage continues. This function is really just a wrapper around
678 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
680 $chunks = [ $this->getOutput()->getBottomScripts() ];
682 // Keep the hook appendage separate to preserve WrappedString objects.
683 // This enables BaseTemplate::getTrail() to merge them where possible.
685 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$extraHtml ] );
686 if ( $extraHtml !== '' ) {
687 $chunks[] = $extraHtml;
689 return WrappedString
::join( "\n", $chunks );
693 * Text with the permalink to the source page,
694 * usually shown on the footer of a printed page
696 * @return string HTML text with an URL
698 function printSource() {
699 $oldid = $this->getRevisionId();
701 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
702 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
704 // oldid not available for non existing pages
705 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
708 return $this->msg( 'retrievedfrom' )
709 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
714 * @return string HTML
716 function getUndeleteLink() {
717 $action = $this->getRequest()->getVal( 'action', 'view' );
718 $title = $this->getTitle();
720 if ( ( !$title->exists() ||
$action == 'history' ) &&
721 $title->quickUserCan( 'deletedhistory', $this->getUser() )
723 $n = $title->isDeleted();
726 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
727 $msg = 'thisisdeleted';
729 $msg = 'viewdeleted';
732 return $this->msg( $msg )->rawParams(
734 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
735 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
744 * @param OutputPage|null $out Defaults to $this->getOutput() if left as null
747 function subPageSubtitle( $out = null ) {
748 if ( $out === null ) {
749 $out = $this->getOutput();
751 $title = $out->getTitle();
754 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
758 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
759 $ptext = $title->getPrefixedText();
760 if ( strpos( $ptext, '/' ) !== false ) {
761 $links = explode( '/', $ptext );
766 $lang = $this->getLanguage();
768 foreach ( $links as $link ) {
769 $growinglink .= $link;
771 $linkObj = Title
::newFromText( $growinglink );
773 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
774 $getlink = Linker
::linkKnown(
776 htmlspecialchars( $display )
782 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
784 $subpages .= '< ';
787 $subpages .= $getlink;
803 function getSearchLink() {
804 $searchPage = SpecialPage
::getTitleFor( 'Search' );
805 return $searchPage->getLocalURL();
811 function escapeSearchLink() {
812 return htmlspecialchars( $this->getSearchLink() );
816 * @param string $type
819 function getCopyright( $type = 'detect' ) {
820 if ( $type == 'detect' ) {
821 if ( !$this->isRevisionCurrent()
822 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
830 if ( $type == 'history' ) {
831 $msg = 'history_copyright';
836 $config = $this->getConfig();
838 if ( $config->get( 'RightsPage' ) ) {
839 $title = Title
::newFromText( $config->get( 'RightsPage' ) );
840 $link = Linker
::linkKnown( $title, $config->get( 'RightsText' ) );
841 } elseif ( $config->get( 'RightsUrl' ) ) {
842 $link = Linker
::makeExternalLink( $config->get( 'RightsUrl' ), $config->get( 'RightsText' ) );
843 } elseif ( $config->get( 'RightsText' ) ) {
844 $link = $config->get( 'RightsText' );
850 // Allow for site and per-namespace customization of copyright notice.
851 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
855 'SkinCopyrightFooter',
856 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
859 return $this->msg( $msg )->rawParams( $link )->text();
863 * @return null|string
865 function getCopyrightIcon() {
867 $config = $this->getConfig();
869 $footerIcons = $config->get( 'FooterIcons' );
870 if ( $footerIcons['copyright']['copyright'] ) {
871 $out = $footerIcons['copyright']['copyright'];
872 } elseif ( $config->get( 'RightsIcon' ) ) {
873 $icon = htmlspecialchars( $config->get( 'RightsIcon' ) );
874 $url = $config->get( 'RightsUrl' );
877 $out .= '<a href="' . htmlspecialchars( $url ) . '">';
880 $text = htmlspecialchars( $config->get( 'RightsText' ) );
881 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
892 * Gets the powered by MediaWiki icon.
895 function getPoweredBy() {
896 $resourceBasePath = $this->getConfig()->get( 'ResourceBasePath' );
897 $url1 = htmlspecialchars(
898 "$resourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
900 $url1_5 = htmlspecialchars(
901 "$resourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
903 $url2 = htmlspecialchars(
904 "$resourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
906 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
907 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
908 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
909 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
914 * Get the timestamp of the latest revision, formatted in user language
918 protected function lastModified() {
919 $timestamp = $this->getOutput()->getRevisionTimestamp();
921 # No cached timestamp, load it from the database
922 if ( $timestamp === null ) {
923 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
927 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
928 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
929 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
934 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLaggedReplicaMode() ) {
935 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
942 * @param string $align
945 function logoText( $align = '' ) {
946 if ( $align != '' ) {
947 $a = " style='float: {$align};'";
952 $mp = $this->msg( 'mainpage' )->escaped();
953 $mptitle = Title
::newMainPage();
954 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
956 $logourl = $this->getLogo();
957 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
963 * Renders a $wgFooterIcons icon according to the method's arguments
964 * @param array $icon The icon to build the html for, see $wgFooterIcons
965 * for the format of this array.
966 * @param bool|string $withImage Whether to use the icon's image or output
967 * a text-only footericon.
968 * @return string HTML
970 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
971 if ( is_string( $icon ) ) {
973 } else { // Assuming array
974 $url = $icon["url"] ??
null;
975 unset( $icon["url"] );
976 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
977 // do this the lazy way, just pass icon data as an attribute array
978 $html = Html
::element( 'img', $icon );
980 $html = htmlspecialchars( $icon["alt"] );
983 $html = Html
::rawElement( 'a',
984 [ "href" => $url, "target" => $this->getConfig()->get( 'ExternalLinkTarget' ) ],
992 * Gets the link to the wiki's main page.
995 function mainPageLink() {
996 $s = Linker
::linkKnown(
997 Title
::newMainPage(),
998 $this->msg( 'mainpage' )->escaped()
1005 * Returns an HTML link for use in the footer
1006 * @param string $desc The i18n message key for the link text
1007 * @param string $page The i18n message key for the page to link to
1008 * @return string HTML anchor
1010 public function footerLink( $desc, $page ) {
1011 $title = $this->footerLinkTitle( $desc, $page );
1016 return Linker
::linkKnown(
1018 $this->msg( $desc )->escaped()
1023 * @param string $desc
1024 * @param string $page
1025 * @return Title|null
1027 private function footerLinkTitle( $desc, $page ) {
1028 // If the link description has been set to "-" in the default language,
1029 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
1030 // then it is disabled, for all languages.
1033 // Otherwise, we display the link for the user, described in their
1034 // language (which may or may not be the same as the default language),
1035 // but we make the link target be the one site-wide page.
1036 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1038 return $title ?
: null;
1042 * Gets the link to the wiki's privacy policy page.
1043 * @return string HTML
1045 function privacyLink() {
1046 return $this->footerLink( 'privacy', 'privacypage' );
1050 * Gets the link to the wiki's about page.
1051 * @return string HTML
1053 function aboutLink() {
1054 return $this->footerLink( 'aboutsite', 'aboutpage' );
1058 * Gets the link to the wiki's general disclaimers page.
1059 * @return string HTML
1061 function disclaimerLink() {
1062 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1066 * Return URL options for the 'edit page' link.
1067 * This may include an 'oldid' specifier, if the current page view is such.
1072 function editUrlOptions() {
1073 $options = [ 'action' => 'edit' ];
1075 if ( !$this->isRevisionCurrent() ) {
1076 $options['oldid'] = intval( $this->getRevisionId() );
1083 * @param User|int $id
1086 function showEmailUser( $id ) {
1087 if ( $id instanceof User
) {
1090 $targetUser = User
::newFromId( $id );
1093 # The sending user must have a confirmed email address and the receiving
1094 # user must accept emails from the sender.
1095 return $this->getUser()->canSendEmail()
1096 && SpecialEmailUser
::validateTarget( $targetUser, $this->getUser() ) === '';
1100 * Return a fully resolved style path URL to images or styles stored in the
1101 * current skin's folder. This method returns a URL resolved using the
1102 * configured skin style path.
1104 * Requires $stylename to be set, otherwise throws MWException.
1106 * @param string $name The name or path of a skin resource file
1107 * @return string The fully resolved style path URL
1108 * @throws MWException
1110 function getSkinStylePath( $name ) {
1111 if ( $this->stylename
=== null ) {
1112 $class = static::class;
1113 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1116 return $this->getConfig()->get( 'StylePath' ) . "/{$this->stylename}/$name";
1119 /* these are used extensively in SkinTemplate, but also some other places */
1122 * @param string|string[] $urlaction
1125 static function makeMainPageUrl( $urlaction = '' ) {
1126 $title = Title
::newMainPage();
1127 self
::checkTitle( $title, '' );
1129 return $title->getLinkURL( $urlaction );
1133 * Make a URL for a Special Page using the given query and protocol.
1135 * If $proto is set to null, make a local URL. Otherwise, make a full
1136 * URL with the protocol specified.
1138 * @param string $name Name of the Special page
1139 * @param string|string[] $urlaction Query to append
1140 * @param string|null $proto Protocol to use or null for a local URL
1143 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1144 $title = SpecialPage
::getSafeTitleFor( $name );
1145 if ( is_null( $proto ) ) {
1146 return $title->getLocalURL( $urlaction );
1148 return $title->getFullURL( $urlaction, false, $proto );
1153 * @param string $name
1154 * @param string $subpage
1155 * @param string|string[] $urlaction
1158 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1159 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1160 return $title->getLocalURL( $urlaction );
1164 * @param string $name
1165 * @param string|string[] $urlaction
1168 static function makeI18nUrl( $name, $urlaction = '' ) {
1169 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1170 self
::checkTitle( $title, $name );
1171 return $title->getLocalURL( $urlaction );
1175 * @param string $name
1176 * @param string|string[] $urlaction
1179 static function makeUrl( $name, $urlaction = '' ) {
1180 $title = Title
::newFromText( $name );
1181 self
::checkTitle( $title, $name );
1183 return $title->getLocalURL( $urlaction );
1187 * If url string starts with http, consider as external URL, else
1189 * @param string $name
1190 * @return string URL
1192 static function makeInternalOrExternalUrl( $name ) {
1193 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1196 return self
::makeUrl( $name );
1201 * this can be passed the NS number as defined in Language.php
1202 * @param string $name
1203 * @param string|string[] $urlaction
1204 * @param int $namespace
1207 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1208 $title = Title
::makeTitleSafe( $namespace, $name );
1209 self
::checkTitle( $title, $name );
1211 return $title->getLocalURL( $urlaction );
1215 * these return an array with the 'href' and boolean 'exists'
1216 * @param string $name
1217 * @param string|string[] $urlaction
1220 static function makeUrlDetails( $name, $urlaction = '' ) {
1221 $title = Title
::newFromText( $name );
1222 self
::checkTitle( $title, $name );
1225 'href' => $title->getLocalURL( $urlaction ),
1226 'exists' => $title->isKnown(),
1231 * Make URL details where the article exists (or at least it's convenient to think so)
1232 * @param string $name Article name
1233 * @param string|string[] $urlaction
1236 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1237 $title = Title
::newFromText( $name );
1238 self
::checkTitle( $title, $name );
1241 'href' => $title->getLocalURL( $urlaction ),
1247 * make sure we have some title to operate on
1249 * @param Title &$title
1250 * @param string $name
1252 static function checkTitle( &$title, $name ) {
1253 if ( !is_object( $title ) ) {
1254 $title = Title
::newFromText( $name );
1255 if ( !is_object( $title ) ) {
1256 $title = Title
::newFromText( '--error: link target missing--' );
1262 * Build an array that represents the sidebar(s), the navigation bar among them.
1264 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1266 * The format of the returned array is [ heading => content, ... ], where:
1267 * - heading is the heading of a navigation portlet. It is either:
1268 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1269 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1270 * - plain text, which should be HTML-escaped by the skin
1271 * - content is the contents of the portlet. It is either:
1272 * - HTML text (<ul><li>...</li>...</ul>)
1273 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1274 * - (for a magic string as a key, any value)
1276 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1277 * and can technically insert anything in here; skin creators are expected to handle
1278 * values described above.
1282 public function buildSidebar() {
1283 $callback = function ( $old = null, &$ttl = null ) {
1285 $this->addToSidebar( $bar, 'sidebar' );
1286 Hooks
::run( 'SkinBuildSidebar', [ $this, &$bar ] );
1287 if ( MessageCache
::singleton()->isDisabled() ) {
1288 $ttl = WANObjectCache
::TTL_UNCACHEABLE
; // bug T133069
1294 $msgCache = MessageCache
::singleton();
1295 $wanCache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1296 $config = $this->getConfig();
1298 $sidebar = $config->get( 'EnableSidebarCache' )
1299 ?
$wanCache->getWithSetCallback(
1300 $wanCache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1301 $config->get( 'SidebarCacheExpiry' ),
1305 // Unless there is both no exact $code override nor an i18n definition
1306 // in the software, the only MediaWiki page to check is for $code.
1307 $msgCache->getCheckKey( $this->getLanguage()->getCode() )
1314 // Apply post-processing to the cached value
1315 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1321 * Add content from a sidebar system message
1322 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1324 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1326 * @param array &$bar
1327 * @param string $message
1329 public function addToSidebar( &$bar, $message ) {
1330 $this->addToSidebarPlain( $bar, $this->msg( $message )->inContentLanguage()->plain() );
1334 * Add content from plain text
1336 * @param array &$bar
1337 * @param string $text
1340 function addToSidebarPlain( &$bar, $text ) {
1341 $lines = explode( "\n", $text );
1344 $config = $this->getConfig();
1345 $messageTitle = $config->get( 'EnableSidebarCache' )
1346 ? Title
::newMainPage() : $this->getTitle();
1348 foreach ( $lines as $line ) {
1349 if ( strpos( $line, '*' ) !== 0 ) {
1352 $line = rtrim( $line, "\r" ); // for Windows compat
1354 if ( strpos( $line, '**' ) !== 0 ) {
1355 $heading = trim( $line, '* ' );
1356 if ( !array_key_exists( $heading, $bar ) ) {
1357 $bar[$heading] = [];
1360 $line = trim( $line, '* ' );
1362 if ( strpos( $line, '|' ) !== false ) { // sanity check
1363 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1364 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1365 if ( count( $line ) !== 2 ) {
1366 // Second sanity check, could be hit by people doing
1367 // funky stuff with parserfuncs... (T35321)
1373 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1374 if ( $msgLink->exists() ) {
1375 $link = $msgLink->text();
1376 if ( $link == '-' ) {
1382 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1383 if ( $msgText->exists() ) {
1384 $text = $msgText->text();
1389 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1392 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1393 if ( $config->get( 'NoFollowLinks' ) &&
1394 !wfMatchesDomainList( $href, $config->get( 'NoFollowDomainExceptions' ) )
1396 $extraAttribs['rel'] = 'nofollow';
1399 if ( $config->get( 'ExternalLinkTarget' ) ) {
1400 $extraAttribs['target'] = $config->get( 'ExternalLinkTarget' );
1403 $title = Title
::newFromText( $link );
1406 $title = $title->fixSpecialName();
1407 $href = $title->getLinkURL();
1409 $href = 'INVALID-TITLE';
1413 $bar[$heading][] = array_merge( [
1416 'id' => Sanitizer
::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1429 * Gets new talk page messages for the current user and returns an
1430 * appropriate alert message (or an empty string if there are no messages)
1433 function getNewtalks() {
1434 $newMessagesAlert = '';
1435 $user = $this->getUser();
1436 $newtalks = $user->getNewMessageLinks();
1437 $out = $this->getOutput();
1439 // Allow extensions to disable or modify the new messages alert
1440 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1443 if ( $newMessagesAlert ) {
1444 return $newMessagesAlert;
1447 if ( count( $newtalks ) == 1 && WikiMap
::isCurrentWikiId( $newtalks[0]['wiki'] ) ) {
1448 $uTalkTitle = $user->getTalkPage();
1449 $lastSeenRev = $newtalks[0]['rev'] ??
null;
1451 if ( $lastSeenRev !== null ) {
1452 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1453 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1454 if ( $latestRev !== null ) {
1455 // Singular if only 1 unseen revision, plural if several unseen revisions.
1456 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1457 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1458 $lastSeenRev, $latestRev, 10, 'include_new' );
1461 // Singular if no revision -> diff link will show latest change only in any case
1464 $plural = $plural ?
999 : 1;
1465 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1466 // the number of revisions or authors is not necessarily the same as the number of
1468 $newMessagesLink = Linker
::linkKnown(
1470 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1472 $uTalkTitle->isRedirect() ?
[ 'redirect' => 'no' ] : []
1475 $newMessagesDiffLink = Linker
::linkKnown(
1477 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1479 $lastSeenRev !== null
1480 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1481 : [ 'diff' => 'cur' ]
1484 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1485 $newMessagesAlert = $this->msg(
1486 'youhavenewmessagesfromusers',
1488 $newMessagesDiffLink
1489 )->numParams( $nofAuthors, $plural );
1491 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1492 $newMessagesAlert = $this->msg(
1493 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1495 $newMessagesDiffLink
1496 )->numParams( $plural );
1498 $newMessagesAlert = $newMessagesAlert->text();
1500 $out->setCdnMaxage( 0 );
1501 } elseif ( count( $newtalks ) ) {
1502 $sep = $this->msg( 'newtalkseparator' )->escaped();
1505 foreach ( $newtalks as $newtalk ) {
1506 $msgs[] = Xml
::element(
1508 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1511 $parts = implode( $sep, $msgs );
1512 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1513 $out->setCdnMaxage( 0 );
1516 return $newMessagesAlert;
1520 * Get a cached notice
1522 * @param string $name Message name, or 'default' for $wgSiteNotice
1523 * @return string|bool HTML fragment, or false to indicate that the caller
1524 * should fall back to the next notice in its sequence
1526 private function getCachedNotice( $name ) {
1527 $config = $this->getConfig();
1529 if ( $name === 'default' ) {
1531 $notice = $config->get( 'SiteNotice' );
1532 if ( empty( $notice ) ) {
1536 $msg = $this->msg( $name )->inContentLanguage();
1537 if ( $msg->isBlank() ) {
1539 } elseif ( $msg->isDisabled() ) {
1542 $notice = $msg->plain();
1545 $services = MediaWikiServices
::getInstance();
1546 $cache = $services->getMainWANObjectCache();
1547 $parsed = $cache->getWithSetCallback(
1548 // Use the extra hash appender to let eg SSL variants separately cache
1549 // Key is verified with md5 hash of unparsed wikitext
1550 $cache->makeKey( $name, $config->get( 'RenderHashAppend' ), md5( $notice ) ),
1553 function () use ( $notice ) {
1554 return $this->getOutput()->parseAsInterface( $notice );
1558 $contLang = $services->getContentLanguage();
1559 return Html
::rawElement(
1562 'id' => 'localNotice',
1563 'lang' => $contLang->getHtmlCode(),
1564 'dir' => $contLang->getDir()
1571 * Get the site notice
1573 * @return string HTML fragment
1575 function getSiteNotice() {
1578 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1579 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1580 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1582 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1583 if ( $anonNotice === false ) {
1584 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1586 $siteNotice = $anonNotice;
1589 if ( $siteNotice === false ) {
1590 $siteNotice = $this->getCachedNotice( 'default' );
1594 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1599 * Create a section edit link.
1601 * @suppress SecurityCheck-XSS $links has keys of different taint types
1602 * @param Title $nt The title being linked to (may not be the same as
1603 * the current page, if the section is included from a template)
1604 * @param string $section The designation of the section being pointed to,
1605 * to be included in the link, like "§ion=$section"
1606 * @param string|null $tooltip The tooltip to use for the link: will be escaped
1607 * and wrapped in the 'editsectionhint' message
1608 * @param Language $lang Language object
1609 * @return string HTML to use for edit link
1611 public function doEditSectionLink( Title
$nt, $section, $tooltip, Language
$lang ) {
1612 // HTML generated here should probably have userlangattributes
1613 // added to it for LTR text on RTL pages
1616 if ( !is_null( $tooltip ) ) {
1617 $attribs['title'] = $this->msg( 'editsectionhint' )->rawParams( $tooltip )
1618 ->inLanguage( $lang )->text();
1623 'text' => $this->msg( 'editsection' )->inLanguage( $lang )->text(),
1624 'targetTitle' => $nt,
1625 'attribs' => $attribs,
1626 'query' => [ 'action' => 'edit', 'section' => $section ],
1627 'options' => [ 'noclasses', 'known' ]
1631 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1633 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1636 foreach ( $links as $k => $linkDetails ) {
1637 $linksHtml[] = Linker
::link(
1638 $linkDetails['targetTitle'],
1639 htmlspecialchars( $linkDetails['text'] ),
1640 $linkDetails['attribs'],
1641 $linkDetails['query'],
1642 $linkDetails['options']
1647 '<span class="mw-editsection-divider">'
1648 . $this->msg( 'pipe-separator' )->inLanguage( $lang )->escaped()
1653 $result .= '<span class="mw-editsection-bracket">]</span></span>';