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 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
59 return $skinFactory->getSkinNames();
63 * Fetch the skinname messages for available skins.
66 static function getSkinNameMessages() {
68 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
69 $messages[] = "skinname-$skinKey";
75 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
76 * Useful for Special:Preferences and other places where you
77 * only want to show skins users _can_ use.
81 public static function getAllowedSkins() {
84 $allowedSkins = self
::getSkinNames();
86 foreach ( $wgSkipSkins as $skip ) {
87 unset( $allowedSkins[$skip] );
94 * Normalize a skin preference value to a form that can be loaded.
96 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
97 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
99 * @param string $key 'monobook', 'vector', etc.
102 static function normalizeKey( $key ) {
103 global $wgDefaultSkin, $wgFallbackSkin;
105 $skinNames = self
::getSkinNames();
107 // Make keys lowercase for case-insensitive matching.
108 $skinNames = array_change_key_case( $skinNames, CASE_LOWER
);
109 $key = strtolower( $key );
110 $defaultSkin = strtolower( $wgDefaultSkin );
111 $fallbackSkin = strtolower( $wgFallbackSkin );
113 if ( $key == '' ||
$key == 'default' ) {
114 // Don't return the default immediately;
115 // in a misconfiguration we need to fall back.
119 if ( isset( $skinNames[$key] ) ) {
123 // Older versions of the software used a numeric setting
124 // in the user preferences.
130 if ( isset( $fallback[$key] ) ) {
131 $key = $fallback[$key];
134 if ( isset( $skinNames[$key] ) ) {
136 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
139 return $fallbackSkin;
145 * @param string|null $skinname
147 public function __construct( $skinname = null ) {
148 if ( is_string( $skinname ) ) {
149 $this->skinname
= $skinname;
154 * @return string|null Skin name
156 public function getSkinName() {
157 return $this->skinname
;
161 * @param OutputPage $out
163 public function initPage( OutputPage
$out ) {
164 $this->preloadExistence();
168 * Defines the ResourceLoader modules that should be added to the skin
169 * It is recommended that skins wishing to override call parent::getDefaultModules()
170 * and substitute out any modules they wish to change by using a key to look them up
172 * Any modules defined with the 'styles' key will be added as render blocking CSS via
173 * Output::addModuleStyles. Similarly, each key should refer to a list of modules
175 * @return array Array of modules with helper keys for easy overriding
177 public function getDefaultModules() {
178 $out = $this->getOutput();
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',
200 // modules that enhance the content in some way
202 'mediawiki.page.ready',
204 // modules relating to search functionality
206 'mediawiki.searchSuggest',
208 // modules relating to functionality relating to watching an article
210 // modules which relate to the current users preferences
212 // modules relating to RSS/Atom Feeds
216 // Preload jquery.tablesorter for mediawiki.page.ready
217 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
218 $modules['content'][] = 'jquery.tablesorter';
219 $modules['styles']['content'][] = 'jquery.tablesorter.styles';
222 // Preload jquery.makeCollapsible for mediawiki.page.ready
223 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
224 $modules['content'][] = 'jquery.makeCollapsible';
225 $modules['styles']['content'][] = 'jquery.makeCollapsible.styles';
228 // Deprecated since 1.26: Unconditional loading of mediawiki.ui.button
229 // on every page is deprecated. Express a dependency instead.
230 if ( strpos( $out->getHTML(), 'mw-ui-button' ) !== false ) {
231 $modules['styles']['content'][] = 'mediawiki.ui.button';
234 if ( $out->isTOCEnabled() ) {
235 $modules['content'][] = 'mediawiki.toc';
236 $modules['styles']['content'][] = 'mediawiki.toc.styles';
239 // Add various resources if required
240 if ( $user->isLoggedIn()
241 && MediaWikiServices
::getInstance()
242 ->getPermissionManager()
243 ->userHasAllRights( $user, 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
244 && $this->getRelevantTitle()->canExist()
246 $modules['watch'][] = 'mediawiki.page.watch.ajax';
249 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
250 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
253 // Crazy edit-on-double-click stuff
254 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
255 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
258 if ( $out->isSyndicated() ) {
259 $modules['styles']['syndicate'][] = 'mediawiki.feedlink';
266 * Preload the existence of three commonly-requested pages in a single query
268 protected function preloadExistence() {
272 $user = $this->getUser();
273 if ( $user->isLoggedIn() ) {
274 $titles[] = $user->getUserPage();
275 $titles[] = $user->getTalkPage();
278 // Check, if the page can hold some kind of content, otherwise do nothing
279 $title = $this->getRelevantTitle();
280 if ( $title->canExist() && $title->canHaveTalkPage() ) {
281 if ( $title->isTalkPage() ) {
282 $titles[] = $title->getSubjectPage();
284 $titles[] = $title->getTalkPage();
288 // Footer links (used by SkinTemplate::prepareQuickTemplate)
290 $this->footerLinkTitle( 'privacy', 'privacypage' ),
291 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
292 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
299 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
302 $lb = new LinkBatch( $titles );
303 $lb->setCaller( __METHOD__
);
309 * Get the current revision ID
311 * @deprecated since 1.34, use OutputPage::getRevisionId instead
314 public function getRevisionId() {
315 return $this->getOutput()->getRevisionId();
319 * Whether the revision displayed is the latest revision of the page
321 * @deprecated since 1.34, use OutputPage::isRevisionCurrent instead
324 public function isRevisionCurrent() {
325 return $this->getOutput()->isRevisionCurrent();
329 * Set the "relevant" title
330 * @see self::getRelevantTitle()
333 public function setRelevantTitle( $t ) {
334 $this->mRelevantTitle
= $t;
338 * Return the "relevant" title.
339 * A "relevant" title is not necessarily the actual title of the page.
340 * Special pages like Special:MovePage use set the page they are acting on
341 * as their "relevant" title, this allows the skin system to display things
342 * such as content tabs which belong to to that page instead of displaying
343 * a basic special page tab which has almost no meaning.
347 public function getRelevantTitle() {
348 return $this->mRelevantTitle ??
$this->getTitle();
352 * Set the "relevant" user
353 * @see self::getRelevantUser()
356 public function setRelevantUser( $u ) {
357 $this->mRelevantUser
= $u;
361 * Return the "relevant" user.
362 * A "relevant" user is similar to a relevant title. Special pages like
363 * Special:Contributions mark the user which they are relevant to so that
364 * things like the toolbox can display the information they usually are only
365 * able to display on a user's userpage and talkpage.
368 public function getRelevantUser() {
369 if ( isset( $this->mRelevantUser
) ) {
370 return $this->mRelevantUser
;
372 $title = $this->getRelevantTitle();
373 if ( $title->hasSubjectNamespace( NS_USER
) ) {
374 $rootUser = $title->getRootText();
375 if ( User
::isIP( $rootUser ) ) {
376 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
378 $user = User
::newFromName( $rootUser, false );
381 $user->load( User
::READ_NORMAL
);
383 if ( $user->isLoggedIn() ) {
384 $this->mRelevantUser
= $user;
388 return $this->mRelevantUser
;
394 * Outputs the HTML generated by other functions.
396 abstract function outputPage();
400 * @param string|null $nonce OutputPage::getCSPNonce()
401 * @return string|WrappedString HTML
403 public static function makeVariablesScript( $data, $nonce = null ) {
405 return ResourceLoader
::makeInlineScript(
406 ResourceLoader
::makeConfigSetScript( $data ),
414 * Get the query to generate a dynamic stylesheet
416 * @deprecated since 1.32 Use action=raw&ctype=text/css directly.
419 public static function getDynamicStylesheetQuery() {
422 'ctype' => 'text/css',
427 * Hook point for adding style modules to OutputPage.
429 * @deprecated since 1.32 Use getDefaultModules() instead.
430 * @param OutputPage $out Legacy parameter, identical to $this->getOutput()
432 public function setupSkinUserCss( OutputPage
$out ) {
438 * @param Title $title
441 function getPageClasses( $title ) {
442 $numeric = 'ns-' . $title->getNamespace();
443 $user = $this->getUser();
445 if ( $title->isSpecialPage() ) {
446 $type = 'ns-special';
447 // T25315: provide a class based on the canonical special page name without subpages
448 list( $canonicalName ) = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
449 resolveAlias( $title->getDBkey() );
450 if ( $canonicalName ) {
451 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
453 $type .= ' mw-invalidspecialpage';
456 if ( $title->isTalkPage() ) {
459 $type = 'ns-subject';
461 // T208315: add HTML class when the user can edit the page
462 if ( $title->quickUserCan( 'edit', $user ) ) {
463 $type .= ' mw-editable';
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
502 return $this->getConfig()->get( 'Logo' );
506 * Whether the logo should be preloaded with an HTTP link header or not
508 * @deprecated since 1.32 Redundant. It now happens automatically based on whether
509 * the skin loads a stylesheet based on ResourceLoaderSkinModule, which all
510 * skins that use wgLogo in CSS do, and other's would not.
514 public function shouldPreloadLogo() {
519 * @return string HTML
521 function getCategoryLinks() {
522 $out = $this->getOutput();
523 $allCats = $out->getCategoryLinks();
524 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
526 if ( $allCats === [] ) {
534 $colon = $this->msg( 'colon-separator' )->escaped();
536 if ( !empty( $allCats['normal'] ) ) {
537 $t = $embed . implode( $pop . $embed, $allCats['normal'] ) . $pop;
539 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) );
540 $linkPage = $this->msg( 'pagecategorieslink' )->inContentLanguage()->text();
541 $title = Title
::newFromText( $linkPage );
542 $link = $title ?
$linkRenderer->makeLink( $title, $msg->text() ) : $msg->escaped();
543 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
544 $link . $colon . '<ul>' . $t . '</ul></div>';
548 if ( isset( $allCats['hidden'] ) ) {
549 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
550 $class = ' mw-hidden-cats-user-shown';
551 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
552 $class = ' mw-hidden-cats-ns-shown';
554 $class = ' mw-hidden-cats-hidden';
557 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
558 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
559 $colon . '<ul>' . $embed . implode( $pop . $embed, $allCats['hidden'] ) . $pop . '</ul>' .
563 # optional 'dmoz-like' category browser. Will be shown under the list
564 # of categories an article belong to
565 if ( $this->getConfig()->get( 'UseCategoryBrowser' ) ) {
566 $s .= '<br /><hr />';
568 # get a big array of the parents tree
569 $parenttree = $this->getTitle()->getParentCategoryTree();
570 # Skin object passed by reference cause it can not be
571 # accessed under the method subfunction drawCategoryBrowser
572 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
573 # Clean out bogus first entry and sort them
574 unset( $tempout[0] );
576 # Output one per line
577 $s .= implode( "<br />\n", $tempout );
584 * Render the array as a series of links.
585 * @param array $tree Categories tree returned by Title::getParentCategoryTree
586 * @return string Separated by >, terminate with "\n"
588 function drawCategoryBrowser( $tree ) {
590 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
592 foreach ( $tree as $element => $parent ) {
593 if ( empty( $parent ) ) {
594 # element start a new list
597 # grab the others elements
598 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
601 # add our current element to the list
602 $eltitle = Title
::newFromText( $element );
603 $return .= $linkRenderer->makeLink( $eltitle, $eltitle->getText() );
610 * @return string HTML
612 function getCategories() {
613 $out = $this->getOutput();
614 $catlinks = $this->getCategoryLinks();
616 // Check what we're showing
617 $allCats = $out->getCategoryLinks();
618 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
619 $this->getTitle()->getNamespace() == NS_CATEGORY
;
621 $classes = [ 'catlinks' ];
622 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
623 $classes[] = 'catlinks-allhidden';
626 return Html
::rawElement(
628 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
634 * This runs a hook to allow extensions placing their stuff after content
635 * and article metadata (e.g. categories).
636 * Note: This function has nothing to do with afterContent().
638 * This hook is placed here in order to allow using the same hook for all
639 * skins, both the SkinTemplate based ones and the older ones, which directly
640 * use this class to get their data.
642 * The output of this function gets processed in SkinTemplate::outputPage() for
643 * the SkinTemplate based skins, all other skins should directly echo it.
645 * @return string Empty by default, if not changed by any hook function.
647 protected function afterContentHook() {
650 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
651 // adding just some spaces shouldn't toggle the output
652 // of the whole <div/>, so we use trim() here
653 if ( trim( $data ) != '' ) {
654 // Doing this here instead of in the skins to
655 // ensure that the div has the same ID in all
657 $data = "<div id='mw-data-after-content'>\n" .
662 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
669 * Generate debug data HTML for displaying at the bottom of the main content
671 * @return string HTML containing debug data, if enabled (otherwise empty).
673 protected function generateDebugHTML() {
674 return MWDebug
::getHTMLDebugLog();
678 * This gets called shortly before the "</body>" tag.
680 * @return string|WrappedStringList HTML containing scripts to put before `</body>`
682 function bottomScripts() {
683 // TODO and the suckage continues. This function is really just a wrapper around
684 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
686 $chunks = [ $this->getOutput()->getBottomScripts() ];
688 // Keep the hook appendage separate to preserve WrappedString objects.
689 // This enables BaseTemplate::getTrail() to merge them where possible.
691 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$extraHtml ] );
692 if ( $extraHtml !== '' ) {
693 $chunks[] = $extraHtml;
695 return WrappedString
::join( "\n", $chunks );
699 * Text with the permalink to the source page,
700 * usually shown on the footer of a printed page
702 * @return string HTML text with an URL
704 function printSource() {
705 $oldid = $this->getOutput()->getRevisionId();
707 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
708 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
710 // oldid not available for non existing pages
711 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
714 return $this->msg( 'retrievedfrom' )
715 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
720 * @return string HTML
722 function getUndeleteLink() {
723 $action = $this->getRequest()->getVal( 'action', 'view' );
724 $title = $this->getTitle();
725 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
727 if ( ( !$title->exists() ||
$action == 'history' ) &&
728 $title->quickUserCan( 'deletedhistory', $this->getUser() )
730 $n = $title->isDeleted();
733 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
734 $msg = 'thisisdeleted';
736 $msg = 'viewdeleted';
739 return $this->msg( $msg )->rawParams(
740 $linkRenderer->makeKnownLink(
741 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
742 $this->msg( 'restorelink' )->numParams( $n )->text() )
751 * @param OutputPage|null $out Defaults to $this->getOutput() if left as null
754 function subPageSubtitle( $out = null ) {
755 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
756 if ( $out === null ) {
757 $out = $this->getOutput();
759 $title = $out->getTitle();
762 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
767 $out->isArticle() && MediaWikiServices
::getInstance()->getNamespaceInfo()->
768 hasSubpages( $title->getNamespace() )
770 $ptext = $title->getPrefixedText();
771 if ( strpos( $ptext, '/' ) !== false ) {
772 $links = explode( '/', $ptext );
777 $lang = $this->getLanguage();
779 foreach ( $links as $link ) {
780 $growinglink .= $link;
782 $linkObj = Title
::newFromText( $growinglink );
784 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
785 $getlink = $linkRenderer->makeKnownLink(
792 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
794 $subpages .= '< ';
797 $subpages .= $getlink;
813 function getSearchLink() {
814 $searchPage = SpecialPage
::getTitleFor( 'Search' );
815 return $searchPage->getLocalURL();
819 * @deprecated since 1.34, use getSearchLink() instead.
822 function escapeSearchLink() {
823 wfDeprecated( __METHOD__
, '1.34' );
824 return htmlspecialchars( $this->getSearchLink() );
828 * @param string $type
831 function getCopyright( $type = 'detect' ) {
832 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
833 if ( $type == 'detect' ) {
834 if ( !$this->getOutput()->isRevisionCurrent()
835 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
843 if ( $type == 'history' ) {
844 $msg = 'history_copyright';
849 $config = $this->getConfig();
851 if ( $config->get( 'RightsPage' ) ) {
852 $title = Title
::newFromText( $config->get( 'RightsPage' ) );
853 $link = $linkRenderer->makeKnownLink(
854 $title, new HtmlArmor( $config->get( 'RightsText' ) )
856 } elseif ( $config->get( 'RightsUrl' ) ) {
857 $link = Linker
::makeExternalLink( $config->get( 'RightsUrl' ), $config->get( 'RightsText' ) );
858 } elseif ( $config->get( 'RightsText' ) ) {
859 $link = $config->get( 'RightsText' );
865 // Allow for site and per-namespace customization of copyright notice.
866 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
870 'SkinCopyrightFooter',
871 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
874 return $this->msg( $msg )->rawParams( $link )->text();
878 * @return null|string
880 function getCopyrightIcon() {
882 $config = $this->getConfig();
884 $footerIcons = $config->get( 'FooterIcons' );
885 if ( $footerIcons['copyright']['copyright'] ) {
886 $out = $footerIcons['copyright']['copyright'];
887 } elseif ( $config->get( 'RightsIcon' ) ) {
888 $icon = htmlspecialchars( $config->get( 'RightsIcon' ) );
889 $url = $config->get( 'RightsUrl' );
892 $out .= '<a href="' . htmlspecialchars( $url ) . '">';
895 $text = htmlspecialchars( $config->get( 'RightsText' ) );
896 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
907 * Gets the powered by MediaWiki icon.
910 function getPoweredBy() {
911 $resourceBasePath = $this->getConfig()->get( 'ResourceBasePath' );
912 $url1 = htmlspecialchars(
913 "$resourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
915 $url1_5 = htmlspecialchars(
916 "$resourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
918 $url2 = htmlspecialchars(
919 "$resourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
921 $text = '<a href="https://www.mediawiki.org/"><img src="' . $url1
922 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
923 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
924 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
929 * Get the timestamp of the latest revision, formatted in user language
933 protected function lastModified() {
934 $timestamp = $this->getOutput()->getRevisionTimestamp();
936 # No cached timestamp, load it from the database
937 if ( $timestamp === null ) {
938 $timestamp = Revision
::getTimestampFromId( $this->getTitle(),
939 $this->getOutput()->getRevisionId() );
943 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
944 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
945 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
950 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLaggedReplicaMode() ) {
951 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
958 * @param string $align
961 function logoText( $align = '' ) {
962 if ( $align != '' ) {
963 $a = " style='float: {$align};'";
968 $mp = $this->msg( 'mainpage' )->escaped();
969 $mptitle = Title
::newMainPage();
970 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
972 $logourl = $this->getLogo();
973 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
979 * Renders a $wgFooterIcons icon according to the method's arguments
980 * @param array $icon The icon to build the html for, see $wgFooterIcons
981 * for the format of this array.
982 * @param bool|string $withImage Whether to use the icon's image or output
983 * a text-only footericon.
984 * @return string HTML
986 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
987 if ( is_string( $icon ) ) {
989 } else { // Assuming array
990 $url = $icon["url"] ??
null;
991 unset( $icon["url"] );
992 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
993 // do this the lazy way, just pass icon data as an attribute array
994 $html = Html
::element( 'img', $icon );
996 $html = htmlspecialchars( $icon["alt"] );
999 $html = Html
::rawElement( 'a',
1000 [ "href" => $url, "target" => $this->getConfig()->get( 'ExternalLinkTarget' ) ],
1008 * Gets the link to the wiki's main page.
1011 function mainPageLink() {
1012 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1013 $s = $linkRenderer->makeKnownLink(
1014 Title
::newMainPage(),
1015 $this->msg( 'mainpage' )->text()
1022 * Returns an HTML link for use in the footer
1023 * @param string $desc The i18n message key for the link text
1024 * @param string $page The i18n message key for the page to link to
1025 * @return string HTML anchor
1027 public function footerLink( $desc, $page ) {
1028 $title = $this->footerLinkTitle( $desc, $page );
1029 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1034 return $linkRenderer->makeKnownLink(
1036 $this->msg( $desc )->text()
1041 * @param string $desc
1042 * @param string $page
1043 * @return Title|null
1045 private function footerLinkTitle( $desc, $page ) {
1046 // If the link description has been set to "-" in the default language,
1047 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
1048 // then it is disabled, for all languages.
1051 // Otherwise, we display the link for the user, described in their
1052 // language (which may or may not be the same as the default language),
1053 // but we make the link target be the one site-wide page.
1054 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1056 return $title ?
: null;
1060 * Gets the link to the wiki's privacy policy page.
1061 * @return string HTML
1063 function privacyLink() {
1064 return $this->footerLink( 'privacy', 'privacypage' );
1068 * Gets the link to the wiki's about page.
1069 * @return string HTML
1071 function aboutLink() {
1072 return $this->footerLink( 'aboutsite', 'aboutpage' );
1076 * Gets the link to the wiki's general disclaimers page.
1077 * @return string HTML
1079 function disclaimerLink() {
1080 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1084 * Return URL options for the 'edit page' link.
1085 * This may include an 'oldid' specifier, if the current page view is such.
1090 function editUrlOptions() {
1091 $options = [ 'action' => 'edit' ];
1093 if ( !$this->getOutput()->isRevisionCurrent() ) {
1094 $options['oldid'] = intval( $this->getOutput()->getRevisionId() );
1101 * @param User|int $id
1104 function showEmailUser( $id ) {
1105 if ( $id instanceof User
) {
1108 $targetUser = User
::newFromId( $id );
1111 # The sending user must have a confirmed email address and the receiving
1112 # user must accept emails from the sender.
1113 return $this->getUser()->canSendEmail()
1114 && SpecialEmailUser
::validateTarget( $targetUser, $this->getUser() ) === '';
1118 * Return a fully resolved style path URL to images or styles stored in the
1119 * current skin's folder. This method returns a URL resolved using the
1120 * configured skin style path.
1122 * Requires $stylename to be set, otherwise throws MWException.
1124 * @param string $name The name or path of a skin resource file
1125 * @return string The fully resolved style path URL
1126 * @throws MWException
1128 function getSkinStylePath( $name ) {
1129 if ( $this->stylename
=== null ) {
1130 $class = static::class;
1131 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1134 return $this->getConfig()->get( 'StylePath' ) . "/{$this->stylename}/$name";
1137 /* these are used extensively in SkinTemplate, but also some other places */
1140 * @param string|string[] $urlaction
1143 static function makeMainPageUrl( $urlaction = '' ) {
1144 $title = Title
::newMainPage();
1145 self
::checkTitle( $title, '' );
1147 return $title->getLinkURL( $urlaction );
1151 * Make a URL for a Special Page using the given query and protocol.
1153 * If $proto is set to null, make a local URL. Otherwise, make a full
1154 * URL with the protocol specified.
1156 * @param string $name Name of the Special page
1157 * @param string|string[] $urlaction Query to append
1158 * @param string|null $proto Protocol to use or null for a local URL
1161 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1162 $title = SpecialPage
::getSafeTitleFor( $name );
1163 if ( is_null( $proto ) ) {
1164 return $title->getLocalURL( $urlaction );
1166 return $title->getFullURL( $urlaction, false, $proto );
1171 * @param string $name
1172 * @param string $subpage
1173 * @param string|string[] $urlaction
1176 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1177 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1178 return $title->getLocalURL( $urlaction );
1182 * @param string $name
1183 * @param string|string[] $urlaction
1186 static function makeI18nUrl( $name, $urlaction = '' ) {
1187 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1188 self
::checkTitle( $title, $name );
1189 return $title->getLocalURL( $urlaction );
1193 * @param string $name
1194 * @param string|string[] $urlaction
1197 static function makeUrl( $name, $urlaction = '' ) {
1198 $title = Title
::newFromText( $name );
1199 self
::checkTitle( $title, $name );
1201 return $title->getLocalURL( $urlaction );
1205 * If url string starts with http, consider as external URL, else
1207 * @param string $name
1208 * @return string URL
1210 static function makeInternalOrExternalUrl( $name ) {
1211 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1214 return self
::makeUrl( $name );
1219 * this can be passed the NS number as defined in Language.php
1220 * @param string $name
1221 * @param string|string[] $urlaction
1222 * @param int $namespace
1225 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1226 $title = Title
::makeTitleSafe( $namespace, $name );
1227 self
::checkTitle( $title, $name );
1229 return $title->getLocalURL( $urlaction );
1233 * these return an array with the 'href' and boolean 'exists'
1234 * @param string $name
1235 * @param string|string[] $urlaction
1238 static function makeUrlDetails( $name, $urlaction = '' ) {
1239 $title = Title
::newFromText( $name );
1240 self
::checkTitle( $title, $name );
1243 'href' => $title->getLocalURL( $urlaction ),
1244 'exists' => $title->isKnown(),
1249 * Make URL details where the article exists (or at least it's convenient to think so)
1250 * @param string $name Article name
1251 * @param string|string[] $urlaction
1254 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1255 $title = Title
::newFromText( $name );
1256 self
::checkTitle( $title, $name );
1259 'href' => $title->getLocalURL( $urlaction ),
1265 * make sure we have some title to operate on
1267 * @param Title &$title
1268 * @param string $name
1270 static function checkTitle( &$title, $name ) {
1271 if ( !is_object( $title ) ) {
1272 $title = Title
::newFromText( $name );
1273 if ( !is_object( $title ) ) {
1274 $title = Title
::newFromText( '--error: link target missing--' );
1280 * Build an array that represents the sidebar(s), the navigation bar among them.
1282 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1284 * The format of the returned array is [ heading => content, ... ], where:
1285 * - heading is the heading of a navigation portlet. It is either:
1286 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1287 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1288 * - plain text, which should be HTML-escaped by the skin
1289 * - content is the contents of the portlet. It is either:
1290 * - HTML text (<ul><li>...</li>...</ul>)
1291 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1292 * - (for a magic string as a key, any value)
1294 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1295 * and can technically insert anything in here; skin creators are expected to handle
1296 * values described above.
1300 public function buildSidebar() {
1301 $callback = function ( $old = null, &$ttl = null ) {
1303 $this->addToSidebar( $bar, 'sidebar' );
1304 Hooks
::run( 'SkinBuildSidebar', [ $this, &$bar ] );
1305 if ( MessageCache
::singleton()->isDisabled() ) {
1306 $ttl = WANObjectCache
::TTL_UNCACHEABLE
; // bug T133069
1312 $msgCache = MessageCache
::singleton();
1313 $wanCache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1314 $config = $this->getConfig();
1316 $sidebar = $config->get( 'EnableSidebarCache' )
1317 ?
$wanCache->getWithSetCallback(
1318 $wanCache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1319 $config->get( 'SidebarCacheExpiry' ),
1323 // Unless there is both no exact $code override nor an i18n definition
1324 // in the software, the only MediaWiki page to check is for $code.
1325 $msgCache->getCheckKey( $this->getLanguage()->getCode() )
1332 // Apply post-processing to the cached value
1333 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1339 * Add content from a sidebar system message
1340 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1342 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1344 * @param array &$bar
1345 * @param string $message
1347 public function addToSidebar( &$bar, $message ) {
1348 $this->addToSidebarPlain( $bar, $this->msg( $message )->inContentLanguage()->plain() );
1352 * Add content from plain text
1354 * @param array &$bar
1355 * @param string $text
1358 function addToSidebarPlain( &$bar, $text ) {
1359 $lines = explode( "\n", $text );
1362 $config = $this->getConfig();
1363 $messageTitle = $config->get( 'EnableSidebarCache' )
1364 ? Title
::newMainPage() : $this->getTitle();
1366 foreach ( $lines as $line ) {
1367 if ( strpos( $line, '*' ) !== 0 ) {
1370 $line = rtrim( $line, "\r" ); // for Windows compat
1372 if ( strpos( $line, '**' ) !== 0 ) {
1373 $heading = trim( $line, '* ' );
1374 if ( !array_key_exists( $heading, $bar ) ) {
1375 $bar[$heading] = [];
1378 $line = trim( $line, '* ' );
1380 if ( strpos( $line, '|' ) !== false ) { // sanity check
1381 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1382 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1383 if ( count( $line ) !== 2 ) {
1384 // Second sanity check, could be hit by people doing
1385 // funky stuff with parserfuncs... (T35321)
1391 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1392 if ( $msgLink->exists() ) {
1393 $link = $msgLink->text();
1394 if ( $link == '-' ) {
1400 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1401 if ( $msgText->exists() ) {
1402 $text = $msgText->text();
1407 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1410 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1411 if ( $config->get( 'NoFollowLinks' ) &&
1412 !wfMatchesDomainList( $href, $config->get( 'NoFollowDomainExceptions' ) )
1414 $extraAttribs['rel'] = 'nofollow';
1417 if ( $config->get( 'ExternalLinkTarget' ) ) {
1418 $extraAttribs['target'] = $config->get( 'ExternalLinkTarget' );
1421 $title = Title
::newFromText( $link );
1424 $title = $title->fixSpecialName();
1425 $href = $title->getLinkURL();
1427 $href = 'INVALID-TITLE';
1431 $bar[$heading][] = array_merge( [
1434 'id' => Sanitizer
::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1447 * Gets new talk page messages for the current user and returns an
1448 * appropriate alert message (or an empty string if there are no messages)
1451 function getNewtalks() {
1452 $newMessagesAlert = '';
1453 $user = $this->getUser();
1454 $newtalks = $user->getNewMessageLinks();
1455 $out = $this->getOutput();
1456 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1458 // Allow extensions to disable or modify the new messages alert
1459 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1462 if ( $newMessagesAlert ) {
1463 return $newMessagesAlert;
1466 if ( count( $newtalks ) == 1 && WikiMap
::isCurrentWikiId( $newtalks[0]['wiki'] ) ) {
1467 $uTalkTitle = $user->getTalkPage();
1468 $lastSeenRev = $newtalks[0]['rev'] ??
null;
1470 if ( $lastSeenRev !== null ) {
1471 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1472 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1473 if ( $latestRev !== null ) {
1474 // Singular if only 1 unseen revision, plural if several unseen revisions.
1475 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1476 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1477 $lastSeenRev, $latestRev, 10, 'include_new' );
1480 // Singular if no revision -> diff link will show latest change only in any case
1483 $plural = $plural ?
999 : 1;
1484 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1485 // the number of revisions or authors is not necessarily the same as the number of
1487 $newMessagesLink = $linkRenderer->makeKnownLink(
1489 $this->msg( 'newmessageslinkplural' )->params( $plural )->text(),
1491 $uTalkTitle->isRedirect() ?
[ 'redirect' => 'no' ] : []
1494 $newMessagesDiffLink = $linkRenderer->makeKnownLink(
1496 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->text(),
1498 $lastSeenRev !== null
1499 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1500 : [ 'diff' => 'cur' ]
1503 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1504 $newMessagesAlert = $this->msg(
1505 'youhavenewmessagesfromusers',
1507 $newMessagesDiffLink
1508 )->numParams( $nofAuthors, $plural );
1510 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1511 $newMessagesAlert = $this->msg(
1512 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1514 $newMessagesDiffLink
1515 )->numParams( $plural );
1517 $newMessagesAlert = $newMessagesAlert->text();
1519 $out->setCdnMaxage( 0 );
1520 } elseif ( count( $newtalks ) ) {
1521 $sep = $this->msg( 'newtalkseparator' )->escaped();
1524 foreach ( $newtalks as $newtalk ) {
1525 $msgs[] = Xml
::element(
1527 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1530 $parts = implode( $sep, $msgs );
1531 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1532 $out->setCdnMaxage( 0 );
1535 return $newMessagesAlert;
1539 * Get a cached notice
1541 * @param string $name Message name, or 'default' for $wgSiteNotice
1542 * @return string|bool HTML fragment, or false to indicate that the caller
1543 * should fall back to the next notice in its sequence
1545 private function getCachedNotice( $name ) {
1546 $config = $this->getConfig();
1548 if ( $name === 'default' ) {
1550 $notice = $config->get( 'SiteNotice' );
1551 if ( empty( $notice ) ) {
1555 $msg = $this->msg( $name )->inContentLanguage();
1556 if ( $msg->isBlank() ) {
1558 } elseif ( $msg->isDisabled() ) {
1561 $notice = $msg->plain();
1564 $services = MediaWikiServices
::getInstance();
1565 $cache = $services->getMainWANObjectCache();
1566 $parsed = $cache->getWithSetCallback(
1567 // Use the extra hash appender to let eg SSL variants separately cache
1568 // Key is verified with md5 hash of unparsed wikitext
1569 $cache->makeKey( $name, $config->get( 'RenderHashAppend' ), md5( $notice ) ),
1572 function () use ( $notice ) {
1573 return $this->getOutput()->parseAsInterface( $notice );
1577 $contLang = $services->getContentLanguage();
1578 return Html
::rawElement(
1581 'id' => 'localNotice',
1582 'lang' => $contLang->getHtmlCode(),
1583 'dir' => $contLang->getDir()
1590 * Get the site notice
1592 * @return string HTML fragment
1594 function getSiteNotice() {
1597 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1598 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1599 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1601 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1602 if ( $anonNotice === false ) {
1603 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1605 $siteNotice = $anonNotice;
1608 if ( $siteNotice === false ) {
1609 $siteNotice = $this->getCachedNotice( 'default' );
1613 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1618 * Create a section edit link.
1620 * @suppress SecurityCheck-XSS $links has keys of different taint types
1621 * @param Title $nt The title being linked to (may not be the same as
1622 * the current page, if the section is included from a template)
1623 * @param string $section The designation of the section being pointed to,
1624 * to be included in the link, like "§ion=$section"
1625 * @param string|null $tooltip The tooltip to use for the link: will be escaped
1626 * and wrapped in the 'editsectionhint' message
1627 * @param Language $lang Language object
1628 * @return string HTML to use for edit link
1630 public function doEditSectionLink( Title
$nt, $section, $tooltip, Language
$lang ) {
1631 // HTML generated here should probably have userlangattributes
1632 // added to it for LTR text on RTL pages
1635 if ( !is_null( $tooltip ) ) {
1636 $attribs['title'] = $this->msg( 'editsectionhint' )->rawParams( $tooltip )
1637 ->inLanguage( $lang )->text();
1642 'text' => $this->msg( 'editsection' )->inLanguage( $lang )->text(),
1643 'targetTitle' => $nt,
1644 'attribs' => $attribs,
1645 'query' => [ 'action' => 'edit', 'section' => $section ]
1649 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1651 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1653 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1655 foreach ( $links as $k => $linkDetails ) {
1656 $linksHtml[] = $linkRenderer->makeKnownLink(
1657 $linkDetails['targetTitle'],
1658 $linkDetails['text'],
1659 $linkDetails['attribs'],
1660 $linkDetails['query']
1665 '<span class="mw-editsection-divider">'
1666 . $this->msg( 'pipe-separator' )->inLanguage( $lang )->escaped()
1671 $result .= '<span class="mw-editsection-bracket">]</span></span>';