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
24 * @defgroup Skins Skins
28 * The main skin class which provides methods and properties for all other skins.
30 * See docs/skin.txt for more information.
34 abstract class Skin
extends ContextSource
{
35 protected $skinname = null;
36 protected $mRelevantTitle = null;
37 protected $mRelevantUser = null;
40 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
41 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
43 public $stylename = null;
46 * Fetch the set of available skins.
47 * @return array Associative array of strings
49 static function getSkinNames() {
50 return SkinFactory
::getDefaultInstance()->getSkinNames();
54 * Fetch the skinname messages for available skins.
57 static function getSkinNameMessages() {
59 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
60 $messages[] = "skinname-$skinKey";
66 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
67 * Useful for Special:Preferences and other places where you
68 * only want to show skins users _can_ use.
72 public static function getAllowedSkins() {
75 $allowedSkins = self
::getSkinNames();
77 foreach ( $wgSkipSkins as $skip ) {
78 unset( $allowedSkins[$skip] );
85 * Normalize a skin preference value to a form that can be loaded.
87 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
88 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
90 * @param string $key 'monobook', 'vector', etc.
93 static function normalizeKey( $key ) {
94 global $wgDefaultSkin, $wgFallbackSkin;
96 $skinNames = Skin
::getSkinNames();
98 // Make keys lowercase for case-insensitive matching.
99 $skinNames = array_change_key_case( $skinNames, CASE_LOWER
);
100 $key = strtolower( $key );
101 $defaultSkin = strtolower( $wgDefaultSkin );
102 $fallbackSkin = strtolower( $wgFallbackSkin );
104 if ( $key == '' ||
$key == 'default' ) {
105 // Don't return the default immediately;
106 // in a misconfiguration we need to fall back.
110 if ( isset( $skinNames[$key] ) ) {
114 // Older versions of the software used a numeric setting
115 // in the user preferences.
121 if ( isset( $fallback[$key] ) ) {
122 $key = $fallback[$key];
125 if ( isset( $skinNames[$key] ) ) {
127 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
130 return $fallbackSkin;
135 * @return string Skin name
137 public function getSkinName() {
138 return $this->skinname
;
142 * @param OutputPage $out
144 public function initPage( OutputPage
$out ) {
145 $this->preloadExistence();
149 * Defines the ResourceLoader modules that should be added to the skin
150 * It is recommended that skins wishing to override call parent::getDefaultModules()
151 * and substitute out any modules they wish to change by using a key to look them up
153 * For style modules, use setupSkinUserCss() instead.
155 * @return array Array of modules with helper keys for easy overriding
157 public function getDefaultModules() {
158 global $wgUseAjax, $wgEnableAPI, $wgEnableWriteAPI;
160 $out = $this->getOutput();
161 $user = $out->getUser();
163 // modules that enhance the page content in some way
165 'mediawiki.page.ready',
167 // modules that exist for legacy reasons
168 'legacy' => ResourceLoaderStartUpModule
::getLegacyModules(),
169 // modules relating to search functionality
171 // modules relating to functionality relating to watching an article
173 // modules which relate to the current users preferences
177 // Preload jquery.tablesorter for mediawiki.page.ready
178 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
179 $modules['content'][] = 'jquery.tablesorter';
182 // Preload jquery.makeCollapsible for mediawiki.page.ready
183 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
184 $modules['content'][] = 'jquery.makeCollapsible';
187 // Add various resources if required
188 if ( $wgUseAjax && $wgEnableAPI ) {
189 if ( $wgEnableWriteAPI && $user->isLoggedIn()
190 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
191 && $this->getRelevantTitle()->canExist()
193 $modules['watch'][] = 'mediawiki.page.watch.ajax';
196 $modules['search'][] = 'mediawiki.searchSuggest';
199 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
200 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
203 // Crazy edit-on-double-click stuff
204 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
205 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
211 * Preload the existence of three commonly-requested pages in a single query
213 protected function preloadExistence() {
217 $user = $this->getUser();
218 if ( $user->isLoggedIn() ) {
219 $titles[] = $user->getUserPage();
220 $titles[] = $user->getTalkPage();
223 // Check, if the page can hold some kind of content, otherwise do nothing
224 $title = $this->getRelevantTitle();
225 if ( $title->canExist() ) {
226 if ( $title->isTalkPage() ) {
227 $titles[] = $title->getSubjectPage();
229 $titles[] = $title->getTalkPage();
233 // Footer links (used by SkinTemplate::prepareQuickTemplate)
235 $this->footerLinkTitle( 'privacy', 'privacypage' ),
236 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
237 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
244 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
247 $lb = new LinkBatch( $titles );
248 $lb->setCaller( __METHOD__
);
254 * Get the current revision ID
258 public function getRevisionId() {
259 return $this->getOutput()->getRevisionId();
263 * Whether the revision displayed is the latest revision of the page
267 public function isRevisionCurrent() {
268 $revID = $this->getRevisionId();
269 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
273 * Set the "relevant" title
274 * @see self::getRelevantTitle()
277 public function setRelevantTitle( $t ) {
278 $this->mRelevantTitle
= $t;
282 * Return the "relevant" title.
283 * A "relevant" title is not necessarily the actual title of the page.
284 * Special pages like Special:MovePage use set the page they are acting on
285 * as their "relevant" title, this allows the skin system to display things
286 * such as content tabs which belong to to that page instead of displaying
287 * a basic special page tab which has almost no meaning.
291 public function getRelevantTitle() {
292 if ( isset( $this->mRelevantTitle
) ) {
293 return $this->mRelevantTitle
;
295 return $this->getTitle();
299 * Set the "relevant" user
300 * @see self::getRelevantUser()
303 public function setRelevantUser( $u ) {
304 $this->mRelevantUser
= $u;
308 * Return the "relevant" user.
309 * A "relevant" user is similar to a relevant title. Special pages like
310 * Special:Contributions mark the user which they are relevant to so that
311 * things like the toolbox can display the information they usually are only
312 * able to display on a user's userpage and talkpage.
315 public function getRelevantUser() {
316 if ( isset( $this->mRelevantUser
) ) {
317 return $this->mRelevantUser
;
319 $title = $this->getRelevantTitle();
320 if ( $title->hasSubjectNamespace( NS_USER
) ) {
321 $rootUser = $title->getRootText();
322 if ( User
::isIP( $rootUser ) ) {
323 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
325 $user = User
::newFromName( $rootUser, false );
328 $user->load( User
::READ_NORMAL
);
330 if ( $user->isLoggedIn() ) {
331 $this->mRelevantUser
= $user;
335 return $this->mRelevantUser
;
341 * Outputs the HTML generated by other functions.
342 * @param OutputPage $out
344 abstract function outputPage( OutputPage
$out = null );
350 static function makeVariablesScript( $data ) {
352 return ResourceLoader
::makeInlineScript(
353 ResourceLoader
::makeConfigSetScript( $data )
361 * Get the query to generate a dynamic stylesheet
365 public static function getDynamicStylesheetQuery() {
366 global $wgSquidMaxage;
370 'maxage' => $wgSquidMaxage,
371 'usemsgcache' => 'yes',
372 'ctype' => 'text/css',
373 'smaxage' => $wgSquidMaxage,
378 * Add skin specific stylesheets
379 * Calling this method with an $out of anything but the same OutputPage
380 * inside ->getOutput() is deprecated. The $out arg is kept
381 * for compatibility purposes with skins.
382 * @param OutputPage $out
385 abstract function setupSkinUserCss( OutputPage
$out );
389 * @param Title $title
392 function getPageClasses( $title ) {
393 $numeric = 'ns-' . $title->getNamespace();
395 if ( $title->isSpecialPage() ) {
396 $type = 'ns-special';
397 // T25315: provide a class based on the canonical special page name without subpages
398 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
399 if ( $canonicalName ) {
400 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
402 $type .= ' mw-invalidspecialpage';
404 } elseif ( $title->isTalkPage() ) {
407 $type = 'ns-subject';
410 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
411 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
413 return "$numeric $type $name $root";
417 * Return values for <html> element
418 * @return array Array of associative name-to-value elements for <html> element
420 public function getHtmlElementAttributes() {
421 $lang = $this->getLanguage();
423 'lang' => $lang->getHtmlCode(),
424 'dir' => $lang->getDir(),
425 'class' => 'client-nojs',
430 * This will be called by OutputPage::headElement when it is creating the
431 * "<body>" tag, skins can override it if they have a need to add in any
432 * body attributes or classes of their own.
433 * @param OutputPage $out
434 * @param array $bodyAttrs
436 function addToBodyAttributes( $out, &$bodyAttrs ) {
437 // does nothing by default
450 * @return string HTML
452 function getCategoryLinks() {
453 global $wgUseCategoryBrowser;
455 $out = $this->getOutput();
456 $allCats = $out->getCategoryLinks();
458 if ( !count( $allCats ) ) {
466 $colon = $this->msg( 'colon-separator' )->escaped();
468 if ( !empty( $allCats['normal'] ) ) {
469 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
471 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
472 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
473 $title = Title
::newFromText( $linkPage );
474 $link = $title ? Linker
::link( $title, $msg ) : $msg;
475 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
476 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
480 if ( isset( $allCats['hidden'] ) ) {
481 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
482 $class = ' mw-hidden-cats-user-shown';
483 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
484 $class = ' mw-hidden-cats-ns-shown';
486 $class = ' mw-hidden-cats-hidden';
489 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
490 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
491 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
495 # optional 'dmoz-like' category browser. Will be shown under the list
496 # of categories an article belong to
497 if ( $wgUseCategoryBrowser ) {
498 $s .= '<br /><hr />';
500 # get a big array of the parents tree
501 $parenttree = $this->getTitle()->getParentCategoryTree();
502 # Skin object passed by reference cause it can not be
503 # accessed under the method subfunction drawCategoryBrowser
504 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
505 # Clean out bogus first entry and sort them
506 unset( $tempout[0] );
508 # Output one per line
509 $s .= implode( "<br />\n", $tempout );
516 * Render the array as a series of links.
517 * @param array $tree Categories tree returned by Title::getParentCategoryTree
518 * @return string Separated by >, terminate with "\n"
520 function drawCategoryBrowser( $tree ) {
523 foreach ( $tree as $element => $parent ) {
524 if ( empty( $parent ) ) {
525 # element start a new list
528 # grab the others elements
529 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
532 # add our current element to the list
533 $eltitle = Title
::newFromText( $element );
534 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
541 * @return string HTML
543 function getCategories() {
544 $out = $this->getOutput();
545 $catlinks = $this->getCategoryLinks();
547 // Check what we're showing
548 $allCats = $out->getCategoryLinks();
549 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
550 $this->getTitle()->getNamespace() == NS_CATEGORY
;
552 $classes = [ 'catlinks' ];
553 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
554 $classes[] = 'catlinks-allhidden';
557 return Html
::rawElement(
559 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
565 * This runs a hook to allow extensions placing their stuff after content
566 * and article metadata (e.g. categories).
567 * Note: This function has nothing to do with afterContent().
569 * This hook is placed here in order to allow using the same hook for all
570 * skins, both the SkinTemplate based ones and the older ones, which directly
571 * use this class to get their data.
573 * The output of this function gets processed in SkinTemplate::outputPage() for
574 * the SkinTemplate based skins, all other skins should directly echo it.
576 * @return string Empty by default, if not changed by any hook function.
578 protected function afterContentHook() {
581 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
582 // adding just some spaces shouldn't toggle the output
583 // of the whole <div/>, so we use trim() here
584 if ( trim( $data ) != '' ) {
585 // Doing this here instead of in the skins to
586 // ensure that the div has the same ID in all
588 $data = "<div id='mw-data-after-content'>\n" .
593 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
600 * Generate debug data HTML for displaying at the bottom of the main content
602 * @return string HTML containing debug data, if enabled (otherwise empty).
604 protected function generateDebugHTML() {
605 return MWDebug
::getHTMLDebugLog();
609 * This gets called shortly before the "</body>" tag.
611 * @return string HTML-wrapped JS code to be put before "</body>"
613 function bottomScripts() {
614 // TODO and the suckage continues. This function is really just a wrapper around
615 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
617 $bottomScriptText = $this->getOutput()->getBottomScripts();
618 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$bottomScriptText ] );
620 return $bottomScriptText;
624 * Text with the permalink to the source page,
625 * usually shown on the footer of a printed page
627 * @return string HTML text with an URL
629 function printSource() {
630 $oldid = $this->getRevisionId();
632 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
633 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
635 // oldid not available for non existing pages
636 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
639 return $this->msg( 'retrievedfrom' )
640 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
645 * @return string HTML
647 function getUndeleteLink() {
648 $action = $this->getRequest()->getVal( 'action', 'view' );
650 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
651 ( !$this->getTitle()->exists() ||
$action == 'history' ) ) {
652 $n = $this->getTitle()->isDeleted();
655 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
656 $msg = 'thisisdeleted';
658 $msg = 'viewdeleted';
661 return $this->msg( $msg )->rawParams(
663 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
664 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
673 * @param OutputPage $out Defaults to $this->getOutput() if left as null
676 function subPageSubtitle( $out = null ) {
677 if ( $out === null ) {
678 $out = $this->getOutput();
680 $title = $out->getTitle();
683 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
687 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
688 $ptext = $title->getPrefixedText();
689 if ( strpos( $ptext, '/' ) !== false ) {
690 $links = explode( '/', $ptext );
695 $lang = $this->getLanguage();
697 foreach ( $links as $link ) {
698 $growinglink .= $link;
700 $linkObj = Title
::newFromText( $growinglink );
702 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
703 $getlink = Linker
::linkKnown(
705 htmlspecialchars( $display )
711 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
713 $subpages .= '< ';
716 $subpages .= $getlink;
730 * @deprecated since 1.27, feature removed
731 * @return bool Always false
733 function showIPinHeader() {
734 wfDeprecated( __METHOD__
, '1.27' );
741 function getSearchLink() {
742 $searchPage = SpecialPage
::getTitleFor( 'Search' );
743 return $searchPage->getLocalURL();
749 function escapeSearchLink() {
750 return htmlspecialchars( $this->getSearchLink() );
754 * @param string $type
757 function getCopyright( $type = 'detect' ) {
758 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
760 if ( $type == 'detect' ) {
761 if ( !$this->isRevisionCurrent()
762 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
770 if ( $type == 'history' ) {
771 $msg = 'history_copyright';
776 if ( $wgRightsPage ) {
777 $title = Title
::newFromText( $wgRightsPage );
778 $link = Linker
::linkKnown( $title, $wgRightsText );
779 } elseif ( $wgRightsUrl ) {
780 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
781 } elseif ( $wgRightsText ) {
782 $link = $wgRightsText;
788 // Allow for site and per-namespace customization of copyright notice.
789 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
793 'SkinCopyrightFooter',
794 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
797 return $this->msg( $msg )->rawParams( $link )->text();
801 * @return null|string
803 function getCopyrightIcon() {
804 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
808 if ( $wgFooterIcons['copyright']['copyright'] ) {
809 $out = $wgFooterIcons['copyright']['copyright'];
810 } elseif ( $wgRightsIcon ) {
811 $icon = htmlspecialchars( $wgRightsIcon );
813 if ( $wgRightsUrl ) {
814 $url = htmlspecialchars( $wgRightsUrl );
815 $out .= '<a href="' . $url . '">';
818 $text = htmlspecialchars( $wgRightsText );
819 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
821 if ( $wgRightsUrl ) {
830 * Gets the powered by MediaWiki icon.
833 function getPoweredBy() {
834 global $wgResourceBasePath;
836 $url1 = htmlspecialchars(
837 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
839 $url1_5 = htmlspecialchars(
840 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
842 $url2 = htmlspecialchars(
843 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
845 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
846 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
847 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
848 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
853 * Get the timestamp of the latest revision, formatted in user language
857 protected function lastModified() {
858 $timestamp = $this->getOutput()->getRevisionTimestamp();
860 # No cached timestamp, load it from the database
861 if ( $timestamp === null ) {
862 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
866 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
867 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
868 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
873 if ( wfGetLB()->getLaggedReplicaMode() ) {
874 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
881 * @param string $align
884 function logoText( $align = '' ) {
885 if ( $align != '' ) {
886 $a = " style='float: {$align};'";
891 $mp = $this->msg( 'mainpage' )->escaped();
892 $mptitle = Title
::newMainPage();
893 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
895 $logourl = $this->getLogo();
896 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
902 * Renders a $wgFooterIcons icon according to the method's arguments
903 * @param array $icon The icon to build the html for, see $wgFooterIcons
904 * for the format of this array.
905 * @param bool|string $withImage Whether to use the icon's image or output
906 * a text-only footericon.
907 * @return string HTML
909 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
910 if ( is_string( $icon ) ) {
912 } else { // Assuming array
913 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
914 unset( $icon["url"] );
915 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
916 // do this the lazy way, just pass icon data as an attribute array
917 $html = Html
::element( 'img', $icon );
919 $html = htmlspecialchars( $icon["alt"] );
922 global $wgExternalLinkTarget;
923 $html = Html
::rawElement( 'a',
924 [ "href" => $url, "target" => $wgExternalLinkTarget ],
932 * Gets the link to the wiki's main page.
935 function mainPageLink() {
936 $s = Linker
::linkKnown(
937 Title
::newMainPage(),
938 $this->msg( 'mainpage' )->escaped()
945 * Returns an HTML link for use in the footer
946 * @param string $desc The i18n message key for the link text
947 * @param string $page The i18n message key for the page to link to
948 * @return string HTML anchor
950 public function footerLink( $desc, $page ) {
951 $title = $this->footerLinkTitle( $desc, $page );
956 return Linker
::linkKnown(
958 $this->msg( $desc )->escaped()
963 * @param string $desc
964 * @param string $page
967 private function footerLinkTitle( $desc, $page ) {
968 // If the link description has been set to "-" in the default language,
969 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
970 // then it is disabled, for all languages.
973 // Otherwise, we display the link for the user, described in their
974 // language (which may or may not be the same as the default language),
975 // but we make the link target be the one site-wide page.
976 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
978 return $title ?
: null;
982 * Gets the link to the wiki's privacy policy page.
983 * @return string HTML
985 function privacyLink() {
986 return $this->footerLink( 'privacy', 'privacypage' );
990 * Gets the link to the wiki's about page.
991 * @return string HTML
993 function aboutLink() {
994 return $this->footerLink( 'aboutsite', 'aboutpage' );
998 * Gets the link to the wiki's general disclaimers page.
999 * @return string HTML
1001 function disclaimerLink() {
1002 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1006 * Return URL options for the 'edit page' link.
1007 * This may include an 'oldid' specifier, if the current page view is such.
1012 function editUrlOptions() {
1013 $options = [ 'action' => 'edit' ];
1015 if ( !$this->isRevisionCurrent() ) {
1016 $options['oldid'] = intval( $this->getRevisionId() );
1023 * @param User|int $id
1026 function showEmailUser( $id ) {
1027 if ( $id instanceof User
) {
1030 $targetUser = User
::newFromId( $id );
1033 # The sending user must have a confirmed email address and the target
1034 # user must have a confirmed email address and allow emails from users.
1035 return $this->getUser()->canSendEmail() &&
1036 $targetUser->canReceiveEmail();
1040 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1041 * This method returns a url resolved using the configured skin style path
1042 * and includes the style version inside of the url.
1044 * Requires $stylename to be set, otherwise throws MWException.
1046 * @param string $name The name or path of a skin resource file
1047 * @return string The fully resolved style path url including styleversion
1048 * @throws MWException
1050 function getSkinStylePath( $name ) {
1051 global $wgStylePath, $wgStyleVersion;
1053 if ( $this->stylename
=== null ) {
1054 $class = static::class;
1055 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1058 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1061 /* these are used extensively in SkinTemplate, but also some other places */
1064 * @param string $urlaction
1067 static function makeMainPageUrl( $urlaction = '' ) {
1068 $title = Title
::newMainPage();
1069 self
::checkTitle( $title, '' );
1071 return $title->getLocalURL( $urlaction );
1075 * Make a URL for a Special Page using the given query and protocol.
1077 * If $proto is set to null, make a local URL. Otherwise, make a full
1078 * URL with the protocol specified.
1080 * @param string $name Name of the Special page
1081 * @param string $urlaction Query to append
1082 * @param string|null $proto Protocol to use or null for a local URL
1085 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1086 $title = SpecialPage
::getSafeTitleFor( $name );
1087 if ( is_null( $proto ) ) {
1088 return $title->getLocalURL( $urlaction );
1090 return $title->getFullURL( $urlaction, false, $proto );
1095 * @param string $name
1096 * @param string $subpage
1097 * @param string $urlaction
1100 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1101 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1102 return $title->getLocalURL( $urlaction );
1106 * @param string $name
1107 * @param string $urlaction
1110 static function makeI18nUrl( $name, $urlaction = '' ) {
1111 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1112 self
::checkTitle( $title, $name );
1113 return $title->getLocalURL( $urlaction );
1117 * @param string $name
1118 * @param string $urlaction
1121 static function makeUrl( $name, $urlaction = '' ) {
1122 $title = Title
::newFromText( $name );
1123 self
::checkTitle( $title, $name );
1125 return $title->getLocalURL( $urlaction );
1129 * If url string starts with http, consider as external URL, else
1131 * @param string $name
1132 * @return string URL
1134 static function makeInternalOrExternalUrl( $name ) {
1135 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1138 return self
::makeUrl( $name );
1143 * this can be passed the NS number as defined in Language.php
1144 * @param string $name
1145 * @param string $urlaction
1146 * @param int $namespace
1149 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1150 $title = Title
::makeTitleSafe( $namespace, $name );
1151 self
::checkTitle( $title, $name );
1153 return $title->getLocalURL( $urlaction );
1157 * these return an array with the 'href' and boolean 'exists'
1158 * @param string $name
1159 * @param string $urlaction
1162 static function makeUrlDetails( $name, $urlaction = '' ) {
1163 $title = Title
::newFromText( $name );
1164 self
::checkTitle( $title, $name );
1167 'href' => $title->getLocalURL( $urlaction ),
1168 'exists' => $title->isKnown(),
1173 * Make URL details where the article exists (or at least it's convenient to think so)
1174 * @param string $name Article name
1175 * @param string $urlaction
1178 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1179 $title = Title
::newFromText( $name );
1180 self
::checkTitle( $title, $name );
1183 'href' => $title->getLocalURL( $urlaction ),
1189 * make sure we have some title to operate on
1191 * @param Title $title
1192 * @param string $name
1194 static function checkTitle( &$title, $name ) {
1195 if ( !is_object( $title ) ) {
1196 $title = Title
::newFromText( $name );
1197 if ( !is_object( $title ) ) {
1198 $title = Title
::newFromText( '--error: link target missing--' );
1204 * Build an array that represents the sidebar(s), the navigation bar among them.
1206 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1208 * The format of the returned array is [ heading => content, ... ], where:
1209 * - heading is the heading of a navigation portlet. It is either:
1210 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1211 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1212 * - plain text, which should be HTML-escaped by the skin
1213 * - content is the contents of the portlet. It is either:
1214 * - HTML text (<ul><li>...</li>...</ul>)
1215 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1216 * - (for a magic string as a key, any value)
1218 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1219 * and can technically insert anything in here; skin creators are expected to handle
1220 * values described above.
1224 function buildSidebar() {
1225 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1228 $callback = function () use ( $that ) {
1230 $that->addToSidebar( $bar, 'sidebar' );
1231 Hooks
::run( 'SkinBuildSidebar', [ $that, &$bar ] );
1236 if ( $wgEnableSidebarCache ) {
1237 $cache = ObjectCache
::getMainWANInstance();
1238 $sidebar = $cache->getWithSetCallback(
1239 $cache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1240 MessageCache
::singleton()->isDisabled()
1241 ?
$cache::TTL_UNCACHEABLE
// bug T133069
1242 : $wgSidebarCacheExpiry,
1247 $sidebar = $callback();
1250 // Apply post-processing to the cached value
1251 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1257 * Add content from a sidebar system message
1258 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1260 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1263 * @param string $message
1265 public function addToSidebar( &$bar, $message ) {
1266 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1270 * Add content from plain text
1273 * @param string $text
1276 function addToSidebarPlain( &$bar, $text ) {
1277 $lines = explode( "\n", $text );
1280 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1281 ? Title
::newMainPage() : $this->getTitle();
1283 foreach ( $lines as $line ) {
1284 if ( strpos( $line, '*' ) !== 0 ) {
1287 $line = rtrim( $line, "\r" ); // for Windows compat
1289 if ( strpos( $line, '**' ) !== 0 ) {
1290 $heading = trim( $line, '* ' );
1291 if ( !array_key_exists( $heading, $bar ) ) {
1292 $bar[$heading] = [];
1295 $line = trim( $line, '* ' );
1297 if ( strpos( $line, '|' ) !== false ) { // sanity check
1298 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1299 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1300 if ( count( $line ) !== 2 ) {
1301 // Second sanity check, could be hit by people doing
1302 // funky stuff with parserfuncs... (T35321)
1308 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1309 if ( $msgLink->exists() ) {
1310 $link = $msgLink->text();
1311 if ( $link == '-' ) {
1317 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1318 if ( $msgText->exists() ) {
1319 $text = $msgText->text();
1324 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1327 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1328 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1329 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1330 $extraAttribs['rel'] = 'nofollow';
1333 global $wgExternalLinkTarget;
1334 if ( $wgExternalLinkTarget ) {
1335 $extraAttribs['target'] = $wgExternalLinkTarget;
1338 $title = Title
::newFromText( $link );
1341 $title = $title->fixSpecialName();
1342 $href = $title->getLinkURL();
1344 $href = 'INVALID-TITLE';
1348 $bar[$heading][] = array_merge( [
1351 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1364 * Gets new talk page messages for the current user and returns an
1365 * appropriate alert message (or an empty string if there are no messages)
1368 function getNewtalks() {
1370 $newMessagesAlert = '';
1371 $user = $this->getUser();
1372 $newtalks = $user->getNewMessageLinks();
1373 $out = $this->getOutput();
1375 // Allow extensions to disable or modify the new messages alert
1376 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1379 if ( $newMessagesAlert ) {
1380 return $newMessagesAlert;
1383 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1384 $uTalkTitle = $user->getTalkPage();
1385 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1387 if ( $lastSeenRev !== null ) {
1388 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1389 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1390 if ( $latestRev !== null ) {
1391 // Singular if only 1 unseen revision, plural if several unseen revisions.
1392 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1393 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1394 $lastSeenRev, $latestRev, 10, 'include_new' );
1397 // Singular if no revision -> diff link will show latest change only in any case
1400 $plural = $plural ?
999 : 1;
1401 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1402 // the number of revisions or authors is not necessarily the same as the number of
1404 $newMessagesLink = Linker
::linkKnown(
1406 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1408 [ 'redirect' => 'no' ]
1411 $newMessagesDiffLink = Linker
::linkKnown(
1413 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1415 $lastSeenRev !== null
1416 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1417 : [ 'diff' => 'cur' ]
1420 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1421 $newMessagesAlert = $this->msg(
1422 'youhavenewmessagesfromusers',
1424 $newMessagesDiffLink
1425 )->numParams( $nofAuthors, $plural );
1427 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1428 $newMessagesAlert = $this->msg(
1429 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1431 $newMessagesDiffLink
1432 )->numParams( $plural );
1434 $newMessagesAlert = $newMessagesAlert->text();
1436 $out->setCdnMaxage( 0 );
1437 } elseif ( count( $newtalks ) ) {
1438 $sep = $this->msg( 'newtalkseparator' )->escaped();
1441 foreach ( $newtalks as $newtalk ) {
1442 $msgs[] = Xml
::element(
1444 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1447 $parts = implode( $sep, $msgs );
1448 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1449 $out->setCdnMaxage( 0 );
1452 return $newMessagesAlert;
1456 * Get a cached notice
1458 * @param string $name Message name, or 'default' for $wgSiteNotice
1459 * @return string|bool HTML fragment, or false to indicate that the caller
1460 * should fall back to the next notice in its sequence
1462 private function getCachedNotice( $name ) {
1463 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1467 if ( $name === 'default' ) {
1469 global $wgSiteNotice;
1470 $notice = $wgSiteNotice;
1471 if ( empty( $notice ) ) {
1475 $msg = $this->msg( $name )->inContentLanguage();
1476 if ( $msg->isBlank() ) {
1478 } elseif ( $msg->isDisabled() ) {
1481 $notice = $msg->plain();
1484 // Use the extra hash appender to let eg SSL variants separately cache.
1485 $key = wfMemcKey( $name . $wgRenderHashAppend );
1486 $cachedNotice = $parserMemc->get( $key );
1487 if ( is_array( $cachedNotice ) ) {
1488 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1489 $notice = $cachedNotice['html'];
1498 $parsed = $this->getOutput()->parse( $notice );
1499 $parserMemc->set( $key, [ 'html' => $parsed, 'hash' => md5( $notice ) ], 600 );
1503 $notice = Html
::rawElement( 'div', [ 'id' => 'localNotice',
1504 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ], $notice );
1509 * Get the site notice
1511 * @return string HTML fragment
1513 function getSiteNotice() {
1516 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1517 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1518 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1520 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1521 if ( $anonNotice === false ) {
1522 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1524 $siteNotice = $anonNotice;
1527 if ( $siteNotice === false ) {
1528 $siteNotice = $this->getCachedNotice( 'default' );
1532 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1537 * Create a section edit link. This supersedes editSectionLink() and
1538 * editSectionLinkForOther().
1540 * @param Title $nt The title being linked to (may not be the same as
1541 * the current page, if the section is included from a template)
1542 * @param string $section The designation of the section being pointed to,
1543 * to be included in the link, like "§ion=$section"
1544 * @param string $tooltip The tooltip to use for the link: will be escaped
1545 * and wrapped in the 'editsectionhint' message
1546 * @param string $lang Language code
1547 * @return string HTML to use for edit link
1549 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1550 // HTML generated here should probably have userlangattributes
1551 // added to it for LTR text on RTL pages
1553 $lang = wfGetLangObj( $lang );
1556 if ( !is_null( $tooltip ) ) {
1557 # T27462: undo double-escaping.
1558 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1559 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1560 ->inLanguage( $lang )->text();
1565 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1566 'targetTitle' => $nt,
1567 'attribs' => $attribs,
1568 'query' => [ 'action' => 'edit', 'section' => $section ],
1569 'options' => [ 'noclasses', 'known' ]
1573 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1575 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1578 foreach ( $links as $k => $linkDetails ) {
1579 $linksHtml[] = Linker
::link(
1580 $linkDetails['targetTitle'],
1581 $linkDetails['text'],
1582 $linkDetails['attribs'],
1583 $linkDetails['query'],
1584 $linkDetails['options']
1589 '<span class="mw-editsection-divider">'
1590 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->text()
1595 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1596 // Deprecated, use SkinEditSectionLinks hook instead
1598 'DoEditSectionLink',
1599 [ $this, $nt, $section, $tooltip, &$result, $lang ],