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 // Add various resources if required
200 if ( $wgUseAjax && $wgEnableAPI ) {
201 if ( $wgEnableWriteAPI && $user->isLoggedIn()
202 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
203 && $this->getRelevantTitle()->canExist()
205 $modules['watch'][] = 'mediawiki.page.watch.ajax';
208 $modules['search'][] = 'mediawiki.searchSuggest';
211 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
212 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
215 // Crazy edit-on-double-click stuff
216 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
217 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
223 * Preload the existence of three commonly-requested pages in a single query
225 protected function preloadExistence() {
229 $user = $this->getUser();
230 if ( $user->isLoggedIn() ) {
231 $titles[] = $user->getUserPage();
232 $titles[] = $user->getTalkPage();
235 // Check, if the page can hold some kind of content, otherwise do nothing
236 $title = $this->getRelevantTitle();
237 if ( $title->canExist() ) {
238 if ( $title->isTalkPage() ) {
239 $titles[] = $title->getSubjectPage();
241 $titles[] = $title->getTalkPage();
245 // Footer links (used by SkinTemplate::prepareQuickTemplate)
247 $this->footerLinkTitle( 'privacy', 'privacypage' ),
248 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
249 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
256 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
259 $lb = new LinkBatch( $titles );
260 $lb->setCaller( __METHOD__
);
266 * Get the current revision ID
270 public function getRevisionId() {
271 return $this->getOutput()->getRevisionId();
275 * Whether the revision displayed is the latest revision of the page
279 public function isRevisionCurrent() {
280 $revID = $this->getRevisionId();
281 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
285 * Set the "relevant" title
286 * @see self::getRelevantTitle()
289 public function setRelevantTitle( $t ) {
290 $this->mRelevantTitle
= $t;
294 * Return the "relevant" title.
295 * A "relevant" title is not necessarily the actual title of the page.
296 * Special pages like Special:MovePage use set the page they are acting on
297 * as their "relevant" title, this allows the skin system to display things
298 * such as content tabs which belong to to that page instead of displaying
299 * a basic special page tab which has almost no meaning.
303 public function getRelevantTitle() {
304 if ( isset( $this->mRelevantTitle
) ) {
305 return $this->mRelevantTitle
;
307 return $this->getTitle();
311 * Set the "relevant" user
312 * @see self::getRelevantUser()
315 public function setRelevantUser( $u ) {
316 $this->mRelevantUser
= $u;
320 * Return the "relevant" user.
321 * A "relevant" user is similar to a relevant title. Special pages like
322 * Special:Contributions mark the user which they are relevant to so that
323 * things like the toolbox can display the information they usually are only
324 * able to display on a user's userpage and talkpage.
327 public function getRelevantUser() {
328 if ( isset( $this->mRelevantUser
) ) {
329 return $this->mRelevantUser
;
331 $title = $this->getRelevantTitle();
332 if ( $title->hasSubjectNamespace( NS_USER
) ) {
333 $rootUser = $title->getRootText();
334 if ( User
::isIP( $rootUser ) ) {
335 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
337 $user = User
::newFromName( $rootUser, false );
340 $user->load( User
::READ_NORMAL
);
342 if ( $user->isLoggedIn() ) {
343 $this->mRelevantUser
= $user;
347 return $this->mRelevantUser
;
353 * Outputs the HTML generated by other functions.
354 * @param OutputPage $out
356 abstract function outputPage( OutputPage
$out = null );
362 static function makeVariablesScript( $data ) {
364 return ResourceLoader
::makeInlineScript(
365 ResourceLoader
::makeConfigSetScript( $data )
373 * Get the query to generate a dynamic stylesheet
377 public static function getDynamicStylesheetQuery() {
378 global $wgSquidMaxage;
382 'maxage' => $wgSquidMaxage,
383 'usemsgcache' => 'yes',
384 'ctype' => 'text/css',
385 'smaxage' => $wgSquidMaxage,
390 * Add skin specific stylesheets
391 * Calling this method with an $out of anything but the same OutputPage
392 * inside ->getOutput() is deprecated. The $out arg is kept
393 * for compatibility purposes with skins.
394 * @param OutputPage $out
397 abstract function setupSkinUserCss( OutputPage
$out );
401 * @param Title $title
404 function getPageClasses( $title ) {
405 $numeric = 'ns-' . $title->getNamespace();
407 if ( $title->isSpecialPage() ) {
408 $type = 'ns-special';
409 // T25315: provide a class based on the canonical special page name without subpages
410 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
411 if ( $canonicalName ) {
412 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
414 $type .= ' mw-invalidspecialpage';
416 } elseif ( $title->isTalkPage() ) {
419 $type = 'ns-subject';
422 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
423 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
425 return "$numeric $type $name $root";
429 * Return values for <html> element
430 * @return array Array of associative name-to-value elements for <html> element
432 public function getHtmlElementAttributes() {
433 $lang = $this->getLanguage();
435 'lang' => $lang->getHtmlCode(),
436 'dir' => $lang->getDir(),
437 'class' => 'client-nojs',
442 * This will be called by OutputPage::headElement when it is creating the
443 * "<body>" tag, skins can override it if they have a need to add in any
444 * body attributes or classes of their own.
445 * @param OutputPage $out
446 * @param array $bodyAttrs
448 function addToBodyAttributes( $out, &$bodyAttrs ) {
449 // does nothing by default
462 * Whether the logo should be preloaded with an HTTP link header or not
466 public function shouldPreloadLogo() {
471 * @return string HTML
473 function getCategoryLinks() {
474 global $wgUseCategoryBrowser;
476 $out = $this->getOutput();
477 $allCats = $out->getCategoryLinks();
479 if ( !count( $allCats ) ) {
487 $colon = $this->msg( 'colon-separator' )->escaped();
489 if ( !empty( $allCats['normal'] ) ) {
490 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
492 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
493 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
494 $title = Title
::newFromText( $linkPage );
495 $link = $title ? Linker
::link( $title, $msg ) : $msg;
496 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
497 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
501 if ( isset( $allCats['hidden'] ) ) {
502 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
503 $class = ' mw-hidden-cats-user-shown';
504 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
505 $class = ' mw-hidden-cats-ns-shown';
507 $class = ' mw-hidden-cats-hidden';
510 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
511 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
512 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
516 # optional 'dmoz-like' category browser. Will be shown under the list
517 # of categories an article belong to
518 if ( $wgUseCategoryBrowser ) {
519 $s .= '<br /><hr />';
521 # get a big array of the parents tree
522 $parenttree = $this->getTitle()->getParentCategoryTree();
523 # Skin object passed by reference cause it can not be
524 # accessed under the method subfunction drawCategoryBrowser
525 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
526 # Clean out bogus first entry and sort them
527 unset( $tempout[0] );
529 # Output one per line
530 $s .= implode( "<br />\n", $tempout );
537 * Render the array as a series of links.
538 * @param array $tree Categories tree returned by Title::getParentCategoryTree
539 * @return string Separated by >, terminate with "\n"
541 function drawCategoryBrowser( $tree ) {
544 foreach ( $tree as $element => $parent ) {
545 if ( empty( $parent ) ) {
546 # element start a new list
549 # grab the others elements
550 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
553 # add our current element to the list
554 $eltitle = Title
::newFromText( $element );
555 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
562 * @return string HTML
564 function getCategories() {
565 $out = $this->getOutput();
566 $catlinks = $this->getCategoryLinks();
568 // Check what we're showing
569 $allCats = $out->getCategoryLinks();
570 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
571 $this->getTitle()->getNamespace() == NS_CATEGORY
;
573 $classes = [ 'catlinks' ];
574 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
575 $classes[] = 'catlinks-allhidden';
578 return Html
::rawElement(
580 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
586 * This runs a hook to allow extensions placing their stuff after content
587 * and article metadata (e.g. categories).
588 * Note: This function has nothing to do with afterContent().
590 * This hook is placed here in order to allow using the same hook for all
591 * skins, both the SkinTemplate based ones and the older ones, which directly
592 * use this class to get their data.
594 * The output of this function gets processed in SkinTemplate::outputPage() for
595 * the SkinTemplate based skins, all other skins should directly echo it.
597 * @return string Empty by default, if not changed by any hook function.
599 protected function afterContentHook() {
602 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
603 // adding just some spaces shouldn't toggle the output
604 // of the whole <div/>, so we use trim() here
605 if ( trim( $data ) != '' ) {
606 // Doing this here instead of in the skins to
607 // ensure that the div has the same ID in all
609 $data = "<div id='mw-data-after-content'>\n" .
614 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
621 * Generate debug data HTML for displaying at the bottom of the main content
623 * @return string HTML containing debug data, if enabled (otherwise empty).
625 protected function generateDebugHTML() {
626 return MWDebug
::getHTMLDebugLog();
630 * This gets called shortly before the "</body>" tag.
632 * @return string HTML-wrapped JS code to be put before "</body>"
634 function bottomScripts() {
635 // TODO and the suckage continues. This function is really just a wrapper around
636 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
638 $bottomScriptText = $this->getOutput()->getBottomScripts();
639 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$bottomScriptText ] );
641 return $bottomScriptText;
645 * Text with the permalink to the source page,
646 * usually shown on the footer of a printed page
648 * @return string HTML text with an URL
650 function printSource() {
651 $oldid = $this->getRevisionId();
653 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
654 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
656 // oldid not available for non existing pages
657 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
660 return $this->msg( 'retrievedfrom' )
661 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
666 * @return string HTML
668 function getUndeleteLink() {
669 $action = $this->getRequest()->getVal( 'action', 'view' );
671 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
672 ( !$this->getTitle()->exists() ||
$action == 'history' ) ) {
673 $n = $this->getTitle()->isDeleted();
676 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
677 $msg = 'thisisdeleted';
679 $msg = 'viewdeleted';
682 return $this->msg( $msg )->rawParams(
684 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
685 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
694 * @param OutputPage $out Defaults to $this->getOutput() if left as null
697 function subPageSubtitle( $out = null ) {
698 if ( $out === null ) {
699 $out = $this->getOutput();
701 $title = $out->getTitle();
704 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
708 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
709 $ptext = $title->getPrefixedText();
710 if ( strpos( $ptext, '/' ) !== false ) {
711 $links = explode( '/', $ptext );
716 $lang = $this->getLanguage();
718 foreach ( $links as $link ) {
719 $growinglink .= $link;
721 $linkObj = Title
::newFromText( $growinglink );
723 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
724 $getlink = Linker
::linkKnown(
726 htmlspecialchars( $display )
732 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
734 $subpages .= '< ';
737 $subpages .= $getlink;
751 * @deprecated since 1.27, feature removed
752 * @return bool Always false
754 function showIPinHeader() {
755 wfDeprecated( __METHOD__
, '1.27' );
762 function getSearchLink() {
763 $searchPage = SpecialPage
::getTitleFor( 'Search' );
764 return $searchPage->getLocalURL();
770 function escapeSearchLink() {
771 return htmlspecialchars( $this->getSearchLink() );
775 * @param string $type
778 function getCopyright( $type = 'detect' ) {
779 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
781 if ( $type == 'detect' ) {
782 if ( !$this->isRevisionCurrent()
783 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
791 if ( $type == 'history' ) {
792 $msg = 'history_copyright';
797 if ( $wgRightsPage ) {
798 $title = Title
::newFromText( $wgRightsPage );
799 $link = Linker
::linkKnown( $title, $wgRightsText );
800 } elseif ( $wgRightsUrl ) {
801 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
802 } elseif ( $wgRightsText ) {
803 $link = $wgRightsText;
809 // Allow for site and per-namespace customization of copyright notice.
810 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
814 'SkinCopyrightFooter',
815 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
818 return $this->msg( $msg )->rawParams( $link )->text();
822 * @return null|string
824 function getCopyrightIcon() {
825 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
829 if ( $wgFooterIcons['copyright']['copyright'] ) {
830 $out = $wgFooterIcons['copyright']['copyright'];
831 } elseif ( $wgRightsIcon ) {
832 $icon = htmlspecialchars( $wgRightsIcon );
834 if ( $wgRightsUrl ) {
835 $url = htmlspecialchars( $wgRightsUrl );
836 $out .= '<a href="' . $url . '">';
839 $text = htmlspecialchars( $wgRightsText );
840 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
842 if ( $wgRightsUrl ) {
851 * Gets the powered by MediaWiki icon.
854 function getPoweredBy() {
855 global $wgResourceBasePath;
857 $url1 = htmlspecialchars(
858 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
860 $url1_5 = htmlspecialchars(
861 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
863 $url2 = htmlspecialchars(
864 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
866 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
867 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
868 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
869 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
874 * Get the timestamp of the latest revision, formatted in user language
878 protected function lastModified() {
879 $timestamp = $this->getOutput()->getRevisionTimestamp();
881 # No cached timestamp, load it from the database
882 if ( $timestamp === null ) {
883 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
887 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
888 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
889 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
894 if ( wfGetLB()->getLaggedReplicaMode() ) {
895 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
902 * @param string $align
905 function logoText( $align = '' ) {
906 if ( $align != '' ) {
907 $a = " style='float: {$align};'";
912 $mp = $this->msg( 'mainpage' )->escaped();
913 $mptitle = Title
::newMainPage();
914 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
916 $logourl = $this->getLogo();
917 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
923 * Renders a $wgFooterIcons icon according to the method's arguments
924 * @param array $icon The icon to build the html for, see $wgFooterIcons
925 * for the format of this array.
926 * @param bool|string $withImage Whether to use the icon's image or output
927 * a text-only footericon.
928 * @return string HTML
930 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
931 if ( is_string( $icon ) ) {
933 } else { // Assuming array
934 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
935 unset( $icon["url"] );
936 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
937 // do this the lazy way, just pass icon data as an attribute array
938 $html = Html
::element( 'img', $icon );
940 $html = htmlspecialchars( $icon["alt"] );
943 global $wgExternalLinkTarget;
944 $html = Html
::rawElement( 'a',
945 [ "href" => $url, "target" => $wgExternalLinkTarget ],
953 * Gets the link to the wiki's main page.
956 function mainPageLink() {
957 $s = Linker
::linkKnown(
958 Title
::newMainPage(),
959 $this->msg( 'mainpage' )->escaped()
966 * Returns an HTML link for use in the footer
967 * @param string $desc The i18n message key for the link text
968 * @param string $page The i18n message key for the page to link to
969 * @return string HTML anchor
971 public function footerLink( $desc, $page ) {
972 $title = $this->footerLinkTitle( $desc, $page );
977 return Linker
::linkKnown(
979 $this->msg( $desc )->escaped()
984 * @param string $desc
985 * @param string $page
988 private function footerLinkTitle( $desc, $page ) {
989 // If the link description has been set to "-" in the default language,
990 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
991 // then it is disabled, for all languages.
994 // Otherwise, we display the link for the user, described in their
995 // language (which may or may not be the same as the default language),
996 // but we make the link target be the one site-wide page.
997 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
999 return $title ?
: null;
1003 * Gets the link to the wiki's privacy policy page.
1004 * @return string HTML
1006 function privacyLink() {
1007 return $this->footerLink( 'privacy', 'privacypage' );
1011 * Gets the link to the wiki's about page.
1012 * @return string HTML
1014 function aboutLink() {
1015 return $this->footerLink( 'aboutsite', 'aboutpage' );
1019 * Gets the link to the wiki's general disclaimers page.
1020 * @return string HTML
1022 function disclaimerLink() {
1023 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1027 * Return URL options for the 'edit page' link.
1028 * This may include an 'oldid' specifier, if the current page view is such.
1033 function editUrlOptions() {
1034 $options = [ 'action' => 'edit' ];
1036 if ( !$this->isRevisionCurrent() ) {
1037 $options['oldid'] = intval( $this->getRevisionId() );
1044 * @param User|int $id
1047 function showEmailUser( $id ) {
1048 if ( $id instanceof User
) {
1051 $targetUser = User
::newFromId( $id );
1054 # The sending user must have a confirmed email address and the target
1055 # user must have a confirmed email address and allow emails from users.
1056 return $this->getUser()->canSendEmail() &&
1057 $targetUser->canReceiveEmail();
1061 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1062 * This method returns a url resolved using the configured skin style path
1063 * and includes the style version inside of the url.
1065 * Requires $stylename to be set, otherwise throws MWException.
1067 * @param string $name The name or path of a skin resource file
1068 * @return string The fully resolved style path url including styleversion
1069 * @throws MWException
1071 function getSkinStylePath( $name ) {
1072 global $wgStylePath, $wgStyleVersion;
1074 if ( $this->stylename
=== null ) {
1075 $class = static::class;
1076 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1079 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1082 /* these are used extensively in SkinTemplate, but also some other places */
1085 * @param string $urlaction
1088 static function makeMainPageUrl( $urlaction = '' ) {
1089 $title = Title
::newMainPage();
1090 self
::checkTitle( $title, '' );
1092 return $title->getLocalURL( $urlaction );
1096 * Make a URL for a Special Page using the given query and protocol.
1098 * If $proto is set to null, make a local URL. Otherwise, make a full
1099 * URL with the protocol specified.
1101 * @param string $name Name of the Special page
1102 * @param string $urlaction Query to append
1103 * @param string|null $proto Protocol to use or null for a local URL
1106 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1107 $title = SpecialPage
::getSafeTitleFor( $name );
1108 if ( is_null( $proto ) ) {
1109 return $title->getLocalURL( $urlaction );
1111 return $title->getFullURL( $urlaction, false, $proto );
1116 * @param string $name
1117 * @param string $subpage
1118 * @param string $urlaction
1121 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1122 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1123 return $title->getLocalURL( $urlaction );
1127 * @param string $name
1128 * @param string $urlaction
1131 static function makeI18nUrl( $name, $urlaction = '' ) {
1132 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1133 self
::checkTitle( $title, $name );
1134 return $title->getLocalURL( $urlaction );
1138 * @param string $name
1139 * @param string $urlaction
1142 static function makeUrl( $name, $urlaction = '' ) {
1143 $title = Title
::newFromText( $name );
1144 self
::checkTitle( $title, $name );
1146 return $title->getLocalURL( $urlaction );
1150 * If url string starts with http, consider as external URL, else
1152 * @param string $name
1153 * @return string URL
1155 static function makeInternalOrExternalUrl( $name ) {
1156 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1159 return self
::makeUrl( $name );
1164 * this can be passed the NS number as defined in Language.php
1165 * @param string $name
1166 * @param string $urlaction
1167 * @param int $namespace
1170 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1171 $title = Title
::makeTitleSafe( $namespace, $name );
1172 self
::checkTitle( $title, $name );
1174 return $title->getLocalURL( $urlaction );
1178 * these return an array with the 'href' and boolean 'exists'
1179 * @param string $name
1180 * @param string $urlaction
1183 static function makeUrlDetails( $name, $urlaction = '' ) {
1184 $title = Title
::newFromText( $name );
1185 self
::checkTitle( $title, $name );
1188 'href' => $title->getLocalURL( $urlaction ),
1189 'exists' => $title->isKnown(),
1194 * Make URL details where the article exists (or at least it's convenient to think so)
1195 * @param string $name Article name
1196 * @param string $urlaction
1199 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1200 $title = Title
::newFromText( $name );
1201 self
::checkTitle( $title, $name );
1204 'href' => $title->getLocalURL( $urlaction ),
1210 * make sure we have some title to operate on
1212 * @param Title $title
1213 * @param string $name
1215 static function checkTitle( &$title, $name ) {
1216 if ( !is_object( $title ) ) {
1217 $title = Title
::newFromText( $name );
1218 if ( !is_object( $title ) ) {
1219 $title = Title
::newFromText( '--error: link target missing--' );
1225 * Build an array that represents the sidebar(s), the navigation bar among them.
1227 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1229 * The format of the returned array is [ heading => content, ... ], where:
1230 * - heading is the heading of a navigation portlet. It is either:
1231 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1232 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1233 * - plain text, which should be HTML-escaped by the skin
1234 * - content is the contents of the portlet. It is either:
1235 * - HTML text (<ul><li>...</li>...</ul>)
1236 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1237 * - (for a magic string as a key, any value)
1239 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1240 * and can technically insert anything in here; skin creators are expected to handle
1241 * values described above.
1245 function buildSidebar() {
1246 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1249 $callback = function () use ( $that ) {
1251 $that->addToSidebar( $bar, 'sidebar' );
1252 Hooks
::run( 'SkinBuildSidebar', [ $that, &$bar ] );
1257 if ( $wgEnableSidebarCache ) {
1258 $cache = ObjectCache
::getMainWANInstance();
1259 $sidebar = $cache->getWithSetCallback(
1260 $cache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1261 MessageCache
::singleton()->isDisabled()
1262 ?
$cache::TTL_UNCACHEABLE
// bug T133069
1263 : $wgSidebarCacheExpiry,
1268 $sidebar = $callback();
1271 // Apply post-processing to the cached value
1272 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1278 * Add content from a sidebar system message
1279 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1281 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1284 * @param string $message
1286 public function addToSidebar( &$bar, $message ) {
1287 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1291 * Add content from plain text
1294 * @param string $text
1297 function addToSidebarPlain( &$bar, $text ) {
1298 $lines = explode( "\n", $text );
1301 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1302 ? Title
::newMainPage() : $this->getTitle();
1304 foreach ( $lines as $line ) {
1305 if ( strpos( $line, '*' ) !== 0 ) {
1308 $line = rtrim( $line, "\r" ); // for Windows compat
1310 if ( strpos( $line, '**' ) !== 0 ) {
1311 $heading = trim( $line, '* ' );
1312 if ( !array_key_exists( $heading, $bar ) ) {
1313 $bar[$heading] = [];
1316 $line = trim( $line, '* ' );
1318 if ( strpos( $line, '|' ) !== false ) { // sanity check
1319 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1320 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1321 if ( count( $line ) !== 2 ) {
1322 // Second sanity check, could be hit by people doing
1323 // funky stuff with parserfuncs... (T35321)
1329 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1330 if ( $msgLink->exists() ) {
1331 $link = $msgLink->text();
1332 if ( $link == '-' ) {
1338 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1339 if ( $msgText->exists() ) {
1340 $text = $msgText->text();
1345 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1348 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1349 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1350 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1351 $extraAttribs['rel'] = 'nofollow';
1354 global $wgExternalLinkTarget;
1355 if ( $wgExternalLinkTarget ) {
1356 $extraAttribs['target'] = $wgExternalLinkTarget;
1359 $title = Title
::newFromText( $link );
1362 $title = $title->fixSpecialName();
1363 $href = $title->getLinkURL();
1365 $href = 'INVALID-TITLE';
1369 $bar[$heading][] = array_merge( [
1372 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1385 * Gets new talk page messages for the current user and returns an
1386 * appropriate alert message (or an empty string if there are no messages)
1389 function getNewtalks() {
1391 $newMessagesAlert = '';
1392 $user = $this->getUser();
1393 $newtalks = $user->getNewMessageLinks();
1394 $out = $this->getOutput();
1396 // Allow extensions to disable or modify the new messages alert
1397 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1400 if ( $newMessagesAlert ) {
1401 return $newMessagesAlert;
1404 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1405 $uTalkTitle = $user->getTalkPage();
1406 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1408 if ( $lastSeenRev !== null ) {
1409 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1410 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1411 if ( $latestRev !== null ) {
1412 // Singular if only 1 unseen revision, plural if several unseen revisions.
1413 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1414 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1415 $lastSeenRev, $latestRev, 10, 'include_new' );
1418 // Singular if no revision -> diff link will show latest change only in any case
1421 $plural = $plural ?
999 : 1;
1422 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1423 // the number of revisions or authors is not necessarily the same as the number of
1425 $newMessagesLink = Linker
::linkKnown(
1427 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1429 [ 'redirect' => 'no' ]
1432 $newMessagesDiffLink = Linker
::linkKnown(
1434 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1436 $lastSeenRev !== null
1437 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1438 : [ 'diff' => 'cur' ]
1441 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1442 $newMessagesAlert = $this->msg(
1443 'youhavenewmessagesfromusers',
1445 $newMessagesDiffLink
1446 )->numParams( $nofAuthors, $plural );
1448 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1449 $newMessagesAlert = $this->msg(
1450 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1452 $newMessagesDiffLink
1453 )->numParams( $plural );
1455 $newMessagesAlert = $newMessagesAlert->text();
1457 $out->setCdnMaxage( 0 );
1458 } elseif ( count( $newtalks ) ) {
1459 $sep = $this->msg( 'newtalkseparator' )->escaped();
1462 foreach ( $newtalks as $newtalk ) {
1463 $msgs[] = Xml
::element(
1465 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1468 $parts = implode( $sep, $msgs );
1469 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1470 $out->setCdnMaxage( 0 );
1473 return $newMessagesAlert;
1477 * Get a cached notice
1479 * @param string $name Message name, or 'default' for $wgSiteNotice
1480 * @return string|bool HTML fragment, or false to indicate that the caller
1481 * should fall back to the next notice in its sequence
1483 private function getCachedNotice( $name ) {
1484 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1488 if ( $name === 'default' ) {
1490 global $wgSiteNotice;
1491 $notice = $wgSiteNotice;
1492 if ( empty( $notice ) ) {
1496 $msg = $this->msg( $name )->inContentLanguage();
1497 if ( $msg->isBlank() ) {
1499 } elseif ( $msg->isDisabled() ) {
1502 $notice = $msg->plain();
1505 // Use the extra hash appender to let eg SSL variants separately cache.
1506 $key = wfMemcKey( $name . $wgRenderHashAppend );
1507 $cachedNotice = $parserMemc->get( $key );
1508 if ( is_array( $cachedNotice ) ) {
1509 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1510 $notice = $cachedNotice['html'];
1519 $parsed = $this->getOutput()->parse( $notice );
1520 $parserMemc->set( $key, [ 'html' => $parsed, 'hash' => md5( $notice ) ], 600 );
1524 $notice = Html
::rawElement( 'div', [ 'id' => 'localNotice',
1525 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ], $notice );
1530 * Get the site notice
1532 * @return string HTML fragment
1534 function getSiteNotice() {
1537 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1538 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1539 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1541 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1542 if ( $anonNotice === false ) {
1543 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1545 $siteNotice = $anonNotice;
1548 if ( $siteNotice === false ) {
1549 $siteNotice = $this->getCachedNotice( 'default' );
1553 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1558 * Create a section edit link. This supersedes editSectionLink() and
1559 * editSectionLinkForOther().
1561 * @param Title $nt The title being linked to (may not be the same as
1562 * the current page, if the section is included from a template)
1563 * @param string $section The designation of the section being pointed to,
1564 * to be included in the link, like "§ion=$section"
1565 * @param string $tooltip The tooltip to use for the link: will be escaped
1566 * and wrapped in the 'editsectionhint' message
1567 * @param string $lang Language code
1568 * @return string HTML to use for edit link
1570 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1571 // HTML generated here should probably have userlangattributes
1572 // added to it for LTR text on RTL pages
1574 $lang = wfGetLangObj( $lang );
1577 if ( !is_null( $tooltip ) ) {
1578 # T27462: undo double-escaping.
1579 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1580 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1581 ->inLanguage( $lang )->text();
1586 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1587 'targetTitle' => $nt,
1588 'attribs' => $attribs,
1589 'query' => [ 'action' => 'edit', 'section' => $section ],
1590 'options' => [ 'noclasses', 'known' ]
1594 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1596 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1599 foreach ( $links as $k => $linkDetails ) {
1600 $linksHtml[] = Linker
::link(
1601 $linkDetails['targetTitle'],
1602 $linkDetails['text'],
1603 $linkDetails['attribs'],
1604 $linkDetails['query'],
1605 $linkDetails['options']
1610 '<span class="mw-editsection-divider">'
1611 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->text()
1616 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1617 // Deprecated, use SkinEditSectionLinks hook instead
1619 'DoEditSectionLink',
1620 [ $this, $nt, $section, $tooltip, &$result, $lang ],