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
24 * @defgroup Skins Skins
28 * The main skin class which provides methods and properties for all other skins.
30 * See docs/skin.txt for more information.
34 abstract class Skin
extends ContextSource
{
35 protected $skinname = null;
36 protected $mRelevantTitle = null;
37 protected $mRelevantUser = null;
40 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
41 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
43 public $stylename = null;
46 * Fetch the set of available skins.
47 * @return array Associative array of strings
49 static function getSkinNames() {
50 return SkinFactory
::getDefaultInstance()->getSkinNames();
54 * Fetch the skinname messages for available skins.
57 static function getSkinNameMessages() {
59 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
60 $messages[] = "skinname-$skinKey";
66 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
67 * Useful for Special:Preferences and other places where you
68 * only want to show skins users _can_ use.
72 public static function getAllowedSkins() {
75 $allowedSkins = self
::getSkinNames();
77 foreach ( $wgSkipSkins as $skip ) {
78 unset( $allowedSkins[$skip] );
85 * Normalize a skin preference value to a form that can be loaded.
87 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
88 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
90 * @param string $key 'monobook', 'vector', etc.
93 static function normalizeKey( $key ) {
94 global $wgDefaultSkin, $wgFallbackSkin;
96 $skinNames = Skin
::getSkinNames();
98 // Make keys lowercase for case-insensitive matching.
99 $skinNames = array_change_key_case( $skinNames, CASE_LOWER
);
100 $key = strtolower( $key );
101 $defaultSkin = strtolower( $wgDefaultSkin );
102 $fallbackSkin = strtolower( $wgFallbackSkin );
104 if ( $key == '' ||
$key == 'default' ) {
105 // Don't return the default immediately;
106 // in a misconfiguration we need to fall back.
110 if ( isset( $skinNames[$key] ) ) {
114 // Older versions of the software used a numeric setting
115 // in the user preferences.
121 if ( isset( $fallback[$key] ) ) {
122 $key = $fallback[$key];
125 if ( isset( $skinNames[$key] ) ) {
127 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
130 return $fallbackSkin;
135 * @return string Skin name
137 public function getSkinName() {
138 return $this->skinname
;
142 * @param OutputPage $out
144 public function initPage( OutputPage
$out ) {
145 $this->preloadExistence();
149 * Defines the ResourceLoader modules that should be added to the skin
150 * It is recommended that skins wishing to override call parent::getDefaultModules()
151 * and substitute out any modules they wish to change by using a key to look them up
153 * For style modules, use setupSkinUserCss() instead.
155 * @return array Array of modules with helper keys for easy overriding
157 public function getDefaultModules() {
158 global $wgUseAjax, $wgEnableAPI, $wgEnableWriteAPI;
160 $out = $this->getOutput();
161 $config = $this->getConfig();
162 $user = $out->getUser();
164 // modules not specific to any specific skin or page
166 // Enforce various default modules for all pages and all skins
167 // Keep this list as small as possible
169 'mediawiki.page.startup',
172 // modules that enhance the page content in some way
174 'mediawiki.page.ready',
176 // modules relating to search functionality
178 // modules relating to functionality relating to watching an article
180 // modules which relate to the current users preferences
184 // Support for high-density display images if enabled
185 if ( $config->get( 'ResponsiveImages' ) ) {
186 $modules['core'][] = 'mediawiki.hidpi';
189 // Preload jquery.tablesorter for mediawiki.page.ready
190 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
191 $modules['content'][] = 'jquery.tablesorter';
194 // Preload jquery.makeCollapsible for mediawiki.page.ready
195 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
196 $modules['content'][] = 'jquery.makeCollapsible';
199 if ( $out->isTOCEnabled() ) {
200 $modules['content'][] = 'mediawiki.toc';
203 // Add various resources if required
204 if ( $wgUseAjax && $wgEnableAPI ) {
205 if ( $wgEnableWriteAPI && $user->isLoggedIn()
206 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
207 && $this->getRelevantTitle()->canExist()
209 $modules['watch'][] = 'mediawiki.page.watch.ajax';
212 $modules['search'][] = 'mediawiki.searchSuggest';
215 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
216 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
219 // Crazy edit-on-double-click stuff
220 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
221 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
227 * Preload the existence of three commonly-requested pages in a single query
229 protected function preloadExistence() {
233 $user = $this->getUser();
234 if ( $user->isLoggedIn() ) {
235 $titles[] = $user->getUserPage();
236 $titles[] = $user->getTalkPage();
239 // Check, if the page can hold some kind of content, otherwise do nothing
240 $title = $this->getRelevantTitle();
241 if ( $title->canExist() ) {
242 if ( $title->isTalkPage() ) {
243 $titles[] = $title->getSubjectPage();
245 $titles[] = $title->getTalkPage();
249 // Footer links (used by SkinTemplate::prepareQuickTemplate)
251 $this->footerLinkTitle( 'privacy', 'privacypage' ),
252 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
253 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
260 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
263 $lb = new LinkBatch( $titles );
264 $lb->setCaller( __METHOD__
);
270 * Get the current revision ID
274 public function getRevisionId() {
275 return $this->getOutput()->getRevisionId();
279 * Whether the revision displayed is the latest revision of the page
283 public function isRevisionCurrent() {
284 $revID = $this->getRevisionId();
285 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
289 * Set the "relevant" title
290 * @see self::getRelevantTitle()
293 public function setRelevantTitle( $t ) {
294 $this->mRelevantTitle
= $t;
298 * Return the "relevant" title.
299 * A "relevant" title is not necessarily the actual title of the page.
300 * Special pages like Special:MovePage use set the page they are acting on
301 * as their "relevant" title, this allows the skin system to display things
302 * such as content tabs which belong to to that page instead of displaying
303 * a basic special page tab which has almost no meaning.
307 public function getRelevantTitle() {
308 if ( isset( $this->mRelevantTitle
) ) {
309 return $this->mRelevantTitle
;
311 return $this->getTitle();
315 * Set the "relevant" user
316 * @see self::getRelevantUser()
319 public function setRelevantUser( $u ) {
320 $this->mRelevantUser
= $u;
324 * Return the "relevant" user.
325 * A "relevant" user is similar to a relevant title. Special pages like
326 * Special:Contributions mark the user which they are relevant to so that
327 * things like the toolbox can display the information they usually are only
328 * able to display on a user's userpage and talkpage.
331 public function getRelevantUser() {
332 if ( isset( $this->mRelevantUser
) ) {
333 return $this->mRelevantUser
;
335 $title = $this->getRelevantTitle();
336 if ( $title->hasSubjectNamespace( NS_USER
) ) {
337 $rootUser = $title->getRootText();
338 if ( User
::isIP( $rootUser ) ) {
339 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
341 $user = User
::newFromName( $rootUser, false );
344 $user->load( User
::READ_NORMAL
);
346 if ( $user->isLoggedIn() ) {
347 $this->mRelevantUser
= $user;
351 return $this->mRelevantUser
;
357 * Outputs the HTML generated by other functions.
358 * @param OutputPage $out
360 abstract function outputPage( OutputPage
$out = null );
366 static function makeVariablesScript( $data ) {
368 return ResourceLoader
::makeInlineScript(
369 ResourceLoader
::makeConfigSetScript( $data )
377 * Get the query to generate a dynamic stylesheet
381 public static function getDynamicStylesheetQuery() {
382 global $wgSquidMaxage;
386 'maxage' => $wgSquidMaxage,
387 'usemsgcache' => 'yes',
388 'ctype' => 'text/css',
389 'smaxage' => $wgSquidMaxage,
394 * Add skin specific stylesheets
395 * Calling this method with an $out of anything but the same OutputPage
396 * inside ->getOutput() is deprecated. The $out arg is kept
397 * for compatibility purposes with skins.
398 * @param OutputPage $out
401 abstract function setupSkinUserCss( OutputPage
$out );
405 * @param Title $title
408 function getPageClasses( $title ) {
409 $numeric = 'ns-' . $title->getNamespace();
411 if ( $title->isSpecialPage() ) {
412 $type = 'ns-special';
413 // T25315: provide a class based on the canonical special page name without subpages
414 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
415 if ( $canonicalName ) {
416 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
418 $type .= ' mw-invalidspecialpage';
420 } elseif ( $title->isTalkPage() ) {
423 $type = 'ns-subject';
426 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
427 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
429 return "$numeric $type $name $root";
433 * Return values for <html> element
434 * @return array Array of associative name-to-value elements for <html> element
436 public function getHtmlElementAttributes() {
437 $lang = $this->getLanguage();
439 'lang' => $lang->getHtmlCode(),
440 'dir' => $lang->getDir(),
441 'class' => 'client-nojs',
446 * This will be called by OutputPage::headElement when it is creating the
447 * "<body>" tag, skins can override it if they have a need to add in any
448 * body attributes or classes of their own.
449 * @param OutputPage $out
450 * @param array $bodyAttrs
452 function addToBodyAttributes( $out, &$bodyAttrs ) {
453 // does nothing by default
466 * Whether the logo should be preloaded with an HTTP link header or not
470 public function shouldPreloadLogo() {
475 * @return string HTML
477 function getCategoryLinks() {
478 global $wgUseCategoryBrowser;
480 $out = $this->getOutput();
481 $allCats = $out->getCategoryLinks();
483 if ( !count( $allCats ) ) {
491 $colon = $this->msg( 'colon-separator' )->escaped();
493 if ( !empty( $allCats['normal'] ) ) {
494 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
496 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
497 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
498 $title = Title
::newFromText( $linkPage );
499 $link = $title ? Linker
::link( $title, $msg ) : $msg;
500 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
501 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
505 if ( isset( $allCats['hidden'] ) ) {
506 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
507 $class = ' mw-hidden-cats-user-shown';
508 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
509 $class = ' mw-hidden-cats-ns-shown';
511 $class = ' mw-hidden-cats-hidden';
514 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
515 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
516 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
520 # optional 'dmoz-like' category browser. Will be shown under the list
521 # of categories an article belong to
522 if ( $wgUseCategoryBrowser ) {
523 $s .= '<br /><hr />';
525 # get a big array of the parents tree
526 $parenttree = $this->getTitle()->getParentCategoryTree();
527 # Skin object passed by reference cause it can not be
528 # accessed under the method subfunction drawCategoryBrowser
529 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
530 # Clean out bogus first entry and sort them
531 unset( $tempout[0] );
533 # Output one per line
534 $s .= implode( "<br />\n", $tempout );
541 * Render the array as a series of links.
542 * @param array $tree Categories tree returned by Title::getParentCategoryTree
543 * @return string Separated by >, terminate with "\n"
545 function drawCategoryBrowser( $tree ) {
548 foreach ( $tree as $element => $parent ) {
549 if ( empty( $parent ) ) {
550 # element start a new list
553 # grab the others elements
554 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
557 # add our current element to the list
558 $eltitle = Title
::newFromText( $element );
559 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
566 * @return string HTML
568 function getCategories() {
569 $out = $this->getOutput();
570 $catlinks = $this->getCategoryLinks();
572 // Check what we're showing
573 $allCats = $out->getCategoryLinks();
574 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
575 $this->getTitle()->getNamespace() == NS_CATEGORY
;
577 $classes = [ 'catlinks' ];
578 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
579 $classes[] = 'catlinks-allhidden';
582 return Html
::rawElement(
584 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
590 * This runs a hook to allow extensions placing their stuff after content
591 * and article metadata (e.g. categories).
592 * Note: This function has nothing to do with afterContent().
594 * This hook is placed here in order to allow using the same hook for all
595 * skins, both the SkinTemplate based ones and the older ones, which directly
596 * use this class to get their data.
598 * The output of this function gets processed in SkinTemplate::outputPage() for
599 * the SkinTemplate based skins, all other skins should directly echo it.
601 * @return string Empty by default, if not changed by any hook function.
603 protected function afterContentHook() {
606 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
607 // adding just some spaces shouldn't toggle the output
608 // of the whole <div/>, so we use trim() here
609 if ( trim( $data ) != '' ) {
610 // Doing this here instead of in the skins to
611 // ensure that the div has the same ID in all
613 $data = "<div id='mw-data-after-content'>\n" .
618 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
625 * Generate debug data HTML for displaying at the bottom of the main content
627 * @return string HTML containing debug data, if enabled (otherwise empty).
629 protected function generateDebugHTML() {
630 return MWDebug
::getHTMLDebugLog();
634 * This gets called shortly before the "</body>" tag.
636 * @return string HTML-wrapped JS code to be put before "</body>"
638 function bottomScripts() {
639 // TODO and the suckage continues. This function is really just a wrapper around
640 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
642 $bottomScriptText = $this->getOutput()->getBottomScripts();
643 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$bottomScriptText ] );
645 return $bottomScriptText;
649 * Text with the permalink to the source page,
650 * usually shown on the footer of a printed page
652 * @return string HTML text with an URL
654 function printSource() {
655 $oldid = $this->getRevisionId();
657 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
658 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
660 // oldid not available for non existing pages
661 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
664 return $this->msg( 'retrievedfrom' )
665 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
670 * @return string HTML
672 function getUndeleteLink() {
673 $action = $this->getRequest()->getVal( 'action', 'view' );
675 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
676 ( !$this->getTitle()->exists() ||
$action == 'history' ) ) {
677 $n = $this->getTitle()->isDeleted();
680 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
681 $msg = 'thisisdeleted';
683 $msg = 'viewdeleted';
686 return $this->msg( $msg )->rawParams(
688 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
689 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
698 * @param OutputPage $out Defaults to $this->getOutput() if left as null
701 function subPageSubtitle( $out = null ) {
702 if ( $out === null ) {
703 $out = $this->getOutput();
705 $title = $out->getTitle();
708 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
712 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
713 $ptext = $title->getPrefixedText();
714 if ( strpos( $ptext, '/' ) !== false ) {
715 $links = explode( '/', $ptext );
720 $lang = $this->getLanguage();
722 foreach ( $links as $link ) {
723 $growinglink .= $link;
725 $linkObj = Title
::newFromText( $growinglink );
727 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
728 $getlink = Linker
::linkKnown(
730 htmlspecialchars( $display )
736 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
738 $subpages .= '< ';
741 $subpages .= $getlink;
755 * @deprecated since 1.27, feature removed
756 * @return bool Always false
758 function showIPinHeader() {
759 wfDeprecated( __METHOD__
, '1.27' );
766 function getSearchLink() {
767 $searchPage = SpecialPage
::getTitleFor( 'Search' );
768 return $searchPage->getLocalURL();
774 function escapeSearchLink() {
775 return htmlspecialchars( $this->getSearchLink() );
779 * @param string $type
782 function getCopyright( $type = 'detect' ) {
783 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
785 if ( $type == 'detect' ) {
786 if ( !$this->isRevisionCurrent()
787 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
795 if ( $type == 'history' ) {
796 $msg = 'history_copyright';
801 if ( $wgRightsPage ) {
802 $title = Title
::newFromText( $wgRightsPage );
803 $link = Linker
::linkKnown( $title, $wgRightsText );
804 } elseif ( $wgRightsUrl ) {
805 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
806 } elseif ( $wgRightsText ) {
807 $link = $wgRightsText;
813 // Allow for site and per-namespace customization of copyright notice.
814 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
818 'SkinCopyrightFooter',
819 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
822 return $this->msg( $msg )->rawParams( $link )->text();
826 * @return null|string
828 function getCopyrightIcon() {
829 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
833 if ( $wgFooterIcons['copyright']['copyright'] ) {
834 $out = $wgFooterIcons['copyright']['copyright'];
835 } elseif ( $wgRightsIcon ) {
836 $icon = htmlspecialchars( $wgRightsIcon );
838 if ( $wgRightsUrl ) {
839 $url = htmlspecialchars( $wgRightsUrl );
840 $out .= '<a href="' . $url . '">';
843 $text = htmlspecialchars( $wgRightsText );
844 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
846 if ( $wgRightsUrl ) {
855 * Gets the powered by MediaWiki icon.
858 function getPoweredBy() {
859 global $wgResourceBasePath;
861 $url1 = htmlspecialchars(
862 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
864 $url1_5 = htmlspecialchars(
865 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
867 $url2 = htmlspecialchars(
868 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
870 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
871 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
872 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
873 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
878 * Get the timestamp of the latest revision, formatted in user language
882 protected function lastModified() {
883 $timestamp = $this->getOutput()->getRevisionTimestamp();
885 # No cached timestamp, load it from the database
886 if ( $timestamp === null ) {
887 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
891 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
892 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
893 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
898 if ( wfGetLB()->getLaggedReplicaMode() ) {
899 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
906 * @param string $align
909 function logoText( $align = '' ) {
910 if ( $align != '' ) {
911 $a = " style='float: {$align};'";
916 $mp = $this->msg( 'mainpage' )->escaped();
917 $mptitle = Title
::newMainPage();
918 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
920 $logourl = $this->getLogo();
921 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
927 * Renders a $wgFooterIcons icon according to the method's arguments
928 * @param array $icon The icon to build the html for, see $wgFooterIcons
929 * for the format of this array.
930 * @param bool|string $withImage Whether to use the icon's image or output
931 * a text-only footericon.
932 * @return string HTML
934 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
935 if ( is_string( $icon ) ) {
937 } else { // Assuming array
938 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
939 unset( $icon["url"] );
940 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
941 // do this the lazy way, just pass icon data as an attribute array
942 $html = Html
::element( 'img', $icon );
944 $html = htmlspecialchars( $icon["alt"] );
947 global $wgExternalLinkTarget;
948 $html = Html
::rawElement( 'a',
949 [ "href" => $url, "target" => $wgExternalLinkTarget ],
957 * Gets the link to the wiki's main page.
960 function mainPageLink() {
961 $s = Linker
::linkKnown(
962 Title
::newMainPage(),
963 $this->msg( 'mainpage' )->escaped()
970 * Returns an HTML link for use in the footer
971 * @param string $desc The i18n message key for the link text
972 * @param string $page The i18n message key for the page to link to
973 * @return string HTML anchor
975 public function footerLink( $desc, $page ) {
976 $title = $this->footerLinkTitle( $desc, $page );
981 return Linker
::linkKnown(
983 $this->msg( $desc )->escaped()
988 * @param string $desc
989 * @param string $page
992 private function footerLinkTitle( $desc, $page ) {
993 // If the link description has been set to "-" in the default language,
994 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
995 // then it is disabled, for all languages.
998 // Otherwise, we display the link for the user, described in their
999 // language (which may or may not be the same as the default language),
1000 // but we make the link target be the one site-wide page.
1001 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1003 return $title ?
: null;
1007 * Gets the link to the wiki's privacy policy page.
1008 * @return string HTML
1010 function privacyLink() {
1011 return $this->footerLink( 'privacy', 'privacypage' );
1015 * Gets the link to the wiki's about page.
1016 * @return string HTML
1018 function aboutLink() {
1019 return $this->footerLink( 'aboutsite', 'aboutpage' );
1023 * Gets the link to the wiki's general disclaimers page.
1024 * @return string HTML
1026 function disclaimerLink() {
1027 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1031 * Return URL options for the 'edit page' link.
1032 * This may include an 'oldid' specifier, if the current page view is such.
1037 function editUrlOptions() {
1038 $options = [ 'action' => 'edit' ];
1040 if ( !$this->isRevisionCurrent() ) {
1041 $options['oldid'] = intval( $this->getRevisionId() );
1048 * @param User|int $id
1051 function showEmailUser( $id ) {
1052 if ( $id instanceof User
) {
1055 $targetUser = User
::newFromId( $id );
1058 # The sending user must have a confirmed email address and the target
1059 # user must have a confirmed email address and allow emails from users.
1060 return $this->getUser()->canSendEmail() &&
1061 $targetUser->canReceiveEmail();
1065 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1066 * This method returns a url resolved using the configured skin style path
1067 * and includes the style version inside of the url.
1069 * Requires $stylename to be set, otherwise throws MWException.
1071 * @param string $name The name or path of a skin resource file
1072 * @return string The fully resolved style path url including styleversion
1073 * @throws MWException
1075 function getSkinStylePath( $name ) {
1076 global $wgStylePath, $wgStyleVersion;
1078 if ( $this->stylename
=== null ) {
1079 $class = static::class;
1080 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1083 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1086 /* these are used extensively in SkinTemplate, but also some other places */
1089 * @param string $urlaction
1092 static function makeMainPageUrl( $urlaction = '' ) {
1093 $title = Title
::newMainPage();
1094 self
::checkTitle( $title, '' );
1096 return $title->getLocalURL( $urlaction );
1100 * Make a URL for a Special Page using the given query and protocol.
1102 * If $proto is set to null, make a local URL. Otherwise, make a full
1103 * URL with the protocol specified.
1105 * @param string $name Name of the Special page
1106 * @param string $urlaction Query to append
1107 * @param string|null $proto Protocol to use or null for a local URL
1110 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1111 $title = SpecialPage
::getSafeTitleFor( $name );
1112 if ( is_null( $proto ) ) {
1113 return $title->getLocalURL( $urlaction );
1115 return $title->getFullURL( $urlaction, false, $proto );
1120 * @param string $name
1121 * @param string $subpage
1122 * @param string $urlaction
1125 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1126 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1127 return $title->getLocalURL( $urlaction );
1131 * @param string $name
1132 * @param string $urlaction
1135 static function makeI18nUrl( $name, $urlaction = '' ) {
1136 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1137 self
::checkTitle( $title, $name );
1138 return $title->getLocalURL( $urlaction );
1142 * @param string $name
1143 * @param string $urlaction
1146 static function makeUrl( $name, $urlaction = '' ) {
1147 $title = Title
::newFromText( $name );
1148 self
::checkTitle( $title, $name );
1150 return $title->getLocalURL( $urlaction );
1154 * If url string starts with http, consider as external URL, else
1156 * @param string $name
1157 * @return string URL
1159 static function makeInternalOrExternalUrl( $name ) {
1160 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1163 return self
::makeUrl( $name );
1168 * this can be passed the NS number as defined in Language.php
1169 * @param string $name
1170 * @param string $urlaction
1171 * @param int $namespace
1174 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1175 $title = Title
::makeTitleSafe( $namespace, $name );
1176 self
::checkTitle( $title, $name );
1178 return $title->getLocalURL( $urlaction );
1182 * these return an array with the 'href' and boolean 'exists'
1183 * @param string $name
1184 * @param string $urlaction
1187 static function makeUrlDetails( $name, $urlaction = '' ) {
1188 $title = Title
::newFromText( $name );
1189 self
::checkTitle( $title, $name );
1192 'href' => $title->getLocalURL( $urlaction ),
1193 'exists' => $title->isKnown(),
1198 * Make URL details where the article exists (or at least it's convenient to think so)
1199 * @param string $name Article name
1200 * @param string $urlaction
1203 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1204 $title = Title
::newFromText( $name );
1205 self
::checkTitle( $title, $name );
1208 'href' => $title->getLocalURL( $urlaction ),
1214 * make sure we have some title to operate on
1216 * @param Title $title
1217 * @param string $name
1219 static function checkTitle( &$title, $name ) {
1220 if ( !is_object( $title ) ) {
1221 $title = Title
::newFromText( $name );
1222 if ( !is_object( $title ) ) {
1223 $title = Title
::newFromText( '--error: link target missing--' );
1229 * Build an array that represents the sidebar(s), the navigation bar among them.
1231 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1233 * The format of the returned array is [ heading => content, ... ], where:
1234 * - heading is the heading of a navigation portlet. It is either:
1235 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1236 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1237 * - plain text, which should be HTML-escaped by the skin
1238 * - content is the contents of the portlet. It is either:
1239 * - HTML text (<ul><li>...</li>...</ul>)
1240 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1241 * - (for a magic string as a key, any value)
1243 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1244 * and can technically insert anything in here; skin creators are expected to handle
1245 * values described above.
1249 function buildSidebar() {
1250 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1253 $callback = function () use ( $that ) {
1255 $that->addToSidebar( $bar, 'sidebar' );
1256 Hooks
::run( 'SkinBuildSidebar', [ $that, &$bar ] );
1261 if ( $wgEnableSidebarCache ) {
1262 $cache = ObjectCache
::getMainWANInstance();
1263 $sidebar = $cache->getWithSetCallback(
1264 $cache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1265 MessageCache
::singleton()->isDisabled()
1266 ?
$cache::TTL_UNCACHEABLE
// bug T133069
1267 : $wgSidebarCacheExpiry,
1272 $sidebar = $callback();
1275 // Apply post-processing to the cached value
1276 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1282 * Add content from a sidebar system message
1283 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1285 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1288 * @param string $message
1290 public function addToSidebar( &$bar, $message ) {
1291 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1295 * Add content from plain text
1298 * @param string $text
1301 function addToSidebarPlain( &$bar, $text ) {
1302 $lines = explode( "\n", $text );
1305 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1306 ? Title
::newMainPage() : $this->getTitle();
1308 foreach ( $lines as $line ) {
1309 if ( strpos( $line, '*' ) !== 0 ) {
1312 $line = rtrim( $line, "\r" ); // for Windows compat
1314 if ( strpos( $line, '**' ) !== 0 ) {
1315 $heading = trim( $line, '* ' );
1316 if ( !array_key_exists( $heading, $bar ) ) {
1317 $bar[$heading] = [];
1320 $line = trim( $line, '* ' );
1322 if ( strpos( $line, '|' ) !== false ) { // sanity check
1323 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1324 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1325 if ( count( $line ) !== 2 ) {
1326 // Second sanity check, could be hit by people doing
1327 // funky stuff with parserfuncs... (T35321)
1333 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1334 if ( $msgLink->exists() ) {
1335 $link = $msgLink->text();
1336 if ( $link == '-' ) {
1342 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1343 if ( $msgText->exists() ) {
1344 $text = $msgText->text();
1349 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1352 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1353 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1354 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1355 $extraAttribs['rel'] = 'nofollow';
1358 global $wgExternalLinkTarget;
1359 if ( $wgExternalLinkTarget ) {
1360 $extraAttribs['target'] = $wgExternalLinkTarget;
1363 $title = Title
::newFromText( $link );
1366 $title = $title->fixSpecialName();
1367 $href = $title->getLinkURL();
1369 $href = 'INVALID-TITLE';
1373 $bar[$heading][] = array_merge( [
1376 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1389 * Gets new talk page messages for the current user and returns an
1390 * appropriate alert message (or an empty string if there are no messages)
1393 function getNewtalks() {
1395 $newMessagesAlert = '';
1396 $user = $this->getUser();
1397 $newtalks = $user->getNewMessageLinks();
1398 $out = $this->getOutput();
1400 // Allow extensions to disable or modify the new messages alert
1401 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1404 if ( $newMessagesAlert ) {
1405 return $newMessagesAlert;
1408 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1409 $uTalkTitle = $user->getTalkPage();
1410 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1412 if ( $lastSeenRev !== null ) {
1413 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1414 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1415 if ( $latestRev !== null ) {
1416 // Singular if only 1 unseen revision, plural if several unseen revisions.
1417 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1418 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1419 $lastSeenRev, $latestRev, 10, 'include_new' );
1422 // Singular if no revision -> diff link will show latest change only in any case
1425 $plural = $plural ?
999 : 1;
1426 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1427 // the number of revisions or authors is not necessarily the same as the number of
1429 $newMessagesLink = Linker
::linkKnown(
1431 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1433 [ 'redirect' => 'no' ]
1436 $newMessagesDiffLink = Linker
::linkKnown(
1438 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1440 $lastSeenRev !== null
1441 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1442 : [ 'diff' => 'cur' ]
1445 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1446 $newMessagesAlert = $this->msg(
1447 'youhavenewmessagesfromusers',
1449 $newMessagesDiffLink
1450 )->numParams( $nofAuthors, $plural );
1452 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1453 $newMessagesAlert = $this->msg(
1454 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1456 $newMessagesDiffLink
1457 )->numParams( $plural );
1459 $newMessagesAlert = $newMessagesAlert->text();
1461 $out->setCdnMaxage( 0 );
1462 } elseif ( count( $newtalks ) ) {
1463 $sep = $this->msg( 'newtalkseparator' )->escaped();
1466 foreach ( $newtalks as $newtalk ) {
1467 $msgs[] = Xml
::element(
1469 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1472 $parts = implode( $sep, $msgs );
1473 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1474 $out->setCdnMaxage( 0 );
1477 return $newMessagesAlert;
1481 * Get a cached notice
1483 * @param string $name Message name, or 'default' for $wgSiteNotice
1484 * @return string|bool HTML fragment, or false to indicate that the caller
1485 * should fall back to the next notice in its sequence
1487 private function getCachedNotice( $name ) {
1488 global $wgRenderHashAppend, $wgContLang;
1492 if ( $name === 'default' ) {
1494 global $wgSiteNotice;
1495 $notice = $wgSiteNotice;
1496 if ( empty( $notice ) ) {
1500 $msg = $this->msg( $name )->inContentLanguage();
1501 if ( $msg->isBlank() ) {
1503 } elseif ( $msg->isDisabled() ) {
1506 $notice = $msg->plain();
1509 $cache = wfGetCache( CACHE_ANYTHING
);
1510 // Use the extra hash appender to let eg SSL variants separately cache.
1511 $key = $cache->makeKey( $name . $wgRenderHashAppend );
1512 $cachedNotice = $cache->get( $key );
1513 if ( is_array( $cachedNotice ) ) {
1514 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1515 $notice = $cachedNotice['html'];
1524 $parsed = $this->getOutput()->parse( $notice );
1525 $cache->set( $key, [ 'html' => $parsed, 'hash' => md5( $notice ) ], 600 );
1529 $notice = Html
::rawElement( 'div', [ 'id' => 'localNotice',
1530 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ], $notice );
1535 * Get the site notice
1537 * @return string HTML fragment
1539 function getSiteNotice() {
1542 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1543 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1544 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1546 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1547 if ( $anonNotice === false ) {
1548 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1550 $siteNotice = $anonNotice;
1553 if ( $siteNotice === false ) {
1554 $siteNotice = $this->getCachedNotice( 'default' );
1558 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1563 * Create a section edit link. This supersedes editSectionLink() and
1564 * editSectionLinkForOther().
1566 * @param Title $nt The title being linked to (may not be the same as
1567 * the current page, if the section is included from a template)
1568 * @param string $section The designation of the section being pointed to,
1569 * to be included in the link, like "§ion=$section"
1570 * @param string $tooltip The tooltip to use for the link: will be escaped
1571 * and wrapped in the 'editsectionhint' message
1572 * @param string $lang Language code
1573 * @return string HTML to use for edit link
1575 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1576 // HTML generated here should probably have userlangattributes
1577 // added to it for LTR text on RTL pages
1579 $lang = wfGetLangObj( $lang );
1582 if ( !is_null( $tooltip ) ) {
1583 # T27462: undo double-escaping.
1584 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1585 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1586 ->inLanguage( $lang )->text();
1591 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1592 'targetTitle' => $nt,
1593 'attribs' => $attribs,
1594 'query' => [ 'action' => 'edit', 'section' => $section ],
1595 'options' => [ 'noclasses', 'known' ]
1599 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1601 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1604 foreach ( $links as $k => $linkDetails ) {
1605 $linksHtml[] = Linker
::link(
1606 $linkDetails['targetTitle'],
1607 $linkDetails['text'],
1608 $linkDetails['attribs'],
1609 $linkDetails['query'],
1610 $linkDetails['options']
1615 '<span class="mw-editsection-divider">'
1616 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->text()
1621 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1622 // Deprecated, use SkinEditSectionLinks hook instead
1624 'DoEditSectionLink',
1625 [ $this, $nt, $section, $tooltip, &$result, $lang ],