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 = $out->getUser();
179 // Styles key sets render blocking styles
180 // Unlike other keys in this definition it is an associative array
181 // where each key is the group name and points to a list of modules
183 // modules not specific to any specific skin or page
185 // Enforce various default modules for all pages and all skins
186 // Keep this list as small as possible
188 'mediawiki.page.startup',
191 // modules that enhance the page content in some way
193 'mediawiki.page.ready',
195 // modules relating to search functionality
197 // modules relating to functionality relating to watching an article
199 // modules which relate to the current users preferences
203 // Support for high-density display images if enabled
204 if ( $config->get( 'ResponsiveImages' ) ) {
205 $modules['core'][] = 'mediawiki.hidpi';
208 // Preload jquery.tablesorter for mediawiki.page.ready
209 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
210 $modules['content'][] = 'jquery.tablesorter';
213 // Preload jquery.makeCollapsible for mediawiki.page.ready
214 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
215 $modules['content'][] = 'jquery.makeCollapsible';
218 if ( $out->isTOCEnabled() ) {
219 $modules['content'][] = 'mediawiki.toc';
222 // Add various resources if required
223 if ( $user->isLoggedIn()
224 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
225 && $this->getRelevantTitle()->canExist()
227 $modules['watch'][] = 'mediawiki.page.watch.ajax';
230 $modules['search'][] = 'mediawiki.searchSuggest';
232 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
233 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
236 // Crazy edit-on-double-click stuff
237 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
238 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
244 * Preload the existence of three commonly-requested pages in a single query
246 protected function preloadExistence() {
250 $user = $this->getUser();
251 if ( $user->isLoggedIn() ) {
252 $titles[] = $user->getUserPage();
253 $titles[] = $user->getTalkPage();
256 // Check, if the page can hold some kind of content, otherwise do nothing
257 $title = $this->getRelevantTitle();
258 if ( $title->canExist() ) {
259 if ( $title->isTalkPage() ) {
260 $titles[] = $title->getSubjectPage();
262 $titles[] = $title->getTalkPage();
266 // Footer links (used by SkinTemplate::prepareQuickTemplate)
268 $this->footerLinkTitle( 'privacy', 'privacypage' ),
269 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
270 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
277 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
280 $lb = new LinkBatch( $titles );
281 $lb->setCaller( __METHOD__
);
287 * Get the current revision ID
291 public function getRevisionId() {
292 return $this->getOutput()->getRevisionId();
296 * Whether the revision displayed is the latest revision of the page
300 public function isRevisionCurrent() {
301 $revID = $this->getRevisionId();
302 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
306 * Set the "relevant" title
307 * @see self::getRelevantTitle()
310 public function setRelevantTitle( $t ) {
311 $this->mRelevantTitle
= $t;
315 * Return the "relevant" title.
316 * A "relevant" title is not necessarily the actual title of the page.
317 * Special pages like Special:MovePage use set the page they are acting on
318 * as their "relevant" title, this allows the skin system to display things
319 * such as content tabs which belong to to that page instead of displaying
320 * a basic special page tab which has almost no meaning.
324 public function getRelevantTitle() {
325 if ( isset( $this->mRelevantTitle
) ) {
326 return $this->mRelevantTitle
;
328 return $this->getTitle();
332 * Set the "relevant" user
333 * @see self::getRelevantUser()
336 public function setRelevantUser( $u ) {
337 $this->mRelevantUser
= $u;
341 * Return the "relevant" user.
342 * A "relevant" user is similar to a relevant title. Special pages like
343 * Special:Contributions mark the user which they are relevant to so that
344 * things like the toolbox can display the information they usually are only
345 * able to display on a user's userpage and talkpage.
348 public function getRelevantUser() {
349 if ( isset( $this->mRelevantUser
) ) {
350 return $this->mRelevantUser
;
352 $title = $this->getRelevantTitle();
353 if ( $title->hasSubjectNamespace( NS_USER
) ) {
354 $rootUser = $title->getRootText();
355 if ( User
::isIP( $rootUser ) ) {
356 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
358 $user = User
::newFromName( $rootUser, false );
361 $user->load( User
::READ_NORMAL
);
363 if ( $user->isLoggedIn() ) {
364 $this->mRelevantUser
= $user;
368 return $this->mRelevantUser
;
374 * Outputs the HTML generated by other functions.
375 * @param OutputPage $out
377 abstract function outputPage( OutputPage
$out = null );
383 static function makeVariablesScript( $data ) {
385 return ResourceLoader
::makeInlineScript(
386 ResourceLoader
::makeConfigSetScript( $data )
394 * Get the query to generate a dynamic stylesheet
398 public static function getDynamicStylesheetQuery() {
399 global $wgSquidMaxage;
403 'maxage' => $wgSquidMaxage,
404 'usemsgcache' => 'yes',
405 'ctype' => 'text/css',
406 'smaxage' => $wgSquidMaxage,
411 * Add skin specific stylesheets
412 * Calling this method with an $out of anything but the same OutputPage
413 * inside ->getOutput() is deprecated. The $out arg is kept
414 * for compatibility purposes with skins.
415 * @param OutputPage $out
418 abstract function setupSkinUserCss( OutputPage
$out );
422 * @param Title $title
425 function getPageClasses( $title ) {
426 $numeric = 'ns-' . $title->getNamespace();
428 if ( $title->isSpecialPage() ) {
429 $type = 'ns-special';
430 // T25315: provide a class based on the canonical special page name without subpages
431 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
432 if ( $canonicalName ) {
433 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
435 $type .= ' mw-invalidspecialpage';
437 } elseif ( $title->isTalkPage() ) {
440 $type = 'ns-subject';
443 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
444 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
446 return "$numeric $type $name $root";
450 * Return values for <html> element
451 * @return array Array of associative name-to-value elements for <html> element
453 public function getHtmlElementAttributes() {
454 $lang = $this->getLanguage();
456 'lang' => $lang->getHtmlCode(),
457 'dir' => $lang->getDir(),
458 'class' => 'client-nojs',
463 * This will be called by OutputPage::headElement when it is creating the
464 * "<body>" tag, skins can override it if they have a need to add in any
465 * body attributes or classes of their own.
466 * @param OutputPage $out
467 * @param array &$bodyAttrs
469 function addToBodyAttributes( $out, &$bodyAttrs ) {
470 // does nothing by default
483 * Whether the logo should be preloaded with an HTTP link header or not
487 public function shouldPreloadLogo() {
492 * @return string HTML
494 function getCategoryLinks() {
495 global $wgUseCategoryBrowser;
497 $out = $this->getOutput();
498 $allCats = $out->getCategoryLinks();
500 if ( !count( $allCats ) ) {
508 $colon = $this->msg( 'colon-separator' )->escaped();
510 if ( !empty( $allCats['normal'] ) ) {
511 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
513 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
514 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
515 $title = Title
::newFromText( $linkPage );
516 $link = $title ? Linker
::link( $title, $msg ) : $msg;
517 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
518 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
522 if ( isset( $allCats['hidden'] ) ) {
523 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
524 $class = ' mw-hidden-cats-user-shown';
525 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
526 $class = ' mw-hidden-cats-ns-shown';
528 $class = ' mw-hidden-cats-hidden';
531 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
532 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
533 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
537 # optional 'dmoz-like' category browser. Will be shown under the list
538 # of categories an article belong to
539 if ( $wgUseCategoryBrowser ) {
540 $s .= '<br /><hr />';
542 # get a big array of the parents tree
543 $parenttree = $this->getTitle()->getParentCategoryTree();
544 # Skin object passed by reference cause it can not be
545 # accessed under the method subfunction drawCategoryBrowser
546 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
547 # Clean out bogus first entry and sort them
548 unset( $tempout[0] );
550 # Output one per line
551 $s .= implode( "<br />\n", $tempout );
558 * Render the array as a series of links.
559 * @param array $tree Categories tree returned by Title::getParentCategoryTree
560 * @return string Separated by >, terminate with "\n"
562 function drawCategoryBrowser( $tree ) {
565 foreach ( $tree as $element => $parent ) {
566 if ( empty( $parent ) ) {
567 # element start a new list
570 # grab the others elements
571 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
574 # add our current element to the list
575 $eltitle = Title
::newFromText( $element );
576 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
583 * @return string HTML
585 function getCategories() {
586 $out = $this->getOutput();
587 $catlinks = $this->getCategoryLinks();
589 // Check what we're showing
590 $allCats = $out->getCategoryLinks();
591 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
592 $this->getTitle()->getNamespace() == NS_CATEGORY
;
594 $classes = [ 'catlinks' ];
595 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
596 $classes[] = 'catlinks-allhidden';
599 return Html
::rawElement(
601 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
607 * This runs a hook to allow extensions placing their stuff after content
608 * and article metadata (e.g. categories).
609 * Note: This function has nothing to do with afterContent().
611 * This hook is placed here in order to allow using the same hook for all
612 * skins, both the SkinTemplate based ones and the older ones, which directly
613 * use this class to get their data.
615 * The output of this function gets processed in SkinTemplate::outputPage() for
616 * the SkinTemplate based skins, all other skins should directly echo it.
618 * @return string Empty by default, if not changed by any hook function.
620 protected function afterContentHook() {
623 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
624 // adding just some spaces shouldn't toggle the output
625 // of the whole <div/>, so we use trim() here
626 if ( trim( $data ) != '' ) {
627 // Doing this here instead of in the skins to
628 // ensure that the div has the same ID in all
630 $data = "<div id='mw-data-after-content'>\n" .
635 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
642 * Generate debug data HTML for displaying at the bottom of the main content
644 * @return string HTML containing debug data, if enabled (otherwise empty).
646 protected function generateDebugHTML() {
647 return MWDebug
::getHTMLDebugLog();
651 * This gets called shortly before the "</body>" tag.
653 * @return string HTML-wrapped JS code to be put before "</body>"
655 function bottomScripts() {
656 // TODO and the suckage continues. This function is really just a wrapper around
657 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
659 $bottomScriptText = $this->getOutput()->getBottomScripts();
660 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$bottomScriptText ] );
662 return $bottomScriptText;
666 * Text with the permalink to the source page,
667 * usually shown on the footer of a printed page
669 * @return string HTML text with an URL
671 function printSource() {
672 $oldid = $this->getRevisionId();
674 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
675 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
677 // oldid not available for non existing pages
678 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
681 return $this->msg( 'retrievedfrom' )
682 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
687 * @return string HTML
689 function getUndeleteLink() {
690 $action = $this->getRequest()->getVal( 'action', 'view' );
692 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
693 ( !$this->getTitle()->exists() ||
$action == 'history' ) ) {
694 $n = $this->getTitle()->isDeleted();
697 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
698 $msg = 'thisisdeleted';
700 $msg = 'viewdeleted';
703 return $this->msg( $msg )->rawParams(
705 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
706 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
715 * @param OutputPage $out Defaults to $this->getOutput() if left as null
718 function subPageSubtitle( $out = null ) {
719 if ( $out === null ) {
720 $out = $this->getOutput();
722 $title = $out->getTitle();
725 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
729 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
730 $ptext = $title->getPrefixedText();
731 if ( strpos( $ptext, '/' ) !== false ) {
732 $links = explode( '/', $ptext );
737 $lang = $this->getLanguage();
739 foreach ( $links as $link ) {
740 $growinglink .= $link;
742 $linkObj = Title
::newFromText( $growinglink );
744 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
745 $getlink = Linker
::linkKnown(
747 htmlspecialchars( $display )
753 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
755 $subpages .= '< ';
758 $subpages .= $getlink;
774 function getSearchLink() {
775 $searchPage = SpecialPage
::getTitleFor( 'Search' );
776 return $searchPage->getLocalURL();
782 function escapeSearchLink() {
783 return htmlspecialchars( $this->getSearchLink() );
787 * @param string $type
790 function getCopyright( $type = 'detect' ) {
791 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
793 if ( $type == 'detect' ) {
794 if ( !$this->isRevisionCurrent()
795 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
803 if ( $type == 'history' ) {
804 $msg = 'history_copyright';
809 if ( $wgRightsPage ) {
810 $title = Title
::newFromText( $wgRightsPage );
811 $link = Linker
::linkKnown( $title, $wgRightsText );
812 } elseif ( $wgRightsUrl ) {
813 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
814 } elseif ( $wgRightsText ) {
815 $link = $wgRightsText;
821 // Allow for site and per-namespace customization of copyright notice.
822 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
826 'SkinCopyrightFooter',
827 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
830 return $this->msg( $msg )->rawParams( $link )->text();
834 * @return null|string
836 function getCopyrightIcon() {
837 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
841 if ( $wgFooterIcons['copyright']['copyright'] ) {
842 $out = $wgFooterIcons['copyright']['copyright'];
843 } elseif ( $wgRightsIcon ) {
844 $icon = htmlspecialchars( $wgRightsIcon );
846 if ( $wgRightsUrl ) {
847 $url = htmlspecialchars( $wgRightsUrl );
848 $out .= '<a href="' . $url . '">';
851 $text = htmlspecialchars( $wgRightsText );
852 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
854 if ( $wgRightsUrl ) {
863 * Gets the powered by MediaWiki icon.
866 function getPoweredBy() {
867 global $wgResourceBasePath;
869 $url1 = htmlspecialchars(
870 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
872 $url1_5 = htmlspecialchars(
873 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
875 $url2 = htmlspecialchars(
876 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
878 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
879 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
880 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
881 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
886 * Get the timestamp of the latest revision, formatted in user language
890 protected function lastModified() {
891 $timestamp = $this->getOutput()->getRevisionTimestamp();
893 # No cached timestamp, load it from the database
894 if ( $timestamp === null ) {
895 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
899 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
900 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
901 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
906 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLaggedReplicaMode() ) {
907 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
914 * @param string $align
917 function logoText( $align = '' ) {
918 if ( $align != '' ) {
919 $a = " style='float: {$align};'";
924 $mp = $this->msg( 'mainpage' )->escaped();
925 $mptitle = Title
::newMainPage();
926 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
928 $logourl = $this->getLogo();
929 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
935 * Renders a $wgFooterIcons icon according to the method's arguments
936 * @param array $icon The icon to build the html for, see $wgFooterIcons
937 * for the format of this array.
938 * @param bool|string $withImage Whether to use the icon's image or output
939 * a text-only footericon.
940 * @return string HTML
942 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
943 if ( is_string( $icon ) ) {
945 } else { // Assuming array
946 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
947 unset( $icon["url"] );
948 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
949 // do this the lazy way, just pass icon data as an attribute array
950 $html = Html
::element( 'img', $icon );
952 $html = htmlspecialchars( $icon["alt"] );
955 global $wgExternalLinkTarget;
956 $html = Html
::rawElement( 'a',
957 [ "href" => $url, "target" => $wgExternalLinkTarget ],
965 * Gets the link to the wiki's main page.
968 function mainPageLink() {
969 $s = Linker
::linkKnown(
970 Title
::newMainPage(),
971 $this->msg( 'mainpage' )->escaped()
978 * Returns an HTML link for use in the footer
979 * @param string $desc The i18n message key for the link text
980 * @param string $page The i18n message key for the page to link to
981 * @return string HTML anchor
983 public function footerLink( $desc, $page ) {
984 $title = $this->footerLinkTitle( $desc, $page );
989 return Linker
::linkKnown(
991 $this->msg( $desc )->escaped()
996 * @param string $desc
997 * @param string $page
1000 private function footerLinkTitle( $desc, $page ) {
1001 // If the link description has been set to "-" in the default language,
1002 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
1003 // then it is disabled, for all languages.
1006 // Otherwise, we display the link for the user, described in their
1007 // language (which may or may not be the same as the default language),
1008 // but we make the link target be the one site-wide page.
1009 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1011 return $title ?
: null;
1015 * Gets the link to the wiki's privacy policy page.
1016 * @return string HTML
1018 function privacyLink() {
1019 return $this->footerLink( 'privacy', 'privacypage' );
1023 * Gets the link to the wiki's about page.
1024 * @return string HTML
1026 function aboutLink() {
1027 return $this->footerLink( 'aboutsite', 'aboutpage' );
1031 * Gets the link to the wiki's general disclaimers page.
1032 * @return string HTML
1034 function disclaimerLink() {
1035 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1039 * Return URL options for the 'edit page' link.
1040 * This may include an 'oldid' specifier, if the current page view is such.
1045 function editUrlOptions() {
1046 $options = [ 'action' => 'edit' ];
1048 if ( !$this->isRevisionCurrent() ) {
1049 $options['oldid'] = intval( $this->getRevisionId() );
1056 * @param User|int $id
1059 function showEmailUser( $id ) {
1060 if ( $id instanceof User
) {
1063 $targetUser = User
::newFromId( $id );
1066 # The sending user must have a confirmed email address and the receiving
1067 # user must accept emails from the sender.
1068 return $this->getUser()->canSendEmail()
1069 && SpecialEmailUser
::validateTarget( $targetUser, $this->getUser() ) === '';
1073 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1074 * This method returns a url resolved using the configured skin style path
1075 * and includes the style version inside of the url.
1077 * Requires $stylename to be set, otherwise throws MWException.
1079 * @param string $name The name or path of a skin resource file
1080 * @return string The fully resolved style path url including styleversion
1081 * @throws MWException
1083 function getSkinStylePath( $name ) {
1084 global $wgStylePath, $wgStyleVersion;
1086 if ( $this->stylename
=== null ) {
1087 $class = static::class;
1088 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1091 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1094 /* these are used extensively in SkinTemplate, but also some other places */
1097 * @param string|string[] $urlaction
1100 static function makeMainPageUrl( $urlaction = '' ) {
1101 $title = Title
::newMainPage();
1102 self
::checkTitle( $title, '' );
1104 return $title->getLinkURL( $urlaction );
1108 * Make a URL for a Special Page using the given query and protocol.
1110 * If $proto is set to null, make a local URL. Otherwise, make a full
1111 * URL with the protocol specified.
1113 * @param string $name Name of the Special page
1114 * @param string|string[] $urlaction Query to append
1115 * @param string|null $proto Protocol to use or null for a local URL
1118 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1119 $title = SpecialPage
::getSafeTitleFor( $name );
1120 if ( is_null( $proto ) ) {
1121 return $title->getLocalURL( $urlaction );
1123 return $title->getFullURL( $urlaction, false, $proto );
1128 * @param string $name
1129 * @param string $subpage
1130 * @param string|string[] $urlaction
1133 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1134 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1135 return $title->getLocalURL( $urlaction );
1139 * @param string $name
1140 * @param string|string[] $urlaction
1143 static function makeI18nUrl( $name, $urlaction = '' ) {
1144 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1145 self
::checkTitle( $title, $name );
1146 return $title->getLocalURL( $urlaction );
1150 * @param string $name
1151 * @param string|string[] $urlaction
1154 static function makeUrl( $name, $urlaction = '' ) {
1155 $title = Title
::newFromText( $name );
1156 self
::checkTitle( $title, $name );
1158 return $title->getLocalURL( $urlaction );
1162 * If url string starts with http, consider as external URL, else
1164 * @param string $name
1165 * @return string URL
1167 static function makeInternalOrExternalUrl( $name ) {
1168 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1171 return self
::makeUrl( $name );
1176 * this can be passed the NS number as defined in Language.php
1177 * @param string $name
1178 * @param string|string[] $urlaction
1179 * @param int $namespace
1182 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1183 $title = Title
::makeTitleSafe( $namespace, $name );
1184 self
::checkTitle( $title, $name );
1186 return $title->getLocalURL( $urlaction );
1190 * these return an array with the 'href' and boolean 'exists'
1191 * @param string $name
1192 * @param string|string[] $urlaction
1195 static function makeUrlDetails( $name, $urlaction = '' ) {
1196 $title = Title
::newFromText( $name );
1197 self
::checkTitle( $title, $name );
1200 'href' => $title->getLocalURL( $urlaction ),
1201 'exists' => $title->isKnown(),
1206 * Make URL details where the article exists (or at least it's convenient to think so)
1207 * @param string $name Article name
1208 * @param string|string[] $urlaction
1211 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1212 $title = Title
::newFromText( $name );
1213 self
::checkTitle( $title, $name );
1216 'href' => $title->getLocalURL( $urlaction ),
1222 * make sure we have some title to operate on
1224 * @param Title &$title
1225 * @param string $name
1227 static function checkTitle( &$title, $name ) {
1228 if ( !is_object( $title ) ) {
1229 $title = Title
::newFromText( $name );
1230 if ( !is_object( $title ) ) {
1231 $title = Title
::newFromText( '--error: link target missing--' );
1237 * Build an array that represents the sidebar(s), the navigation bar among them.
1239 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1241 * The format of the returned array is [ heading => content, ... ], where:
1242 * - heading is the heading of a navigation portlet. It is either:
1243 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1244 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1245 * - plain text, which should be HTML-escaped by the skin
1246 * - content is the contents of the portlet. It is either:
1247 * - HTML text (<ul><li>...</li>...</ul>)
1248 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1249 * - (for a magic string as a key, any value)
1251 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1252 * and can technically insert anything in here; skin creators are expected to handle
1253 * values described above.
1257 public function buildSidebar() {
1258 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1260 $callback = function ( $old = null, &$ttl = null ) {
1262 $this->addToSidebar( $bar, 'sidebar' );
1263 Hooks
::run( 'SkinBuildSidebar', [ $this, &$bar ] );
1264 if ( MessageCache
::singleton()->isDisabled() ) {
1265 $ttl = WANObjectCache
::TTL_UNCACHEABLE
; // bug T133069
1271 $msgCache = MessageCache
::singleton();
1272 $wanCache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1274 $sidebar = $wgEnableSidebarCache
1275 ?
$wanCache->getWithSetCallback(
1276 $wanCache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1277 $wgSidebarCacheExpiry,
1281 // Unless there is both no exact $code override nor an i18n definition
1282 // in the the software, the only MediaWiki page to check is for $code.
1283 $msgCache->getCheckKey( $this->getLanguage()->getCode() )
1290 // Apply post-processing to the cached value
1291 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1297 * Add content from a sidebar system message
1298 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1300 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1302 * @param array &$bar
1303 * @param string $message
1305 public function addToSidebar( &$bar, $message ) {
1306 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1310 * Add content from plain text
1312 * @param array &$bar
1313 * @param string $text
1316 function addToSidebarPlain( &$bar, $text ) {
1317 $lines = explode( "\n", $text );
1320 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1321 ? Title
::newMainPage() : $this->getTitle();
1323 foreach ( $lines as $line ) {
1324 if ( strpos( $line, '*' ) !== 0 ) {
1327 $line = rtrim( $line, "\r" ); // for Windows compat
1329 if ( strpos( $line, '**' ) !== 0 ) {
1330 $heading = trim( $line, '* ' );
1331 if ( !array_key_exists( $heading, $bar ) ) {
1332 $bar[$heading] = [];
1335 $line = trim( $line, '* ' );
1337 if ( strpos( $line, '|' ) !== false ) { // sanity check
1338 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1339 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1340 if ( count( $line ) !== 2 ) {
1341 // Second sanity check, could be hit by people doing
1342 // funky stuff with parserfuncs... (T35321)
1348 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1349 if ( $msgLink->exists() ) {
1350 $link = $msgLink->text();
1351 if ( $link == '-' ) {
1357 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1358 if ( $msgText->exists() ) {
1359 $text = $msgText->text();
1364 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1367 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1368 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1369 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1370 $extraAttribs['rel'] = 'nofollow';
1373 global $wgExternalLinkTarget;
1374 if ( $wgExternalLinkTarget ) {
1375 $extraAttribs['target'] = $wgExternalLinkTarget;
1378 $title = Title
::newFromText( $link );
1381 $title = $title->fixSpecialName();
1382 $href = $title->getLinkURL();
1384 $href = 'INVALID-TITLE';
1388 $bar[$heading][] = array_merge( [
1391 'id' => Sanitizer
::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1404 * Gets new talk page messages for the current user and returns an
1405 * appropriate alert message (or an empty string if there are no messages)
1408 function getNewtalks() {
1409 $newMessagesAlert = '';
1410 $user = $this->getUser();
1411 $newtalks = $user->getNewMessageLinks();
1412 $out = $this->getOutput();
1414 // Allow extensions to disable or modify the new messages alert
1415 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1418 if ( $newMessagesAlert ) {
1419 return $newMessagesAlert;
1422 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1423 $uTalkTitle = $user->getTalkPage();
1424 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1426 if ( $lastSeenRev !== null ) {
1427 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1428 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1429 if ( $latestRev !== null ) {
1430 // Singular if only 1 unseen revision, plural if several unseen revisions.
1431 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1432 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1433 $lastSeenRev, $latestRev, 10, 'include_new' );
1436 // Singular if no revision -> diff link will show latest change only in any case
1439 $plural = $plural ?
999 : 1;
1440 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1441 // the number of revisions or authors is not necessarily the same as the number of
1443 $newMessagesLink = Linker
::linkKnown(
1445 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1447 [ 'redirect' => 'no' ]
1450 $newMessagesDiffLink = Linker
::linkKnown(
1452 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1454 $lastSeenRev !== null
1455 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1456 : [ 'diff' => 'cur' ]
1459 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1460 $newMessagesAlert = $this->msg(
1461 'youhavenewmessagesfromusers',
1463 $newMessagesDiffLink
1464 )->numParams( $nofAuthors, $plural );
1466 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1467 $newMessagesAlert = $this->msg(
1468 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1470 $newMessagesDiffLink
1471 )->numParams( $plural );
1473 $newMessagesAlert = $newMessagesAlert->text();
1475 $out->setCdnMaxage( 0 );
1476 } elseif ( count( $newtalks ) ) {
1477 $sep = $this->msg( 'newtalkseparator' )->escaped();
1480 foreach ( $newtalks as $newtalk ) {
1481 $msgs[] = Xml
::element(
1483 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1486 $parts = implode( $sep, $msgs );
1487 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1488 $out->setCdnMaxage( 0 );
1491 return $newMessagesAlert;
1495 * Get a cached notice
1497 * @param string $name Message name, or 'default' for $wgSiteNotice
1498 * @return string|bool HTML fragment, or false to indicate that the caller
1499 * should fall back to the next notice in its sequence
1501 private function getCachedNotice( $name ) {
1502 global $wgRenderHashAppend, $wgContLang;
1506 if ( $name === 'default' ) {
1508 global $wgSiteNotice;
1509 $notice = $wgSiteNotice;
1510 if ( empty( $notice ) ) {
1514 $msg = $this->msg( $name )->inContentLanguage();
1515 if ( $msg->isBlank() ) {
1517 } elseif ( $msg->isDisabled() ) {
1520 $notice = $msg->plain();
1523 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1524 $parsed = $cache->getWithSetCallback(
1525 // Use the extra hash appender to let eg SSL variants separately cache
1526 // Key is verified with md5 hash of unparsed wikitext
1527 $cache->makeKey( $name, $wgRenderHashAppend, md5( $notice ) ),
1530 function () use ( $notice ) {
1531 return $this->getOutput()->parse( $notice );
1535 return Html
::rawElement(
1538 'id' => 'localNotice',
1539 'lang' => $wgContLang->getHtmlCode(),
1540 'dir' => $wgContLang->getDir()
1547 * Get the site notice
1549 * @return string HTML fragment
1551 function getSiteNotice() {
1554 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1555 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1556 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1558 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1559 if ( $anonNotice === false ) {
1560 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1562 $siteNotice = $anonNotice;
1565 if ( $siteNotice === false ) {
1566 $siteNotice = $this->getCachedNotice( 'default' );
1570 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1575 * Create a section edit link. This supersedes editSectionLink() and
1576 * editSectionLinkForOther().
1578 * @param Title $nt The title being linked to (may not be the same as
1579 * the current page, if the section is included from a template)
1580 * @param string $section The designation of the section being pointed to,
1581 * to be included in the link, like "§ion=$section"
1582 * @param string $tooltip The tooltip to use for the link: will be escaped
1583 * and wrapped in the 'editsectionhint' message
1584 * @param string $lang Language code
1585 * @return string HTML to use for edit link
1587 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1588 // HTML generated here should probably have userlangattributes
1589 // added to it for LTR text on RTL pages
1591 $lang = wfGetLangObj( $lang );
1594 if ( !is_null( $tooltip ) ) {
1595 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1596 ->inLanguage( $lang )->text();
1601 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1602 'targetTitle' => $nt,
1603 'attribs' => $attribs,
1604 'query' => [ 'action' => 'edit', 'section' => $section ],
1605 'options' => [ 'noclasses', 'known' ]
1609 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1611 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1614 foreach ( $links as $k => $linkDetails ) {
1615 $linksHtml[] = Linker
::link(
1616 $linkDetails['targetTitle'],
1617 $linkDetails['text'],
1618 $linkDetails['attribs'],
1619 $linkDetails['query'],
1620 $linkDetails['options']
1625 '<span class="mw-editsection-divider">'
1626 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->escaped()
1631 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1632 // Deprecated, use SkinEditSectionLinks hook instead
1634 'DoEditSectionLink',
1635 [ $this, $nt, $section, $tooltip, &$result, $lang ],