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
;
26 * @defgroup Skins Skins
30 * The main skin class which provides methods and properties for all other skins.
32 * See docs/skin.txt for more information.
36 abstract class Skin
extends ContextSource
{
40 protected $skinname = null;
42 protected $mRelevantTitle = null;
43 protected $mRelevantUser = null;
46 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
47 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
49 public $stylename = null;
52 * Fetch the set of available skins.
53 * @return array Associative array of strings
55 static function getSkinNames() {
56 return SkinFactory
::getDefaultInstance()->getSkinNames();
60 * Fetch the skinname messages for available skins.
63 static function getSkinNameMessages() {
65 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
66 $messages[] = "skinname-$skinKey";
72 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
73 * Useful for Special:Preferences and other places where you
74 * only want to show skins users _can_ use.
78 public static function getAllowedSkins() {
81 $allowedSkins = self
::getSkinNames();
83 foreach ( $wgSkipSkins as $skip ) {
84 unset( $allowedSkins[$skip] );
91 * Normalize a skin preference value to a form that can be loaded.
93 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
94 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
96 * @param string $key 'monobook', 'vector', etc.
99 static function normalizeKey( $key ) {
100 global $wgDefaultSkin, $wgFallbackSkin;
102 $skinNames = self
::getSkinNames();
104 // Make keys lowercase for case-insensitive matching.
105 $skinNames = array_change_key_case( $skinNames, CASE_LOWER
);
106 $key = strtolower( $key );
107 $defaultSkin = strtolower( $wgDefaultSkin );
108 $fallbackSkin = strtolower( $wgFallbackSkin );
110 if ( $key == '' ||
$key == 'default' ) {
111 // Don't return the default immediately;
112 // in a misconfiguration we need to fall back.
116 if ( isset( $skinNames[$key] ) ) {
120 // Older versions of the software used a numeric setting
121 // in the user preferences.
127 if ( isset( $fallback[$key] ) ) {
128 $key = $fallback[$key];
131 if ( isset( $skinNames[$key] ) ) {
133 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
136 return $fallbackSkin;
142 * @param string|null $skinname
144 public function __construct( $skinname = null ) {
145 if ( is_string( $skinname ) ) {
146 $this->skinname
= $skinname;
151 * @return string|null Skin name
153 public function getSkinName() {
154 return $this->skinname
;
158 * @param OutputPage $out
160 public function initPage( OutputPage
$out ) {
161 $this->preloadExistence();
165 * Defines the ResourceLoader modules that should be added to the skin
166 * It is recommended that skins wishing to override call parent::getDefaultModules()
167 * and substitute out any modules they wish to change by using a key to look them up
169 * For style modules, use setupSkinUserCss() instead.
171 * @return array Array of modules with helper keys for easy overriding
173 public function getDefaultModules() {
174 $out = $this->getOutput();
175 $config = $this->getConfig();
176 $user = $out->getUser();
178 // modules not specific to any specific skin or page
180 // Enforce various default modules for all pages and all skins
181 // Keep this list as small as possible
183 'mediawiki.page.startup',
186 // modules that enhance the page content in some way
188 'mediawiki.page.ready',
190 // modules relating to search functionality
192 // modules relating to functionality relating to watching an article
194 // modules which relate to the current users preferences
198 // Support for high-density display images if enabled
199 if ( $config->get( 'ResponsiveImages' ) ) {
200 $modules['core'][] = 'mediawiki.hidpi';
203 // Preload jquery.tablesorter for mediawiki.page.ready
204 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
205 $modules['content'][] = 'jquery.tablesorter';
208 // Preload jquery.makeCollapsible for mediawiki.page.ready
209 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
210 $modules['content'][] = 'jquery.makeCollapsible';
213 if ( $out->isTOCEnabled() ) {
214 $modules['content'][] = 'mediawiki.toc';
217 // Add various resources if required
218 if ( $user->isLoggedIn()
219 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
220 && $this->getRelevantTitle()->canExist()
222 $modules['watch'][] = 'mediawiki.page.watch.ajax';
225 $modules['search'][] = 'mediawiki.searchSuggest';
227 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
228 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
231 // Crazy edit-on-double-click stuff
232 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
233 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
239 * Preload the existence of three commonly-requested pages in a single query
241 protected function preloadExistence() {
245 $user = $this->getUser();
246 if ( $user->isLoggedIn() ) {
247 $titles[] = $user->getUserPage();
248 $titles[] = $user->getTalkPage();
251 // Check, if the page can hold some kind of content, otherwise do nothing
252 $title = $this->getRelevantTitle();
253 if ( $title->canExist() ) {
254 if ( $title->isTalkPage() ) {
255 $titles[] = $title->getSubjectPage();
257 $titles[] = $title->getTalkPage();
261 // Footer links (used by SkinTemplate::prepareQuickTemplate)
263 $this->footerLinkTitle( 'privacy', 'privacypage' ),
264 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
265 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
272 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
275 $lb = new LinkBatch( $titles );
276 $lb->setCaller( __METHOD__
);
282 * Get the current revision ID
286 public function getRevisionId() {
287 return $this->getOutput()->getRevisionId();
291 * Whether the revision displayed is the latest revision of the page
295 public function isRevisionCurrent() {
296 $revID = $this->getRevisionId();
297 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
301 * Set the "relevant" title
302 * @see self::getRelevantTitle()
305 public function setRelevantTitle( $t ) {
306 $this->mRelevantTitle
= $t;
310 * Return the "relevant" title.
311 * A "relevant" title is not necessarily the actual title of the page.
312 * Special pages like Special:MovePage use set the page they are acting on
313 * as their "relevant" title, this allows the skin system to display things
314 * such as content tabs which belong to to that page instead of displaying
315 * a basic special page tab which has almost no meaning.
319 public function getRelevantTitle() {
320 if ( isset( $this->mRelevantTitle
) ) {
321 return $this->mRelevantTitle
;
323 return $this->getTitle();
327 * Set the "relevant" user
328 * @see self::getRelevantUser()
331 public function setRelevantUser( $u ) {
332 $this->mRelevantUser
= $u;
336 * Return the "relevant" user.
337 * A "relevant" user is similar to a relevant title. Special pages like
338 * Special:Contributions mark the user which they are relevant to so that
339 * things like the toolbox can display the information they usually are only
340 * able to display on a user's userpage and talkpage.
343 public function getRelevantUser() {
344 if ( isset( $this->mRelevantUser
) ) {
345 return $this->mRelevantUser
;
347 $title = $this->getRelevantTitle();
348 if ( $title->hasSubjectNamespace( NS_USER
) ) {
349 $rootUser = $title->getRootText();
350 if ( User
::isIP( $rootUser ) ) {
351 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
353 $user = User
::newFromName( $rootUser, false );
356 $user->load( User
::READ_NORMAL
);
358 if ( $user->isLoggedIn() ) {
359 $this->mRelevantUser
= $user;
363 return $this->mRelevantUser
;
369 * Outputs the HTML generated by other functions.
370 * @param OutputPage $out
372 abstract function outputPage( OutputPage
$out = null );
378 static function makeVariablesScript( $data ) {
380 return ResourceLoader
::makeInlineScript(
381 ResourceLoader
::makeConfigSetScript( $data )
389 * Get the query to generate a dynamic stylesheet
393 public static function getDynamicStylesheetQuery() {
394 global $wgSquidMaxage;
398 'maxage' => $wgSquidMaxage,
399 'usemsgcache' => 'yes',
400 'ctype' => 'text/css',
401 'smaxage' => $wgSquidMaxage,
406 * Add skin specific stylesheets
407 * Calling this method with an $out of anything but the same OutputPage
408 * inside ->getOutput() is deprecated. The $out arg is kept
409 * for compatibility purposes with skins.
410 * @param OutputPage $out
413 abstract function setupSkinUserCss( OutputPage
$out );
417 * @param Title $title
420 function getPageClasses( $title ) {
421 $numeric = 'ns-' . $title->getNamespace();
423 if ( $title->isSpecialPage() ) {
424 $type = 'ns-special';
425 // T25315: provide a class based on the canonical special page name without subpages
426 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
427 if ( $canonicalName ) {
428 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
430 $type .= ' mw-invalidspecialpage';
432 } elseif ( $title->isTalkPage() ) {
435 $type = 'ns-subject';
438 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
439 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
441 return "$numeric $type $name $root";
445 * Return values for <html> element
446 * @return array Array of associative name-to-value elements for <html> element
448 public function getHtmlElementAttributes() {
449 $lang = $this->getLanguage();
451 'lang' => $lang->getHtmlCode(),
452 'dir' => $lang->getDir(),
453 'class' => 'client-nojs',
458 * This will be called by OutputPage::headElement when it is creating the
459 * "<body>" tag, skins can override it if they have a need to add in any
460 * body attributes or classes of their own.
461 * @param OutputPage $out
462 * @param array &$bodyAttrs
464 function addToBodyAttributes( $out, &$bodyAttrs ) {
465 // does nothing by default
478 * Whether the logo should be preloaded with an HTTP link header or not
482 public function shouldPreloadLogo() {
487 * @return string HTML
489 function getCategoryLinks() {
490 global $wgUseCategoryBrowser;
492 $out = $this->getOutput();
493 $allCats = $out->getCategoryLinks();
495 if ( !count( $allCats ) ) {
503 $colon = $this->msg( 'colon-separator' )->escaped();
505 if ( !empty( $allCats['normal'] ) ) {
506 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
508 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
509 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
510 $title = Title
::newFromText( $linkPage );
511 $link = $title ? Linker
::link( $title, $msg ) : $msg;
512 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
513 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
517 if ( isset( $allCats['hidden'] ) ) {
518 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
519 $class = ' mw-hidden-cats-user-shown';
520 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
521 $class = ' mw-hidden-cats-ns-shown';
523 $class = ' mw-hidden-cats-hidden';
526 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
527 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
528 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
532 # optional 'dmoz-like' category browser. Will be shown under the list
533 # of categories an article belong to
534 if ( $wgUseCategoryBrowser ) {
535 $s .= '<br /><hr />';
537 # get a big array of the parents tree
538 $parenttree = $this->getTitle()->getParentCategoryTree();
539 # Skin object passed by reference cause it can not be
540 # accessed under the method subfunction drawCategoryBrowser
541 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
542 # Clean out bogus first entry and sort them
543 unset( $tempout[0] );
545 # Output one per line
546 $s .= implode( "<br />\n", $tempout );
553 * Render the array as a series of links.
554 * @param array $tree Categories tree returned by Title::getParentCategoryTree
555 * @return string Separated by >, terminate with "\n"
557 function drawCategoryBrowser( $tree ) {
560 foreach ( $tree as $element => $parent ) {
561 if ( empty( $parent ) ) {
562 # element start a new list
565 # grab the others elements
566 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
569 # add our current element to the list
570 $eltitle = Title
::newFromText( $element );
571 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
578 * @return string HTML
580 function getCategories() {
581 $out = $this->getOutput();
582 $catlinks = $this->getCategoryLinks();
584 // Check what we're showing
585 $allCats = $out->getCategoryLinks();
586 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
587 $this->getTitle()->getNamespace() == NS_CATEGORY
;
589 $classes = [ 'catlinks' ];
590 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
591 $classes[] = 'catlinks-allhidden';
594 return Html
::rawElement(
596 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
602 * This runs a hook to allow extensions placing their stuff after content
603 * and article metadata (e.g. categories).
604 * Note: This function has nothing to do with afterContent().
606 * This hook is placed here in order to allow using the same hook for all
607 * skins, both the SkinTemplate based ones and the older ones, which directly
608 * use this class to get their data.
610 * The output of this function gets processed in SkinTemplate::outputPage() for
611 * the SkinTemplate based skins, all other skins should directly echo it.
613 * @return string Empty by default, if not changed by any hook function.
615 protected function afterContentHook() {
618 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
619 // adding just some spaces shouldn't toggle the output
620 // of the whole <div/>, so we use trim() here
621 if ( trim( $data ) != '' ) {
622 // Doing this here instead of in the skins to
623 // ensure that the div has the same ID in all
625 $data = "<div id='mw-data-after-content'>\n" .
630 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
637 * Generate debug data HTML for displaying at the bottom of the main content
639 * @return string HTML containing debug data, if enabled (otherwise empty).
641 protected function generateDebugHTML() {
642 return MWDebug
::getHTMLDebugLog();
646 * This gets called shortly before the "</body>" tag.
648 * @return string HTML-wrapped JS code to be put before "</body>"
650 function bottomScripts() {
651 // TODO and the suckage continues. This function is really just a wrapper around
652 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
654 $bottomScriptText = $this->getOutput()->getBottomScripts();
655 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$bottomScriptText ] );
657 return $bottomScriptText;
661 * Text with the permalink to the source page,
662 * usually shown on the footer of a printed page
664 * @return string HTML text with an URL
666 function printSource() {
667 $oldid = $this->getRevisionId();
669 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
670 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
672 // oldid not available for non existing pages
673 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
676 return $this->msg( 'retrievedfrom' )
677 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
682 * @return string HTML
684 function getUndeleteLink() {
685 $action = $this->getRequest()->getVal( 'action', 'view' );
687 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
688 ( !$this->getTitle()->exists() ||
$action == 'history' ) ) {
689 $n = $this->getTitle()->isDeleted();
692 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
693 $msg = 'thisisdeleted';
695 $msg = 'viewdeleted';
698 return $this->msg( $msg )->rawParams(
700 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
701 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
710 * @param OutputPage $out Defaults to $this->getOutput() if left as null
713 function subPageSubtitle( $out = null ) {
714 if ( $out === null ) {
715 $out = $this->getOutput();
717 $title = $out->getTitle();
720 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
724 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
725 $ptext = $title->getPrefixedText();
726 if ( strpos( $ptext, '/' ) !== false ) {
727 $links = explode( '/', $ptext );
732 $lang = $this->getLanguage();
734 foreach ( $links as $link ) {
735 $growinglink .= $link;
737 $linkObj = Title
::newFromText( $growinglink );
739 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
740 $getlink = Linker
::linkKnown(
742 htmlspecialchars( $display )
748 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
750 $subpages .= '< ';
753 $subpages .= $getlink;
769 function getSearchLink() {
770 $searchPage = SpecialPage
::getTitleFor( 'Search' );
771 return $searchPage->getLocalURL();
777 function escapeSearchLink() {
778 return htmlspecialchars( $this->getSearchLink() );
782 * @param string $type
785 function getCopyright( $type = 'detect' ) {
786 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
788 if ( $type == 'detect' ) {
789 if ( !$this->isRevisionCurrent()
790 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
798 if ( $type == 'history' ) {
799 $msg = 'history_copyright';
804 if ( $wgRightsPage ) {
805 $title = Title
::newFromText( $wgRightsPage );
806 $link = Linker
::linkKnown( $title, $wgRightsText );
807 } elseif ( $wgRightsUrl ) {
808 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
809 } elseif ( $wgRightsText ) {
810 $link = $wgRightsText;
816 // Allow for site and per-namespace customization of copyright notice.
817 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
821 'SkinCopyrightFooter',
822 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
825 return $this->msg( $msg )->rawParams( $link )->text();
829 * @return null|string
831 function getCopyrightIcon() {
832 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
836 if ( $wgFooterIcons['copyright']['copyright'] ) {
837 $out = $wgFooterIcons['copyright']['copyright'];
838 } elseif ( $wgRightsIcon ) {
839 $icon = htmlspecialchars( $wgRightsIcon );
841 if ( $wgRightsUrl ) {
842 $url = htmlspecialchars( $wgRightsUrl );
843 $out .= '<a href="' . $url . '">';
846 $text = htmlspecialchars( $wgRightsText );
847 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
849 if ( $wgRightsUrl ) {
858 * Gets the powered by MediaWiki icon.
861 function getPoweredBy() {
862 global $wgResourceBasePath;
864 $url1 = htmlspecialchars(
865 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
867 $url1_5 = htmlspecialchars(
868 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
870 $url2 = htmlspecialchars(
871 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
873 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
874 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
875 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
876 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
881 * Get the timestamp of the latest revision, formatted in user language
885 protected function lastModified() {
886 $timestamp = $this->getOutput()->getRevisionTimestamp();
888 # No cached timestamp, load it from the database
889 if ( $timestamp === null ) {
890 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
894 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
895 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
896 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
901 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLaggedReplicaMode() ) {
902 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
909 * @param string $align
912 function logoText( $align = '' ) {
913 if ( $align != '' ) {
914 $a = " style='float: {$align};'";
919 $mp = $this->msg( 'mainpage' )->escaped();
920 $mptitle = Title
::newMainPage();
921 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
923 $logourl = $this->getLogo();
924 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
930 * Renders a $wgFooterIcons icon according to the method's arguments
931 * @param array $icon The icon to build the html for, see $wgFooterIcons
932 * for the format of this array.
933 * @param bool|string $withImage Whether to use the icon's image or output
934 * a text-only footericon.
935 * @return string HTML
937 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
938 if ( is_string( $icon ) ) {
940 } else { // Assuming array
941 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
942 unset( $icon["url"] );
943 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
944 // do this the lazy way, just pass icon data as an attribute array
945 $html = Html
::element( 'img', $icon );
947 $html = htmlspecialchars( $icon["alt"] );
950 global $wgExternalLinkTarget;
951 $html = Html
::rawElement( 'a',
952 [ "href" => $url, "target" => $wgExternalLinkTarget ],
960 * Gets the link to the wiki's main page.
963 function mainPageLink() {
964 $s = Linker
::linkKnown(
965 Title
::newMainPage(),
966 $this->msg( 'mainpage' )->escaped()
973 * Returns an HTML link for use in the footer
974 * @param string $desc The i18n message key for the link text
975 * @param string $page The i18n message key for the page to link to
976 * @return string HTML anchor
978 public function footerLink( $desc, $page ) {
979 $title = $this->footerLinkTitle( $desc, $page );
984 return Linker
::linkKnown(
986 $this->msg( $desc )->escaped()
991 * @param string $desc
992 * @param string $page
995 private function footerLinkTitle( $desc, $page ) {
996 // If the link description has been set to "-" in the default language,
997 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
998 // then it is disabled, for all languages.
1001 // Otherwise, we display the link for the user, described in their
1002 // language (which may or may not be the same as the default language),
1003 // but we make the link target be the one site-wide page.
1004 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1006 return $title ?
: null;
1010 * Gets the link to the wiki's privacy policy page.
1011 * @return string HTML
1013 function privacyLink() {
1014 return $this->footerLink( 'privacy', 'privacypage' );
1018 * Gets the link to the wiki's about page.
1019 * @return string HTML
1021 function aboutLink() {
1022 return $this->footerLink( 'aboutsite', 'aboutpage' );
1026 * Gets the link to the wiki's general disclaimers page.
1027 * @return string HTML
1029 function disclaimerLink() {
1030 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1034 * Return URL options for the 'edit page' link.
1035 * This may include an 'oldid' specifier, if the current page view is such.
1040 function editUrlOptions() {
1041 $options = [ 'action' => 'edit' ];
1043 if ( !$this->isRevisionCurrent() ) {
1044 $options['oldid'] = intval( $this->getRevisionId() );
1051 * @param User|int $id
1054 function showEmailUser( $id ) {
1055 if ( $id instanceof User
) {
1058 $targetUser = User
::newFromId( $id );
1061 # The sending user must have a confirmed email address and the receiving
1062 # user must accept emails from the sender.
1063 return $this->getUser()->canSendEmail()
1064 && SpecialEmailUser
::validateTarget( $targetUser, $this->getUser() ) === '';
1068 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1069 * This method returns a url resolved using the configured skin style path
1070 * and includes the style version inside of the url.
1072 * Requires $stylename to be set, otherwise throws MWException.
1074 * @param string $name The name or path of a skin resource file
1075 * @return string The fully resolved style path url including styleversion
1076 * @throws MWException
1078 function getSkinStylePath( $name ) {
1079 global $wgStylePath, $wgStyleVersion;
1081 if ( $this->stylename
=== null ) {
1082 $class = static::class;
1083 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1086 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1089 /* these are used extensively in SkinTemplate, but also some other places */
1092 * @param string|string[] $urlaction
1095 static function makeMainPageUrl( $urlaction = '' ) {
1096 $title = Title
::newMainPage();
1097 self
::checkTitle( $title, '' );
1099 return $title->getLinkURL( $urlaction );
1103 * Make a URL for a Special Page using the given query and protocol.
1105 * If $proto is set to null, make a local URL. Otherwise, make a full
1106 * URL with the protocol specified.
1108 * @param string $name Name of the Special page
1109 * @param string|string[] $urlaction Query to append
1110 * @param string|null $proto Protocol to use or null for a local URL
1113 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1114 $title = SpecialPage
::getSafeTitleFor( $name );
1115 if ( is_null( $proto ) ) {
1116 return $title->getLocalURL( $urlaction );
1118 return $title->getFullURL( $urlaction, false, $proto );
1123 * @param string $name
1124 * @param string $subpage
1125 * @param string|string[] $urlaction
1128 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1129 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1130 return $title->getLocalURL( $urlaction );
1134 * @param string $name
1135 * @param string|string[] $urlaction
1138 static function makeI18nUrl( $name, $urlaction = '' ) {
1139 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1140 self
::checkTitle( $title, $name );
1141 return $title->getLocalURL( $urlaction );
1145 * @param string $name
1146 * @param string|string[] $urlaction
1149 static function makeUrl( $name, $urlaction = '' ) {
1150 $title = Title
::newFromText( $name );
1151 self
::checkTitle( $title, $name );
1153 return $title->getLocalURL( $urlaction );
1157 * If url string starts with http, consider as external URL, else
1159 * @param string $name
1160 * @return string URL
1162 static function makeInternalOrExternalUrl( $name ) {
1163 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1166 return self
::makeUrl( $name );
1171 * this can be passed the NS number as defined in Language.php
1172 * @param string $name
1173 * @param string|string[] $urlaction
1174 * @param int $namespace
1177 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1178 $title = Title
::makeTitleSafe( $namespace, $name );
1179 self
::checkTitle( $title, $name );
1181 return $title->getLocalURL( $urlaction );
1185 * these return an array with the 'href' and boolean 'exists'
1186 * @param string $name
1187 * @param string|string[] $urlaction
1190 static function makeUrlDetails( $name, $urlaction = '' ) {
1191 $title = Title
::newFromText( $name );
1192 self
::checkTitle( $title, $name );
1195 'href' => $title->getLocalURL( $urlaction ),
1196 'exists' => $title->isKnown(),
1201 * Make URL details where the article exists (or at least it's convenient to think so)
1202 * @param string $name Article name
1203 * @param string|string[] $urlaction
1206 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1207 $title = Title
::newFromText( $name );
1208 self
::checkTitle( $title, $name );
1211 'href' => $title->getLocalURL( $urlaction ),
1217 * make sure we have some title to operate on
1219 * @param Title &$title
1220 * @param string $name
1222 static function checkTitle( &$title, $name ) {
1223 if ( !is_object( $title ) ) {
1224 $title = Title
::newFromText( $name );
1225 if ( !is_object( $title ) ) {
1226 $title = Title
::newFromText( '--error: link target missing--' );
1232 * Build an array that represents the sidebar(s), the navigation bar among them.
1234 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1236 * The format of the returned array is [ heading => content, ... ], where:
1237 * - heading is the heading of a navigation portlet. It is either:
1238 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1239 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1240 * - plain text, which should be HTML-escaped by the skin
1241 * - content is the contents of the portlet. It is either:
1242 * - HTML text (<ul><li>...</li>...</ul>)
1243 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1244 * - (for a magic string as a key, any value)
1246 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1247 * and can technically insert anything in here; skin creators are expected to handle
1248 * values described above.
1252 public function buildSidebar() {
1253 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1255 $callback = function ( $old = null, &$ttl = null ) {
1257 $this->addToSidebar( $bar, 'sidebar' );
1258 Hooks
::run( 'SkinBuildSidebar', [ $this, &$bar ] );
1259 if ( MessageCache
::singleton()->isDisabled() ) {
1260 $ttl = WANObjectCache
::TTL_UNCACHEABLE
; // bug T133069
1266 $msgCache = MessageCache
::singleton();
1267 $wanCache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1269 $sidebar = $wgEnableSidebarCache
1270 ?
$wanCache->getWithSetCallback(
1271 $wanCache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1272 $wgSidebarCacheExpiry,
1276 // Unless there is both no exact $code override nor an i18n definition
1277 // in the the software, the only MediaWiki page to check is for $code.
1278 $msgCache->getCheckKey( $this->getLanguage()->getCode() )
1285 // Apply post-processing to the cached value
1286 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1292 * Add content from a sidebar system message
1293 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1295 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1297 * @param array &$bar
1298 * @param string $message
1300 public function addToSidebar( &$bar, $message ) {
1301 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1305 * Add content from plain text
1307 * @param array &$bar
1308 * @param string $text
1311 function addToSidebarPlain( &$bar, $text ) {
1312 $lines = explode( "\n", $text );
1315 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1316 ? Title
::newMainPage() : $this->getTitle();
1318 foreach ( $lines as $line ) {
1319 if ( strpos( $line, '*' ) !== 0 ) {
1322 $line = rtrim( $line, "\r" ); // for Windows compat
1324 if ( strpos( $line, '**' ) !== 0 ) {
1325 $heading = trim( $line, '* ' );
1326 if ( !array_key_exists( $heading, $bar ) ) {
1327 $bar[$heading] = [];
1330 $line = trim( $line, '* ' );
1332 if ( strpos( $line, '|' ) !== false ) { // sanity check
1333 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1334 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1335 if ( count( $line ) !== 2 ) {
1336 // Second sanity check, could be hit by people doing
1337 // funky stuff with parserfuncs... (T35321)
1343 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1344 if ( $msgLink->exists() ) {
1345 $link = $msgLink->text();
1346 if ( $link == '-' ) {
1352 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1353 if ( $msgText->exists() ) {
1354 $text = $msgText->text();
1359 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1362 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1363 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1364 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1365 $extraAttribs['rel'] = 'nofollow';
1368 global $wgExternalLinkTarget;
1369 if ( $wgExternalLinkTarget ) {
1370 $extraAttribs['target'] = $wgExternalLinkTarget;
1373 $title = Title
::newFromText( $link );
1376 $title = $title->fixSpecialName();
1377 $href = $title->getLinkURL();
1379 $href = 'INVALID-TITLE';
1383 $bar[$heading][] = array_merge( [
1386 'id' => Sanitizer
::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1399 * Gets new talk page messages for the current user and returns an
1400 * appropriate alert message (or an empty string if there are no messages)
1403 function getNewtalks() {
1404 $newMessagesAlert = '';
1405 $user = $this->getUser();
1406 $newtalks = $user->getNewMessageLinks();
1407 $out = $this->getOutput();
1409 // Allow extensions to disable or modify the new messages alert
1410 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1413 if ( $newMessagesAlert ) {
1414 return $newMessagesAlert;
1417 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1418 $uTalkTitle = $user->getTalkPage();
1419 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1421 if ( $lastSeenRev !== null ) {
1422 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1423 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1424 if ( $latestRev !== null ) {
1425 // Singular if only 1 unseen revision, plural if several unseen revisions.
1426 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1427 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1428 $lastSeenRev, $latestRev, 10, 'include_new' );
1431 // Singular if no revision -> diff link will show latest change only in any case
1434 $plural = $plural ?
999 : 1;
1435 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1436 // the number of revisions or authors is not necessarily the same as the number of
1438 $newMessagesLink = Linker
::linkKnown(
1440 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1442 [ 'redirect' => 'no' ]
1445 $newMessagesDiffLink = Linker
::linkKnown(
1447 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1449 $lastSeenRev !== null
1450 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1451 : [ 'diff' => 'cur' ]
1454 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1455 $newMessagesAlert = $this->msg(
1456 'youhavenewmessagesfromusers',
1458 $newMessagesDiffLink
1459 )->numParams( $nofAuthors, $plural );
1461 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1462 $newMessagesAlert = $this->msg(
1463 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1465 $newMessagesDiffLink
1466 )->numParams( $plural );
1468 $newMessagesAlert = $newMessagesAlert->text();
1470 $out->setCdnMaxage( 0 );
1471 } elseif ( count( $newtalks ) ) {
1472 $sep = $this->msg( 'newtalkseparator' )->escaped();
1475 foreach ( $newtalks as $newtalk ) {
1476 $msgs[] = Xml
::element(
1478 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1481 $parts = implode( $sep, $msgs );
1482 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1483 $out->setCdnMaxage( 0 );
1486 return $newMessagesAlert;
1490 * Get a cached notice
1492 * @param string $name Message name, or 'default' for $wgSiteNotice
1493 * @return string|bool HTML fragment, or false to indicate that the caller
1494 * should fall back to the next notice in its sequence
1496 private function getCachedNotice( $name ) {
1497 global $wgRenderHashAppend, $wgContLang;
1501 if ( $name === 'default' ) {
1503 global $wgSiteNotice;
1504 $notice = $wgSiteNotice;
1505 if ( empty( $notice ) ) {
1509 $msg = $this->msg( $name )->inContentLanguage();
1510 if ( $msg->isBlank() ) {
1512 } elseif ( $msg->isDisabled() ) {
1515 $notice = $msg->plain();
1518 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1519 $parsed = $cache->getWithSetCallback(
1520 // Use the extra hash appender to let eg SSL variants separately cache
1521 // Key is verified with md5 hash of unparsed wikitext
1522 $cache->makeKey( $name, $wgRenderHashAppend, md5( $notice ) ),
1525 function () use ( $notice ) {
1526 return $this->getOutput()->parse( $notice );
1530 return Html
::rawElement(
1533 'id' => 'localNotice',
1534 'lang' => $wgContLang->getHtmlCode(),
1535 'dir' => $wgContLang->getDir()
1542 * Get the site notice
1544 * @return string HTML fragment
1546 function getSiteNotice() {
1549 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1550 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1551 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1553 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1554 if ( $anonNotice === false ) {
1555 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1557 $siteNotice = $anonNotice;
1560 if ( $siteNotice === false ) {
1561 $siteNotice = $this->getCachedNotice( 'default' );
1565 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1570 * Create a section edit link. This supersedes editSectionLink() and
1571 * editSectionLinkForOther().
1573 * @param Title $nt The title being linked to (may not be the same as
1574 * the current page, if the section is included from a template)
1575 * @param string $section The designation of the section being pointed to,
1576 * to be included in the link, like "§ion=$section"
1577 * @param string $tooltip The tooltip to use for the link: will be escaped
1578 * and wrapped in the 'editsectionhint' message
1579 * @param string $lang Language code
1580 * @return string HTML to use for edit link
1582 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1583 // HTML generated here should probably have userlangattributes
1584 // added to it for LTR text on RTL pages
1586 $lang = wfGetLangObj( $lang );
1589 if ( !is_null( $tooltip ) ) {
1590 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1591 ->inLanguage( $lang )->text();
1596 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1597 'targetTitle' => $nt,
1598 'attribs' => $attribs,
1599 'query' => [ 'action' => 'edit', 'section' => $section ],
1600 'options' => [ 'noclasses', 'known' ]
1604 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1606 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1609 foreach ( $links as $k => $linkDetails ) {
1610 $linksHtml[] = Linker
::link(
1611 $linkDetails['targetTitle'],
1612 $linkDetails['text'],
1613 $linkDetails['attribs'],
1614 $linkDetails['query'],
1615 $linkDetails['options']
1620 '<span class="mw-editsection-divider">'
1621 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->escaped()
1626 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1627 // Deprecated, use SkinEditSectionLinks hook instead
1629 'DoEditSectionLink',
1630 [ $this, $nt, $section, $tooltip, &$result, $lang ],