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 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
59 return $skinFactory->getSkinNames();
63 * Fetch the skinname messages for available skins.
64 * @deprecated since 1.34, no longer used.
67 static function getSkinNameMessages() {
68 wfDeprecated( __METHOD__
, '1.34' );
70 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
71 $messages[] = "skinname-$skinKey";
77 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
78 * Useful for Special:Preferences and other places where you
79 * only want to show skins users _can_ use.
83 public static function getAllowedSkins() {
86 $allowedSkins = self
::getSkinNames();
88 foreach ( $wgSkipSkins as $skip ) {
89 unset( $allowedSkins[$skip] );
96 * Normalize a skin preference value to a form that can be loaded.
98 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
99 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
101 * @param string $key 'monobook', 'vector', etc.
104 static function normalizeKey( $key ) {
105 global $wgDefaultSkin, $wgFallbackSkin;
107 $skinNames = self
::getSkinNames();
109 // Make keys lowercase for case-insensitive matching.
110 $skinNames = array_change_key_case( $skinNames, CASE_LOWER
);
111 $key = strtolower( $key );
112 $defaultSkin = strtolower( $wgDefaultSkin );
113 $fallbackSkin = strtolower( $wgFallbackSkin );
115 if ( $key == '' ||
$key == 'default' ) {
116 // Don't return the default immediately;
117 // in a misconfiguration we need to fall back.
121 if ( isset( $skinNames[$key] ) ) {
125 // Older versions of the software used a numeric setting
126 // in the user preferences.
132 if ( isset( $fallback[$key] ) ) {
133 $key = $fallback[$key];
136 if ( isset( $skinNames[$key] ) ) {
138 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
141 return $fallbackSkin;
147 * @param string|null $skinname
149 public function __construct( $skinname = null ) {
150 if ( is_string( $skinname ) ) {
151 $this->skinname
= $skinname;
156 * @return string|null Skin name
158 public function getSkinName() {
159 return $this->skinname
;
163 * @param OutputPage $out
165 public function initPage( OutputPage
$out ) {
166 $this->preloadExistence();
170 * Defines the ResourceLoader modules that should be added to the skin
171 * It is recommended that skins wishing to override call parent::getDefaultModules()
172 * and substitute out any modules they wish to change by using a key to look them up
174 * Any modules defined with the 'styles' key will be added as render blocking CSS via
175 * Output::addModuleStyles. Similarly, each key should refer to a list of modules
177 * @return array Array of modules with helper keys for easy overriding
179 public function getDefaultModules() {
180 $out = $this->getOutput();
181 $user = $this->getUser();
183 // Modules declared in the $modules literal are loaded
184 // for ALL users, on ALL pages, in ALL skins.
185 // Keep this list as small as possible!
188 // The 'styles' key sets render-blocking style modules
189 // Unlike other keys in $modules, this is an associative array
190 // where each key is its own group pointing to a list of modules
192 'mediawiki.legacy.shared',
193 'mediawiki.legacy.commonPrint',
200 'mediawiki.page.startup',
202 // modules that enhance the content in some way
204 'mediawiki.page.ready',
206 // modules relating to search functionality
208 'mediawiki.searchSuggest',
210 // modules relating to functionality relating to watching an article
212 // modules which relate to the current users preferences
214 // modules relating to RSS/Atom Feeds
218 // Preload jquery.tablesorter for mediawiki.page.ready
219 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
220 $modules['content'][] = 'jquery.tablesorter';
221 $modules['styles']['content'][] = 'jquery.tablesorter.styles';
224 // Preload jquery.makeCollapsible for mediawiki.page.ready
225 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
226 $modules['content'][] = 'jquery.makeCollapsible';
227 $modules['styles']['content'][] = 'jquery.makeCollapsible.styles';
230 // Deprecated since 1.26: Unconditional loading of mediawiki.ui.button
231 // on every page is deprecated. Express a dependency instead.
232 if ( strpos( $out->getHTML(), 'mw-ui-button' ) !== false ) {
233 $modules['styles']['content'][] = 'mediawiki.ui.button';
236 if ( $out->isTOCEnabled() ) {
237 $modules['content'][] = 'mediawiki.toc';
238 $modules['styles']['content'][] = 'mediawiki.toc.styles';
241 // Add various resources if required
242 if ( $user->isLoggedIn()
243 && MediaWikiServices
::getInstance()
244 ->getPermissionManager()
245 ->userHasAllRights( $user, 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
246 && $this->getRelevantTitle()->canExist()
248 $modules['watch'][] = 'mediawiki.page.watch.ajax';
251 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
252 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
255 // Crazy edit-on-double-click stuff
256 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
257 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
260 if ( $out->isSyndicated() ) {
261 $modules['styles']['syndicate'][] = 'mediawiki.feedlink';
268 * Preload the existence of three commonly-requested pages in a single query
270 protected function preloadExistence() {
274 $user = $this->getUser();
275 if ( $user->isLoggedIn() ) {
276 $titles[] = $user->getUserPage();
277 $titles[] = $user->getTalkPage();
280 // Check, if the page can hold some kind of content, otherwise do nothing
281 $title = $this->getRelevantTitle();
282 if ( $title->canExist() && $title->canHaveTalkPage() ) {
283 if ( $title->isTalkPage() ) {
284 $titles[] = $title->getSubjectPage();
286 $titles[] = $title->getTalkPage();
290 // Footer links (used by SkinTemplate::prepareQuickTemplate)
292 $this->footerLinkTitle( 'privacy', 'privacypage' ),
293 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
294 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
301 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
304 $lb = new LinkBatch( $titles );
305 $lb->setCaller( __METHOD__
);
311 * Get the current revision ID
313 * @deprecated since 1.34, use OutputPage::getRevisionId instead
316 public function getRevisionId() {
317 return $this->getOutput()->getRevisionId();
321 * Whether the revision displayed is the latest revision of the page
323 * @deprecated since 1.34, use OutputPage::isRevisionCurrent instead
326 public function isRevisionCurrent() {
327 return $this->getOutput()->isRevisionCurrent();
331 * Set the "relevant" title
332 * @see self::getRelevantTitle()
335 public function setRelevantTitle( $t ) {
336 $this->mRelevantTitle
= $t;
340 * Return the "relevant" title.
341 * A "relevant" title is not necessarily the actual title of the page.
342 * Special pages like Special:MovePage use set the page they are acting on
343 * as their "relevant" title, this allows the skin system to display things
344 * such as content tabs which belong to to that page instead of displaying
345 * a basic special page tab which has almost no meaning.
349 public function getRelevantTitle() {
350 return $this->mRelevantTitle ??
$this->getTitle();
354 * Set the "relevant" user
355 * @see self::getRelevantUser()
358 public function setRelevantUser( $u ) {
359 $this->mRelevantUser
= $u;
363 * Return the "relevant" user.
364 * A "relevant" user is similar to a relevant title. Special pages like
365 * Special:Contributions mark the user which they are relevant to so that
366 * things like the toolbox can display the information they usually are only
367 * able to display on a user's userpage and talkpage.
370 public function getRelevantUser() {
371 if ( isset( $this->mRelevantUser
) ) {
372 return $this->mRelevantUser
;
374 $title = $this->getRelevantTitle();
375 if ( $title->hasSubjectNamespace( NS_USER
) ) {
376 $rootUser = $title->getRootText();
377 if ( User
::isIP( $rootUser ) ) {
378 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
380 $user = User
::newFromName( $rootUser, false );
383 $user->load( User
::READ_NORMAL
);
385 if ( $user->isLoggedIn() ) {
386 $this->mRelevantUser
= $user;
390 return $this->mRelevantUser
;
396 * Outputs the HTML generated by other functions.
398 abstract function outputPage();
402 * @param string|null $nonce OutputPage::getCSPNonce()
403 * @return string|WrappedString HTML
405 public static function makeVariablesScript( $data, $nonce = null ) {
407 return ResourceLoader
::makeInlineScript(
408 ResourceLoader
::makeConfigSetScript( $data ),
416 * Get the query to generate a dynamic stylesheet
418 * @deprecated since 1.32 Use action=raw&ctype=text/css directly.
421 public static function getDynamicStylesheetQuery() {
424 'ctype' => 'text/css',
429 * Hook point for adding style modules to OutputPage.
431 * @deprecated since 1.32 Use getDefaultModules() instead.
432 * @param OutputPage $out Legacy parameter, identical to $this->getOutput()
434 public function setupSkinUserCss( OutputPage
$out ) {
440 * @param Title $title
443 function getPageClasses( $title ) {
444 $numeric = 'ns-' . $title->getNamespace();
445 $user = $this->getUser();
447 if ( $title->isSpecialPage() ) {
448 $type = 'ns-special';
449 // T25315: provide a class based on the canonical special page name without subpages
450 list( $canonicalName ) = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
451 resolveAlias( $title->getDBkey() );
452 if ( $canonicalName ) {
453 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
455 $type .= ' mw-invalidspecialpage';
458 if ( $title->isTalkPage() ) {
461 $type = 'ns-subject';
463 // T208315: add HTML class when the user can edit the page
464 if ( MediaWikiServices
::getInstance()->getPermissionManager()
465 ->quickUserCan( 'edit', $user, $title )
467 $type .= ' mw-editable';
471 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
472 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
474 return "$numeric $type $name $root";
478 * Return values for <html> element
479 * @return array Array of associative name-to-value elements for <html> element
481 public function getHtmlElementAttributes() {
482 $lang = $this->getLanguage();
484 'lang' => $lang->getHtmlCode(),
485 'dir' => $lang->getDir(),
486 'class' => 'client-nojs',
491 * This will be called by OutputPage::headElement when it is creating the
492 * "<body>" tag, skins can override it if they have a need to add in any
493 * body attributes or classes of their own.
494 * @param OutputPage $out
495 * @param array &$bodyAttrs
497 function addToBodyAttributes( $out, &$bodyAttrs ) {
498 // does nothing by default
506 return $this->getConfig()->get( 'Logo' );
510 * Whether the logo should be preloaded with an HTTP link header or not
512 * @deprecated since 1.32 Redundant. It now happens automatically based on whether
513 * the skin loads a stylesheet based on ResourceLoaderSkinModule, which all
514 * skins that use wgLogo in CSS do, and other's would not.
518 public function shouldPreloadLogo() {
523 * @return string HTML
525 function getCategoryLinks() {
526 $out = $this->getOutput();
527 $allCats = $out->getCategoryLinks();
528 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
530 if ( $allCats === [] ) {
538 $colon = $this->msg( 'colon-separator' )->escaped();
540 if ( !empty( $allCats['normal'] ) ) {
541 $t = $embed . implode( $pop . $embed, $allCats['normal'] ) . $pop;
543 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) );
544 $linkPage = $this->msg( 'pagecategorieslink' )->inContentLanguage()->text();
545 $title = Title
::newFromText( $linkPage );
546 $link = $title ?
$linkRenderer->makeLink( $title, $msg->text() ) : $msg->escaped();
547 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
548 $link . $colon . '<ul>' . $t . '</ul></div>';
552 if ( isset( $allCats['hidden'] ) ) {
553 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
554 $class = ' mw-hidden-cats-user-shown';
555 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
556 $class = ' mw-hidden-cats-ns-shown';
558 $class = ' mw-hidden-cats-hidden';
561 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
562 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
563 $colon . '<ul>' . $embed . implode( $pop . $embed, $allCats['hidden'] ) . $pop . '</ul>' .
567 # optional 'dmoz-like' category browser. Will be shown under the list
568 # of categories an article belong to
569 if ( $this->getConfig()->get( 'UseCategoryBrowser' ) ) {
570 $s .= '<br /><hr />';
572 # get a big array of the parents tree
573 $parenttree = $this->getTitle()->getParentCategoryTree();
574 # Skin object passed by reference cause it can not be
575 # accessed under the method subfunction drawCategoryBrowser
576 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
577 # Clean out bogus first entry and sort them
578 unset( $tempout[0] );
580 # Output one per line
581 $s .= implode( "<br />\n", $tempout );
588 * Render the array as a series of links.
589 * @param array $tree Categories tree returned by Title::getParentCategoryTree
590 * @return string Separated by >, terminate with "\n"
592 function drawCategoryBrowser( $tree ) {
594 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
596 foreach ( $tree as $element => $parent ) {
597 if ( empty( $parent ) ) {
598 # element start a new list
601 # grab the others elements
602 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
605 # add our current element to the list
606 $eltitle = Title
::newFromText( $element );
607 $return .= $linkRenderer->makeLink( $eltitle, $eltitle->getText() );
614 * @return string HTML
616 function getCategories() {
617 $out = $this->getOutput();
618 $catlinks = $this->getCategoryLinks();
620 // Check what we're showing
621 $allCats = $out->getCategoryLinks();
622 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
623 $this->getTitle()->getNamespace() == NS_CATEGORY
;
625 $classes = [ 'catlinks' ];
626 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
627 $classes[] = 'catlinks-allhidden';
630 return Html
::rawElement(
632 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
638 * This runs a hook to allow extensions placing their stuff after content
639 * and article metadata (e.g. categories).
640 * Note: This function has nothing to do with afterContent().
642 * This hook is placed here in order to allow using the same hook for all
643 * skins, both the SkinTemplate based ones and the older ones, which directly
644 * use this class to get their data.
646 * The output of this function gets processed in SkinTemplate::outputPage() for
647 * the SkinTemplate based skins, all other skins should directly echo it.
649 * @return string Empty by default, if not changed by any hook function.
651 protected function afterContentHook() {
654 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
655 // adding just some spaces shouldn't toggle the output
656 // of the whole <div/>, so we use trim() here
657 if ( trim( $data ) != '' ) {
658 // Doing this here instead of in the skins to
659 // ensure that the div has the same ID in all
661 $data = "<div id='mw-data-after-content'>\n" .
666 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
673 * Generate debug data HTML for displaying at the bottom of the main content
675 * @return string HTML containing debug data, if enabled (otherwise empty).
677 protected function generateDebugHTML() {
678 return MWDebug
::getHTMLDebugLog();
682 * This gets called shortly before the "</body>" tag.
684 * @return string|WrappedStringList HTML containing scripts to put before `</body>`
686 function bottomScripts() {
687 // TODO and the suckage continues. This function is really just a wrapper around
688 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
690 $chunks = [ $this->getOutput()->getBottomScripts() ];
692 // Keep the hook appendage separate to preserve WrappedString objects.
693 // This enables BaseTemplate::getTrail() to merge them where possible.
695 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$extraHtml ] );
696 if ( $extraHtml !== '' ) {
697 $chunks[] = $extraHtml;
699 return WrappedString
::join( "\n", $chunks );
703 * Text with the permalink to the source page,
704 * usually shown on the footer of a printed page
706 * @return string HTML text with an URL
708 function printSource() {
709 $oldid = $this->getOutput()->getRevisionId();
711 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
712 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
714 // oldid not available for non existing pages
715 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
718 return $this->msg( 'retrievedfrom' )
719 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
724 * @return string HTML
726 function getUndeleteLink() {
727 $action = $this->getRequest()->getVal( 'action', 'view' );
728 $title = $this->getTitle();
729 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
730 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
732 if ( ( !$title->exists() ||
$action == 'history' ) &&
733 $permissionManager->quickUserCan( 'deletedhistory', $this->getUser(), $title )
735 $n = $title->isDeleted();
738 if ( $permissionManager->quickUserCan( 'undelete',
739 $this->getUser(), $this->getTitle() )
741 $msg = 'thisisdeleted';
743 $msg = 'viewdeleted';
746 $subtitle = $this->msg( $msg )->rawParams(
747 $linkRenderer->makeKnownLink(
748 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
749 $this->msg( 'restorelink' )->numParams( $n )->text() )
752 // Allow extensions to add more links
754 Hooks
::run( 'UndeletePageToolLinks', [ $this->getContext(), $linkRenderer, &$links ] );
758 . $this->msg( 'word-separator' )->escaped()
759 . $this->msg( 'parentheses' )
760 ->rawParams( $this->getLanguage()->pipeList( $links ) )
763 return Html
::rawElement( 'div', [ 'class' => 'mw-undelete-subtitle' ], $subtitle );
771 * @param OutputPage|null $out Defaults to $this->getOutput() if left as null
774 function subPageSubtitle( $out = null ) {
775 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
776 if ( $out === null ) {
777 $out = $this->getOutput();
779 $title = $out->getTitle();
782 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
787 $out->isArticle() && MediaWikiServices
::getInstance()->getNamespaceInfo()->
788 hasSubpages( $title->getNamespace() )
790 $ptext = $title->getPrefixedText();
791 if ( strpos( $ptext, '/' ) !== false ) {
792 $links = explode( '/', $ptext );
797 $lang = $this->getLanguage();
799 foreach ( $links as $link ) {
800 $growinglink .= $link;
802 $linkObj = Title
::newFromText( $growinglink );
804 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
805 $getlink = $linkRenderer->makeKnownLink(
812 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
814 $subpages .= '< ';
817 $subpages .= $getlink;
833 function getSearchLink() {
834 $searchPage = SpecialPage
::getTitleFor( 'Search' );
835 return $searchPage->getLocalURL();
839 * @deprecated since 1.34, use getSearchLink() instead.
842 function escapeSearchLink() {
843 wfDeprecated( __METHOD__
, '1.34' );
844 return htmlspecialchars( $this->getSearchLink() );
848 * @param string $type
851 function getCopyright( $type = 'detect' ) {
852 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
853 if ( $type == 'detect' ) {
854 if ( !$this->getOutput()->isRevisionCurrent()
855 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
863 if ( $type == 'history' ) {
864 $msg = 'history_copyright';
869 $config = $this->getConfig();
871 if ( $config->get( 'RightsPage' ) ) {
872 $title = Title
::newFromText( $config->get( 'RightsPage' ) );
873 $link = $linkRenderer->makeKnownLink(
874 $title, new HtmlArmor( $config->get( 'RightsText' ) )
876 } elseif ( $config->get( 'RightsUrl' ) ) {
877 $link = Linker
::makeExternalLink( $config->get( 'RightsUrl' ), $config->get( 'RightsText' ) );
878 } elseif ( $config->get( 'RightsText' ) ) {
879 $link = $config->get( 'RightsText' );
885 // Allow for site and per-namespace customization of copyright notice.
886 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
890 'SkinCopyrightFooter',
891 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
894 return $this->msg( $msg )->rawParams( $link )->text();
898 * @return null|string
900 function getCopyrightIcon() {
902 $config = $this->getConfig();
904 $footerIcons = $config->get( 'FooterIcons' );
905 if ( $footerIcons['copyright']['copyright'] ) {
906 $out = $footerIcons['copyright']['copyright'];
907 } elseif ( $config->get( 'RightsIcon' ) ) {
908 $icon = htmlspecialchars( $config->get( 'RightsIcon' ) );
909 $url = $config->get( 'RightsUrl' );
912 $out .= '<a href="' . htmlspecialchars( $url ) . '">';
915 $text = htmlspecialchars( $config->get( 'RightsText' ) );
916 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
927 * Gets the powered by MediaWiki icon.
930 function getPoweredBy() {
931 $resourceBasePath = $this->getConfig()->get( 'ResourceBasePath' );
932 $url1 = htmlspecialchars(
933 "$resourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
935 $url1_5 = htmlspecialchars(
936 "$resourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
938 $url2 = htmlspecialchars(
939 "$resourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
941 $text = '<a href="https://www.mediawiki.org/"><img src="' . $url1
942 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
943 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
944 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
949 * Get the timestamp of the latest revision, formatted in user language
953 protected function lastModified() {
954 $timestamp = $this->getOutput()->getRevisionTimestamp();
956 # No cached timestamp, load it from the database
957 if ( $timestamp === null ) {
958 $timestamp = Revision
::getTimestampFromId( $this->getTitle(),
959 $this->getOutput()->getRevisionId() );
963 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
964 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
965 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
970 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLaggedReplicaMode() ) {
971 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
978 * @param string $align
981 function logoText( $align = '' ) {
982 if ( $align != '' ) {
983 $a = " style='float: {$align};'";
988 $mp = $this->msg( 'mainpage' )->escaped();
989 $mptitle = Title
::newMainPage();
990 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
992 $logourl = $this->getLogo();
993 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
999 * Renders a $wgFooterIcons icon according to the method's arguments
1000 * @param array $icon The icon to build the html for, see $wgFooterIcons
1001 * for the format of this array.
1002 * @param bool|string $withImage Whether to use the icon's image or output
1003 * a text-only footericon.
1004 * @return string HTML
1006 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
1007 if ( is_string( $icon ) ) {
1009 } else { // Assuming array
1010 $url = $icon["url"] ??
null;
1011 unset( $icon["url"] );
1012 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
1013 // do this the lazy way, just pass icon data as an attribute array
1014 $html = Html
::element( 'img', $icon );
1016 $html = htmlspecialchars( $icon["alt"] );
1019 $html = Html
::rawElement( 'a',
1020 [ "href" => $url, "target" => $this->getConfig()->get( 'ExternalLinkTarget' ) ],
1028 * Gets the link to the wiki's main page.
1031 function mainPageLink() {
1032 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1033 $s = $linkRenderer->makeKnownLink(
1034 Title
::newMainPage(),
1035 $this->msg( 'mainpage' )->text()
1042 * Returns an HTML link for use in the footer
1043 * @param string $desc The i18n message key for the link text
1044 * @param string $page The i18n message key for the page to link to
1045 * @return string HTML anchor
1047 public function footerLink( $desc, $page ) {
1048 $title = $this->footerLinkTitle( $desc, $page );
1049 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1054 return $linkRenderer->makeKnownLink(
1056 $this->msg( $desc )->text()
1061 * @param string $desc
1062 * @param string $page
1063 * @return Title|null
1065 private function footerLinkTitle( $desc, $page ) {
1066 // If the link description has been set to "-" in the default language,
1067 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
1068 // then it is disabled, for all languages.
1071 // Otherwise, we display the link for the user, described in their
1072 // language (which may or may not be the same as the default language),
1073 // but we make the link target be the one site-wide page.
1074 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1076 return $title ?
: null;
1080 * Gets the link to the wiki's privacy policy page.
1081 * @return string HTML
1083 function privacyLink() {
1084 return $this->footerLink( 'privacy', 'privacypage' );
1088 * Gets the link to the wiki's about page.
1089 * @return string HTML
1091 function aboutLink() {
1092 return $this->footerLink( 'aboutsite', 'aboutpage' );
1096 * Gets the link to the wiki's general disclaimers page.
1097 * @return string HTML
1099 function disclaimerLink() {
1100 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1104 * Return URL options for the 'edit page' link.
1105 * This may include an 'oldid' specifier, if the current page view is such.
1110 function editUrlOptions() {
1111 $options = [ 'action' => 'edit' ];
1113 if ( !$this->getOutput()->isRevisionCurrent() ) {
1114 $options['oldid'] = intval( $this->getOutput()->getRevisionId() );
1121 * @param User|int $id
1124 function showEmailUser( $id ) {
1125 if ( $id instanceof User
) {
1128 $targetUser = User
::newFromId( $id );
1131 # The sending user must have a confirmed email address and the receiving
1132 # user must accept emails from the sender.
1133 return $this->getUser()->canSendEmail()
1134 && SpecialEmailUser
::validateTarget( $targetUser, $this->getUser() ) === '';
1138 * Return a fully resolved style path URL to images or styles stored in the
1139 * current skin's folder. This method returns a URL resolved using the
1140 * configured skin style path.
1142 * Requires $stylename to be set, otherwise throws MWException.
1144 * @param string $name The name or path of a skin resource file
1145 * @return string The fully resolved style path URL
1146 * @throws MWException
1148 function getSkinStylePath( $name ) {
1149 if ( $this->stylename
=== null ) {
1150 $class = static::class;
1151 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1154 return $this->getConfig()->get( 'StylePath' ) . "/{$this->stylename}/$name";
1157 /* these are used extensively in SkinTemplate, but also some other places */
1160 * @param string|string[] $urlaction
1163 static function makeMainPageUrl( $urlaction = '' ) {
1164 $title = Title
::newMainPage();
1165 self
::checkTitle( $title, '' );
1167 return $title->getLinkURL( $urlaction );
1171 * Make a URL for a Special Page using the given query and protocol.
1173 * If $proto is set to null, make a local URL. Otherwise, make a full
1174 * URL with the protocol specified.
1176 * @param string $name Name of the Special page
1177 * @param string|string[] $urlaction Query to append
1178 * @param string|null $proto Protocol to use or null for a local URL
1181 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1182 $title = SpecialPage
::getSafeTitleFor( $name );
1183 if ( is_null( $proto ) ) {
1184 return $title->getLocalURL( $urlaction );
1186 return $title->getFullURL( $urlaction, false, $proto );
1191 * @param string $name
1192 * @param string $subpage
1193 * @param string|string[] $urlaction
1196 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1197 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1198 return $title->getLocalURL( $urlaction );
1202 * @param string $name
1203 * @param string|string[] $urlaction
1206 static function makeI18nUrl( $name, $urlaction = '' ) {
1207 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1208 self
::checkTitle( $title, $name );
1209 return $title->getLocalURL( $urlaction );
1213 * @param string $name
1214 * @param string|string[] $urlaction
1217 static function makeUrl( $name, $urlaction = '' ) {
1218 $title = Title
::newFromText( $name );
1219 self
::checkTitle( $title, $name );
1221 return $title->getLocalURL( $urlaction );
1225 * If url string starts with http, consider as external URL, else
1227 * @param string $name
1228 * @return string URL
1230 static function makeInternalOrExternalUrl( $name ) {
1231 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1234 return self
::makeUrl( $name );
1239 * this can be passed the NS number as defined in Language.php
1240 * @param string $name
1241 * @param string|string[] $urlaction
1242 * @param int $namespace
1245 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1246 $title = Title
::makeTitleSafe( $namespace, $name );
1247 self
::checkTitle( $title, $name );
1249 return $title->getLocalURL( $urlaction );
1253 * these return an array with the 'href' and boolean 'exists'
1254 * @param string $name
1255 * @param string|string[] $urlaction
1258 static function makeUrlDetails( $name, $urlaction = '' ) {
1259 $title = Title
::newFromText( $name );
1260 self
::checkTitle( $title, $name );
1263 'href' => $title->getLocalURL( $urlaction ),
1264 'exists' => $title->isKnown(),
1269 * Make URL details where the article exists (or at least it's convenient to think so)
1270 * @param string $name Article name
1271 * @param string|string[] $urlaction
1274 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1275 $title = Title
::newFromText( $name );
1276 self
::checkTitle( $title, $name );
1279 'href' => $title->getLocalURL( $urlaction ),
1285 * make sure we have some title to operate on
1287 * @param Title &$title
1288 * @param string $name
1290 static function checkTitle( &$title, $name ) {
1291 if ( !is_object( $title ) ) {
1292 $title = Title
::newFromText( $name );
1293 if ( !is_object( $title ) ) {
1294 $title = Title
::newFromText( '--error: link target missing--' );
1300 * Build an array that represents the sidebar(s), the navigation bar among them.
1302 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1304 * The format of the returned array is [ heading => content, ... ], where:
1305 * - heading is the heading of a navigation portlet. It is either:
1306 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1307 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1308 * - plain text, which should be HTML-escaped by the skin
1309 * - content is the contents of the portlet. It is either:
1310 * - HTML text (<ul><li>...</li>...</ul>)
1311 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1312 * - (for a magic string as a key, any value)
1314 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1315 * and can technically insert anything in here; skin creators are expected to handle
1316 * values described above.
1320 public function buildSidebar() {
1321 $services = MediaWikiServices
::getInstance();
1322 $callback = function ( $old = null, &$ttl = null ) {
1324 $this->addToSidebar( $bar, 'sidebar' );
1325 Hooks
::run( 'SkinBuildSidebar', [ $this, &$bar ] );
1326 $msgCache = MediaWikiServices
::getInstance()->getMessageCache();
1327 if ( $msgCache->isDisabled() ) {
1328 $ttl = WANObjectCache
::TTL_UNCACHEABLE
; // bug T133069
1334 $msgCache = $services->getMessageCache();
1335 $wanCache = $services->getMainWANObjectCache();
1336 $config = $this->getConfig();
1338 $sidebar = $config->get( 'EnableSidebarCache' )
1339 ?
$wanCache->getWithSetCallback(
1340 $wanCache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1341 $config->get( 'SidebarCacheExpiry' ),
1345 // Unless there is both no exact $code override nor an i18n definition
1346 // in the software, the only MediaWiki page to check is for $code.
1347 $msgCache->getCheckKey( $this->getLanguage()->getCode() )
1354 // Apply post-processing to the cached value
1355 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1361 * Add content from a sidebar system message
1362 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1364 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1366 * @param array &$bar
1367 * @param string $message
1369 public function addToSidebar( &$bar, $message ) {
1370 $this->addToSidebarPlain( $bar, $this->msg( $message )->inContentLanguage()->plain() );
1374 * Add content from plain text
1376 * @param array &$bar
1377 * @param string $text
1380 function addToSidebarPlain( &$bar, $text ) {
1381 $lines = explode( "\n", $text );
1384 $config = $this->getConfig();
1385 $messageTitle = $config->get( 'EnableSidebarCache' )
1386 ? Title
::newMainPage() : $this->getTitle();
1388 foreach ( $lines as $line ) {
1389 if ( strpos( $line, '*' ) !== 0 ) {
1392 $line = rtrim( $line, "\r" ); // for Windows compat
1394 if ( strpos( $line, '**' ) !== 0 ) {
1395 $heading = trim( $line, '* ' );
1396 if ( !array_key_exists( $heading, $bar ) ) {
1397 $bar[$heading] = [];
1400 $line = trim( $line, '* ' );
1402 if ( strpos( $line, '|' ) !== false ) { // sanity check
1403 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1404 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1405 if ( count( $line ) !== 2 ) {
1406 // Second sanity check, could be hit by people doing
1407 // funky stuff with parserfuncs... (T35321)
1413 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1414 if ( $msgLink->exists() ) {
1415 $link = $msgLink->text();
1416 if ( $link == '-' ) {
1422 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1423 if ( $msgText->exists() ) {
1424 $text = $msgText->text();
1429 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1432 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1433 if ( $config->get( 'NoFollowLinks' ) &&
1434 !wfMatchesDomainList( $href, $config->get( 'NoFollowDomainExceptions' ) )
1436 $extraAttribs['rel'] = 'nofollow';
1439 if ( $config->get( 'ExternalLinkTarget' ) ) {
1440 $extraAttribs['target'] = $config->get( 'ExternalLinkTarget' );
1443 $title = Title
::newFromText( $link );
1446 $title = $title->fixSpecialName();
1447 $href = $title->getLinkURL();
1449 $href = 'INVALID-TITLE';
1453 $bar[$heading][] = array_merge( [
1456 'id' => Sanitizer
::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1469 * Gets new talk page messages for the current user and returns an
1470 * appropriate alert message (or an empty string if there are no messages)
1473 function getNewtalks() {
1474 $newMessagesAlert = '';
1475 $user = $this->getUser();
1476 $newtalks = $user->getNewMessageLinks();
1477 $out = $this->getOutput();
1478 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1480 // Allow extensions to disable or modify the new messages alert
1481 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1484 if ( $newMessagesAlert ) {
1485 return $newMessagesAlert;
1488 if ( count( $newtalks ) == 1 && WikiMap
::isCurrentWikiId( $newtalks[0]['wiki'] ) ) {
1489 $uTalkTitle = $user->getTalkPage();
1490 $lastSeenRev = $newtalks[0]['rev'] ??
null;
1492 if ( $lastSeenRev !== null ) {
1493 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1494 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1495 if ( $latestRev !== null ) {
1496 // Singular if only 1 unseen revision, plural if several unseen revisions.
1497 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1498 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1499 $lastSeenRev, $latestRev, 10, 'include_new' );
1502 // Singular if no revision -> diff link will show latest change only in any case
1505 $plural = $plural ?
999 : 1;
1506 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1507 // the number of revisions or authors is not necessarily the same as the number of
1509 $newMessagesLink = $linkRenderer->makeKnownLink(
1511 $this->msg( 'newmessageslinkplural' )->params( $plural )->text(),
1513 $uTalkTitle->isRedirect() ?
[ 'redirect' => 'no' ] : []
1516 $newMessagesDiffLink = $linkRenderer->makeKnownLink(
1518 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->text(),
1520 $lastSeenRev !== null
1521 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1522 : [ 'diff' => 'cur' ]
1525 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1526 $newMessagesAlert = $this->msg(
1527 'youhavenewmessagesfromusers',
1529 $newMessagesDiffLink
1530 )->numParams( $nofAuthors, $plural );
1532 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1533 $newMessagesAlert = $this->msg(
1534 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1536 $newMessagesDiffLink
1537 )->numParams( $plural );
1539 $newMessagesAlert = $newMessagesAlert->text();
1541 $out->setCdnMaxage( 0 );
1542 } elseif ( count( $newtalks ) ) {
1543 $sep = $this->msg( 'newtalkseparator' )->escaped();
1546 foreach ( $newtalks as $newtalk ) {
1547 $msgs[] = Xml
::element(
1549 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1552 $parts = implode( $sep, $msgs );
1553 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1554 $out->setCdnMaxage( 0 );
1557 return $newMessagesAlert;
1561 * Get a cached notice
1563 * @param string $name Message name, or 'default' for $wgSiteNotice
1564 * @return string|bool HTML fragment, or false to indicate that the caller
1565 * should fall back to the next notice in its sequence
1567 private function getCachedNotice( $name ) {
1568 $config = $this->getConfig();
1570 if ( $name === 'default' ) {
1572 $notice = $config->get( 'SiteNotice' );
1573 if ( empty( $notice ) ) {
1577 $msg = $this->msg( $name )->inContentLanguage();
1578 if ( $msg->isBlank() ) {
1580 } elseif ( $msg->isDisabled() ) {
1583 $notice = $msg->plain();
1586 $services = MediaWikiServices
::getInstance();
1587 $cache = $services->getMainWANObjectCache();
1588 $parsed = $cache->getWithSetCallback(
1589 // Use the extra hash appender to let eg SSL variants separately cache
1590 // Key is verified with md5 hash of unparsed wikitext
1591 $cache->makeKey( $name, $config->get( 'RenderHashAppend' ), md5( $notice ) ),
1594 function () use ( $notice ) {
1595 return $this->getOutput()->parseAsInterface( $notice );
1599 $contLang = $services->getContentLanguage();
1600 return Html
::rawElement(
1603 'id' => 'localNotice',
1604 'lang' => $contLang->getHtmlCode(),
1605 'dir' => $contLang->getDir()
1612 * Get the site notice
1614 * @return string HTML fragment
1616 function getSiteNotice() {
1619 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1620 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1621 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1623 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1624 if ( $anonNotice === false ) {
1625 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1627 $siteNotice = $anonNotice;
1630 if ( $siteNotice === false ) {
1631 $siteNotice = $this->getCachedNotice( 'default' );
1635 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1640 * Create a section edit link.
1642 * @suppress SecurityCheck-XSS $links has keys of different taint types
1643 * @param Title $nt The title being linked to (may not be the same as
1644 * the current page, if the section is included from a template)
1645 * @param string $section The designation of the section being pointed to,
1646 * to be included in the link, like "§ion=$section"
1647 * @param string|null $tooltip The tooltip to use for the link: will be escaped
1648 * and wrapped in the 'editsectionhint' message
1649 * @param Language $lang Language object
1650 * @return string HTML to use for edit link
1652 public function doEditSectionLink( Title
$nt, $section, $tooltip, Language
$lang ) {
1653 // HTML generated here should probably have userlangattributes
1654 // added to it for LTR text on RTL pages
1657 if ( !is_null( $tooltip ) ) {
1658 $attribs['title'] = $this->msg( 'editsectionhint' )->rawParams( $tooltip )
1659 ->inLanguage( $lang )->text();
1664 'text' => $this->msg( 'editsection' )->inLanguage( $lang )->text(),
1665 'targetTitle' => $nt,
1666 'attribs' => $attribs,
1667 'query' => [ 'action' => 'edit', 'section' => $section ]
1671 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1673 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1675 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1677 foreach ( $links as $k => $linkDetails ) {
1678 $linksHtml[] = $linkRenderer->makeKnownLink(
1679 $linkDetails['targetTitle'],
1680 $linkDetails['text'],
1681 $linkDetails['attribs'],
1682 $linkDetails['query']
1687 '<span class="mw-editsection-divider">'
1688 . $this->msg( 'pipe-separator' )->inLanguage( $lang )->escaped()
1693 $result .= '<span class="mw-editsection-bracket">]</span></span>';