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 * Any modules defined with the 'styles' key will be added as render blocking CSS via
170 * Output::addModuleStyles. Similarly, each key should refer to a list of modules
172 * @return array Array of modules with helper keys for easy overriding
174 public function getDefaultModules() {
175 $out = $this->getOutput();
176 $config = $this->getConfig();
177 $user = $this->getUser();
179 // Modules declared in the $modules literal are loaded
180 // for ALL users, on ALL pages, in ALL skins.
181 // Keep this list as small as possible!
184 // The 'styles' key sets render-blocking style modules
185 // Unlike other keys in $modules, this is an associative array
186 // where each key is its own group pointing to a list of modules
188 'mediawiki.legacy.shared',
189 'mediawiki.legacy.commonPrint',
196 'mediawiki.page.startup',
199 // modules that enhance the content in some way
201 'mediawiki.page.ready',
203 // modules relating to search functionality
205 // modules relating to functionality relating to watching an article
207 // modules which relate to the current users preferences
209 // modules relating to RSS/Atom Feeds
213 // Support for high-density display images if enabled
214 if ( $config->get( 'ResponsiveImages' ) ) {
215 $modules['core'][] = 'mediawiki.hidpi';
218 // Preload jquery.tablesorter for mediawiki.page.ready
219 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
220 $modules['content'][] = 'jquery.tablesorter';
221 $modules['styles']['content'][] = 'jquery.tablesorter.styles';
224 // Preload jquery.makeCollapsible for mediawiki.page.ready
225 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
226 $modules['content'][] = 'jquery.makeCollapsible';
227 $modules['styles']['content'][] = 'jquery.makeCollapsible.styles';
230 // Deprecated since 1.26: Unconditional loading of mediawiki.ui.button
231 // on every page is deprecated. Express a dependency instead.
232 if ( strpos( $out->getHTML(), 'mw-ui-button' ) !== false ) {
233 $modules['styles']['content'][] = 'mediawiki.ui.button';
236 if ( $out->isTOCEnabled() ) {
237 $modules['content'][] = 'mediawiki.toc';
238 $modules['styles']['content'][] = 'mediawiki.toc.styles';
241 // Add various resources if required
242 if ( $user->isLoggedIn()
243 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
244 && $this->getRelevantTitle()->canExist()
246 $modules['watch'][] = 'mediawiki.page.watch.ajax';
249 $modules['search'][] = 'mediawiki.searchSuggest';
251 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
252 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
255 // Crazy edit-on-double-click stuff
256 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
257 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
260 if ( $out->isSyndicated() ) {
261 $modules['styles']['syndicate'][] = 'mediawiki.feedlink';
268 * Preload the existence of three commonly-requested pages in a single query
270 protected function preloadExistence() {
274 $user = $this->getUser();
275 if ( $user->isLoggedIn() ) {
276 $titles[] = $user->getUserPage();
277 $titles[] = $user->getTalkPage();
280 // Check, if the page can hold some kind of content, otherwise do nothing
281 $title = $this->getRelevantTitle();
282 if ( $title->canExist() ) {
283 if ( $title->isTalkPage() ) {
284 $titles[] = $title->getSubjectPage();
286 $titles[] = $title->getTalkPage();
290 // Footer links (used by SkinTemplate::prepareQuickTemplate)
292 $this->footerLinkTitle( 'privacy', 'privacypage' ),
293 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
294 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
301 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
304 $lb = new LinkBatch( $titles );
305 $lb->setCaller( __METHOD__
);
311 * Get the current revision ID
315 public function getRevisionId() {
316 return $this->getOutput()->getRevisionId();
320 * Whether the revision displayed is the latest revision of the page
324 public function isRevisionCurrent() {
325 $revID = $this->getRevisionId();
326 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
330 * Set the "relevant" title
331 * @see self::getRelevantTitle()
334 public function setRelevantTitle( $t ) {
335 $this->mRelevantTitle
= $t;
339 * Return the "relevant" title.
340 * A "relevant" title is not necessarily the actual title of the page.
341 * Special pages like Special:MovePage use set the page they are acting on
342 * as their "relevant" title, this allows the skin system to display things
343 * such as content tabs which belong to to that page instead of displaying
344 * a basic special page tab which has almost no meaning.
348 public function getRelevantTitle() {
349 if ( isset( $this->mRelevantTitle
) ) {
350 return $this->mRelevantTitle
;
352 return $this->getTitle();
356 * Set the "relevant" user
357 * @see self::getRelevantUser()
360 public function setRelevantUser( $u ) {
361 $this->mRelevantUser
= $u;
365 * Return the "relevant" user.
366 * A "relevant" user is similar to a relevant title. Special pages like
367 * Special:Contributions mark the user which they are relevant to so that
368 * things like the toolbox can display the information they usually are only
369 * able to display on a user's userpage and talkpage.
372 public function getRelevantUser() {
373 if ( isset( $this->mRelevantUser
) ) {
374 return $this->mRelevantUser
;
376 $title = $this->getRelevantTitle();
377 if ( $title->hasSubjectNamespace( NS_USER
) ) {
378 $rootUser = $title->getRootText();
379 if ( User
::isIP( $rootUser ) ) {
380 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
382 $user = User
::newFromName( $rootUser, false );
385 $user->load( User
::READ_NORMAL
);
387 if ( $user->isLoggedIn() ) {
388 $this->mRelevantUser
= $user;
392 return $this->mRelevantUser
;
398 * Outputs the HTML generated by other functions.
399 * @param OutputPage $out
401 abstract function outputPage( OutputPage
$out = null );
407 static function makeVariablesScript( $data ) {
409 return ResourceLoader
::makeInlineScript(
410 ResourceLoader
::makeConfigSetScript( $data )
418 * Get the query to generate a dynamic stylesheet
422 public static function getDynamicStylesheetQuery() {
423 global $wgSquidMaxage;
427 'maxage' => $wgSquidMaxage,
428 'usemsgcache' => 'yes',
429 'ctype' => 'text/css',
430 'smaxage' => $wgSquidMaxage,
435 * Hook point for adding style modules to OutputPage.
437 * @deprecated since 1.32 Use getDefaultModules() instead.
438 * @param OutputPage $out Legacy parameter, identical to $this->getOutput()
440 public function setupSkinUserCss( OutputPage
$out ) {
446 * @param Title $title
449 function getPageClasses( $title ) {
450 $numeric = 'ns-' . $title->getNamespace();
452 if ( $title->isSpecialPage() ) {
453 $type = 'ns-special';
454 // T25315: provide a class based on the canonical special page name without subpages
455 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
456 if ( $canonicalName ) {
457 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
459 $type .= ' mw-invalidspecialpage';
461 } elseif ( $title->isTalkPage() ) {
464 $type = 'ns-subject';
467 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
468 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
470 return "$numeric $type $name $root";
474 * Return values for <html> element
475 * @return array Array of associative name-to-value elements for <html> element
477 public function getHtmlElementAttributes() {
478 $lang = $this->getLanguage();
480 'lang' => $lang->getHtmlCode(),
481 'dir' => $lang->getDir(),
482 'class' => 'client-nojs',
487 * This will be called by OutputPage::headElement when it is creating the
488 * "<body>" tag, skins can override it if they have a need to add in any
489 * body attributes or classes of their own.
490 * @param OutputPage $out
491 * @param array &$bodyAttrs
493 function addToBodyAttributes( $out, &$bodyAttrs ) {
494 // does nothing by default
507 * Whether the logo should be preloaded with an HTTP link header or not
511 public function shouldPreloadLogo() {
516 * @return string HTML
518 function getCategoryLinks() {
519 global $wgUseCategoryBrowser;
521 $out = $this->getOutput();
522 $allCats = $out->getCategoryLinks();
524 if ( !count( $allCats ) ) {
532 $colon = $this->msg( 'colon-separator' )->escaped();
534 if ( !empty( $allCats['normal'] ) ) {
535 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
537 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
538 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
539 $title = Title
::newFromText( $linkPage );
540 $link = $title ? Linker
::link( $title, $msg ) : $msg;
541 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
542 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
546 if ( isset( $allCats['hidden'] ) ) {
547 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
548 $class = ' mw-hidden-cats-user-shown';
549 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
550 $class = ' mw-hidden-cats-ns-shown';
552 $class = ' mw-hidden-cats-hidden';
555 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
556 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
557 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
561 # optional 'dmoz-like' category browser. Will be shown under the list
562 # of categories an article belong to
563 if ( $wgUseCategoryBrowser ) {
564 $s .= '<br /><hr />';
566 # get a big array of the parents tree
567 $parenttree = $this->getTitle()->getParentCategoryTree();
568 # Skin object passed by reference cause it can not be
569 # accessed under the method subfunction drawCategoryBrowser
570 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
571 # Clean out bogus first entry and sort them
572 unset( $tempout[0] );
574 # Output one per line
575 $s .= implode( "<br />\n", $tempout );
582 * Render the array as a series of links.
583 * @param array $tree Categories tree returned by Title::getParentCategoryTree
584 * @return string Separated by >, terminate with "\n"
586 function drawCategoryBrowser( $tree ) {
589 foreach ( $tree as $element => $parent ) {
590 if ( empty( $parent ) ) {
591 # element start a new list
594 # grab the others elements
595 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
598 # add our current element to the list
599 $eltitle = Title
::newFromText( $element );
600 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
607 * @return string HTML
609 function getCategories() {
610 $out = $this->getOutput();
611 $catlinks = $this->getCategoryLinks();
613 // Check what we're showing
614 $allCats = $out->getCategoryLinks();
615 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
616 $this->getTitle()->getNamespace() == NS_CATEGORY
;
618 $classes = [ 'catlinks' ];
619 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
620 $classes[] = 'catlinks-allhidden';
623 return Html
::rawElement(
625 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
631 * This runs a hook to allow extensions placing their stuff after content
632 * and article metadata (e.g. categories).
633 * Note: This function has nothing to do with afterContent().
635 * This hook is placed here in order to allow using the same hook for all
636 * skins, both the SkinTemplate based ones and the older ones, which directly
637 * use this class to get their data.
639 * The output of this function gets processed in SkinTemplate::outputPage() for
640 * the SkinTemplate based skins, all other skins should directly echo it.
642 * @return string Empty by default, if not changed by any hook function.
644 protected function afterContentHook() {
647 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
648 // adding just some spaces shouldn't toggle the output
649 // of the whole <div/>, so we use trim() here
650 if ( trim( $data ) != '' ) {
651 // Doing this here instead of in the skins to
652 // ensure that the div has the same ID in all
654 $data = "<div id='mw-data-after-content'>\n" .
659 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
666 * Generate debug data HTML for displaying at the bottom of the main content
668 * @return string HTML containing debug data, if enabled (otherwise empty).
670 protected function generateDebugHTML() {
671 return MWDebug
::getHTMLDebugLog();
675 * This gets called shortly before the "</body>" tag.
677 * @return string HTML-wrapped JS code to be put before "</body>"
679 function bottomScripts() {
680 // TODO and the suckage continues. This function is really just a wrapper around
681 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
683 $bottomScriptText = $this->getOutput()->getBottomScripts();
684 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$bottomScriptText ] );
686 return $bottomScriptText;
690 * Text with the permalink to the source page,
691 * usually shown on the footer of a printed page
693 * @return string HTML text with an URL
695 function printSource() {
696 $oldid = $this->getRevisionId();
698 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
699 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
701 // oldid not available for non existing pages
702 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
705 return $this->msg( 'retrievedfrom' )
706 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
711 * @return string HTML
713 function getUndeleteLink() {
714 $action = $this->getRequest()->getVal( 'action', 'view' );
716 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
717 ( !$this->getTitle()->exists() ||
$action == 'history' ) ) {
718 $n = $this->getTitle()->isDeleted();
721 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
722 $msg = 'thisisdeleted';
724 $msg = 'viewdeleted';
727 return $this->msg( $msg )->rawParams(
729 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
730 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
739 * @param OutputPage $out Defaults to $this->getOutput() if left as null
742 function subPageSubtitle( $out = null ) {
743 if ( $out === null ) {
744 $out = $this->getOutput();
746 $title = $out->getTitle();
749 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
753 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
754 $ptext = $title->getPrefixedText();
755 if ( strpos( $ptext, '/' ) !== false ) {
756 $links = explode( '/', $ptext );
761 $lang = $this->getLanguage();
763 foreach ( $links as $link ) {
764 $growinglink .= $link;
766 $linkObj = Title
::newFromText( $growinglink );
768 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
769 $getlink = Linker
::linkKnown(
771 htmlspecialchars( $display )
777 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
779 $subpages .= '< ';
782 $subpages .= $getlink;
798 function getSearchLink() {
799 $searchPage = SpecialPage
::getTitleFor( 'Search' );
800 return $searchPage->getLocalURL();
806 function escapeSearchLink() {
807 return htmlspecialchars( $this->getSearchLink() );
811 * @param string $type
814 function getCopyright( $type = 'detect' ) {
815 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
817 if ( $type == 'detect' ) {
818 if ( !$this->isRevisionCurrent()
819 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
827 if ( $type == 'history' ) {
828 $msg = 'history_copyright';
833 if ( $wgRightsPage ) {
834 $title = Title
::newFromText( $wgRightsPage );
835 $link = Linker
::linkKnown( $title, $wgRightsText );
836 } elseif ( $wgRightsUrl ) {
837 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
838 } elseif ( $wgRightsText ) {
839 $link = $wgRightsText;
845 // Allow for site and per-namespace customization of copyright notice.
846 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
850 'SkinCopyrightFooter',
851 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
854 return $this->msg( $msg )->rawParams( $link )->text();
858 * @return null|string
860 function getCopyrightIcon() {
861 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
865 if ( $wgFooterIcons['copyright']['copyright'] ) {
866 $out = $wgFooterIcons['copyright']['copyright'];
867 } elseif ( $wgRightsIcon ) {
868 $icon = htmlspecialchars( $wgRightsIcon );
870 if ( $wgRightsUrl ) {
871 $url = htmlspecialchars( $wgRightsUrl );
872 $out .= '<a href="' . $url . '">';
875 $text = htmlspecialchars( $wgRightsText );
876 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
878 if ( $wgRightsUrl ) {
887 * Gets the powered by MediaWiki icon.
890 function getPoweredBy() {
891 global $wgResourceBasePath;
893 $url1 = htmlspecialchars(
894 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
896 $url1_5 = htmlspecialchars(
897 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
899 $url2 = htmlspecialchars(
900 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
902 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
903 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
904 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
905 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
910 * Get the timestamp of the latest revision, formatted in user language
914 protected function lastModified() {
915 $timestamp = $this->getOutput()->getRevisionTimestamp();
917 # No cached timestamp, load it from the database
918 if ( $timestamp === null ) {
919 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
923 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
924 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
925 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
930 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLaggedReplicaMode() ) {
931 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
938 * @param string $align
941 function logoText( $align = '' ) {
942 if ( $align != '' ) {
943 $a = " style='float: {$align};'";
948 $mp = $this->msg( 'mainpage' )->escaped();
949 $mptitle = Title
::newMainPage();
950 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
952 $logourl = $this->getLogo();
953 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
959 * Renders a $wgFooterIcons icon according to the method's arguments
960 * @param array $icon The icon to build the html for, see $wgFooterIcons
961 * for the format of this array.
962 * @param bool|string $withImage Whether to use the icon's image or output
963 * a text-only footericon.
964 * @return string HTML
966 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
967 if ( is_string( $icon ) ) {
969 } else { // Assuming array
970 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
971 unset( $icon["url"] );
972 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
973 // do this the lazy way, just pass icon data as an attribute array
974 $html = Html
::element( 'img', $icon );
976 $html = htmlspecialchars( $icon["alt"] );
979 global $wgExternalLinkTarget;
980 $html = Html
::rawElement( 'a',
981 [ "href" => $url, "target" => $wgExternalLinkTarget ],
989 * Gets the link to the wiki's main page.
992 function mainPageLink() {
993 $s = Linker
::linkKnown(
994 Title
::newMainPage(),
995 $this->msg( 'mainpage' )->escaped()
1002 * Returns an HTML link for use in the footer
1003 * @param string $desc The i18n message key for the link text
1004 * @param string $page The i18n message key for the page to link to
1005 * @return string HTML anchor
1007 public function footerLink( $desc, $page ) {
1008 $title = $this->footerLinkTitle( $desc, $page );
1013 return Linker
::linkKnown(
1015 $this->msg( $desc )->escaped()
1020 * @param string $desc
1021 * @param string $page
1022 * @return Title|null
1024 private function footerLinkTitle( $desc, $page ) {
1025 // If the link description has been set to "-" in the default language,
1026 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
1027 // then it is disabled, for all languages.
1030 // Otherwise, we display the link for the user, described in their
1031 // language (which may or may not be the same as the default language),
1032 // but we make the link target be the one site-wide page.
1033 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1035 return $title ?
: null;
1039 * Gets the link to the wiki's privacy policy page.
1040 * @return string HTML
1042 function privacyLink() {
1043 return $this->footerLink( 'privacy', 'privacypage' );
1047 * Gets the link to the wiki's about page.
1048 * @return string HTML
1050 function aboutLink() {
1051 return $this->footerLink( 'aboutsite', 'aboutpage' );
1055 * Gets the link to the wiki's general disclaimers page.
1056 * @return string HTML
1058 function disclaimerLink() {
1059 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1063 * Return URL options for the 'edit page' link.
1064 * This may include an 'oldid' specifier, if the current page view is such.
1069 function editUrlOptions() {
1070 $options = [ 'action' => 'edit' ];
1072 if ( !$this->isRevisionCurrent() ) {
1073 $options['oldid'] = intval( $this->getRevisionId() );
1080 * @param User|int $id
1083 function showEmailUser( $id ) {
1084 if ( $id instanceof User
) {
1087 $targetUser = User
::newFromId( $id );
1090 # The sending user must have a confirmed email address and the receiving
1091 # user must accept emails from the sender.
1092 return $this->getUser()->canSendEmail()
1093 && SpecialEmailUser
::validateTarget( $targetUser, $this->getUser() ) === '';
1097 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1098 * This method returns a url resolved using the configured skin style path
1099 * and includes the style version inside of the url.
1101 * Requires $stylename to be set, otherwise throws MWException.
1103 * @param string $name The name or path of a skin resource file
1104 * @return string The fully resolved style path url including styleversion
1105 * @throws MWException
1107 function getSkinStylePath( $name ) {
1108 global $wgStylePath, $wgStyleVersion;
1110 if ( $this->stylename
=== null ) {
1111 $class = static::class;
1112 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1115 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1118 /* these are used extensively in SkinTemplate, but also some other places */
1121 * @param string|string[] $urlaction
1124 static function makeMainPageUrl( $urlaction = '' ) {
1125 $title = Title
::newMainPage();
1126 self
::checkTitle( $title, '' );
1128 return $title->getLinkURL( $urlaction );
1132 * Make a URL for a Special Page using the given query and protocol.
1134 * If $proto is set to null, make a local URL. Otherwise, make a full
1135 * URL with the protocol specified.
1137 * @param string $name Name of the Special page
1138 * @param string|string[] $urlaction Query to append
1139 * @param string|null $proto Protocol to use or null for a local URL
1142 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1143 $title = SpecialPage
::getSafeTitleFor( $name );
1144 if ( is_null( $proto ) ) {
1145 return $title->getLocalURL( $urlaction );
1147 return $title->getFullURL( $urlaction, false, $proto );
1152 * @param string $name
1153 * @param string $subpage
1154 * @param string|string[] $urlaction
1157 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1158 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1159 return $title->getLocalURL( $urlaction );
1163 * @param string $name
1164 * @param string|string[] $urlaction
1167 static function makeI18nUrl( $name, $urlaction = '' ) {
1168 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1169 self
::checkTitle( $title, $name );
1170 return $title->getLocalURL( $urlaction );
1174 * @param string $name
1175 * @param string|string[] $urlaction
1178 static function makeUrl( $name, $urlaction = '' ) {
1179 $title = Title
::newFromText( $name );
1180 self
::checkTitle( $title, $name );
1182 return $title->getLocalURL( $urlaction );
1186 * If url string starts with http, consider as external URL, else
1188 * @param string $name
1189 * @return string URL
1191 static function makeInternalOrExternalUrl( $name ) {
1192 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1195 return self
::makeUrl( $name );
1200 * this can be passed the NS number as defined in Language.php
1201 * @param string $name
1202 * @param string|string[] $urlaction
1203 * @param int $namespace
1206 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1207 $title = Title
::makeTitleSafe( $namespace, $name );
1208 self
::checkTitle( $title, $name );
1210 return $title->getLocalURL( $urlaction );
1214 * these return an array with the 'href' and boolean 'exists'
1215 * @param string $name
1216 * @param string|string[] $urlaction
1219 static function makeUrlDetails( $name, $urlaction = '' ) {
1220 $title = Title
::newFromText( $name );
1221 self
::checkTitle( $title, $name );
1224 'href' => $title->getLocalURL( $urlaction ),
1225 'exists' => $title->isKnown(),
1230 * Make URL details where the article exists (or at least it's convenient to think so)
1231 * @param string $name Article name
1232 * @param string|string[] $urlaction
1235 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1236 $title = Title
::newFromText( $name );
1237 self
::checkTitle( $title, $name );
1240 'href' => $title->getLocalURL( $urlaction ),
1246 * make sure we have some title to operate on
1248 * @param Title &$title
1249 * @param string $name
1251 static function checkTitle( &$title, $name ) {
1252 if ( !is_object( $title ) ) {
1253 $title = Title
::newFromText( $name );
1254 if ( !is_object( $title ) ) {
1255 $title = Title
::newFromText( '--error: link target missing--' );
1261 * Build an array that represents the sidebar(s), the navigation bar among them.
1263 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1265 * The format of the returned array is [ heading => content, ... ], where:
1266 * - heading is the heading of a navigation portlet. It is either:
1267 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1268 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1269 * - plain text, which should be HTML-escaped by the skin
1270 * - content is the contents of the portlet. It is either:
1271 * - HTML text (<ul><li>...</li>...</ul>)
1272 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1273 * - (for a magic string as a key, any value)
1275 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1276 * and can technically insert anything in here; skin creators are expected to handle
1277 * values described above.
1281 public function buildSidebar() {
1282 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1284 $callback = function ( $old = null, &$ttl = null ) {
1286 $this->addToSidebar( $bar, 'sidebar' );
1287 Hooks
::run( 'SkinBuildSidebar', [ $this, &$bar ] );
1288 if ( MessageCache
::singleton()->isDisabled() ) {
1289 $ttl = WANObjectCache
::TTL_UNCACHEABLE
; // bug T133069
1295 $msgCache = MessageCache
::singleton();
1296 $wanCache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1298 $sidebar = $wgEnableSidebarCache
1299 ?
$wanCache->getWithSetCallback(
1300 $wanCache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1301 $wgSidebarCacheExpiry,
1305 // Unless there is both no exact $code override nor an i18n definition
1306 // in the the software, the only MediaWiki page to check is for $code.
1307 $msgCache->getCheckKey( $this->getLanguage()->getCode() )
1314 // Apply post-processing to the cached value
1315 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1321 * Add content from a sidebar system message
1322 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1324 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1326 * @param array &$bar
1327 * @param string $message
1329 public function addToSidebar( &$bar, $message ) {
1330 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1334 * Add content from plain text
1336 * @param array &$bar
1337 * @param string $text
1340 function addToSidebarPlain( &$bar, $text ) {
1341 $lines = explode( "\n", $text );
1344 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1345 ? Title
::newMainPage() : $this->getTitle();
1347 foreach ( $lines as $line ) {
1348 if ( strpos( $line, '*' ) !== 0 ) {
1351 $line = rtrim( $line, "\r" ); // for Windows compat
1353 if ( strpos( $line, '**' ) !== 0 ) {
1354 $heading = trim( $line, '* ' );
1355 if ( !array_key_exists( $heading, $bar ) ) {
1356 $bar[$heading] = [];
1359 $line = trim( $line, '* ' );
1361 if ( strpos( $line, '|' ) !== false ) { // sanity check
1362 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1363 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1364 if ( count( $line ) !== 2 ) {
1365 // Second sanity check, could be hit by people doing
1366 // funky stuff with parserfuncs... (T35321)
1372 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1373 if ( $msgLink->exists() ) {
1374 $link = $msgLink->text();
1375 if ( $link == '-' ) {
1381 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1382 if ( $msgText->exists() ) {
1383 $text = $msgText->text();
1388 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1391 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1392 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1393 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1394 $extraAttribs['rel'] = 'nofollow';
1397 global $wgExternalLinkTarget;
1398 if ( $wgExternalLinkTarget ) {
1399 $extraAttribs['target'] = $wgExternalLinkTarget;
1402 $title = Title
::newFromText( $link );
1405 $title = $title->fixSpecialName();
1406 $href = $title->getLinkURL();
1408 $href = 'INVALID-TITLE';
1412 $bar[$heading][] = array_merge( [
1415 'id' => Sanitizer
::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1428 * Gets new talk page messages for the current user and returns an
1429 * appropriate alert message (or an empty string if there are no messages)
1432 function getNewtalks() {
1433 $newMessagesAlert = '';
1434 $user = $this->getUser();
1435 $newtalks = $user->getNewMessageLinks();
1436 $out = $this->getOutput();
1438 // Allow extensions to disable or modify the new messages alert
1439 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1442 if ( $newMessagesAlert ) {
1443 return $newMessagesAlert;
1446 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1447 $uTalkTitle = $user->getTalkPage();
1448 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1450 if ( $lastSeenRev !== null ) {
1451 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1452 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1453 if ( $latestRev !== null ) {
1454 // Singular if only 1 unseen revision, plural if several unseen revisions.
1455 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1456 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1457 $lastSeenRev, $latestRev, 10, 'include_new' );
1460 // Singular if no revision -> diff link will show latest change only in any case
1463 $plural = $plural ?
999 : 1;
1464 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1465 // the number of revisions or authors is not necessarily the same as the number of
1467 $newMessagesLink = Linker
::linkKnown(
1469 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1471 [ 'redirect' => 'no' ]
1474 $newMessagesDiffLink = Linker
::linkKnown(
1476 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1478 $lastSeenRev !== null
1479 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1480 : [ 'diff' => 'cur' ]
1483 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1484 $newMessagesAlert = $this->msg(
1485 'youhavenewmessagesfromusers',
1487 $newMessagesDiffLink
1488 )->numParams( $nofAuthors, $plural );
1490 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1491 $newMessagesAlert = $this->msg(
1492 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1494 $newMessagesDiffLink
1495 )->numParams( $plural );
1497 $newMessagesAlert = $newMessagesAlert->text();
1499 $out->setCdnMaxage( 0 );
1500 } elseif ( count( $newtalks ) ) {
1501 $sep = $this->msg( 'newtalkseparator' )->escaped();
1504 foreach ( $newtalks as $newtalk ) {
1505 $msgs[] = Xml
::element(
1507 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1510 $parts = implode( $sep, $msgs );
1511 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1512 $out->setCdnMaxage( 0 );
1515 return $newMessagesAlert;
1519 * Get a cached notice
1521 * @param string $name Message name, or 'default' for $wgSiteNotice
1522 * @return string|bool HTML fragment, or false to indicate that the caller
1523 * should fall back to the next notice in its sequence
1525 private function getCachedNotice( $name ) {
1526 global $wgRenderHashAppend, $wgContLang;
1530 if ( $name === 'default' ) {
1532 global $wgSiteNotice;
1533 $notice = $wgSiteNotice;
1534 if ( empty( $notice ) ) {
1538 $msg = $this->msg( $name )->inContentLanguage();
1539 if ( $msg->isBlank() ) {
1541 } elseif ( $msg->isDisabled() ) {
1544 $notice = $msg->plain();
1547 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1548 $parsed = $cache->getWithSetCallback(
1549 // Use the extra hash appender to let eg SSL variants separately cache
1550 // Key is verified with md5 hash of unparsed wikitext
1551 $cache->makeKey( $name, $wgRenderHashAppend, md5( $notice ) ),
1554 function () use ( $notice ) {
1555 return $this->getOutput()->parse( $notice );
1559 return Html
::rawElement(
1562 'id' => 'localNotice',
1563 'lang' => $wgContLang->getHtmlCode(),
1564 'dir' => $wgContLang->getDir()
1571 * Get the site notice
1573 * @return string HTML fragment
1575 function getSiteNotice() {
1578 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1579 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1580 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1582 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1583 if ( $anonNotice === false ) {
1584 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1586 $siteNotice = $anonNotice;
1589 if ( $siteNotice === false ) {
1590 $siteNotice = $this->getCachedNotice( 'default' );
1594 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1599 * Create a section edit link. This supersedes editSectionLink() and
1600 * editSectionLinkForOther().
1602 * @param Title $nt The title being linked to (may not be the same as
1603 * the current page, if the section is included from a template)
1604 * @param string $section The designation of the section being pointed to,
1605 * to be included in the link, like "§ion=$section"
1606 * @param string $tooltip The tooltip to use for the link: will be escaped
1607 * and wrapped in the 'editsectionhint' message
1608 * @param string $lang Language code
1609 * @return string HTML to use for edit link
1611 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1612 // HTML generated here should probably have userlangattributes
1613 // added to it for LTR text on RTL pages
1615 $lang = wfGetLangObj( $lang );
1618 if ( !is_null( $tooltip ) ) {
1619 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1620 ->inLanguage( $lang )->text();
1625 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1626 'targetTitle' => $nt,
1627 'attribs' => $attribs,
1628 'query' => [ 'action' => 'edit', 'section' => $section ],
1629 'options' => [ 'noclasses', 'known' ]
1633 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1635 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1638 foreach ( $links as $k => $linkDetails ) {
1639 $linksHtml[] = Linker
::link(
1640 $linkDetails['targetTitle'],
1641 $linkDetails['text'],
1642 $linkDetails['attribs'],
1643 $linkDetails['query'],
1644 $linkDetails['options']
1649 '<span class="mw-editsection-divider">'
1650 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->escaped()
1655 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1656 // Deprecated, use SkinEditSectionLinks hook instead
1658 'DoEditSectionLink',
1659 [ $this, $nt, $section, $tooltip, &$result, $lang ],