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 * Fetch the set of available skins.
41 * @return array Associative array of strings
43 static function getSkinNames() {
44 global $wgValidSkinNames;
45 static $skinsInitialised = false;
47 if ( !$skinsInitialised ||
!count( $wgValidSkinNames ) ) {
48 # Get a list of available skins
49 # Build using the regular expression '^(.*).php$'
50 # Array keys are all lower case, array value keep the case used by filename
52 wfProfileIn( __METHOD__
. '-init' );
54 global $wgStyleDirectory;
56 $skinDir = dir( $wgStyleDirectory );
58 if ( $skinDir !== false && $skinDir !== null ) {
59 # while code from www.php.net
60 while ( false !== ( $file = $skinDir->read() ) ) {
61 // Skip non-PHP files, hidden files, and '.dep' includes
64 if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
66 $wgValidSkinNames[strtolower( $aSkin )] = $aSkin;
71 $skinsInitialised = true;
72 wfProfileOut( __METHOD__
. '-init' );
74 return $wgValidSkinNames;
78 * Fetch the skinname messages for available skins.
81 static function getSkinNameMessages() {
83 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
84 // Messages: skinname-vector, skinname-monobook
85 $messages[] = "skinname-$skinKey";
91 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
92 * Useful for Special:Preferences and other places where you
93 * only want to show skins users _can_ use.
97 public static function getAllowedSkins() {
100 $allowedSkins = self
::getSkinNames();
102 foreach ( $wgSkipSkins as $skip ) {
103 unset( $allowedSkins[$skip] );
106 return $allowedSkins;
110 * @deprecated since 1.23, use getAllowedSkins
113 public static function getUsableSkins() {
114 wfDeprecated( __METHOD__
, '1.23' );
115 return self
::getAllowedSkins();
119 * Normalize a skin preference value to a form that can be loaded.
120 * If a skin can't be found, it will fall back to the configured
121 * default, or the hardcoded default if that's broken.
122 * @param string $key 'monobook', 'vector', etc.
125 static function normalizeKey( $key ) {
126 global $wgDefaultSkin;
128 $skinNames = Skin
::getSkinNames();
130 if ( $key == '' ||
$key == 'default' ) {
131 // Don't return the default immediately;
132 // in a misconfiguration we need to fall back.
133 $key = $wgDefaultSkin;
136 if ( isset( $skinNames[$key] ) ) {
140 // Older versions of the software used a numeric setting
141 // in the user preferences.
147 if ( isset( $fallback[$key] ) ) {
148 $key = $fallback[$key];
151 if ( isset( $skinNames[$key] ) ) {
153 } elseif ( isset( $skinNames[$wgDefaultSkin] ) ) {
154 return $wgDefaultSkin;
161 * Factory method for loading a skin of a given type
162 * @param string $key 'monobook', 'vector', etc.
165 static function &newFromKey( $key ) {
166 global $wgStyleDirectory;
168 $key = Skin
::normalizeKey( $key );
170 $skinNames = Skin
::getSkinNames();
171 $skinName = $skinNames[$key];
172 $className = "Skin{$skinName}";
174 # Grab the skin class and initialise it.
175 if ( !class_exists( $className ) ) {
177 require_once "{$wgStyleDirectory}/{$skinName}.php";
179 # Check if we got if not fallback to default skin
180 if ( !class_exists( $className ) ) {
181 # DO NOT die if the class isn't found. This breaks maintenance
182 # scripts and can cause a user account to be unrecoverable
183 # except by SQL manipulation if a previously valid skin name
184 # is no longer valid.
185 wfDebug( "Skin class does not exist: $className\n" );
186 $className = 'SkinVector';
187 require_once "{$wgStyleDirectory}/Vector.php";
190 $skin = new $className( $key );
195 * @return string Skin name
197 public function getSkinName() {
198 return $this->skinname
;
202 * @param OutputPage $out
204 function initPage( OutputPage
$out ) {
205 wfProfileIn( __METHOD__
);
207 $this->preloadExistence();
209 wfProfileOut( __METHOD__
);
213 * Defines the ResourceLoader modules that should be added to the skin
214 * It is recommended that skins wishing to override call parent::getDefaultModules()
215 * and substitute out any modules they wish to change by using a key to look them up
216 * @return array Array of modules with helper keys for easy overriding
218 public function getDefaultModules() {
219 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
220 $wgAjaxWatch, $wgEnableAPI, $wgEnableWriteAPI;
222 $out = $this->getOutput();
223 $user = $out->getUser();
225 // modules that enhance the page content in some way
227 'mediawiki.page.ready',
229 // modules that exist for legacy reasons
231 // modules relating to search functionality
233 // modules relating to functionality relating to watching an article
235 // modules which relate to the current users preferences
238 if ( $wgIncludeLegacyJavaScript ) {
239 $modules['legacy'][] = 'mediawiki.legacy.wikibits';
242 if ( $wgPreloadJavaScriptMwUtil ) {
243 $modules['legacy'][] = 'mediawiki.util';
246 // Add various resources if required
248 $modules['legacy'][] = 'mediawiki.legacy.ajax';
250 if ( $wgEnableAPI ) {
251 if ( $wgEnableWriteAPI && $wgAjaxWatch && $user->isLoggedIn()
252 && $user->isAllowed( 'writeapi' )
254 $modules['watch'][] = 'mediawiki.page.watch.ajax';
257 $modules['search'][] = 'mediawiki.searchSuggest';
261 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
262 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
265 // Crazy edit-on-double-click stuff
266 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
267 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
273 * Preload the existence of three commonly-requested pages in a single query
275 function preloadExistence() {
276 $user = $this->getUser();
279 $titles = array( $user->getUserPage(), $user->getTalkPage() );
282 if ( $this->getTitle()->isSpecialPage() ) {
284 } elseif ( $this->getTitle()->isTalkPage() ) {
285 $titles[] = $this->getTitle()->getSubjectPage();
287 $titles[] = $this->getTitle()->getTalkPage();
290 $lb = new LinkBatch( $titles );
291 $lb->setCaller( __METHOD__
);
296 * Get the current revision ID
300 public function getRevisionId() {
301 return $this->getOutput()->getRevisionId();
305 * Whether the revision displayed is the latest revision of the page
309 public function isRevisionCurrent() {
310 $revID = $this->getRevisionId();
311 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
315 * Set the "relevant" title
316 * @see self::getRelevantTitle()
319 public function setRelevantTitle( $t ) {
320 $this->mRelevantTitle
= $t;
324 * Return the "relevant" title.
325 * A "relevant" title is not necessarily the actual title of the page.
326 * Special pages like Special:MovePage use set the page they are acting on
327 * as their "relevant" title, this allows the skin system to display things
328 * such as content tabs which belong to to that page instead of displaying
329 * a basic special page tab which has almost no meaning.
333 public function getRelevantTitle() {
334 if ( isset( $this->mRelevantTitle
) ) {
335 return $this->mRelevantTitle
;
337 return $this->getTitle();
341 * Set the "relevant" user
342 * @see self::getRelevantUser()
345 public function setRelevantUser( $u ) {
346 $this->mRelevantUser
= $u;
350 * Return the "relevant" user.
351 * A "relevant" user is similar to a relevant title. Special pages like
352 * Special:Contributions mark the user which they are relevant to so that
353 * things like the toolbox can display the information they usually are only
354 * able to display on a user's userpage and talkpage.
357 public function getRelevantUser() {
358 if ( isset( $this->mRelevantUser
) ) {
359 return $this->mRelevantUser
;
361 $title = $this->getRelevantTitle();
362 if ( $title->hasSubjectNamespace( NS_USER
) ) {
363 $rootUser = $title->getRootText();
364 if ( User
::isIP( $rootUser ) ) {
365 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
367 $user = User
::newFromName( $rootUser, false );
368 if ( $user && $user->isLoggedIn() ) {
369 $this->mRelevantUser
= $user;
372 return $this->mRelevantUser
;
378 * Outputs the HTML generated by other functions.
379 * @param OutputPage $out
381 abstract function outputPage( OutputPage
$out = null );
387 static function makeVariablesScript( $data ) {
389 return Html
::inlineScript(
390 ResourceLoader
::makeLoaderConditionalScript( ResourceLoader
::makeConfigSetScript( $data ) )
398 * Make a "<script>" tag containing global variables
400 * @deprecated since 1.19
401 * @param mixed $unused
402 * @return string HTML fragment
404 public static function makeGlobalVariablesScript( $unused ) {
407 wfDeprecated( __METHOD__
, '1.19' );
409 return self
::makeVariablesScript( $wgOut->getJSVars() );
413 * Get the query to generate a dynamic stylesheet
417 public static function getDynamicStylesheetQuery() {
418 global $wgSquidMaxage;
422 'maxage' => $wgSquidMaxage,
423 'usemsgcache' => 'yes',
424 'ctype' => 'text/css',
425 'smaxage' => $wgSquidMaxage,
430 * Add skin specific stylesheets
431 * Calling this method with an $out of anything but the same OutputPage
432 * inside ->getOutput() is deprecated. The $out arg is kept
433 * for compatibility purposes with skins.
434 * @param OutputPage $out
437 abstract function setupSkinUserCss( OutputPage
$out );
441 * @param Title $title
444 function getPageClasses( $title ) {
445 $numeric = 'ns-' . $title->getNamespace();
447 if ( $title->isSpecialPage() ) {
448 $type = 'ns-special';
449 // bug 23315: provide a class based on the canonical special page name without subpages
450 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
451 if ( $canonicalName ) {
452 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
454 $type .= ' mw-invalidspecialpage';
456 } elseif ( $title->isTalkPage() ) {
459 $type = 'ns-subject';
462 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
464 return "$numeric $type $name";
468 * Return values for <html> element
469 * @return array of associative name-to-value elements for <html> element
471 public function getHtmlElementAttributes() {
472 $lang = $this->getLanguage();
474 'lang' => $lang->getHtmlCode(),
475 'dir' => $lang->getDir(),
476 'class' => 'client-nojs',
481 * This will be called by OutputPage::headElement when it is creating the
482 * "<body>" tag, skins can override it if they have a need to add in any
483 * body attributes or classes of their own.
484 * @param OutputPage $out
485 * @param array $bodyAttrs
487 function addToBodyAttributes( $out, &$bodyAttrs ) {
488 // does nothing by default
503 function getCategoryLinks() {
504 global $wgUseCategoryBrowser;
506 $out = $this->getOutput();
507 $allCats = $out->getCategoryLinks();
509 if ( !count( $allCats ) ) {
517 $colon = $this->msg( 'colon-separator' )->escaped();
519 if ( !empty( $allCats['normal'] ) ) {
520 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
522 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
523 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
524 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
525 Linker
::link( Title
::newFromText( $linkPage ), $msg )
526 . $colon . '<ul>' . $t . '</ul>' . '</div>';
530 if ( isset( $allCats['hidden'] ) ) {
531 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
532 $class = ' mw-hidden-cats-user-shown';
533 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
534 $class = ' mw-hidden-cats-ns-shown';
536 $class = ' mw-hidden-cats-hidden';
539 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
540 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
541 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
545 # optional 'dmoz-like' category browser. Will be shown under the list
546 # of categories an article belong to
547 if ( $wgUseCategoryBrowser ) {
548 $s .= '<br /><hr />';
550 # get a big array of the parents tree
551 $parenttree = $this->getTitle()->getParentCategoryTree();
552 # Skin object passed by reference cause it can not be
553 # accessed under the method subfunction drawCategoryBrowser
554 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
555 # Clean out bogus first entry and sort them
556 unset( $tempout[0] );
558 # Output one per line
559 $s .= implode( "<br />\n", $tempout );
566 * Render the array as a series of links.
567 * @param array $tree Categories tree returned by Title::getParentCategoryTree
568 * @return string Separated by >, terminate with "\n"
570 function drawCategoryBrowser( $tree ) {
573 foreach ( $tree as $element => $parent ) {
574 if ( empty( $parent ) ) {
575 # element start a new list
578 # grab the others elements
579 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
582 # add our current element to the list
583 $eltitle = Title
::newFromText( $element );
584 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
593 function getCategories() {
594 $out = $this->getOutput();
596 $catlinks = $this->getCategoryLinks();
598 $classes = 'catlinks';
600 // Check what we're showing
601 $allCats = $out->getCategoryLinks();
602 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
603 $this->getTitle()->getNamespace() == NS_CATEGORY
;
605 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
606 $classes .= ' catlinks-allhidden';
609 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
613 * This runs a hook to allow extensions placing their stuff after content
614 * and article metadata (e.g. categories).
615 * Note: This function has nothing to do with afterContent().
617 * This hook is placed here in order to allow using the same hook for all
618 * skins, both the SkinTemplate based ones and the older ones, which directly
619 * use this class to get their data.
621 * The output of this function gets processed in SkinTemplate::outputPage() for
622 * the SkinTemplate based skins, all other skins should directly echo it.
624 * @return string Empty by default, if not changed by any hook function.
626 protected function afterContentHook() {
629 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
630 // adding just some spaces shouldn't toggle the output
631 // of the whole <div/>, so we use trim() here
632 if ( trim( $data ) != '' ) {
633 // Doing this here instead of in the skins to
634 // ensure that the div has the same ID in all
636 $data = "<div id='mw-data-after-content'>\n" .
641 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
648 * Generate debug data HTML for displaying at the bottom of the main content
650 * @return string HTML containing debug data, if enabled (otherwise empty).
652 protected function generateDebugHTML() {
653 return MWDebug
::getHTMLDebugLog();
657 * This gets called shortly before the "</body>" tag.
659 * @return string HTML-wrapped JS code to be put before "</body>"
661 function bottomScripts() {
662 // TODO and the suckage continues. This function is really just a wrapper around
663 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
665 $bottomScriptText = $this->getOutput()->getBottomScripts();
666 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
668 return $bottomScriptText;
672 * Text with the permalink to the source page,
673 * usually shown on the footer of a printed page
675 * @return string HTML text with an URL
677 function printSource() {
678 $oldid = $this->getRevisionId();
680 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
681 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
683 // oldid not available for non existing pages
684 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
687 return $this->msg( 'retrievedfrom', '<a dir="ltr" href="' . $url
688 . '">' . $url . '</a>' )->text();
694 function getUndeleteLink() {
695 $action = $this->getRequest()->getVal( 'action', 'view' );
697 if ( $this->getUser()->isAllowed( 'deletedhistory' ) &&
698 ( $this->getTitle()->getArticleID() == 0 ||
$action == 'history' ) ) {
699 $n = $this->getTitle()->isDeleted();
702 if ( $this->getUser()->isAllowed( 'undelete' ) ) {
703 $msg = 'thisisdeleted';
705 $msg = 'viewdeleted';
708 return $this->msg( $msg )->rawParams(
710 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
711 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
722 function subPageSubtitle() {
723 $out = $this->getOutput();
726 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
730 if ( $out->isArticle() && MWNamespace
::hasSubpages( $out->getTitle()->getNamespace() ) ) {
731 $ptext = $this->getTitle()->getPrefixedText();
732 if ( preg_match( '/\//', $ptext ) ) {
733 $links = explode( '/', $ptext );
738 $lang = $this->getLanguage();
740 foreach ( $links as $link ) {
741 $growinglink .= $link;
743 $linkObj = Title
::newFromText( $growinglink );
745 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
746 $getlink = Linker
::linkKnown(
748 htmlspecialchars( $display )
754 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
756 $subpages .= '< ';
759 $subpages .= $getlink;
773 * Returns true if the IP should be shown in the header
776 function showIPinHeader() {
777 global $wgShowIPinHeader;
778 return $wgShowIPinHeader && session_id() != '';
784 function getSearchLink() {
785 $searchPage = SpecialPage
::getTitleFor( 'Search' );
786 return $searchPage->getLocalURL();
792 function escapeSearchLink() {
793 return htmlspecialchars( $this->getSearchLink() );
797 * @param string $type
800 function getCopyright( $type = 'detect' ) {
801 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgContLang;
803 if ( $type == 'detect' ) {
804 if ( !$this->isRevisionCurrent()
805 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
813 if ( $type == 'history' ) {
814 $msg = 'history_copyright';
819 if ( $wgRightsPage ) {
820 $title = Title
::newFromText( $wgRightsPage );
821 $link = Linker
::linkKnown( $title, $wgRightsText );
822 } elseif ( $wgRightsUrl ) {
823 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
824 } elseif ( $wgRightsText ) {
825 $link = $wgRightsText;
831 // Allow for site and per-namespace customization of copyright notice.
832 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
836 'SkinCopyrightFooter',
837 array( $this->getTitle(), $type, &$msg, &$link, &$forContent )
840 return $this->msg( $msg )->rawParams( $link )->text();
844 * @return null|string
846 function getCopyrightIcon() {
847 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
851 if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
852 $out = $wgCopyrightIcon;
853 } elseif ( $wgRightsIcon ) {
854 $icon = htmlspecialchars( $wgRightsIcon );
856 if ( $wgRightsUrl ) {
857 $url = htmlspecialchars( $wgRightsUrl );
858 $out .= '<a href="' . $url . '">';
861 $text = htmlspecialchars( $wgRightsText );
862 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
864 if ( $wgRightsUrl ) {
873 * Gets the powered by MediaWiki icon.
876 function getPoweredBy() {
879 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
880 $text = '<a href="//www.mediawiki.org/"><img src="' . $url
881 . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
882 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
887 * Get the timestamp of the latest revision, formatted in user language
891 protected function lastModified() {
892 $timestamp = $this->getOutput()->getRevisionTimestamp();
894 # No cached timestamp, load it from the database
895 if ( $timestamp === null ) {
896 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
900 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
901 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
902 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text();
907 if ( wfGetLB()->getLaggedSlaveMode() ) {
908 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->text() . '</strong>';
915 * @param string $align
918 function logoText( $align = '' ) {
919 if ( $align != '' ) {
920 $a = " style='float: {$align};'";
925 $mp = $this->msg( 'mainpage' )->escaped();
926 $mptitle = Title
::newMainPage();
927 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
929 $logourl = $this->getLogo();
930 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
936 * Renders a $wgFooterIcons icon according to the method's arguments
937 * @param array $icon The icon to build the html for, see $wgFooterIcons
938 * for the format of this array.
939 * @param bool|string $withImage Whether to use the icon's image or output
940 * a text-only footericon.
941 * @return string HTML
943 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
944 if ( is_string( $icon ) ) {
946 } else { // Assuming array
947 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
948 unset( $icon["url"] );
949 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
950 // do this the lazy way, just pass icon data as an attribute array
951 $html = Html
::element( 'img', $icon );
953 $html = htmlspecialchars( $icon["alt"] );
956 $html = Html
::rawElement( 'a', array( "href" => $url ), $html );
963 * Gets the link to the wiki's main page.
966 function mainPageLink() {
967 $s = Linker
::linkKnown(
968 Title
::newMainPage(),
969 $this->msg( 'mainpage' )->escaped()
976 * Returns an HTML link for use in the footer
977 * @param string $desc i18n message key for the link text
978 * @param string $page i18n message key for the page to link to
979 * @return string HTML anchor
981 public function footerLink( $desc, $page ) {
982 // if the link description has been set to "-" in the default language,
983 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
984 // then it is disabled, for all languages.
987 // Otherwise, we display the link for the user, described in their
988 // language (which may or may not be the same as the default language),
989 // but we make the link target be the one site-wide page.
990 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
992 return Linker
::linkKnown(
994 $this->msg( $desc )->escaped()
1000 * Gets the link to the wiki's privacy policy page.
1001 * @return string HTML
1003 function privacyLink() {
1004 return $this->footerLink( 'privacy', 'privacypage' );
1008 * Gets the link to the wiki's about page.
1009 * @return string HTML
1011 function aboutLink() {
1012 return $this->footerLink( 'aboutsite', 'aboutpage' );
1016 * Gets the link to the wiki's general disclaimers page.
1017 * @return string HTML
1019 function disclaimerLink() {
1020 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1024 * Return URL options for the 'edit page' link.
1025 * This may include an 'oldid' specifier, if the current page view is such.
1030 function editUrlOptions() {
1031 $options = array( 'action' => 'edit' );
1033 if ( !$this->isRevisionCurrent() ) {
1034 $options['oldid'] = intval( $this->getRevisionId() );
1041 * @param User|int $id
1044 function showEmailUser( $id ) {
1045 if ( $id instanceof User
) {
1048 $targetUser = User
::newFromId( $id );
1051 # The sending user must have a confirmed email address and the target
1052 # user must have a confirmed email address and allow emails from users.
1053 return $this->getUser()->canSendEmail() &&
1054 $targetUser->canReceiveEmail();
1058 * Return a fully resolved style path url to images or styles stored in the common folder.
1059 * This method returns a url resolved using the configured skin style path
1060 * and includes the style version inside of the url.
1061 * @param string $name The name or path of a skin resource file
1062 * @return string The fully resolved style path url including styleversion
1064 function getCommonStylePath( $name ) {
1065 global $wgStylePath, $wgStyleVersion;
1066 return "$wgStylePath/common/$name?$wgStyleVersion";
1070 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1071 * This method returns a url resolved using the configured skin style path
1072 * and includes the style version inside of the url.
1073 * @param string $name The name or path of a skin resource file
1074 * @return string The fully resolved style path url including styleversion
1076 function getSkinStylePath( $name ) {
1077 global $wgStylePath, $wgStyleVersion;
1078 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1081 /* these are used extensively in SkinTemplate, but also some other places */
1084 * @param string $urlaction
1087 static function makeMainPageUrl( $urlaction = '' ) {
1088 $title = Title
::newMainPage();
1089 self
::checkTitle( $title, '' );
1091 return $title->getLocalURL( $urlaction );
1095 * Make a URL for a Special Page using the given query and protocol.
1097 * If $proto is set to null, make a local URL. Otherwise, make a full
1098 * URL with the protocol specified.
1100 * @param string $name Name of the Special page
1101 * @param string $urlaction Query to append
1102 * @param string|null $proto Protocol to use or null for a local URL
1105 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1106 $title = SpecialPage
::getSafeTitleFor( $name );
1107 if ( is_null( $proto ) ) {
1108 return $title->getLocalURL( $urlaction );
1110 return $title->getFullURL( $urlaction, false, $proto );
1115 * @param string $name
1116 * @param string $subpage
1117 * @param string $urlaction
1120 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1121 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1122 return $title->getLocalURL( $urlaction );
1126 * @param string $name
1127 * @param string $urlaction
1130 static function makeI18nUrl( $name, $urlaction = '' ) {
1131 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1132 self
::checkTitle( $title, $name );
1133 return $title->getLocalURL( $urlaction );
1137 * @param string $name
1138 * @param string $urlaction
1141 static function makeUrl( $name, $urlaction = '' ) {
1142 $title = Title
::newFromText( $name );
1143 self
::checkTitle( $title, $name );
1145 return $title->getLocalURL( $urlaction );
1149 * If url string starts with http, consider as external URL, else
1151 * @param string $name
1152 * @return string URL
1154 static function makeInternalOrExternalUrl( $name ) {
1155 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1158 return self
::makeUrl( $name );
1163 * this can be passed the NS number as defined in Language.php
1164 * @param string $name
1165 * @param string $urlaction
1166 * @param int $namespace
1169 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1170 $title = Title
::makeTitleSafe( $namespace, $name );
1171 self
::checkTitle( $title, $name );
1173 return $title->getLocalURL( $urlaction );
1177 * these return an array with the 'href' and boolean 'exists'
1178 * @param string $name
1179 * @param string $urlaction
1182 static function makeUrlDetails( $name, $urlaction = '' ) {
1183 $title = Title
::newFromText( $name );
1184 self
::checkTitle( $title, $name );
1187 'href' => $title->getLocalURL( $urlaction ),
1188 'exists' => $title->getArticleID() != 0,
1193 * Make URL details where the article exists (or at least it's convenient to think so)
1194 * @param string $name Article name
1195 * @param string $urlaction
1198 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1199 $title = Title
::newFromText( $name );
1200 self
::checkTitle( $title, $name );
1203 'href' => $title->getLocalURL( $urlaction ),
1209 * make sure we have some title to operate on
1211 * @param Title $title
1212 * @param string $name
1214 static function checkTitle( &$title, $name ) {
1215 if ( !is_object( $title ) ) {
1216 $title = Title
::newFromText( $name );
1217 if ( !is_object( $title ) ) {
1218 $title = Title
::newFromText( '--error: link target missing--' );
1224 * Build an array that represents the sidebar(s), the navigation bar among them.
1226 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1228 * The format of the returned array is array( heading => content, ... ), where:
1229 * - heading is the heading of a navigation portlet. It is either:
1230 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1231 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1232 * - plain text, which should be HTML-escaped by the skin
1233 * - content is the contents of the portlet. It is either:
1234 * - HTML text (<ul><li>...</li>...</ul>)
1235 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1236 * - (for a magic string as a key, any value)
1238 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1239 * and can technically insert anything in here; skin creators are expected to handle
1240 * values described above.
1244 function buildSidebar() {
1245 global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1246 wfProfileIn( __METHOD__
);
1248 $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() );
1250 if ( $wgEnableSidebarCache ) {
1251 $cachedsidebar = $wgMemc->get( $key );
1252 if ( $cachedsidebar ) {
1253 wfRunHooks( 'SidebarBeforeOutput', array( $this, &$cachedsidebar ) );
1255 wfProfileOut( __METHOD__
);
1256 return $cachedsidebar;
1261 $this->addToSidebar( $bar, 'sidebar' );
1263 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1264 if ( $wgEnableSidebarCache ) {
1265 $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1268 wfRunHooks( 'SidebarBeforeOutput', array( $this, &$bar ) );
1270 wfProfileOut( __METHOD__
);
1275 * Add content from a sidebar system message
1276 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1278 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1281 * @param string $message
1283 function addToSidebar( &$bar, $message ) {
1284 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1288 * Add content from plain text
1291 * @param string $text
1294 function addToSidebarPlain( &$bar, $text ) {
1295 $lines = explode( "\n", $text );
1299 foreach ( $lines as $line ) {
1300 if ( strpos( $line, '*' ) !== 0 ) {
1303 $line = rtrim( $line, "\r" ); // for Windows compat
1305 if ( strpos( $line, '**' ) !== 0 ) {
1306 $heading = trim( $line, '* ' );
1307 if ( !array_key_exists( $heading, $bar ) ) {
1308 $bar[$heading] = array();
1311 $line = trim( $line, '* ' );
1313 if ( strpos( $line, '|' ) !== false ) { // sanity check
1314 $line = MessageCache
::singleton()->transform( $line, false, null, $this->getTitle() );
1315 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1316 if ( count( $line ) !== 2 ) {
1317 // Second sanity check, could be hit by people doing
1318 // funky stuff with parserfuncs... (bug 33321)
1322 $extraAttribs = array();
1324 $msgLink = $this->msg( $line[0] )->inContentLanguage();
1325 if ( $msgLink->exists() ) {
1326 $link = $msgLink->text();
1327 if ( $link == '-' ) {
1333 $msgText = $this->msg( $line[1] );
1334 if ( $msgText->exists() ) {
1335 $text = $msgText->text();
1340 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1343 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1344 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1345 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1346 $extraAttribs['rel'] = 'nofollow';
1349 global $wgExternalLinkTarget;
1350 if ( $wgExternalLinkTarget ) {
1351 $extraAttribs['target'] = $wgExternalLinkTarget;
1354 $title = Title
::newFromText( $link );
1357 $title = $title->fixSpecialName();
1358 $href = $title->getLinkURL();
1360 $href = 'INVALID-TITLE';
1364 $bar[$heading][] = array_merge( array(
1367 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1380 * This function previously controlled whether the 'mediawiki.legacy.wikiprintable' module
1381 * should be loaded by OutputPage. That module no longer exists and the return value of this
1382 * method is ignored.
1384 * If your skin doesn't provide its own print styles, the 'mediawiki.legacy.commonPrint' module
1385 * can be used instead (SkinTemplate-based skins do it automatically).
1387 * @deprecated since 1.22
1390 public function commonPrintStylesheet() {
1391 wfDeprecated( __METHOD__
, '1.22' );
1396 * Gets new talk page messages for the current user and returns an
1397 * appropriate alert message (or an empty string if there are no messages)
1400 function getNewtalks() {
1402 $newMessagesAlert = '';
1403 $user = $this->getUser();
1404 $newtalks = $user->getNewMessageLinks();
1405 $out = $this->getOutput();
1407 // Allow extensions to disable or modify the new messages alert
1408 if ( !wfRunHooks( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) {
1411 if ( $newMessagesAlert ) {
1412 return $newMessagesAlert;
1415 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1416 $uTalkTitle = $user->getTalkPage();
1417 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1419 if ( $lastSeenRev !== null ) {
1420 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1421 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1422 if ( $latestRev !== null ) {
1423 // Singular if only 1 unseen revision, plural if several unseen revisions.
1424 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1425 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1426 $lastSeenRev, $latestRev, 10, 'include_new' );
1429 // Singular if no revision -> diff link will show latest change only in any case
1432 $plural = $plural ?
999 : 1;
1433 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1434 // the number of revisions or authors is not necessarily the same as the number of
1436 $newMessagesLink = Linker
::linkKnown(
1438 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1440 array( 'redirect' => 'no' )
1443 $newMessagesDiffLink = Linker
::linkKnown(
1445 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1447 $lastSeenRev !== null
1448 ?
array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' )
1449 : array( 'diff' => 'cur' )
1452 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1453 $newMessagesAlert = $this->msg(
1454 'youhavenewmessagesfromusers',
1456 $newMessagesDiffLink
1457 )->numParams( $nofAuthors, $plural );
1459 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1460 $newMessagesAlert = $this->msg(
1461 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1463 $newMessagesDiffLink
1464 )->numParams( $plural );
1466 $newMessagesAlert = $newMessagesAlert->text();
1467 # Disable Squid cache
1468 $out->setSquidMaxage( 0 );
1469 } elseif ( count( $newtalks ) ) {
1470 $sep = $this->msg( 'newtalkseparator' )->escaped();
1473 foreach ( $newtalks as $newtalk ) {
1474 $msgs[] = Xml
::element(
1476 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1479 $parts = implode( $sep, $msgs );
1480 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1481 $out->setSquidMaxage( 0 );
1484 return $newMessagesAlert;
1488 * Get a cached notice
1490 * @param string $name Message name, or 'default' for $wgSiteNotice
1491 * @return string HTML fragment
1493 private function getCachedNotice( $name ) {
1494 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1496 wfProfileIn( __METHOD__
);
1500 if ( $name === 'default' ) {
1502 global $wgSiteNotice;
1503 $notice = $wgSiteNotice;
1504 if ( empty( $notice ) ) {
1505 wfProfileOut( __METHOD__
);
1509 $msg = $this->msg( $name )->inContentLanguage();
1510 if ( $msg->isDisabled() ) {
1511 wfProfileOut( __METHOD__
);
1514 $notice = $msg->plain();
1517 // Use the extra hash appender to let eg SSL variants separately cache.
1518 $key = wfMemcKey( $name . $wgRenderHashAppend );
1519 $cachedNotice = $parserMemc->get( $key );
1520 if ( is_array( $cachedNotice ) ) {
1521 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1522 $notice = $cachedNotice['html'];
1531 $parsed = $this->getOutput()->parse( $notice );
1532 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1536 $notice = Html
::rawElement( 'div', array( 'id' => 'localNotice',
1537 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice );
1538 wfProfileOut( __METHOD__
);
1543 * Get a notice based on page's namespace
1545 * @return string HTML fragment
1547 function getNamespaceNotice() {
1548 wfProfileIn( __METHOD__
);
1550 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1551 $namespaceNotice = $this->getCachedNotice( $key );
1552 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
1553 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1555 $namespaceNotice = '';
1558 wfProfileOut( __METHOD__
);
1559 return $namespaceNotice;
1563 * Get the site notice
1565 * @return string HTML fragment
1567 function getSiteNotice() {
1568 wfProfileIn( __METHOD__
);
1571 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1572 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1573 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1575 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1576 if ( !$anonNotice ) {
1577 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1579 $siteNotice = $anonNotice;
1582 if ( !$siteNotice ) {
1583 $siteNotice = $this->getCachedNotice( 'default' );
1587 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1588 wfProfileOut( __METHOD__
);
1593 * Create a section edit link. This supersedes editSectionLink() and
1594 * editSectionLinkForOther().
1596 * @param Title $nt The title being linked to (may not be the same as
1597 * the current page, if the section is included from a template)
1598 * @param string $section The designation of the section being pointed to,
1599 * to be included in the link, like "§ion=$section"
1600 * @param string $tooltip The tooltip to use for the link: will be escaped
1601 * and wrapped in the 'editsectionhint' message
1602 * @param string $lang Language code
1603 * @return string HTML to use for edit link
1605 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1606 // HTML generated here should probably have userlangattributes
1607 // added to it for LTR text on RTL pages
1609 $lang = wfGetLangObj( $lang );
1612 if ( !is_null( $tooltip ) ) {
1613 # Bug 25462: undo double-escaping.
1614 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1615 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1616 ->inLanguage( $lang )->text();
1618 $link = Linker
::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(),
1620 array( 'action' => 'edit', 'section' => $section ),
1621 array( 'noclasses', 'known' )
1624 # Add the brackets and the span and run the hook.
1625 $result = '<span class="mw-editsection">'
1626 . '<span class="mw-editsection-bracket">[</span>'
1628 . '<span class="mw-editsection-bracket">]</span>'
1631 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1636 * Use PHP's magic __call handler to intercept legacy calls to the linker
1637 * for backwards compatibility.
1639 * @param string $fname Name of called method
1640 * @param array $args Arguments to the method
1641 * @throws MWException
1644 function __call( $fname, $args ) {
1645 $realFunction = array( 'Linker', $fname );
1646 if ( is_callable( $realFunction ) ) {
1647 wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' );
1648 return call_user_func_array( $realFunction, $args );
1650 $className = get_class( $this );
1651 throw new MWException( "Call to undefined method $className::$fname" );