3 * Base class for all skins.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
24 use Wikimedia\WrappedString
;
25 use Wikimedia\WrappedStringList
;
28 * @defgroup Skins Skins
32 * The main skin class which provides methods and properties for all other skins.
34 * See docs/skin.txt for more information.
38 abstract class Skin
extends ContextSource
{
42 protected $skinname = null;
44 protected $mRelevantTitle = null;
45 protected $mRelevantUser = null;
48 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
49 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
51 public $stylename = null;
54 * Fetch the set of available skins.
55 * @return array Associative array of strings
57 static function getSkinNames() {
58 return SkinFactory
::getDefaultInstance()->getSkinNames();
62 * Fetch the skinname messages for available skins.
65 static function getSkinNameMessages() {
67 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
68 $messages[] = "skinname-$skinKey";
74 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
75 * Useful for Special:Preferences and other places where you
76 * only want to show skins users _can_ use.
80 public static function getAllowedSkins() {
83 $allowedSkins = self
::getSkinNames();
85 foreach ( $wgSkipSkins as $skip ) {
86 unset( $allowedSkins[$skip] );
93 * Normalize a skin preference value to a form that can be loaded.
95 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
96 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
98 * @param string $key 'monobook', 'vector', etc.
101 static function normalizeKey( $key ) {
102 global $wgDefaultSkin, $wgFallbackSkin;
104 $skinNames = self
::getSkinNames();
106 // Make keys lowercase for case-insensitive matching.
107 $skinNames = array_change_key_case( $skinNames, CASE_LOWER
);
108 $key = strtolower( $key );
109 $defaultSkin = strtolower( $wgDefaultSkin );
110 $fallbackSkin = strtolower( $wgFallbackSkin );
112 if ( $key == '' ||
$key == 'default' ) {
113 // Don't return the default immediately;
114 // in a misconfiguration we need to fall back.
118 if ( isset( $skinNames[$key] ) ) {
122 // Older versions of the software used a numeric setting
123 // in the user preferences.
129 if ( isset( $fallback[$key] ) ) {
130 $key = $fallback[$key];
133 if ( isset( $skinNames[$key] ) ) {
135 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
138 return $fallbackSkin;
144 * @param string|null $skinname
146 public function __construct( $skinname = null ) {
147 if ( is_string( $skinname ) ) {
148 $this->skinname
= $skinname;
153 * @return string|null Skin name
155 public function getSkinName() {
156 return $this->skinname
;
160 * @param OutputPage $out
162 public function initPage( OutputPage
$out ) {
163 $this->preloadExistence();
167 * Defines the ResourceLoader modules that should be added to the skin
168 * It is recommended that skins wishing to override call parent::getDefaultModules()
169 * and substitute out any modules they wish to change by using a key to look them up
171 * Any modules defined with the 'styles' key will be added as render blocking CSS via
172 * Output::addModuleStyles. Similarly, each key should refer to a list of modules
174 * @return array Array of modules with helper keys for easy overriding
176 public function getDefaultModules() {
177 $out = $this->getOutput();
178 $config = $this->getConfig();
179 $user = $this->getUser();
181 // Modules declared in the $modules literal are loaded
182 // for ALL users, on ALL pages, in ALL skins.
183 // Keep this list as small as possible!
186 // The 'styles' key sets render-blocking style modules
187 // Unlike other keys in $modules, this is an associative array
188 // where each key is its own group pointing to a list of modules
190 'mediawiki.legacy.shared',
191 'mediawiki.legacy.commonPrint',
198 'mediawiki.page.startup',
201 // modules that enhance the content in some way
203 'mediawiki.page.ready',
205 // modules relating to search functionality
207 // modules relating to functionality relating to watching an article
209 // modules which relate to the current users preferences
211 // modules relating to RSS/Atom Feeds
215 // Preload jquery.tablesorter for mediawiki.page.ready
216 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
217 $modules['content'][] = 'jquery.tablesorter';
220 // Preload jquery.makeCollapsible for mediawiki.page.ready
221 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
222 $modules['content'][] = 'jquery.makeCollapsible';
223 $modules['styles']['content'][] = 'jquery.makeCollapsible.styles';
226 // Deprecated since 1.26: Unconditional loading of mediawiki.ui.button
227 // on every page is deprecated. Express a dependency instead.
228 if ( strpos( $out->getHTML(), 'mw-ui-button' ) !== false ) {
229 $modules['styles']['content'][] = 'mediawiki.ui.button';
232 if ( $out->isTOCEnabled() ) {
233 $modules['content'][] = 'mediawiki.toc';
236 // Add various resources if required
237 if ( $user->isLoggedIn()
238 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
239 && $this->getRelevantTitle()->canExist()
241 $modules['watch'][] = 'mediawiki.page.watch.ajax';
244 $modules['search'][] = 'mediawiki.searchSuggest';
246 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
247 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
250 // Crazy edit-on-double-click stuff
251 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
252 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
255 if ( $out->isSyndicated() ) {
256 $modules['styles']['syndicate'][] = 'mediawiki.feedlink';
263 * Preload the existence of three commonly-requested pages in a single query
265 protected function preloadExistence() {
269 $user = $this->getUser();
270 if ( $user->isLoggedIn() ) {
271 $titles[] = $user->getUserPage();
272 $titles[] = $user->getTalkPage();
275 // Check, if the page can hold some kind of content, otherwise do nothing
276 $title = $this->getRelevantTitle();
277 if ( $title->canExist() ) {
278 if ( $title->isTalkPage() ) {
279 $titles[] = $title->getSubjectPage();
281 $titles[] = $title->getTalkPage();
285 // Footer links (used by SkinTemplate::prepareQuickTemplate)
287 $this->footerLinkTitle( 'privacy', 'privacypage' ),
288 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
289 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
296 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
299 $lb = new LinkBatch( $titles );
300 $lb->setCaller( __METHOD__
);
306 * Get the current revision ID
310 public function getRevisionId() {
311 return $this->getOutput()->getRevisionId();
315 * Whether the revision displayed is the latest revision of the page
319 public function isRevisionCurrent() {
320 $revID = $this->getRevisionId();
321 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
325 * Set the "relevant" title
326 * @see self::getRelevantTitle()
329 public function setRelevantTitle( $t ) {
330 $this->mRelevantTitle
= $t;
334 * Return the "relevant" title.
335 * A "relevant" title is not necessarily the actual title of the page.
336 * Special pages like Special:MovePage use set the page they are acting on
337 * as their "relevant" title, this allows the skin system to display things
338 * such as content tabs which belong to to that page instead of displaying
339 * a basic special page tab which has almost no meaning.
343 public function getRelevantTitle() {
344 if ( isset( $this->mRelevantTitle
) ) {
345 return $this->mRelevantTitle
;
347 return $this->getTitle();
351 * Set the "relevant" user
352 * @see self::getRelevantUser()
355 public function setRelevantUser( $u ) {
356 $this->mRelevantUser
= $u;
360 * Return the "relevant" user.
361 * A "relevant" user is similar to a relevant title. Special pages like
362 * Special:Contributions mark the user which they are relevant to so that
363 * things like the toolbox can display the information they usually are only
364 * able to display on a user's userpage and talkpage.
367 public function getRelevantUser() {
368 if ( isset( $this->mRelevantUser
) ) {
369 return $this->mRelevantUser
;
371 $title = $this->getRelevantTitle();
372 if ( $title->hasSubjectNamespace( NS_USER
) ) {
373 $rootUser = $title->getRootText();
374 if ( User
::isIP( $rootUser ) ) {
375 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
377 $user = User
::newFromName( $rootUser, false );
380 $user->load( User
::READ_NORMAL
);
382 if ( $user->isLoggedIn() ) {
383 $this->mRelevantUser
= $user;
387 return $this->mRelevantUser
;
393 * Outputs the HTML generated by other functions.
394 * @param OutputPage $out
396 abstract function outputPage( OutputPage
$out = null );
400 * @param string $nonce OutputPage::getCSPNonce()
401 * @return string|WrappedString HTML
403 static function makeVariablesScript( $data, $nonce = null ) {
405 return ResourceLoader
::makeInlineScript(
406 ResourceLoader
::makeConfigSetScript( $data ),
415 * Get the query to generate a dynamic stylesheet
419 public static function getDynamicStylesheetQuery() {
420 global $wgSquidMaxage;
424 'maxage' => $wgSquidMaxage,
425 'usemsgcache' => 'yes',
426 'ctype' => 'text/css',
427 'smaxage' => $wgSquidMaxage,
432 * Hook point for adding style modules to OutputPage.
434 * @deprecated since 1.32 Use getDefaultModules() instead.
435 * @param OutputPage $out Legacy parameter, identical to $this->getOutput()
437 public function setupSkinUserCss( OutputPage
$out ) {
443 * @param Title $title
446 function getPageClasses( $title ) {
447 $numeric = 'ns-' . $title->getNamespace();
449 if ( $title->isSpecialPage() ) {
450 $type = 'ns-special';
451 // T25315: provide a class based on the canonical special page name without subpages
452 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
453 if ( $canonicalName ) {
454 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
456 $type .= ' mw-invalidspecialpage';
458 } elseif ( $title->isTalkPage() ) {
461 $type = 'ns-subject';
464 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
465 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
467 return "$numeric $type $name $root";
471 * Return values for <html> element
472 * @return array Array of associative name-to-value elements for <html> element
474 public function getHtmlElementAttributes() {
475 $lang = $this->getLanguage();
477 'lang' => $lang->getHtmlCode(),
478 'dir' => $lang->getDir(),
479 'class' => 'client-nojs',
484 * This will be called by OutputPage::headElement when it is creating the
485 * "<body>" tag, skins can override it if they have a need to add in any
486 * body attributes or classes of their own.
487 * @param OutputPage $out
488 * @param array &$bodyAttrs
490 function addToBodyAttributes( $out, &$bodyAttrs ) {
491 // does nothing by default
504 * Whether the logo should be preloaded with an HTTP link header or not
508 public function shouldPreloadLogo() {
513 * @return string HTML
515 function getCategoryLinks() {
516 global $wgUseCategoryBrowser;
518 $out = $this->getOutput();
519 $allCats = $out->getCategoryLinks();
521 if ( !count( $allCats ) ) {
529 $colon = $this->msg( 'colon-separator' )->escaped();
531 if ( !empty( $allCats['normal'] ) ) {
532 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
534 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
535 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
536 $title = Title
::newFromText( $linkPage );
537 $link = $title ? Linker
::link( $title, $msg ) : $msg;
538 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
539 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
543 if ( isset( $allCats['hidden'] ) ) {
544 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
545 $class = ' mw-hidden-cats-user-shown';
546 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
547 $class = ' mw-hidden-cats-ns-shown';
549 $class = ' mw-hidden-cats-hidden';
552 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
553 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
554 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
558 # optional 'dmoz-like' category browser. Will be shown under the list
559 # of categories an article belong to
560 if ( $wgUseCategoryBrowser ) {
561 $s .= '<br /><hr />';
563 # get a big array of the parents tree
564 $parenttree = $this->getTitle()->getParentCategoryTree();
565 # Skin object passed by reference cause it can not be
566 # accessed under the method subfunction drawCategoryBrowser
567 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
568 # Clean out bogus first entry and sort them
569 unset( $tempout[0] );
571 # Output one per line
572 $s .= implode( "<br />\n", $tempout );
579 * Render the array as a series of links.
580 * @param array $tree Categories tree returned by Title::getParentCategoryTree
581 * @return string Separated by >, terminate with "\n"
583 function drawCategoryBrowser( $tree ) {
586 foreach ( $tree as $element => $parent ) {
587 if ( empty( $parent ) ) {
588 # element start a new list
591 # grab the others elements
592 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
595 # add our current element to the list
596 $eltitle = Title
::newFromText( $element );
597 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
604 * @return string HTML
606 function getCategories() {
607 $out = $this->getOutput();
608 $catlinks = $this->getCategoryLinks();
610 // Check what we're showing
611 $allCats = $out->getCategoryLinks();
612 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
613 $this->getTitle()->getNamespace() == NS_CATEGORY
;
615 $classes = [ 'catlinks' ];
616 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
617 $classes[] = 'catlinks-allhidden';
620 return Html
::rawElement(
622 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
628 * This runs a hook to allow extensions placing their stuff after content
629 * and article metadata (e.g. categories).
630 * Note: This function has nothing to do with afterContent().
632 * This hook is placed here in order to allow using the same hook for all
633 * skins, both the SkinTemplate based ones and the older ones, which directly
634 * use this class to get their data.
636 * The output of this function gets processed in SkinTemplate::outputPage() for
637 * the SkinTemplate based skins, all other skins should directly echo it.
639 * @return string Empty by default, if not changed by any hook function.
641 protected function afterContentHook() {
644 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
645 // adding just some spaces shouldn't toggle the output
646 // of the whole <div/>, so we use trim() here
647 if ( trim( $data ) != '' ) {
648 // Doing this here instead of in the skins to
649 // ensure that the div has the same ID in all
651 $data = "<div id='mw-data-after-content'>\n" .
656 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
663 * Generate debug data HTML for displaying at the bottom of the main content
665 * @return string HTML containing debug data, if enabled (otherwise empty).
667 protected function generateDebugHTML() {
668 return MWDebug
::getHTMLDebugLog();
672 * This gets called shortly before the "</body>" tag.
674 * @return string|WrappedStringList HTML containing scripts to put before `</body>`
676 function bottomScripts() {
677 // TODO and the suckage continues. This function is really just a wrapper around
678 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
680 $chunks = [ $this->getOutput()->getBottomScripts() ];
682 // Keep the hook appendage separate to preserve WrappedString objects.
683 // This enables BaseTemplate::getTrail() to merge them where possible.
685 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$extraHtml ] );
686 if ( $extraHtml !== '' ) {
687 $chunks[] = $extraHtml;
689 return WrappedString
::join( "\n", $chunks );
693 * Text with the permalink to the source page,
694 * usually shown on the footer of a printed page
696 * @return string HTML text with an URL
698 function printSource() {
699 $oldid = $this->getRevisionId();
701 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
702 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
704 // oldid not available for non existing pages
705 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
708 return $this->msg( 'retrievedfrom' )
709 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
714 * @return string HTML
716 function getUndeleteLink() {
717 $action = $this->getRequest()->getVal( 'action', 'view' );
719 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
720 ( !$this->getTitle()->exists() ||
$action == 'history' ) ) {
721 $n = $this->getTitle()->isDeleted();
724 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
725 $msg = 'thisisdeleted';
727 $msg = 'viewdeleted';
730 return $this->msg( $msg )->rawParams(
732 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
733 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
742 * @param OutputPage $out Defaults to $this->getOutput() if left as null
745 function subPageSubtitle( $out = null ) {
746 if ( $out === null ) {
747 $out = $this->getOutput();
749 $title = $out->getTitle();
752 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
756 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
757 $ptext = $title->getPrefixedText();
758 if ( strpos( $ptext, '/' ) !== false ) {
759 $links = explode( '/', $ptext );
764 $lang = $this->getLanguage();
766 foreach ( $links as $link ) {
767 $growinglink .= $link;
769 $linkObj = Title
::newFromText( $growinglink );
771 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
772 $getlink = Linker
::linkKnown(
774 htmlspecialchars( $display )
780 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
782 $subpages .= '< ';
785 $subpages .= $getlink;
801 function getSearchLink() {
802 $searchPage = SpecialPage
::getTitleFor( 'Search' );
803 return $searchPage->getLocalURL();
809 function escapeSearchLink() {
810 return htmlspecialchars( $this->getSearchLink() );
814 * @param string $type
817 function getCopyright( $type = 'detect' ) {
818 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
820 if ( $type == 'detect' ) {
821 if ( !$this->isRevisionCurrent()
822 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
830 if ( $type == 'history' ) {
831 $msg = 'history_copyright';
836 if ( $wgRightsPage ) {
837 $title = Title
::newFromText( $wgRightsPage );
838 $link = Linker
::linkKnown( $title, $wgRightsText );
839 } elseif ( $wgRightsUrl ) {
840 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
841 } elseif ( $wgRightsText ) {
842 $link = $wgRightsText;
848 // Allow for site and per-namespace customization of copyright notice.
849 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
853 'SkinCopyrightFooter',
854 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
857 return $this->msg( $msg )->rawParams( $link )->text();
861 * @return null|string
863 function getCopyrightIcon() {
864 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
868 if ( $wgFooterIcons['copyright']['copyright'] ) {
869 $out = $wgFooterIcons['copyright']['copyright'];
870 } elseif ( $wgRightsIcon ) {
871 $icon = htmlspecialchars( $wgRightsIcon );
873 if ( $wgRightsUrl ) {
874 $url = htmlspecialchars( $wgRightsUrl );
875 $out .= '<a href="' . $url . '">';
878 $text = htmlspecialchars( $wgRightsText );
879 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
881 if ( $wgRightsUrl ) {
890 * Gets the powered by MediaWiki icon.
893 function getPoweredBy() {
894 global $wgResourceBasePath;
896 $url1 = htmlspecialchars(
897 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
899 $url1_5 = htmlspecialchars(
900 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
902 $url2 = htmlspecialchars(
903 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
905 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
906 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
907 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
908 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
913 * Get the timestamp of the latest revision, formatted in user language
917 protected function lastModified() {
918 $timestamp = $this->getOutput()->getRevisionTimestamp();
920 # No cached timestamp, load it from the database
921 if ( $timestamp === null ) {
922 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
926 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
927 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
928 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
933 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLaggedReplicaMode() ) {
934 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
941 * @param string $align
944 function logoText( $align = '' ) {
945 if ( $align != '' ) {
946 $a = " style='float: {$align};'";
951 $mp = $this->msg( 'mainpage' )->escaped();
952 $mptitle = Title
::newMainPage();
953 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
955 $logourl = $this->getLogo();
956 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
962 * Renders a $wgFooterIcons icon according to the method's arguments
963 * @param array $icon The icon to build the html for, see $wgFooterIcons
964 * for the format of this array.
965 * @param bool|string $withImage Whether to use the icon's image or output
966 * a text-only footericon.
967 * @return string HTML
969 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
970 if ( is_string( $icon ) ) {
972 } else { // Assuming array
973 $url = $icon["url"] ??
null;
974 unset( $icon["url"] );
975 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
976 // do this the lazy way, just pass icon data as an attribute array
977 $html = Html
::element( 'img', $icon );
979 $html = htmlspecialchars( $icon["alt"] );
982 global $wgExternalLinkTarget;
983 $html = Html
::rawElement( 'a',
984 [ "href" => $url, "target" => $wgExternalLinkTarget ],
992 * Gets the link to the wiki's main page.
995 function mainPageLink() {
996 $s = Linker
::linkKnown(
997 Title
::newMainPage(),
998 $this->msg( 'mainpage' )->escaped()
1005 * Returns an HTML link for use in the footer
1006 * @param string $desc The i18n message key for the link text
1007 * @param string $page The i18n message key for the page to link to
1008 * @return string HTML anchor
1010 public function footerLink( $desc, $page ) {
1011 $title = $this->footerLinkTitle( $desc, $page );
1016 return Linker
::linkKnown(
1018 $this->msg( $desc )->escaped()
1023 * @param string $desc
1024 * @param string $page
1025 * @return Title|null
1027 private function footerLinkTitle( $desc, $page ) {
1028 // If the link description has been set to "-" in the default language,
1029 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
1030 // then it is disabled, for all languages.
1033 // Otherwise, we display the link for the user, described in their
1034 // language (which may or may not be the same as the default language),
1035 // but we make the link target be the one site-wide page.
1036 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1038 return $title ?
: null;
1042 * Gets the link to the wiki's privacy policy page.
1043 * @return string HTML
1045 function privacyLink() {
1046 return $this->footerLink( 'privacy', 'privacypage' );
1050 * Gets the link to the wiki's about page.
1051 * @return string HTML
1053 function aboutLink() {
1054 return $this->footerLink( 'aboutsite', 'aboutpage' );
1058 * Gets the link to the wiki's general disclaimers page.
1059 * @return string HTML
1061 function disclaimerLink() {
1062 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1066 * Return URL options for the 'edit page' link.
1067 * This may include an 'oldid' specifier, if the current page view is such.
1072 function editUrlOptions() {
1073 $options = [ 'action' => 'edit' ];
1075 if ( !$this->isRevisionCurrent() ) {
1076 $options['oldid'] = intval( $this->getRevisionId() );
1083 * @param User|int $id
1086 function showEmailUser( $id ) {
1087 if ( $id instanceof User
) {
1090 $targetUser = User
::newFromId( $id );
1093 # The sending user must have a confirmed email address and the receiving
1094 # user must accept emails from the sender.
1095 return $this->getUser()->canSendEmail()
1096 && SpecialEmailUser
::validateTarget( $targetUser, $this->getUser() ) === '';
1100 * Return a fully resolved style path URL to images or styles stored in the
1101 * current skin's folder. This method returns a URL resolved using the
1102 * configured skin style path.
1104 * Requires $stylename to be set, otherwise throws MWException.
1106 * @param string $name The name or path of a skin resource file
1107 * @return string The fully resolved style path URL
1108 * @throws MWException
1110 function getSkinStylePath( $name ) {
1111 global $wgStylePath;
1113 if ( $this->stylename
=== null ) {
1114 $class = static::class;
1115 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1118 return "$wgStylePath/{$this->stylename}/$name";
1121 /* these are used extensively in SkinTemplate, but also some other places */
1124 * @param string|string[] $urlaction
1127 static function makeMainPageUrl( $urlaction = '' ) {
1128 $title = Title
::newMainPage();
1129 self
::checkTitle( $title, '' );
1131 return $title->getLinkURL( $urlaction );
1135 * Make a URL for a Special Page using the given query and protocol.
1137 * If $proto is set to null, make a local URL. Otherwise, make a full
1138 * URL with the protocol specified.
1140 * @param string $name Name of the Special page
1141 * @param string|string[] $urlaction Query to append
1142 * @param string|null $proto Protocol to use or null for a local URL
1145 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1146 $title = SpecialPage
::getSafeTitleFor( $name );
1147 if ( is_null( $proto ) ) {
1148 return $title->getLocalURL( $urlaction );
1150 return $title->getFullURL( $urlaction, false, $proto );
1155 * @param string $name
1156 * @param string $subpage
1157 * @param string|string[] $urlaction
1160 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1161 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1162 return $title->getLocalURL( $urlaction );
1166 * @param string $name
1167 * @param string|string[] $urlaction
1170 static function makeI18nUrl( $name, $urlaction = '' ) {
1171 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1172 self
::checkTitle( $title, $name );
1173 return $title->getLocalURL( $urlaction );
1177 * @param string $name
1178 * @param string|string[] $urlaction
1181 static function makeUrl( $name, $urlaction = '' ) {
1182 $title = Title
::newFromText( $name );
1183 self
::checkTitle( $title, $name );
1185 return $title->getLocalURL( $urlaction );
1189 * If url string starts with http, consider as external URL, else
1191 * @param string $name
1192 * @return string URL
1194 static function makeInternalOrExternalUrl( $name ) {
1195 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1198 return self
::makeUrl( $name );
1203 * this can be passed the NS number as defined in Language.php
1204 * @param string $name
1205 * @param string|string[] $urlaction
1206 * @param int $namespace
1209 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1210 $title = Title
::makeTitleSafe( $namespace, $name );
1211 self
::checkTitle( $title, $name );
1213 return $title->getLocalURL( $urlaction );
1217 * these return an array with the 'href' and boolean 'exists'
1218 * @param string $name
1219 * @param string|string[] $urlaction
1222 static function makeUrlDetails( $name, $urlaction = '' ) {
1223 $title = Title
::newFromText( $name );
1224 self
::checkTitle( $title, $name );
1227 'href' => $title->getLocalURL( $urlaction ),
1228 'exists' => $title->isKnown(),
1233 * Make URL details where the article exists (or at least it's convenient to think so)
1234 * @param string $name Article name
1235 * @param string|string[] $urlaction
1238 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1239 $title = Title
::newFromText( $name );
1240 self
::checkTitle( $title, $name );
1243 'href' => $title->getLocalURL( $urlaction ),
1249 * make sure we have some title to operate on
1251 * @param Title &$title
1252 * @param string $name
1254 static function checkTitle( &$title, $name ) {
1255 if ( !is_object( $title ) ) {
1256 $title = Title
::newFromText( $name );
1257 if ( !is_object( $title ) ) {
1258 $title = Title
::newFromText( '--error: link target missing--' );
1264 * Build an array that represents the sidebar(s), the navigation bar among them.
1266 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1268 * The format of the returned array is [ heading => content, ... ], where:
1269 * - heading is the heading of a navigation portlet. It is either:
1270 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1271 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1272 * - plain text, which should be HTML-escaped by the skin
1273 * - content is the contents of the portlet. It is either:
1274 * - HTML text (<ul><li>...</li>...</ul>)
1275 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1276 * - (for a magic string as a key, any value)
1278 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1279 * and can technically insert anything in here; skin creators are expected to handle
1280 * values described above.
1284 public function buildSidebar() {
1285 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1287 $callback = function ( $old = null, &$ttl = null ) {
1289 $this->addToSidebar( $bar, 'sidebar' );
1290 Hooks
::run( 'SkinBuildSidebar', [ $this, &$bar ] );
1291 if ( MessageCache
::singleton()->isDisabled() ) {
1292 $ttl = WANObjectCache
::TTL_UNCACHEABLE
; // bug T133069
1298 $msgCache = MessageCache
::singleton();
1299 $wanCache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1301 $sidebar = $wgEnableSidebarCache
1302 ?
$wanCache->getWithSetCallback(
1303 $wanCache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1304 $wgSidebarCacheExpiry,
1308 // Unless there is both no exact $code override nor an i18n definition
1309 // in the the software, the only MediaWiki page to check is for $code.
1310 $msgCache->getCheckKey( $this->getLanguage()->getCode() )
1317 // Apply post-processing to the cached value
1318 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1324 * Add content from a sidebar system message
1325 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1327 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1329 * @param array &$bar
1330 * @param string $message
1332 public function addToSidebar( &$bar, $message ) {
1333 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1337 * Add content from plain text
1339 * @param array &$bar
1340 * @param string $text
1343 function addToSidebarPlain( &$bar, $text ) {
1344 $lines = explode( "\n", $text );
1347 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1348 ? Title
::newMainPage() : $this->getTitle();
1350 foreach ( $lines as $line ) {
1351 if ( strpos( $line, '*' ) !== 0 ) {
1354 $line = rtrim( $line, "\r" ); // for Windows compat
1356 if ( strpos( $line, '**' ) !== 0 ) {
1357 $heading = trim( $line, '* ' );
1358 if ( !array_key_exists( $heading, $bar ) ) {
1359 $bar[$heading] = [];
1362 $line = trim( $line, '* ' );
1364 if ( strpos( $line, '|' ) !== false ) { // sanity check
1365 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1366 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1367 if ( count( $line ) !== 2 ) {
1368 // Second sanity check, could be hit by people doing
1369 // funky stuff with parserfuncs... (T35321)
1375 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1376 if ( $msgLink->exists() ) {
1377 $link = $msgLink->text();
1378 if ( $link == '-' ) {
1384 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1385 if ( $msgText->exists() ) {
1386 $text = $msgText->text();
1391 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1394 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1395 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1396 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1397 $extraAttribs['rel'] = 'nofollow';
1400 global $wgExternalLinkTarget;
1401 if ( $wgExternalLinkTarget ) {
1402 $extraAttribs['target'] = $wgExternalLinkTarget;
1405 $title = Title
::newFromText( $link );
1408 $title = $title->fixSpecialName();
1409 $href = $title->getLinkURL();
1411 $href = 'INVALID-TITLE';
1415 $bar[$heading][] = array_merge( [
1418 'id' => Sanitizer
::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1431 * Gets new talk page messages for the current user and returns an
1432 * appropriate alert message (or an empty string if there are no messages)
1435 function getNewtalks() {
1436 $newMessagesAlert = '';
1437 $user = $this->getUser();
1438 $newtalks = $user->getNewMessageLinks();
1439 $out = $this->getOutput();
1441 // Allow extensions to disable or modify the new messages alert
1442 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1445 if ( $newMessagesAlert ) {
1446 return $newMessagesAlert;
1449 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1450 $uTalkTitle = $user->getTalkPage();
1451 $lastSeenRev = $newtalks[0]['rev'] ??
null;
1453 if ( $lastSeenRev !== null ) {
1454 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1455 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1456 if ( $latestRev !== null ) {
1457 // Singular if only 1 unseen revision, plural if several unseen revisions.
1458 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1459 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1460 $lastSeenRev, $latestRev, 10, 'include_new' );
1463 // Singular if no revision -> diff link will show latest change only in any case
1466 $plural = $plural ?
999 : 1;
1467 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1468 // the number of revisions or authors is not necessarily the same as the number of
1470 $newMessagesLink = Linker
::linkKnown(
1472 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1474 [ 'redirect' => 'no' ]
1477 $newMessagesDiffLink = Linker
::linkKnown(
1479 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1481 $lastSeenRev !== null
1482 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1483 : [ 'diff' => 'cur' ]
1486 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1487 $newMessagesAlert = $this->msg(
1488 'youhavenewmessagesfromusers',
1490 $newMessagesDiffLink
1491 )->numParams( $nofAuthors, $plural );
1493 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1494 $newMessagesAlert = $this->msg(
1495 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1497 $newMessagesDiffLink
1498 )->numParams( $plural );
1500 $newMessagesAlert = $newMessagesAlert->text();
1502 $out->setCdnMaxage( 0 );
1503 } elseif ( count( $newtalks ) ) {
1504 $sep = $this->msg( 'newtalkseparator' )->escaped();
1507 foreach ( $newtalks as $newtalk ) {
1508 $msgs[] = Xml
::element(
1510 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1513 $parts = implode( $sep, $msgs );
1514 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1515 $out->setCdnMaxage( 0 );
1518 return $newMessagesAlert;
1522 * Get a cached notice
1524 * @param string $name Message name, or 'default' for $wgSiteNotice
1525 * @return string|bool HTML fragment, or false to indicate that the caller
1526 * should fall back to the next notice in its sequence
1528 private function getCachedNotice( $name ) {
1529 global $wgRenderHashAppend, $wgContLang;
1533 if ( $name === 'default' ) {
1535 global $wgSiteNotice;
1536 $notice = $wgSiteNotice;
1537 if ( empty( $notice ) ) {
1541 $msg = $this->msg( $name )->inContentLanguage();
1542 if ( $msg->isBlank() ) {
1544 } elseif ( $msg->isDisabled() ) {
1547 $notice = $msg->plain();
1550 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1551 $parsed = $cache->getWithSetCallback(
1552 // Use the extra hash appender to let eg SSL variants separately cache
1553 // Key is verified with md5 hash of unparsed wikitext
1554 $cache->makeKey( $name, $wgRenderHashAppend, md5( $notice ) ),
1557 function () use ( $notice ) {
1558 return $this->getOutput()->parse( $notice );
1562 return Html
::rawElement(
1565 'id' => 'localNotice',
1566 'lang' => $wgContLang->getHtmlCode(),
1567 'dir' => $wgContLang->getDir()
1574 * Get the site notice
1576 * @return string HTML fragment
1578 function getSiteNotice() {
1581 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1582 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1583 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1585 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1586 if ( $anonNotice === false ) {
1587 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1589 $siteNotice = $anonNotice;
1592 if ( $siteNotice === false ) {
1593 $siteNotice = $this->getCachedNotice( 'default' );
1597 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1602 * Create a section edit link.
1604 * @param Title $nt The title being linked to (may not be the same as
1605 * the current page, if the section is included from a template)
1606 * @param string $section The designation of the section being pointed to,
1607 * to be included in the link, like "§ion=$section"
1608 * @param string $tooltip The tooltip to use for the link: will be escaped
1609 * and wrapped in the 'editsectionhint' message
1610 * @param string $lang Language code
1611 * @return string HTML to use for edit link
1613 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1614 // HTML generated here should probably have userlangattributes
1615 // added to it for LTR text on RTL pages
1617 $lang = wfGetLangObj( $lang );
1620 if ( !is_null( $tooltip ) ) {
1621 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1622 ->inLanguage( $lang )->text();
1627 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1628 'targetTitle' => $nt,
1629 'attribs' => $attribs,
1630 'query' => [ 'action' => 'edit', 'section' => $section ],
1631 'options' => [ 'noclasses', 'known' ]
1635 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1637 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1640 foreach ( $links as $k => $linkDetails ) {
1641 $linksHtml[] = Linker
::link(
1642 $linkDetails['targetTitle'],
1643 $linkDetails['text'],
1644 $linkDetails['attribs'],
1645 $linkDetails['query'],
1646 $linkDetails['options']
1651 '<span class="mw-editsection-divider">'
1652 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->escaped()
1657 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1658 // Deprecated, use SkinEditSectionLinks hook instead
1660 'DoEditSectionLink',
1661 [ $this, $nt, $section, $tooltip, &$result, $lang ],