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 ( $title->quickUserCan( 'edit', $user ) ) {
465 $type .= ' mw-editable';
469 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
470 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
472 return "$numeric $type $name $root";
476 * Return values for <html> element
477 * @return array Array of associative name-to-value elements for <html> element
479 public function getHtmlElementAttributes() {
480 $lang = $this->getLanguage();
482 'lang' => $lang->getHtmlCode(),
483 'dir' => $lang->getDir(),
484 'class' => 'client-nojs',
489 * This will be called by OutputPage::headElement when it is creating the
490 * "<body>" tag, skins can override it if they have a need to add in any
491 * body attributes or classes of their own.
492 * @param OutputPage $out
493 * @param array &$bodyAttrs
495 function addToBodyAttributes( $out, &$bodyAttrs ) {
496 // does nothing by default
504 return $this->getConfig()->get( 'Logo' );
508 * Whether the logo should be preloaded with an HTTP link header or not
510 * @deprecated since 1.32 Redundant. It now happens automatically based on whether
511 * the skin loads a stylesheet based on ResourceLoaderSkinModule, which all
512 * skins that use wgLogo in CSS do, and other's would not.
516 public function shouldPreloadLogo() {
521 * @return string HTML
523 function getCategoryLinks() {
524 $out = $this->getOutput();
525 $allCats = $out->getCategoryLinks();
526 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
528 if ( $allCats === [] ) {
536 $colon = $this->msg( 'colon-separator' )->escaped();
538 if ( !empty( $allCats['normal'] ) ) {
539 $t = $embed . implode( $pop . $embed, $allCats['normal'] ) . $pop;
541 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) );
542 $linkPage = $this->msg( 'pagecategorieslink' )->inContentLanguage()->text();
543 $title = Title
::newFromText( $linkPage );
544 $link = $title ?
$linkRenderer->makeLink( $title, $msg->text() ) : $msg->escaped();
545 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
546 $link . $colon . '<ul>' . $t . '</ul></div>';
550 if ( isset( $allCats['hidden'] ) ) {
551 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
552 $class = ' mw-hidden-cats-user-shown';
553 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
554 $class = ' mw-hidden-cats-ns-shown';
556 $class = ' mw-hidden-cats-hidden';
559 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
560 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
561 $colon . '<ul>' . $embed . implode( $pop . $embed, $allCats['hidden'] ) . $pop . '</ul>' .
565 # optional 'dmoz-like' category browser. Will be shown under the list
566 # of categories an article belong to
567 if ( $this->getConfig()->get( 'UseCategoryBrowser' ) ) {
568 $s .= '<br /><hr />';
570 # get a big array of the parents tree
571 $parenttree = $this->getTitle()->getParentCategoryTree();
572 # Skin object passed by reference cause it can not be
573 # accessed under the method subfunction drawCategoryBrowser
574 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
575 # Clean out bogus first entry and sort them
576 unset( $tempout[0] );
578 # Output one per line
579 $s .= implode( "<br />\n", $tempout );
586 * Render the array as a series of links.
587 * @param array $tree Categories tree returned by Title::getParentCategoryTree
588 * @return string Separated by >, terminate with "\n"
590 function drawCategoryBrowser( $tree ) {
592 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
594 foreach ( $tree as $element => $parent ) {
595 if ( empty( $parent ) ) {
596 # element start a new list
599 # grab the others elements
600 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
603 # add our current element to the list
604 $eltitle = Title
::newFromText( $element );
605 $return .= $linkRenderer->makeLink( $eltitle, $eltitle->getText() );
612 * @return string HTML
614 function getCategories() {
615 $out = $this->getOutput();
616 $catlinks = $this->getCategoryLinks();
618 // Check what we're showing
619 $allCats = $out->getCategoryLinks();
620 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
621 $this->getTitle()->getNamespace() == NS_CATEGORY
;
623 $classes = [ 'catlinks' ];
624 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
625 $classes[] = 'catlinks-allhidden';
628 return Html
::rawElement(
630 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
636 * This runs a hook to allow extensions placing their stuff after content
637 * and article metadata (e.g. categories).
638 * Note: This function has nothing to do with afterContent().
640 * This hook is placed here in order to allow using the same hook for all
641 * skins, both the SkinTemplate based ones and the older ones, which directly
642 * use this class to get their data.
644 * The output of this function gets processed in SkinTemplate::outputPage() for
645 * the SkinTemplate based skins, all other skins should directly echo it.
647 * @return string Empty by default, if not changed by any hook function.
649 protected function afterContentHook() {
652 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
653 // adding just some spaces shouldn't toggle the output
654 // of the whole <div/>, so we use trim() here
655 if ( trim( $data ) != '' ) {
656 // Doing this here instead of in the skins to
657 // ensure that the div has the same ID in all
659 $data = "<div id='mw-data-after-content'>\n" .
664 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
671 * Generate debug data HTML for displaying at the bottom of the main content
673 * @return string HTML containing debug data, if enabled (otherwise empty).
675 protected function generateDebugHTML() {
676 return MWDebug
::getHTMLDebugLog();
680 * This gets called shortly before the "</body>" tag.
682 * @return string|WrappedStringList HTML containing scripts to put before `</body>`
684 function bottomScripts() {
685 // TODO and the suckage continues. This function is really just a wrapper around
686 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
688 $chunks = [ $this->getOutput()->getBottomScripts() ];
690 // Keep the hook appendage separate to preserve WrappedString objects.
691 // This enables BaseTemplate::getTrail() to merge them where possible.
693 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$extraHtml ] );
694 if ( $extraHtml !== '' ) {
695 $chunks[] = $extraHtml;
697 return WrappedString
::join( "\n", $chunks );
701 * Text with the permalink to the source page,
702 * usually shown on the footer of a printed page
704 * @return string HTML text with an URL
706 function printSource() {
707 $oldid = $this->getOutput()->getRevisionId();
709 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
710 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
712 // oldid not available for non existing pages
713 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
716 return $this->msg( 'retrievedfrom' )
717 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
722 * @return string HTML
724 function getUndeleteLink() {
725 $action = $this->getRequest()->getVal( 'action', 'view' );
726 $title = $this->getTitle();
727 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
729 if ( ( !$title->exists() ||
$action == 'history' ) &&
730 $title->quickUserCan( 'deletedhistory', $this->getUser() )
732 $n = $title->isDeleted();
735 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
736 $msg = 'thisisdeleted';
738 $msg = 'viewdeleted';
741 $subtitle = $this->msg( $msg )->rawParams(
742 $linkRenderer->makeKnownLink(
743 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
744 $this->msg( 'restorelink' )->numParams( $n )->text() )
747 // Allow extensions to add more links
749 Hooks
::run( 'UndeletePageToolLinks', [ $this->getContext(), $linkRenderer, &$links ] );
753 . $this->msg( 'word-separator' )->escaped()
754 . $this->msg( 'parentheses' )
755 ->rawParams( $this->getLanguage()->pipeList( $links ) )
758 return Html
::rawElement( 'div', [ 'class' => 'mw-undelete-subtitle' ], $subtitle );
766 * @param OutputPage|null $out Defaults to $this->getOutput() if left as null
769 function subPageSubtitle( $out = null ) {
770 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
771 if ( $out === null ) {
772 $out = $this->getOutput();
774 $title = $out->getTitle();
777 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
782 $out->isArticle() && MediaWikiServices
::getInstance()->getNamespaceInfo()->
783 hasSubpages( $title->getNamespace() )
785 $ptext = $title->getPrefixedText();
786 if ( strpos( $ptext, '/' ) !== false ) {
787 $links = explode( '/', $ptext );
792 $lang = $this->getLanguage();
794 foreach ( $links as $link ) {
795 $growinglink .= $link;
797 $linkObj = Title
::newFromText( $growinglink );
799 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
800 $getlink = $linkRenderer->makeKnownLink(
807 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
809 $subpages .= '< ';
812 $subpages .= $getlink;
828 function getSearchLink() {
829 $searchPage = SpecialPage
::getTitleFor( 'Search' );
830 return $searchPage->getLocalURL();
834 * @deprecated since 1.34, use getSearchLink() instead.
837 function escapeSearchLink() {
838 wfDeprecated( __METHOD__
, '1.34' );
839 return htmlspecialchars( $this->getSearchLink() );
843 * @param string $type
846 function getCopyright( $type = 'detect' ) {
847 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
848 if ( $type == 'detect' ) {
849 if ( !$this->getOutput()->isRevisionCurrent()
850 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
858 if ( $type == 'history' ) {
859 $msg = 'history_copyright';
864 $config = $this->getConfig();
866 if ( $config->get( 'RightsPage' ) ) {
867 $title = Title
::newFromText( $config->get( 'RightsPage' ) );
868 $link = $linkRenderer->makeKnownLink(
869 $title, new HtmlArmor( $config->get( 'RightsText' ) )
871 } elseif ( $config->get( 'RightsUrl' ) ) {
872 $link = Linker
::makeExternalLink( $config->get( 'RightsUrl' ), $config->get( 'RightsText' ) );
873 } elseif ( $config->get( 'RightsText' ) ) {
874 $link = $config->get( 'RightsText' );
880 // Allow for site and per-namespace customization of copyright notice.
881 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
885 'SkinCopyrightFooter',
886 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
889 return $this->msg( $msg )->rawParams( $link )->text();
893 * @return null|string
895 function getCopyrightIcon() {
897 $config = $this->getConfig();
899 $footerIcons = $config->get( 'FooterIcons' );
900 if ( $footerIcons['copyright']['copyright'] ) {
901 $out = $footerIcons['copyright']['copyright'];
902 } elseif ( $config->get( 'RightsIcon' ) ) {
903 $icon = htmlspecialchars( $config->get( 'RightsIcon' ) );
904 $url = $config->get( 'RightsUrl' );
907 $out .= '<a href="' . htmlspecialchars( $url ) . '">';
910 $text = htmlspecialchars( $config->get( 'RightsText' ) );
911 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
922 * Gets the powered by MediaWiki icon.
925 function getPoweredBy() {
926 $resourceBasePath = $this->getConfig()->get( 'ResourceBasePath' );
927 $url1 = htmlspecialchars(
928 "$resourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
930 $url1_5 = htmlspecialchars(
931 "$resourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
933 $url2 = htmlspecialchars(
934 "$resourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
936 $text = '<a href="https://www.mediawiki.org/"><img src="' . $url1
937 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
938 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
939 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
944 * Get the timestamp of the latest revision, formatted in user language
948 protected function lastModified() {
949 $timestamp = $this->getOutput()->getRevisionTimestamp();
951 # No cached timestamp, load it from the database
952 if ( $timestamp === null ) {
953 $timestamp = Revision
::getTimestampFromId( $this->getTitle(),
954 $this->getOutput()->getRevisionId() );
958 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
959 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
960 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
965 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLaggedReplicaMode() ) {
966 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
973 * @param string $align
976 function logoText( $align = '' ) {
977 if ( $align != '' ) {
978 $a = " style='float: {$align};'";
983 $mp = $this->msg( 'mainpage' )->escaped();
984 $mptitle = Title
::newMainPage();
985 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
987 $logourl = $this->getLogo();
988 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
994 * Renders a $wgFooterIcons icon according to the method's arguments
995 * @param array $icon The icon to build the html for, see $wgFooterIcons
996 * for the format of this array.
997 * @param bool|string $withImage Whether to use the icon's image or output
998 * a text-only footericon.
999 * @return string HTML
1001 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
1002 if ( is_string( $icon ) ) {
1004 } else { // Assuming array
1005 $url = $icon["url"] ??
null;
1006 unset( $icon["url"] );
1007 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
1008 // do this the lazy way, just pass icon data as an attribute array
1009 $html = Html
::element( 'img', $icon );
1011 $html = htmlspecialchars( $icon["alt"] );
1014 $html = Html
::rawElement( 'a',
1015 [ "href" => $url, "target" => $this->getConfig()->get( 'ExternalLinkTarget' ) ],
1023 * Gets the link to the wiki's main page.
1026 function mainPageLink() {
1027 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1028 $s = $linkRenderer->makeKnownLink(
1029 Title
::newMainPage(),
1030 $this->msg( 'mainpage' )->text()
1037 * Returns an HTML link for use in the footer
1038 * @param string $desc The i18n message key for the link text
1039 * @param string $page The i18n message key for the page to link to
1040 * @return string HTML anchor
1042 public function footerLink( $desc, $page ) {
1043 $title = $this->footerLinkTitle( $desc, $page );
1044 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1049 return $linkRenderer->makeKnownLink(
1051 $this->msg( $desc )->text()
1056 * @param string $desc
1057 * @param string $page
1058 * @return Title|null
1060 private function footerLinkTitle( $desc, $page ) {
1061 // If the link description has been set to "-" in the default language,
1062 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
1063 // then it is disabled, for all languages.
1066 // Otherwise, we display the link for the user, described in their
1067 // language (which may or may not be the same as the default language),
1068 // but we make the link target be the one site-wide page.
1069 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1071 return $title ?
: null;
1075 * Gets the link to the wiki's privacy policy page.
1076 * @return string HTML
1078 function privacyLink() {
1079 return $this->footerLink( 'privacy', 'privacypage' );
1083 * Gets the link to the wiki's about page.
1084 * @return string HTML
1086 function aboutLink() {
1087 return $this->footerLink( 'aboutsite', 'aboutpage' );
1091 * Gets the link to the wiki's general disclaimers page.
1092 * @return string HTML
1094 function disclaimerLink() {
1095 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1099 * Return URL options for the 'edit page' link.
1100 * This may include an 'oldid' specifier, if the current page view is such.
1105 function editUrlOptions() {
1106 $options = [ 'action' => 'edit' ];
1108 if ( !$this->getOutput()->isRevisionCurrent() ) {
1109 $options['oldid'] = intval( $this->getOutput()->getRevisionId() );
1116 * @param User|int $id
1119 function showEmailUser( $id ) {
1120 if ( $id instanceof User
) {
1123 $targetUser = User
::newFromId( $id );
1126 # The sending user must have a confirmed email address and the receiving
1127 # user must accept emails from the sender.
1128 return $this->getUser()->canSendEmail()
1129 && SpecialEmailUser
::validateTarget( $targetUser, $this->getUser() ) === '';
1133 * Return a fully resolved style path URL to images or styles stored in the
1134 * current skin's folder. This method returns a URL resolved using the
1135 * configured skin style path.
1137 * Requires $stylename to be set, otherwise throws MWException.
1139 * @param string $name The name or path of a skin resource file
1140 * @return string The fully resolved style path URL
1141 * @throws MWException
1143 function getSkinStylePath( $name ) {
1144 if ( $this->stylename
=== null ) {
1145 $class = static::class;
1146 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1149 return $this->getConfig()->get( 'StylePath' ) . "/{$this->stylename}/$name";
1152 /* these are used extensively in SkinTemplate, but also some other places */
1155 * @param string|string[] $urlaction
1158 static function makeMainPageUrl( $urlaction = '' ) {
1159 $title = Title
::newMainPage();
1160 self
::checkTitle( $title, '' );
1162 return $title->getLinkURL( $urlaction );
1166 * Make a URL for a Special Page using the given query and protocol.
1168 * If $proto is set to null, make a local URL. Otherwise, make a full
1169 * URL with the protocol specified.
1171 * @param string $name Name of the Special page
1172 * @param string|string[] $urlaction Query to append
1173 * @param string|null $proto Protocol to use or null for a local URL
1176 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1177 $title = SpecialPage
::getSafeTitleFor( $name );
1178 if ( is_null( $proto ) ) {
1179 return $title->getLocalURL( $urlaction );
1181 return $title->getFullURL( $urlaction, false, $proto );
1186 * @param string $name
1187 * @param string $subpage
1188 * @param string|string[] $urlaction
1191 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1192 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1193 return $title->getLocalURL( $urlaction );
1197 * @param string $name
1198 * @param string|string[] $urlaction
1201 static function makeI18nUrl( $name, $urlaction = '' ) {
1202 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1203 self
::checkTitle( $title, $name );
1204 return $title->getLocalURL( $urlaction );
1208 * @param string $name
1209 * @param string|string[] $urlaction
1212 static function makeUrl( $name, $urlaction = '' ) {
1213 $title = Title
::newFromText( $name );
1214 self
::checkTitle( $title, $name );
1216 return $title->getLocalURL( $urlaction );
1220 * If url string starts with http, consider as external URL, else
1222 * @param string $name
1223 * @return string URL
1225 static function makeInternalOrExternalUrl( $name ) {
1226 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1229 return self
::makeUrl( $name );
1234 * this can be passed the NS number as defined in Language.php
1235 * @param string $name
1236 * @param string|string[] $urlaction
1237 * @param int $namespace
1240 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1241 $title = Title
::makeTitleSafe( $namespace, $name );
1242 self
::checkTitle( $title, $name );
1244 return $title->getLocalURL( $urlaction );
1248 * these return an array with the 'href' and boolean 'exists'
1249 * @param string $name
1250 * @param string|string[] $urlaction
1253 static function makeUrlDetails( $name, $urlaction = '' ) {
1254 $title = Title
::newFromText( $name );
1255 self
::checkTitle( $title, $name );
1258 'href' => $title->getLocalURL( $urlaction ),
1259 'exists' => $title->isKnown(),
1264 * Make URL details where the article exists (or at least it's convenient to think so)
1265 * @param string $name Article name
1266 * @param string|string[] $urlaction
1269 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1270 $title = Title
::newFromText( $name );
1271 self
::checkTitle( $title, $name );
1274 'href' => $title->getLocalURL( $urlaction ),
1280 * make sure we have some title to operate on
1282 * @param Title &$title
1283 * @param string $name
1285 static function checkTitle( &$title, $name ) {
1286 if ( !is_object( $title ) ) {
1287 $title = Title
::newFromText( $name );
1288 if ( !is_object( $title ) ) {
1289 $title = Title
::newFromText( '--error: link target missing--' );
1295 * Build an array that represents the sidebar(s), the navigation bar among them.
1297 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1299 * The format of the returned array is [ heading => content, ... ], where:
1300 * - heading is the heading of a navigation portlet. It is either:
1301 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1302 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1303 * - plain text, which should be HTML-escaped by the skin
1304 * - content is the contents of the portlet. It is either:
1305 * - HTML text (<ul><li>...</li>...</ul>)
1306 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1307 * - (for a magic string as a key, any value)
1309 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1310 * and can technically insert anything in here; skin creators are expected to handle
1311 * values described above.
1315 public function buildSidebar() {
1316 $services = MediaWikiServices
::getInstance();
1317 $callback = function ( $old = null, &$ttl = null ) {
1319 $this->addToSidebar( $bar, 'sidebar' );
1320 Hooks
::run( 'SkinBuildSidebar', [ $this, &$bar ] );
1321 $msgCache = MediaWikiServices
::getInstance()->getMessageCache();
1322 if ( $msgCache->isDisabled() ) {
1323 $ttl = WANObjectCache
::TTL_UNCACHEABLE
; // bug T133069
1329 $msgCache = $services->getMessageCache();
1330 $wanCache = $services->getMainWANObjectCache();
1331 $config = $this->getConfig();
1333 $sidebar = $config->get( 'EnableSidebarCache' )
1334 ?
$wanCache->getWithSetCallback(
1335 $wanCache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1336 $config->get( 'SidebarCacheExpiry' ),
1340 // Unless there is both no exact $code override nor an i18n definition
1341 // in the software, the only MediaWiki page to check is for $code.
1342 $msgCache->getCheckKey( $this->getLanguage()->getCode() )
1349 // Apply post-processing to the cached value
1350 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1356 * Add content from a sidebar system message
1357 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1359 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1361 * @param array &$bar
1362 * @param string $message
1364 public function addToSidebar( &$bar, $message ) {
1365 $this->addToSidebarPlain( $bar, $this->msg( $message )->inContentLanguage()->plain() );
1369 * Add content from plain text
1371 * @param array &$bar
1372 * @param string $text
1375 function addToSidebarPlain( &$bar, $text ) {
1376 $lines = explode( "\n", $text );
1379 $config = $this->getConfig();
1380 $messageTitle = $config->get( 'EnableSidebarCache' )
1381 ? Title
::newMainPage() : $this->getTitle();
1383 foreach ( $lines as $line ) {
1384 if ( strpos( $line, '*' ) !== 0 ) {
1387 $line = rtrim( $line, "\r" ); // for Windows compat
1389 if ( strpos( $line, '**' ) !== 0 ) {
1390 $heading = trim( $line, '* ' );
1391 if ( !array_key_exists( $heading, $bar ) ) {
1392 $bar[$heading] = [];
1395 $line = trim( $line, '* ' );
1397 if ( strpos( $line, '|' ) !== false ) { // sanity check
1398 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1399 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1400 if ( count( $line ) !== 2 ) {
1401 // Second sanity check, could be hit by people doing
1402 // funky stuff with parserfuncs... (T35321)
1408 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1409 if ( $msgLink->exists() ) {
1410 $link = $msgLink->text();
1411 if ( $link == '-' ) {
1417 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1418 if ( $msgText->exists() ) {
1419 $text = $msgText->text();
1424 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1427 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1428 if ( $config->get( 'NoFollowLinks' ) &&
1429 !wfMatchesDomainList( $href, $config->get( 'NoFollowDomainExceptions' ) )
1431 $extraAttribs['rel'] = 'nofollow';
1434 if ( $config->get( 'ExternalLinkTarget' ) ) {
1435 $extraAttribs['target'] = $config->get( 'ExternalLinkTarget' );
1438 $title = Title
::newFromText( $link );
1441 $title = $title->fixSpecialName();
1442 $href = $title->getLinkURL();
1444 $href = 'INVALID-TITLE';
1448 $bar[$heading][] = array_merge( [
1451 'id' => Sanitizer
::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1464 * Gets new talk page messages for the current user and returns an
1465 * appropriate alert message (or an empty string if there are no messages)
1468 function getNewtalks() {
1469 $newMessagesAlert = '';
1470 $user = $this->getUser();
1471 $newtalks = $user->getNewMessageLinks();
1472 $out = $this->getOutput();
1473 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1475 // Allow extensions to disable or modify the new messages alert
1476 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1479 if ( $newMessagesAlert ) {
1480 return $newMessagesAlert;
1483 if ( count( $newtalks ) == 1 && WikiMap
::isCurrentWikiId( $newtalks[0]['wiki'] ) ) {
1484 $uTalkTitle = $user->getTalkPage();
1485 $lastSeenRev = $newtalks[0]['rev'] ??
null;
1487 if ( $lastSeenRev !== null ) {
1488 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1489 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1490 if ( $latestRev !== null ) {
1491 // Singular if only 1 unseen revision, plural if several unseen revisions.
1492 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1493 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1494 $lastSeenRev, $latestRev, 10, 'include_new' );
1497 // Singular if no revision -> diff link will show latest change only in any case
1500 $plural = $plural ?
999 : 1;
1501 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1502 // the number of revisions or authors is not necessarily the same as the number of
1504 $newMessagesLink = $linkRenderer->makeKnownLink(
1506 $this->msg( 'newmessageslinkplural' )->params( $plural )->text(),
1508 $uTalkTitle->isRedirect() ?
[ 'redirect' => 'no' ] : []
1511 $newMessagesDiffLink = $linkRenderer->makeKnownLink(
1513 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->text(),
1515 $lastSeenRev !== null
1516 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1517 : [ 'diff' => 'cur' ]
1520 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1521 $newMessagesAlert = $this->msg(
1522 'youhavenewmessagesfromusers',
1524 $newMessagesDiffLink
1525 )->numParams( $nofAuthors, $plural );
1527 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1528 $newMessagesAlert = $this->msg(
1529 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1531 $newMessagesDiffLink
1532 )->numParams( $plural );
1534 $newMessagesAlert = $newMessagesAlert->text();
1536 $out->setCdnMaxage( 0 );
1537 } elseif ( count( $newtalks ) ) {
1538 $sep = $this->msg( 'newtalkseparator' )->escaped();
1541 foreach ( $newtalks as $newtalk ) {
1542 $msgs[] = Xml
::element(
1544 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1547 $parts = implode( $sep, $msgs );
1548 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1549 $out->setCdnMaxage( 0 );
1552 return $newMessagesAlert;
1556 * Get a cached notice
1558 * @param string $name Message name, or 'default' for $wgSiteNotice
1559 * @return string|bool HTML fragment, or false to indicate that the caller
1560 * should fall back to the next notice in its sequence
1562 private function getCachedNotice( $name ) {
1563 $config = $this->getConfig();
1565 if ( $name === 'default' ) {
1567 $notice = $config->get( 'SiteNotice' );
1568 if ( empty( $notice ) ) {
1572 $msg = $this->msg( $name )->inContentLanguage();
1573 if ( $msg->isBlank() ) {
1575 } elseif ( $msg->isDisabled() ) {
1578 $notice = $msg->plain();
1581 $services = MediaWikiServices
::getInstance();
1582 $cache = $services->getMainWANObjectCache();
1583 $parsed = $cache->getWithSetCallback(
1584 // Use the extra hash appender to let eg SSL variants separately cache
1585 // Key is verified with md5 hash of unparsed wikitext
1586 $cache->makeKey( $name, $config->get( 'RenderHashAppend' ), md5( $notice ) ),
1589 function () use ( $notice ) {
1590 return $this->getOutput()->parseAsInterface( $notice );
1594 $contLang = $services->getContentLanguage();
1595 return Html
::rawElement(
1598 'id' => 'localNotice',
1599 'lang' => $contLang->getHtmlCode(),
1600 'dir' => $contLang->getDir()
1607 * Get the site notice
1609 * @return string HTML fragment
1611 function getSiteNotice() {
1614 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1615 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1616 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1618 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1619 if ( $anonNotice === false ) {
1620 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1622 $siteNotice = $anonNotice;
1625 if ( $siteNotice === false ) {
1626 $siteNotice = $this->getCachedNotice( 'default' );
1630 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1635 * Create a section edit link.
1637 * @suppress SecurityCheck-XSS $links has keys of different taint types
1638 * @param Title $nt The title being linked to (may not be the same as
1639 * the current page, if the section is included from a template)
1640 * @param string $section The designation of the section being pointed to,
1641 * to be included in the link, like "§ion=$section"
1642 * @param string|null $tooltip The tooltip to use for the link: will be escaped
1643 * and wrapped in the 'editsectionhint' message
1644 * @param Language $lang Language object
1645 * @return string HTML to use for edit link
1647 public function doEditSectionLink( Title
$nt, $section, $tooltip, Language
$lang ) {
1648 // HTML generated here should probably have userlangattributes
1649 // added to it for LTR text on RTL pages
1652 if ( !is_null( $tooltip ) ) {
1653 $attribs['title'] = $this->msg( 'editsectionhint' )->rawParams( $tooltip )
1654 ->inLanguage( $lang )->text();
1659 'text' => $this->msg( 'editsection' )->inLanguage( $lang )->text(),
1660 'targetTitle' => $nt,
1661 'attribs' => $attribs,
1662 'query' => [ 'action' => 'edit', 'section' => $section ]
1666 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1668 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1670 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1672 foreach ( $links as $k => $linkDetails ) {
1673 $linksHtml[] = $linkRenderer->makeKnownLink(
1674 $linkDetails['targetTitle'],
1675 $linkDetails['text'],
1676 $linkDetails['attribs'],
1677 $linkDetails['query']
1682 '<span class="mw-editsection-divider">'
1683 . $this->msg( 'pipe-separator' )->inLanguage( $lang )->escaped()
1688 $result .= '<span class="mw-editsection-bracket">]</span></span>';