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
{
37 protected $skinname = null;
38 protected $mRelevantTitle = null;
39 protected $mRelevantUser = null;
42 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
43 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
45 public $stylename = null;
48 * Fetch the set of available skins.
49 * @return array Associative array of strings
51 static function getSkinNames() {
52 return SkinFactory
::getDefaultInstance()->getSkinNames();
56 * Fetch the skinname messages for available skins.
59 static function getSkinNameMessages() {
61 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
62 $messages[] = "skinname-$skinKey";
68 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
69 * Useful for Special:Preferences and other places where you
70 * only want to show skins users _can_ use.
74 public static function getAllowedSkins() {
77 $allowedSkins = self
::getSkinNames();
79 foreach ( $wgSkipSkins as $skip ) {
80 unset( $allowedSkins[$skip] );
87 * Normalize a skin preference value to a form that can be loaded.
89 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
90 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
92 * @param string $key 'monobook', 'vector', etc.
95 static function normalizeKey( $key ) {
96 global $wgDefaultSkin, $wgFallbackSkin;
98 $skinNames = self
::getSkinNames();
100 // Make keys lowercase for case-insensitive matching.
101 $skinNames = array_change_key_case( $skinNames, CASE_LOWER
);
102 $key = strtolower( $key );
103 $defaultSkin = strtolower( $wgDefaultSkin );
104 $fallbackSkin = strtolower( $wgFallbackSkin );
106 if ( $key == '' ||
$key == 'default' ) {
107 // Don't return the default immediately;
108 // in a misconfiguration we need to fall back.
112 if ( isset( $skinNames[$key] ) ) {
116 // Older versions of the software used a numeric setting
117 // in the user preferences.
123 if ( isset( $fallback[$key] ) ) {
124 $key = $fallback[$key];
127 if ( isset( $skinNames[$key] ) ) {
129 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
132 return $fallbackSkin;
137 * @return string Skin name
139 public function getSkinName() {
140 return $this->skinname
;
144 * @param OutputPage $out
146 public function initPage( OutputPage
$out ) {
147 $this->preloadExistence();
151 * Defines the ResourceLoader modules that should be added to the skin
152 * It is recommended that skins wishing to override call parent::getDefaultModules()
153 * and substitute out any modules they wish to change by using a key to look them up
155 * For style modules, use setupSkinUserCss() instead.
157 * @return array Array of modules with helper keys for easy overriding
159 public function getDefaultModules() {
160 global $wgUseAjax, $wgEnableAPI, $wgEnableWriteAPI;
162 $out = $this->getOutput();
163 $config = $this->getConfig();
164 $user = $out->getUser();
166 // modules not specific to any specific skin or page
168 // Enforce various default modules for all pages and all skins
169 // Keep this list as small as possible
171 'mediawiki.page.startup',
174 // modules that enhance the page content in some way
176 'mediawiki.page.ready',
178 // modules relating to search functionality
180 // modules relating to functionality relating to watching an article
182 // modules which relate to the current users preferences
186 // Support for high-density display images if enabled
187 if ( $config->get( 'ResponsiveImages' ) ) {
188 $modules['core'][] = 'mediawiki.hidpi';
191 // Preload jquery.tablesorter for mediawiki.page.ready
192 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
193 $modules['content'][] = 'jquery.tablesorter';
196 // Preload jquery.makeCollapsible for mediawiki.page.ready
197 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
198 $modules['content'][] = 'jquery.makeCollapsible';
201 if ( $out->isTOCEnabled() ) {
202 $modules['content'][] = 'mediawiki.toc';
205 // Add various resources if required
206 if ( $wgUseAjax && $wgEnableAPI ) {
207 if ( $wgEnableWriteAPI && $user->isLoggedIn()
208 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
209 && $this->getRelevantTitle()->canExist()
211 $modules['watch'][] = 'mediawiki.page.watch.ajax';
214 $modules['search'][] = 'mediawiki.searchSuggest';
217 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
218 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
221 // Crazy edit-on-double-click stuff
222 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
223 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
229 * Preload the existence of three commonly-requested pages in a single query
231 protected function preloadExistence() {
235 $user = $this->getUser();
236 if ( $user->isLoggedIn() ) {
237 $titles[] = $user->getUserPage();
238 $titles[] = $user->getTalkPage();
241 // Check, if the page can hold some kind of content, otherwise do nothing
242 $title = $this->getRelevantTitle();
243 if ( $title->canExist() ) {
244 if ( $title->isTalkPage() ) {
245 $titles[] = $title->getSubjectPage();
247 $titles[] = $title->getTalkPage();
251 // Footer links (used by SkinTemplate::prepareQuickTemplate)
253 $this->footerLinkTitle( 'privacy', 'privacypage' ),
254 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
255 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
262 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
265 $lb = new LinkBatch( $titles );
266 $lb->setCaller( __METHOD__
);
272 * Get the current revision ID
276 public function getRevisionId() {
277 return $this->getOutput()->getRevisionId();
281 * Whether the revision displayed is the latest revision of the page
285 public function isRevisionCurrent() {
286 $revID = $this->getRevisionId();
287 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
291 * Set the "relevant" title
292 * @see self::getRelevantTitle()
295 public function setRelevantTitle( $t ) {
296 $this->mRelevantTitle
= $t;
300 * Return the "relevant" title.
301 * A "relevant" title is not necessarily the actual title of the page.
302 * Special pages like Special:MovePage use set the page they are acting on
303 * as their "relevant" title, this allows the skin system to display things
304 * such as content tabs which belong to to that page instead of displaying
305 * a basic special page tab which has almost no meaning.
309 public function getRelevantTitle() {
310 if ( isset( $this->mRelevantTitle
) ) {
311 return $this->mRelevantTitle
;
313 return $this->getTitle();
317 * Set the "relevant" user
318 * @see self::getRelevantUser()
321 public function setRelevantUser( $u ) {
322 $this->mRelevantUser
= $u;
326 * Return the "relevant" user.
327 * A "relevant" user is similar to a relevant title. Special pages like
328 * Special:Contributions mark the user which they are relevant to so that
329 * things like the toolbox can display the information they usually are only
330 * able to display on a user's userpage and talkpage.
333 public function getRelevantUser() {
334 if ( isset( $this->mRelevantUser
) ) {
335 return $this->mRelevantUser
;
337 $title = $this->getRelevantTitle();
338 if ( $title->hasSubjectNamespace( NS_USER
) ) {
339 $rootUser = $title->getRootText();
340 if ( User
::isIP( $rootUser ) ) {
341 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
343 $user = User
::newFromName( $rootUser, false );
346 $user->load( User
::READ_NORMAL
);
348 if ( $user->isLoggedIn() ) {
349 $this->mRelevantUser
= $user;
353 return $this->mRelevantUser
;
359 * Outputs the HTML generated by other functions.
360 * @param OutputPage $out
362 abstract function outputPage( OutputPage
$out = null );
368 static function makeVariablesScript( $data ) {
370 return ResourceLoader
::makeInlineScript(
371 ResourceLoader
::makeConfigSetScript( $data )
379 * Get the query to generate a dynamic stylesheet
383 public static function getDynamicStylesheetQuery() {
384 global $wgSquidMaxage;
388 'maxage' => $wgSquidMaxage,
389 'usemsgcache' => 'yes',
390 'ctype' => 'text/css',
391 'smaxage' => $wgSquidMaxage,
396 * Add skin specific stylesheets
397 * Calling this method with an $out of anything but the same OutputPage
398 * inside ->getOutput() is deprecated. The $out arg is kept
399 * for compatibility purposes with skins.
400 * @param OutputPage $out
403 abstract function setupSkinUserCss( OutputPage
$out );
407 * @param Title $title
410 function getPageClasses( $title ) {
411 $numeric = 'ns-' . $title->getNamespace();
413 if ( $title->isSpecialPage() ) {
414 $type = 'ns-special';
415 // T25315: provide a class based on the canonical special page name without subpages
416 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
417 if ( $canonicalName ) {
418 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
420 $type .= ' mw-invalidspecialpage';
422 } elseif ( $title->isTalkPage() ) {
425 $type = 'ns-subject';
428 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
429 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
431 return "$numeric $type $name $root";
435 * Return values for <html> element
436 * @return array Array of associative name-to-value elements for <html> element
438 public function getHtmlElementAttributes() {
439 $lang = $this->getLanguage();
441 'lang' => $lang->getHtmlCode(),
442 'dir' => $lang->getDir(),
443 'class' => 'client-nojs',
448 * This will be called by OutputPage::headElement when it is creating the
449 * "<body>" tag, skins can override it if they have a need to add in any
450 * body attributes or classes of their own.
451 * @param OutputPage $out
452 * @param array &$bodyAttrs
454 function addToBodyAttributes( $out, &$bodyAttrs ) {
455 // does nothing by default
468 * Whether the logo should be preloaded with an HTTP link header or not
472 public function shouldPreloadLogo() {
477 * @return string HTML
479 function getCategoryLinks() {
480 global $wgUseCategoryBrowser;
482 $out = $this->getOutput();
483 $allCats = $out->getCategoryLinks();
485 if ( !count( $allCats ) ) {
493 $colon = $this->msg( 'colon-separator' )->escaped();
495 if ( !empty( $allCats['normal'] ) ) {
496 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
498 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
499 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
500 $title = Title
::newFromText( $linkPage );
501 $link = $title ? Linker
::link( $title, $msg ) : $msg;
502 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
503 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
507 if ( isset( $allCats['hidden'] ) ) {
508 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
509 $class = ' mw-hidden-cats-user-shown';
510 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
511 $class = ' mw-hidden-cats-ns-shown';
513 $class = ' mw-hidden-cats-hidden';
516 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
517 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
518 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
522 # optional 'dmoz-like' category browser. Will be shown under the list
523 # of categories an article belong to
524 if ( $wgUseCategoryBrowser ) {
525 $s .= '<br /><hr />';
527 # get a big array of the parents tree
528 $parenttree = $this->getTitle()->getParentCategoryTree();
529 # Skin object passed by reference cause it can not be
530 # accessed under the method subfunction drawCategoryBrowser
531 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
532 # Clean out bogus first entry and sort them
533 unset( $tempout[0] );
535 # Output one per line
536 $s .= implode( "<br />\n", $tempout );
543 * Render the array as a series of links.
544 * @param array $tree Categories tree returned by Title::getParentCategoryTree
545 * @return string Separated by >, terminate with "\n"
547 function drawCategoryBrowser( $tree ) {
550 foreach ( $tree as $element => $parent ) {
551 if ( empty( $parent ) ) {
552 # element start a new list
555 # grab the others elements
556 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
559 # add our current element to the list
560 $eltitle = Title
::newFromText( $element );
561 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
568 * @return string HTML
570 function getCategories() {
571 $out = $this->getOutput();
572 $catlinks = $this->getCategoryLinks();
574 // Check what we're showing
575 $allCats = $out->getCategoryLinks();
576 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
577 $this->getTitle()->getNamespace() == NS_CATEGORY
;
579 $classes = [ 'catlinks' ];
580 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
581 $classes[] = 'catlinks-allhidden';
584 return Html
::rawElement(
586 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
592 * This runs a hook to allow extensions placing their stuff after content
593 * and article metadata (e.g. categories).
594 * Note: This function has nothing to do with afterContent().
596 * This hook is placed here in order to allow using the same hook for all
597 * skins, both the SkinTemplate based ones and the older ones, which directly
598 * use this class to get their data.
600 * The output of this function gets processed in SkinTemplate::outputPage() for
601 * the SkinTemplate based skins, all other skins should directly echo it.
603 * @return string Empty by default, if not changed by any hook function.
605 protected function afterContentHook() {
608 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
609 // adding just some spaces shouldn't toggle the output
610 // of the whole <div/>, so we use trim() here
611 if ( trim( $data ) != '' ) {
612 // Doing this here instead of in the skins to
613 // ensure that the div has the same ID in all
615 $data = "<div id='mw-data-after-content'>\n" .
620 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
627 * Generate debug data HTML for displaying at the bottom of the main content
629 * @return string HTML containing debug data, if enabled (otherwise empty).
631 protected function generateDebugHTML() {
632 return MWDebug
::getHTMLDebugLog();
636 * This gets called shortly before the "</body>" tag.
638 * @return string HTML-wrapped JS code to be put before "</body>"
640 function bottomScripts() {
641 // TODO and the suckage continues. This function is really just a wrapper around
642 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
644 $bottomScriptText = $this->getOutput()->getBottomScripts();
645 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$bottomScriptText ] );
647 return $bottomScriptText;
651 * Text with the permalink to the source page,
652 * usually shown on the footer of a printed page
654 * @return string HTML text with an URL
656 function printSource() {
657 $oldid = $this->getRevisionId();
659 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
660 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
662 // oldid not available for non existing pages
663 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
666 return $this->msg( 'retrievedfrom' )
667 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
672 * @return string HTML
674 function getUndeleteLink() {
675 $action = $this->getRequest()->getVal( 'action', 'view' );
677 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
678 ( !$this->getTitle()->exists() ||
$action == 'history' ) ) {
679 $n = $this->getTitle()->isDeleted();
682 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
683 $msg = 'thisisdeleted';
685 $msg = 'viewdeleted';
688 return $this->msg( $msg )->rawParams(
690 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
691 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
700 * @param OutputPage $out Defaults to $this->getOutput() if left as null
703 function subPageSubtitle( $out = null ) {
704 if ( $out === null ) {
705 $out = $this->getOutput();
707 $title = $out->getTitle();
710 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
714 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
715 $ptext = $title->getPrefixedText();
716 if ( strpos( $ptext, '/' ) !== false ) {
717 $links = explode( '/', $ptext );
722 $lang = $this->getLanguage();
724 foreach ( $links as $link ) {
725 $growinglink .= $link;
727 $linkObj = Title
::newFromText( $growinglink );
729 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
730 $getlink = Linker
::linkKnown(
732 htmlspecialchars( $display )
738 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
740 $subpages .= '< ';
743 $subpages .= $getlink;
757 * @deprecated since 1.27, feature removed
758 * @return bool Always false
760 function showIPinHeader() {
761 wfDeprecated( __METHOD__
, '1.27' );
768 function getSearchLink() {
769 $searchPage = SpecialPage
::getTitleFor( 'Search' );
770 return $searchPage->getLocalURL();
776 function escapeSearchLink() {
777 return htmlspecialchars( $this->getSearchLink() );
781 * @param string $type
784 function getCopyright( $type = 'detect' ) {
785 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
787 if ( $type == 'detect' ) {
788 if ( !$this->isRevisionCurrent()
789 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
797 if ( $type == 'history' ) {
798 $msg = 'history_copyright';
803 if ( $wgRightsPage ) {
804 $title = Title
::newFromText( $wgRightsPage );
805 $link = Linker
::linkKnown( $title, $wgRightsText );
806 } elseif ( $wgRightsUrl ) {
807 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
808 } elseif ( $wgRightsText ) {
809 $link = $wgRightsText;
815 // Allow for site and per-namespace customization of copyright notice.
816 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
820 'SkinCopyrightFooter',
821 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
824 return $this->msg( $msg )->rawParams( $link )->text();
828 * @return null|string
830 function getCopyrightIcon() {
831 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
835 if ( $wgFooterIcons['copyright']['copyright'] ) {
836 $out = $wgFooterIcons['copyright']['copyright'];
837 } elseif ( $wgRightsIcon ) {
838 $icon = htmlspecialchars( $wgRightsIcon );
840 if ( $wgRightsUrl ) {
841 $url = htmlspecialchars( $wgRightsUrl );
842 $out .= '<a href="' . $url . '">';
845 $text = htmlspecialchars( $wgRightsText );
846 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
848 if ( $wgRightsUrl ) {
857 * Gets the powered by MediaWiki icon.
860 function getPoweredBy() {
861 global $wgResourceBasePath;
863 $url1 = htmlspecialchars(
864 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
866 $url1_5 = htmlspecialchars(
867 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
869 $url2 = htmlspecialchars(
870 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
872 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
873 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
874 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
875 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
880 * Get the timestamp of the latest revision, formatted in user language
884 protected function lastModified() {
885 $timestamp = $this->getOutput()->getRevisionTimestamp();
887 # No cached timestamp, load it from the database
888 if ( $timestamp === null ) {
889 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
893 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
894 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
895 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
900 if ( wfGetLB()->getLaggedReplicaMode() ) {
901 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
908 * @param string $align
911 function logoText( $align = '' ) {
912 if ( $align != '' ) {
913 $a = " style='float: {$align};'";
918 $mp = $this->msg( 'mainpage' )->escaped();
919 $mptitle = Title
::newMainPage();
920 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
922 $logourl = $this->getLogo();
923 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
929 * Renders a $wgFooterIcons icon according to the method's arguments
930 * @param array $icon The icon to build the html for, see $wgFooterIcons
931 * for the format of this array.
932 * @param bool|string $withImage Whether to use the icon's image or output
933 * a text-only footericon.
934 * @return string HTML
936 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
937 if ( is_string( $icon ) ) {
939 } else { // Assuming array
940 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
941 unset( $icon["url"] );
942 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
943 // do this the lazy way, just pass icon data as an attribute array
944 $html = Html
::element( 'img', $icon );
946 $html = htmlspecialchars( $icon["alt"] );
949 global $wgExternalLinkTarget;
950 $html = Html
::rawElement( 'a',
951 [ "href" => $url, "target" => $wgExternalLinkTarget ],
959 * Gets the link to the wiki's main page.
962 function mainPageLink() {
963 $s = Linker
::linkKnown(
964 Title
::newMainPage(),
965 $this->msg( 'mainpage' )->escaped()
972 * Returns an HTML link for use in the footer
973 * @param string $desc The i18n message key for the link text
974 * @param string $page The i18n message key for the page to link to
975 * @return string HTML anchor
977 public function footerLink( $desc, $page ) {
978 $title = $this->footerLinkTitle( $desc, $page );
983 return Linker
::linkKnown(
985 $this->msg( $desc )->escaped()
990 * @param string $desc
991 * @param string $page
994 private function footerLinkTitle( $desc, $page ) {
995 // If the link description has been set to "-" in the default language,
996 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
997 // then it is disabled, for all languages.
1000 // Otherwise, we display the link for the user, described in their
1001 // language (which may or may not be the same as the default language),
1002 // but we make the link target be the one site-wide page.
1003 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1005 return $title ?
: null;
1009 * Gets the link to the wiki's privacy policy page.
1010 * @return string HTML
1012 function privacyLink() {
1013 return $this->footerLink( 'privacy', 'privacypage' );
1017 * Gets the link to the wiki's about page.
1018 * @return string HTML
1020 function aboutLink() {
1021 return $this->footerLink( 'aboutsite', 'aboutpage' );
1025 * Gets the link to the wiki's general disclaimers page.
1026 * @return string HTML
1028 function disclaimerLink() {
1029 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1033 * Return URL options for the 'edit page' link.
1034 * This may include an 'oldid' specifier, if the current page view is such.
1039 function editUrlOptions() {
1040 $options = [ 'action' => 'edit' ];
1042 if ( !$this->isRevisionCurrent() ) {
1043 $options['oldid'] = intval( $this->getRevisionId() );
1050 * @param User|int $id
1053 function showEmailUser( $id ) {
1054 if ( $id instanceof User
) {
1057 $targetUser = User
::newFromId( $id );
1060 # The sending user must have a confirmed email address and the target
1061 # user must have a confirmed email address and allow emails from users.
1062 return $this->getUser()->canSendEmail() &&
1063 $targetUser->canReceiveEmail();
1067 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1068 * This method returns a url resolved using the configured skin style path
1069 * and includes the style version inside of the url.
1071 * Requires $stylename to be set, otherwise throws MWException.
1073 * @param string $name The name or path of a skin resource file
1074 * @return string The fully resolved style path url including styleversion
1075 * @throws MWException
1077 function getSkinStylePath( $name ) {
1078 global $wgStylePath, $wgStyleVersion;
1080 if ( $this->stylename
=== null ) {
1081 $class = static::class;
1082 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1085 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1088 /* these are used extensively in SkinTemplate, but also some other places */
1091 * @param string $urlaction
1094 static function makeMainPageUrl( $urlaction = '' ) {
1095 $title = Title
::newMainPage();
1096 self
::checkTitle( $title, '' );
1098 return $title->getLocalURL( $urlaction );
1102 * Make a URL for a Special Page using the given query and protocol.
1104 * If $proto is set to null, make a local URL. Otherwise, make a full
1105 * URL with the protocol specified.
1107 * @param string $name Name of the Special page
1108 * @param string $urlaction Query to append
1109 * @param string|null $proto Protocol to use or null for a local URL
1112 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1113 $title = SpecialPage
::getSafeTitleFor( $name );
1114 if ( is_null( $proto ) ) {
1115 return $title->getLocalURL( $urlaction );
1117 return $title->getFullURL( $urlaction, false, $proto );
1122 * @param string $name
1123 * @param string $subpage
1124 * @param string $urlaction
1127 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1128 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1129 return $title->getLocalURL( $urlaction );
1133 * @param string $name
1134 * @param string $urlaction
1137 static function makeI18nUrl( $name, $urlaction = '' ) {
1138 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1139 self
::checkTitle( $title, $name );
1140 return $title->getLocalURL( $urlaction );
1144 * @param string $name
1145 * @param string $urlaction
1148 static function makeUrl( $name, $urlaction = '' ) {
1149 $title = Title
::newFromText( $name );
1150 self
::checkTitle( $title, $name );
1152 return $title->getLocalURL( $urlaction );
1156 * If url string starts with http, consider as external URL, else
1158 * @param string $name
1159 * @return string URL
1161 static function makeInternalOrExternalUrl( $name ) {
1162 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1165 return self
::makeUrl( $name );
1170 * this can be passed the NS number as defined in Language.php
1171 * @param string $name
1172 * @param string $urlaction
1173 * @param int $namespace
1176 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1177 $title = Title
::makeTitleSafe( $namespace, $name );
1178 self
::checkTitle( $title, $name );
1180 return $title->getLocalURL( $urlaction );
1184 * these return an array with the 'href' and boolean 'exists'
1185 * @param string $name
1186 * @param string $urlaction
1189 static function makeUrlDetails( $name, $urlaction = '' ) {
1190 $title = Title
::newFromText( $name );
1191 self
::checkTitle( $title, $name );
1194 'href' => $title->getLocalURL( $urlaction ),
1195 'exists' => $title->isKnown(),
1200 * Make URL details where the article exists (or at least it's convenient to think so)
1201 * @param string $name Article name
1202 * @param string $urlaction
1205 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1206 $title = Title
::newFromText( $name );
1207 self
::checkTitle( $title, $name );
1210 'href' => $title->getLocalURL( $urlaction ),
1216 * make sure we have some title to operate on
1218 * @param Title &$title
1219 * @param string $name
1221 static function checkTitle( &$title, $name ) {
1222 if ( !is_object( $title ) ) {
1223 $title = Title
::newFromText( $name );
1224 if ( !is_object( $title ) ) {
1225 $title = Title
::newFromText( '--error: link target missing--' );
1231 * Build an array that represents the sidebar(s), the navigation bar among them.
1233 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1235 * The format of the returned array is [ heading => content, ... ], where:
1236 * - heading is the heading of a navigation portlet. It is either:
1237 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1238 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1239 * - plain text, which should be HTML-escaped by the skin
1240 * - content is the contents of the portlet. It is either:
1241 * - HTML text (<ul><li>...</li>...</ul>)
1242 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1243 * - (for a magic string as a key, any value)
1245 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1246 * and can technically insert anything in here; skin creators are expected to handle
1247 * values described above.
1251 function buildSidebar() {
1252 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1255 $callback = function () use ( $that ) {
1257 $that->addToSidebar( $bar, 'sidebar' );
1258 Hooks
::run( 'SkinBuildSidebar', [ $that, &$bar ] );
1263 if ( $wgEnableSidebarCache ) {
1264 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1265 $sidebar = $cache->getWithSetCallback(
1266 $cache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1267 MessageCache
::singleton()->isDisabled()
1268 ?
$cache::TTL_UNCACHEABLE
// bug T133069
1269 : $wgSidebarCacheExpiry,
1274 $sidebar = $callback();
1277 // Apply post-processing to the cached value
1278 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1284 * Add content from a sidebar system message
1285 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1287 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1289 * @param array &$bar
1290 * @param string $message
1292 public function addToSidebar( &$bar, $message ) {
1293 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1297 * Add content from plain text
1299 * @param array &$bar
1300 * @param string $text
1303 function addToSidebarPlain( &$bar, $text ) {
1304 $lines = explode( "\n", $text );
1307 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1308 ? Title
::newMainPage() : $this->getTitle();
1310 foreach ( $lines as $line ) {
1311 if ( strpos( $line, '*' ) !== 0 ) {
1314 $line = rtrim( $line, "\r" ); // for Windows compat
1316 if ( strpos( $line, '**' ) !== 0 ) {
1317 $heading = trim( $line, '* ' );
1318 if ( !array_key_exists( $heading, $bar ) ) {
1319 $bar[$heading] = [];
1322 $line = trim( $line, '* ' );
1324 if ( strpos( $line, '|' ) !== false ) { // sanity check
1325 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1326 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1327 if ( count( $line ) !== 2 ) {
1328 // Second sanity check, could be hit by people doing
1329 // funky stuff with parserfuncs... (T35321)
1335 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1336 if ( $msgLink->exists() ) {
1337 $link = $msgLink->text();
1338 if ( $link == '-' ) {
1344 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1345 if ( $msgText->exists() ) {
1346 $text = $msgText->text();
1351 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1354 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1355 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1356 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1357 $extraAttribs['rel'] = 'nofollow';
1360 global $wgExternalLinkTarget;
1361 if ( $wgExternalLinkTarget ) {
1362 $extraAttribs['target'] = $wgExternalLinkTarget;
1365 $title = Title
::newFromText( $link );
1368 $title = $title->fixSpecialName();
1369 $href = $title->getLinkURL();
1371 $href = 'INVALID-TITLE';
1375 $bar[$heading][] = array_merge( [
1378 'id' => Sanitizer
::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1391 * Gets new talk page messages for the current user and returns an
1392 * appropriate alert message (or an empty string if there are no messages)
1395 function getNewtalks() {
1396 $newMessagesAlert = '';
1397 $user = $this->getUser();
1398 $newtalks = $user->getNewMessageLinks();
1399 $out = $this->getOutput();
1401 // Allow extensions to disable or modify the new messages alert
1402 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1405 if ( $newMessagesAlert ) {
1406 return $newMessagesAlert;
1409 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1410 $uTalkTitle = $user->getTalkPage();
1411 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1413 if ( $lastSeenRev !== null ) {
1414 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1415 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1416 if ( $latestRev !== null ) {
1417 // Singular if only 1 unseen revision, plural if several unseen revisions.
1418 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1419 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1420 $lastSeenRev, $latestRev, 10, 'include_new' );
1423 // Singular if no revision -> diff link will show latest change only in any case
1426 $plural = $plural ?
999 : 1;
1427 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1428 // the number of revisions or authors is not necessarily the same as the number of
1430 $newMessagesLink = Linker
::linkKnown(
1432 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1434 [ 'redirect' => 'no' ]
1437 $newMessagesDiffLink = Linker
::linkKnown(
1439 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1441 $lastSeenRev !== null
1442 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1443 : [ 'diff' => 'cur' ]
1446 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1447 $newMessagesAlert = $this->msg(
1448 'youhavenewmessagesfromusers',
1450 $newMessagesDiffLink
1451 )->numParams( $nofAuthors, $plural );
1453 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1454 $newMessagesAlert = $this->msg(
1455 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1457 $newMessagesDiffLink
1458 )->numParams( $plural );
1460 $newMessagesAlert = $newMessagesAlert->text();
1462 $out->setCdnMaxage( 0 );
1463 } elseif ( count( $newtalks ) ) {
1464 $sep = $this->msg( 'newtalkseparator' )->escaped();
1467 foreach ( $newtalks as $newtalk ) {
1468 $msgs[] = Xml
::element(
1470 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1473 $parts = implode( $sep, $msgs );
1474 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1475 $out->setCdnMaxage( 0 );
1478 return $newMessagesAlert;
1482 * Get a cached notice
1484 * @param string $name Message name, or 'default' for $wgSiteNotice
1485 * @return string|bool HTML fragment, or false to indicate that the caller
1486 * should fall back to the next notice in its sequence
1488 private function getCachedNotice( $name ) {
1489 global $wgRenderHashAppend, $wgContLang;
1493 if ( $name === 'default' ) {
1495 global $wgSiteNotice;
1496 $notice = $wgSiteNotice;
1497 if ( empty( $notice ) ) {
1501 $msg = $this->msg( $name )->inContentLanguage();
1502 if ( $msg->isBlank() ) {
1504 } elseif ( $msg->isDisabled() ) {
1507 $notice = $msg->plain();
1510 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
1511 $parsed = $cache->getWithSetCallback(
1512 // Use the extra hash appender to let eg SSL variants separately cache
1513 // Key is verified with md5 hash of unparsed wikitext
1514 $cache->makeKey( $name, $wgRenderHashAppend, md5( $notice ) ),
1517 function () use ( $notice ) {
1518 return $this->getOutput()->parse( $notice );
1522 return Html
::rawElement(
1525 'id' => 'localNotice',
1526 'lang' => $wgContLang->getHtmlCode(),
1527 'dir' => $wgContLang->getDir()
1534 * Get the site notice
1536 * @return string HTML fragment
1538 function getSiteNotice() {
1541 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1542 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1543 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1545 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1546 if ( $anonNotice === false ) {
1547 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1549 $siteNotice = $anonNotice;
1552 if ( $siteNotice === false ) {
1553 $siteNotice = $this->getCachedNotice( 'default' );
1557 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1562 * Create a section edit link. This supersedes editSectionLink() and
1563 * editSectionLinkForOther().
1565 * @param Title $nt The title being linked to (may not be the same as
1566 * the current page, if the section is included from a template)
1567 * @param string $section The designation of the section being pointed to,
1568 * to be included in the link, like "§ion=$section"
1569 * @param string $tooltip The tooltip to use for the link: will be escaped
1570 * and wrapped in the 'editsectionhint' message
1571 * @param string $lang Language code
1572 * @return string HTML to use for edit link
1574 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1575 // HTML generated here should probably have userlangattributes
1576 // added to it for LTR text on RTL pages
1578 $lang = wfGetLangObj( $lang );
1581 if ( !is_null( $tooltip ) ) {
1582 # T27462: undo double-escaping.
1583 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1584 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1585 ->inLanguage( $lang )->text();
1590 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1591 'targetTitle' => $nt,
1592 'attribs' => $attribs,
1593 'query' => [ 'action' => 'edit', 'section' => $section ],
1594 'options' => [ 'noclasses', 'known' ]
1598 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1600 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1603 foreach ( $links as $k => $linkDetails ) {
1604 $linksHtml[] = Linker
::link(
1605 $linkDetails['targetTitle'],
1606 $linkDetails['text'],
1607 $linkDetails['attribs'],
1608 $linkDetails['query'],
1609 $linkDetails['options']
1614 '<span class="mw-editsection-divider">'
1615 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->text()
1620 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1621 // Deprecated, use SkinEditSectionLinks hook instead
1623 'DoEditSectionLink',
1624 [ $this, $nt, $section, $tooltip, &$result, $lang ],