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
152 * @return array Array of modules with helper keys for easy overriding
154 public function getDefaultModules() {
155 global $wgUseAjax, $wgEnableAPI, $wgEnableWriteAPI;
157 $out = $this->getOutput();
158 $user = $out->getUser();
160 // modules that enhance the page content in some way
162 'mediawiki.page.ready',
164 // modules that exist for legacy reasons
165 'legacy' => ResourceLoaderStartUpModule
::getLegacyModules(),
166 // modules relating to search functionality
168 // modules relating to functionality relating to watching an article
170 // modules which relate to the current users preferences
174 // Add various resources if required
175 if ( $wgUseAjax && $wgEnableAPI ) {
176 if ( $wgEnableWriteAPI && $user->isLoggedIn()
177 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
178 && $this->getRelevantTitle()->canExist()
180 $modules['watch'][] = 'mediawiki.page.watch.ajax';
183 $modules['search'][] = 'mediawiki.searchSuggest';
186 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
187 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
190 // Crazy edit-on-double-click stuff
191 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
192 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
198 * Preload the existence of three commonly-requested pages in a single query
200 protected function preloadExistence() {
204 $user = $this->getUser();
205 if ( $user->isLoggedIn() ) {
206 $titles[] = $user->getUserPage();
207 $titles[] = $user->getTalkPage();
210 // Check, if the page can hold some kind of content, otherwise do nothing
211 $title = $this->getRelevantTitle();
212 if ( $title->canExist() ) {
213 if ( $title->isTalkPage() ) {
214 $titles[] = $title->getSubjectPage();
216 $titles[] = $title->getTalkPage();
220 // Footer links (used by SkinTemplate::prepareQuickTemplate)
222 $this->footerLinkTitle( 'privacy', 'privacypage' ),
223 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
224 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
231 Hooks
::run( 'SkinPreloadExistence', [ &$titles, $this ] );
234 $lb = new LinkBatch( $titles );
235 $lb->setCaller( __METHOD__
);
241 * Get the current revision ID
245 public function getRevisionId() {
246 return $this->getOutput()->getRevisionId();
250 * Whether the revision displayed is the latest revision of the page
254 public function isRevisionCurrent() {
255 $revID = $this->getRevisionId();
256 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
260 * Set the "relevant" title
261 * @see self::getRelevantTitle()
264 public function setRelevantTitle( $t ) {
265 $this->mRelevantTitle
= $t;
269 * Return the "relevant" title.
270 * A "relevant" title is not necessarily the actual title of the page.
271 * Special pages like Special:MovePage use set the page they are acting on
272 * as their "relevant" title, this allows the skin system to display things
273 * such as content tabs which belong to to that page instead of displaying
274 * a basic special page tab which has almost no meaning.
278 public function getRelevantTitle() {
279 if ( isset( $this->mRelevantTitle
) ) {
280 return $this->mRelevantTitle
;
282 return $this->getTitle();
286 * Set the "relevant" user
287 * @see self::getRelevantUser()
290 public function setRelevantUser( $u ) {
291 $this->mRelevantUser
= $u;
295 * Return the "relevant" user.
296 * A "relevant" user is similar to a relevant title. Special pages like
297 * Special:Contributions mark the user which they are relevant to so that
298 * things like the toolbox can display the information they usually are only
299 * able to display on a user's userpage and talkpage.
302 public function getRelevantUser() {
303 if ( isset( $this->mRelevantUser
) ) {
304 return $this->mRelevantUser
;
306 $title = $this->getRelevantTitle();
307 if ( $title->hasSubjectNamespace( NS_USER
) ) {
308 $rootUser = $title->getRootText();
309 if ( User
::isIP( $rootUser ) ) {
310 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
312 $user = User
::newFromName( $rootUser, false );
315 $user->load( User
::READ_NORMAL
);
317 if ( $user->isLoggedIn() ) {
318 $this->mRelevantUser
= $user;
322 return $this->mRelevantUser
;
328 * Outputs the HTML generated by other functions.
329 * @param OutputPage $out
331 abstract function outputPage( OutputPage
$out = null );
337 static function makeVariablesScript( $data ) {
339 return ResourceLoader
::makeInlineScript(
340 ResourceLoader
::makeConfigSetScript( $data )
348 * Get the query to generate a dynamic stylesheet
352 public static function getDynamicStylesheetQuery() {
353 global $wgSquidMaxage;
357 'maxage' => $wgSquidMaxage,
358 'usemsgcache' => 'yes',
359 'ctype' => 'text/css',
360 'smaxage' => $wgSquidMaxage,
365 * Add skin specific stylesheets
366 * Calling this method with an $out of anything but the same OutputPage
367 * inside ->getOutput() is deprecated. The $out arg is kept
368 * for compatibility purposes with skins.
369 * @param OutputPage $out
372 abstract function setupSkinUserCss( OutputPage
$out );
376 * @param Title $title
379 function getPageClasses( $title ) {
380 $numeric = 'ns-' . $title->getNamespace();
382 if ( $title->isSpecialPage() ) {
383 $type = 'ns-special';
384 // bug 23315: provide a class based on the canonical special page name without subpages
385 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
386 if ( $canonicalName ) {
387 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
389 $type .= ' mw-invalidspecialpage';
391 } elseif ( $title->isTalkPage() ) {
394 $type = 'ns-subject';
397 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
398 $root = Sanitizer
::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
400 return "$numeric $type $name $root";
404 * Return values for <html> element
405 * @return array Array of associative name-to-value elements for <html> element
407 public function getHtmlElementAttributes() {
408 $lang = $this->getLanguage();
410 'lang' => $lang->getHtmlCode(),
411 'dir' => $lang->getDir(),
412 'class' => 'client-nojs',
417 * This will be called by OutputPage::headElement when it is creating the
418 * "<body>" tag, skins can override it if they have a need to add in any
419 * body attributes or classes of their own.
420 * @param OutputPage $out
421 * @param array $bodyAttrs
423 function addToBodyAttributes( $out, &$bodyAttrs ) {
424 // does nothing by default
437 * @return string HTML
439 function getCategoryLinks() {
440 global $wgUseCategoryBrowser;
442 $out = $this->getOutput();
443 $allCats = $out->getCategoryLinks();
445 if ( !count( $allCats ) ) {
453 $colon = $this->msg( 'colon-separator' )->escaped();
455 if ( !empty( $allCats['normal'] ) ) {
456 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
458 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
459 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
460 $title = Title
::newFromText( $linkPage );
461 $link = $title ? Linker
::link( $title, $msg ) : $msg;
462 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
463 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
467 if ( isset( $allCats['hidden'] ) ) {
468 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
469 $class = ' mw-hidden-cats-user-shown';
470 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
471 $class = ' mw-hidden-cats-ns-shown';
473 $class = ' mw-hidden-cats-hidden';
476 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
477 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
478 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
482 # optional 'dmoz-like' category browser. Will be shown under the list
483 # of categories an article belong to
484 if ( $wgUseCategoryBrowser ) {
485 $s .= '<br /><hr />';
487 # get a big array of the parents tree
488 $parenttree = $this->getTitle()->getParentCategoryTree();
489 # Skin object passed by reference cause it can not be
490 # accessed under the method subfunction drawCategoryBrowser
491 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
492 # Clean out bogus first entry and sort them
493 unset( $tempout[0] );
495 # Output one per line
496 $s .= implode( "<br />\n", $tempout );
503 * Render the array as a series of links.
504 * @param array $tree Categories tree returned by Title::getParentCategoryTree
505 * @return string Separated by >, terminate with "\n"
507 function drawCategoryBrowser( $tree ) {
510 foreach ( $tree as $element => $parent ) {
511 if ( empty( $parent ) ) {
512 # element start a new list
515 # grab the others elements
516 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
519 # add our current element to the list
520 $eltitle = Title
::newFromText( $element );
521 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
528 * @return string HTML
530 function getCategories() {
531 $out = $this->getOutput();
532 $catlinks = $this->getCategoryLinks();
534 // Check what we're showing
535 $allCats = $out->getCategoryLinks();
536 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
537 $this->getTitle()->getNamespace() == NS_CATEGORY
;
539 $classes = [ 'catlinks' ];
540 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
541 $classes[] = 'catlinks-allhidden';
544 return Html
::rawElement(
546 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
552 * This runs a hook to allow extensions placing their stuff after content
553 * and article metadata (e.g. categories).
554 * Note: This function has nothing to do with afterContent().
556 * This hook is placed here in order to allow using the same hook for all
557 * skins, both the SkinTemplate based ones and the older ones, which directly
558 * use this class to get their data.
560 * The output of this function gets processed in SkinTemplate::outputPage() for
561 * the SkinTemplate based skins, all other skins should directly echo it.
563 * @return string Empty by default, if not changed by any hook function.
565 protected function afterContentHook() {
568 if ( Hooks
::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
569 // adding just some spaces shouldn't toggle the output
570 // of the whole <div/>, so we use trim() here
571 if ( trim( $data ) != '' ) {
572 // Doing this here instead of in the skins to
573 // ensure that the div has the same ID in all
575 $data = "<div id='mw-data-after-content'>\n" .
580 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
587 * Generate debug data HTML for displaying at the bottom of the main content
589 * @return string HTML containing debug data, if enabled (otherwise empty).
591 protected function generateDebugHTML() {
592 return MWDebug
::getHTMLDebugLog();
596 * This gets called shortly before the "</body>" tag.
598 * @return string HTML-wrapped JS code to be put before "</body>"
600 function bottomScripts() {
601 // TODO and the suckage continues. This function is really just a wrapper around
602 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
604 $bottomScriptText = $this->getOutput()->getBottomScripts();
605 Hooks
::run( 'SkinAfterBottomScripts', [ $this, &$bottomScriptText ] );
607 return $bottomScriptText;
611 * Text with the permalink to the source page,
612 * usually shown on the footer of a printed page
614 * @return string HTML text with an URL
616 function printSource() {
617 $oldid = $this->getRevisionId();
619 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
620 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
622 // oldid not available for non existing pages
623 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
626 return $this->msg( 'retrievedfrom' )
627 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
632 * @return string HTML
634 function getUndeleteLink() {
635 $action = $this->getRequest()->getVal( 'action', 'view' );
637 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
638 ( !$this->getTitle()->exists() ||
$action == 'history' ) ) {
639 $n = $this->getTitle()->isDeleted();
642 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
643 $msg = 'thisisdeleted';
645 $msg = 'viewdeleted';
648 return $this->msg( $msg )->rawParams(
650 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
651 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
660 * @param OutputPage $out Defaults to $this->getOutput() if left as null
663 function subPageSubtitle( $out = null ) {
664 if ( $out === null ) {
665 $out = $this->getOutput();
667 $title = $out->getTitle();
670 if ( !Hooks
::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
674 if ( $out->isArticle() && MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
675 $ptext = $title->getPrefixedText();
676 if ( strpos( $ptext, '/' ) !== false ) {
677 $links = explode( '/', $ptext );
682 $lang = $this->getLanguage();
684 foreach ( $links as $link ) {
685 $growinglink .= $link;
687 $linkObj = Title
::newFromText( $growinglink );
689 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
690 $getlink = Linker
::linkKnown(
692 htmlspecialchars( $display )
698 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
700 $subpages .= '< ';
703 $subpages .= $getlink;
717 * @deprecated since 1.27, feature removed
718 * @return bool Always false
720 function showIPinHeader() {
721 wfDeprecated( __METHOD__
, '1.27' );
728 function getSearchLink() {
729 $searchPage = SpecialPage
::getTitleFor( 'Search' );
730 return $searchPage->getLocalURL();
736 function escapeSearchLink() {
737 return htmlspecialchars( $this->getSearchLink() );
741 * @param string $type
744 function getCopyright( $type = 'detect' ) {
745 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
747 if ( $type == 'detect' ) {
748 if ( !$this->isRevisionCurrent()
749 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
757 if ( $type == 'history' ) {
758 $msg = 'history_copyright';
763 if ( $wgRightsPage ) {
764 $title = Title
::newFromText( $wgRightsPage );
765 $link = Linker
::linkKnown( $title, $wgRightsText );
766 } elseif ( $wgRightsUrl ) {
767 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
768 } elseif ( $wgRightsText ) {
769 $link = $wgRightsText;
775 // Allow for site and per-namespace customization of copyright notice.
776 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
780 'SkinCopyrightFooter',
781 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
784 return $this->msg( $msg )->rawParams( $link )->text();
788 * @return null|string
790 function getCopyrightIcon() {
791 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
795 if ( $wgFooterIcons['copyright']['copyright'] ) {
796 $out = $wgFooterIcons['copyright']['copyright'];
797 } elseif ( $wgRightsIcon ) {
798 $icon = htmlspecialchars( $wgRightsIcon );
800 if ( $wgRightsUrl ) {
801 $url = htmlspecialchars( $wgRightsUrl );
802 $out .= '<a href="' . $url . '">';
805 $text = htmlspecialchars( $wgRightsText );
806 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
808 if ( $wgRightsUrl ) {
817 * Gets the powered by MediaWiki icon.
820 function getPoweredBy() {
821 global $wgResourceBasePath;
823 $url1 = htmlspecialchars(
824 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
826 $url1_5 = htmlspecialchars(
827 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
829 $url2 = htmlspecialchars(
830 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
832 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
833 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
834 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
835 Hooks
::run( 'SkinGetPoweredBy', [ &$text, $this ] );
840 * Get the timestamp of the latest revision, formatted in user language
844 protected function lastModified() {
845 $timestamp = $this->getOutput()->getRevisionTimestamp();
847 # No cached timestamp, load it from the database
848 if ( $timestamp === null ) {
849 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
853 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
854 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
855 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
860 if ( wfGetLB()->getLaggedReplicaMode() ) {
861 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
868 * @param string $align
871 function logoText( $align = '' ) {
872 if ( $align != '' ) {
873 $a = " style='float: {$align};'";
878 $mp = $this->msg( 'mainpage' )->escaped();
879 $mptitle = Title
::newMainPage();
880 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
882 $logourl = $this->getLogo();
883 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
889 * Renders a $wgFooterIcons icon according to the method's arguments
890 * @param array $icon The icon to build the html for, see $wgFooterIcons
891 * for the format of this array.
892 * @param bool|string $withImage Whether to use the icon's image or output
893 * a text-only footericon.
894 * @return string HTML
896 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
897 if ( is_string( $icon ) ) {
899 } else { // Assuming array
900 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
901 unset( $icon["url"] );
902 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
903 // do this the lazy way, just pass icon data as an attribute array
904 $html = Html
::element( 'img', $icon );
906 $html = htmlspecialchars( $icon["alt"] );
909 $html = Html
::rawElement( 'a', [ "href" => $url ], $html );
916 * Gets the link to the wiki's main page.
919 function mainPageLink() {
920 $s = Linker
::linkKnown(
921 Title
::newMainPage(),
922 $this->msg( 'mainpage' )->escaped()
929 * Returns an HTML link for use in the footer
930 * @param string $desc The i18n message key for the link text
931 * @param string $page The i18n message key for the page to link to
932 * @return string HTML anchor
934 public function footerLink( $desc, $page ) {
935 $title = $this->footerLinkTitle( $desc, $page );
940 return Linker
::linkKnown(
942 $this->msg( $desc )->escaped()
947 * @param string $desc
948 * @param string $page
951 private function footerLinkTitle( $desc, $page ) {
952 // If the link description has been set to "-" in the default language,
953 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
954 // then it is disabled, for all languages.
957 // Otherwise, we display the link for the user, described in their
958 // language (which may or may not be the same as the default language),
959 // but we make the link target be the one site-wide page.
960 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
962 return $title ?
: null;
966 * Gets the link to the wiki's privacy policy page.
967 * @return string HTML
969 function privacyLink() {
970 return $this->footerLink( 'privacy', 'privacypage' );
974 * Gets the link to the wiki's about page.
975 * @return string HTML
977 function aboutLink() {
978 return $this->footerLink( 'aboutsite', 'aboutpage' );
982 * Gets the link to the wiki's general disclaimers page.
983 * @return string HTML
985 function disclaimerLink() {
986 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
990 * Return URL options for the 'edit page' link.
991 * This may include an 'oldid' specifier, if the current page view is such.
996 function editUrlOptions() {
997 $options = [ 'action' => 'edit' ];
999 if ( !$this->isRevisionCurrent() ) {
1000 $options['oldid'] = intval( $this->getRevisionId() );
1007 * @param User|int $id
1010 function showEmailUser( $id ) {
1011 if ( $id instanceof User
) {
1014 $targetUser = User
::newFromId( $id );
1017 # The sending user must have a confirmed email address and the target
1018 # user must have a confirmed email address and allow emails from users.
1019 return $this->getUser()->canSendEmail() &&
1020 $targetUser->canReceiveEmail();
1024 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1025 * This method returns a url resolved using the configured skin style path
1026 * and includes the style version inside of the url.
1028 * Requires $stylename to be set, otherwise throws MWException.
1030 * @param string $name The name or path of a skin resource file
1031 * @return string The fully resolved style path url including styleversion
1032 * @throws MWException
1034 function getSkinStylePath( $name ) {
1035 global $wgStylePath, $wgStyleVersion;
1037 if ( $this->stylename
=== null ) {
1038 $class = get_class( $this );
1039 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1042 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1045 /* these are used extensively in SkinTemplate, but also some other places */
1048 * @param string $urlaction
1051 static function makeMainPageUrl( $urlaction = '' ) {
1052 $title = Title
::newMainPage();
1053 self
::checkTitle( $title, '' );
1055 return $title->getLocalURL( $urlaction );
1059 * Make a URL for a Special Page using the given query and protocol.
1061 * If $proto is set to null, make a local URL. Otherwise, make a full
1062 * URL with the protocol specified.
1064 * @param string $name Name of the Special page
1065 * @param string $urlaction Query to append
1066 * @param string|null $proto Protocol to use or null for a local URL
1069 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1070 $title = SpecialPage
::getSafeTitleFor( $name );
1071 if ( is_null( $proto ) ) {
1072 return $title->getLocalURL( $urlaction );
1074 return $title->getFullURL( $urlaction, false, $proto );
1079 * @param string $name
1080 * @param string $subpage
1081 * @param string $urlaction
1084 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1085 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1086 return $title->getLocalURL( $urlaction );
1090 * @param string $name
1091 * @param string $urlaction
1094 static function makeI18nUrl( $name, $urlaction = '' ) {
1095 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1096 self
::checkTitle( $title, $name );
1097 return $title->getLocalURL( $urlaction );
1101 * @param string $name
1102 * @param string $urlaction
1105 static function makeUrl( $name, $urlaction = '' ) {
1106 $title = Title
::newFromText( $name );
1107 self
::checkTitle( $title, $name );
1109 return $title->getLocalURL( $urlaction );
1113 * If url string starts with http, consider as external URL, else
1115 * @param string $name
1116 * @return string URL
1118 static function makeInternalOrExternalUrl( $name ) {
1119 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1122 return self
::makeUrl( $name );
1127 * this can be passed the NS number as defined in Language.php
1128 * @param string $name
1129 * @param string $urlaction
1130 * @param int $namespace
1133 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1134 $title = Title
::makeTitleSafe( $namespace, $name );
1135 self
::checkTitle( $title, $name );
1137 return $title->getLocalURL( $urlaction );
1141 * these return an array with the 'href' and boolean 'exists'
1142 * @param string $name
1143 * @param string $urlaction
1146 static function makeUrlDetails( $name, $urlaction = '' ) {
1147 $title = Title
::newFromText( $name );
1148 self
::checkTitle( $title, $name );
1151 'href' => $title->getLocalURL( $urlaction ),
1152 'exists' => $title->isKnown(),
1157 * Make URL details where the article exists (or at least it's convenient to think so)
1158 * @param string $name Article name
1159 * @param string $urlaction
1162 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1163 $title = Title
::newFromText( $name );
1164 self
::checkTitle( $title, $name );
1167 'href' => $title->getLocalURL( $urlaction ),
1173 * make sure we have some title to operate on
1175 * @param Title $title
1176 * @param string $name
1178 static function checkTitle( &$title, $name ) {
1179 if ( !is_object( $title ) ) {
1180 $title = Title
::newFromText( $name );
1181 if ( !is_object( $title ) ) {
1182 $title = Title
::newFromText( '--error: link target missing--' );
1188 * Build an array that represents the sidebar(s), the navigation bar among them.
1190 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1192 * The format of the returned array is [ heading => content, ... ], where:
1193 * - heading is the heading of a navigation portlet. It is either:
1194 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1195 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1196 * - plain text, which should be HTML-escaped by the skin
1197 * - content is the contents of the portlet. It is either:
1198 * - HTML text (<ul><li>...</li>...</ul>)
1199 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1200 * - (for a magic string as a key, any value)
1202 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1203 * and can technically insert anything in here; skin creators are expected to handle
1204 * values described above.
1208 function buildSidebar() {
1209 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1212 $callback = function () use ( $that ) {
1214 $that->addToSidebar( $bar, 'sidebar' );
1215 Hooks
::run( 'SkinBuildSidebar', [ $that, &$bar ] );
1220 if ( $wgEnableSidebarCache ) {
1221 $cache = ObjectCache
::getMainWANInstance();
1222 $sidebar = $cache->getWithSetCallback(
1223 $cache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1224 MessageCache
::singleton()->isDisabled()
1225 ?
$cache::TTL_UNCACHEABLE
// bug T133069
1226 : $wgSidebarCacheExpiry,
1231 $sidebar = $callback();
1234 // Apply post-processing to the cached value
1235 Hooks
::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1241 * Add content from a sidebar system message
1242 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1244 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1247 * @param string $message
1249 public function addToSidebar( &$bar, $message ) {
1250 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1254 * Add content from plain text
1257 * @param string $text
1260 function addToSidebarPlain( &$bar, $text ) {
1261 $lines = explode( "\n", $text );
1264 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1265 ? Title
::newMainPage() : $this->getTitle();
1267 foreach ( $lines as $line ) {
1268 if ( strpos( $line, '*' ) !== 0 ) {
1271 $line = rtrim( $line, "\r" ); // for Windows compat
1273 if ( strpos( $line, '**' ) !== 0 ) {
1274 $heading = trim( $line, '* ' );
1275 if ( !array_key_exists( $heading, $bar ) ) {
1276 $bar[$heading] = [];
1279 $line = trim( $line, '* ' );
1281 if ( strpos( $line, '|' ) !== false ) { // sanity check
1282 $line = MessageCache
::singleton()->transform( $line, false, null, $messageTitle );
1283 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1284 if ( count( $line ) !== 2 ) {
1285 // Second sanity check, could be hit by people doing
1286 // funky stuff with parserfuncs... (bug 33321)
1292 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1293 if ( $msgLink->exists() ) {
1294 $link = $msgLink->text();
1295 if ( $link == '-' ) {
1301 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1302 if ( $msgText->exists() ) {
1303 $text = $msgText->text();
1308 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1311 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1312 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1313 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1314 $extraAttribs['rel'] = 'nofollow';
1317 global $wgExternalLinkTarget;
1318 if ( $wgExternalLinkTarget ) {
1319 $extraAttribs['target'] = $wgExternalLinkTarget;
1322 $title = Title
::newFromText( $link );
1325 $title = $title->fixSpecialName();
1326 $href = $title->getLinkURL();
1328 $href = 'INVALID-TITLE';
1332 $bar[$heading][] = array_merge( [
1335 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1348 * Gets new talk page messages for the current user and returns an
1349 * appropriate alert message (or an empty string if there are no messages)
1352 function getNewtalks() {
1354 $newMessagesAlert = '';
1355 $user = $this->getUser();
1356 $newtalks = $user->getNewMessageLinks();
1357 $out = $this->getOutput();
1359 // Allow extensions to disable or modify the new messages alert
1360 if ( !Hooks
::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1363 if ( $newMessagesAlert ) {
1364 return $newMessagesAlert;
1367 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1368 $uTalkTitle = $user->getTalkPage();
1369 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1371 if ( $lastSeenRev !== null ) {
1372 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1373 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1374 if ( $latestRev !== null ) {
1375 // Singular if only 1 unseen revision, plural if several unseen revisions.
1376 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1377 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1378 $lastSeenRev, $latestRev, 10, 'include_new' );
1381 // Singular if no revision -> diff link will show latest change only in any case
1384 $plural = $plural ?
999 : 1;
1385 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1386 // the number of revisions or authors is not necessarily the same as the number of
1388 $newMessagesLink = Linker
::linkKnown(
1390 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1392 [ 'redirect' => 'no' ]
1395 $newMessagesDiffLink = Linker
::linkKnown(
1397 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1399 $lastSeenRev !== null
1400 ?
[ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1401 : [ 'diff' => 'cur' ]
1404 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1405 $newMessagesAlert = $this->msg(
1406 'youhavenewmessagesfromusers',
1408 $newMessagesDiffLink
1409 )->numParams( $nofAuthors, $plural );
1411 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1412 $newMessagesAlert = $this->msg(
1413 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1415 $newMessagesDiffLink
1416 )->numParams( $plural );
1418 $newMessagesAlert = $newMessagesAlert->text();
1420 $out->setCdnMaxage( 0 );
1421 } elseif ( count( $newtalks ) ) {
1422 $sep = $this->msg( 'newtalkseparator' )->escaped();
1425 foreach ( $newtalks as $newtalk ) {
1426 $msgs[] = Xml
::element(
1428 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1431 $parts = implode( $sep, $msgs );
1432 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1433 $out->setCdnMaxage( 0 );
1436 return $newMessagesAlert;
1440 * Get a cached notice
1442 * @param string $name Message name, or 'default' for $wgSiteNotice
1443 * @return string|bool HTML fragment, or false to indicate that the caller
1444 * should fall back to the next notice in its sequence
1446 private function getCachedNotice( $name ) {
1447 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1451 if ( $name === 'default' ) {
1453 global $wgSiteNotice;
1454 $notice = $wgSiteNotice;
1455 if ( empty( $notice ) ) {
1459 $msg = $this->msg( $name )->inContentLanguage();
1460 if ( $msg->isBlank() ) {
1462 } elseif ( $msg->isDisabled() ) {
1465 $notice = $msg->plain();
1468 // Use the extra hash appender to let eg SSL variants separately cache.
1469 $key = wfMemcKey( $name . $wgRenderHashAppend );
1470 $cachedNotice = $parserMemc->get( $key );
1471 if ( is_array( $cachedNotice ) ) {
1472 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1473 $notice = $cachedNotice['html'];
1482 $parsed = $this->getOutput()->parse( $notice );
1483 $parserMemc->set( $key, [ 'html' => $parsed, 'hash' => md5( $notice ) ], 600 );
1487 $notice = Html
::rawElement( 'div', [ 'id' => 'localNotice',
1488 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ], $notice );
1493 * Get the site notice
1495 * @return string HTML fragment
1497 function getSiteNotice() {
1500 if ( Hooks
::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1501 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1502 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1504 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1505 if ( $anonNotice === false ) {
1506 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1508 $siteNotice = $anonNotice;
1511 if ( $siteNotice === false ) {
1512 $siteNotice = $this->getCachedNotice( 'default' );
1516 Hooks
::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1521 * Create a section edit link. This supersedes editSectionLink() and
1522 * editSectionLinkForOther().
1524 * @param Title $nt The title being linked to (may not be the same as
1525 * the current page, if the section is included from a template)
1526 * @param string $section The designation of the section being pointed to,
1527 * to be included in the link, like "§ion=$section"
1528 * @param string $tooltip The tooltip to use for the link: will be escaped
1529 * and wrapped in the 'editsectionhint' message
1530 * @param string $lang Language code
1531 * @return string HTML to use for edit link
1533 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1534 // HTML generated here should probably have userlangattributes
1535 // added to it for LTR text on RTL pages
1537 $lang = wfGetLangObj( $lang );
1540 if ( !is_null( $tooltip ) ) {
1541 # Bug 25462: undo double-escaping.
1542 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1543 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1544 ->inLanguage( $lang )->text();
1549 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1550 'targetTitle' => $nt,
1551 'attribs' => $attribs,
1552 'query' => [ 'action' => 'edit', 'section' => $section ],
1553 'options' => [ 'noclasses', 'known' ]
1557 Hooks
::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1559 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1562 foreach ( $links as $k => $linkDetails ) {
1563 $linksHtml[] = Linker
::link(
1564 $linkDetails['targetTitle'],
1565 $linkDetails['text'],
1566 $linkDetails['attribs'],
1567 $linkDetails['query'],
1568 $linkDetails['options']
1573 '<span class="mw-editsection-divider">'
1574 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->text()
1579 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1580 // Deprecated, use SkinEditSectionLinks hook instead
1582 'DoEditSectionLink',
1583 [ $this, $nt, $section, $tooltip, &$result, $lang ],