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.
29 * This base class is also the "Standard" skin.
31 * See docs/skin.txt for more information.
35 abstract class Skin
extends ContextSource
{
36 protected $skinname = 'standard';
37 protected $mRelevantTitle = null;
38 protected $mRelevantUser = null;
41 * Fetch the set of available skins.
42 * @return array associative array of strings
44 static function getSkinNames() {
45 global $wgValidSkinNames;
46 static $skinsInitialised = false;
48 if ( !$skinsInitialised ||
!count( $wgValidSkinNames ) ) {
49 # Get a list of available skins
50 # Build using the regular expression '^(.*).php$'
51 # Array keys are all lower case, array value keep the case used by filename
53 wfProfileIn( __METHOD__
. '-init' );
55 global $wgStyleDirectory;
57 $skinDir = dir( $wgStyleDirectory );
59 if ( $skinDir !== false && $skinDir !== null ) {
60 # while code from www.php.net
61 while ( false !== ( $file = $skinDir->read() ) ) {
62 // Skip non-PHP files, hidden files, and '.dep' includes
65 if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
67 $wgValidSkinNames[strtolower( $aSkin )] = $aSkin;
72 $skinsInitialised = true;
73 wfProfileOut( __METHOD__
. '-init' );
75 return $wgValidSkinNames;
79 * Fetch the skinname messages for available skins.
80 * @return array of strings
82 static function getSkinNameMessages() {
84 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
85 // Messages: skinname-cologneblue, skinname-monobook, skinname-modern, skinname-vector
86 $messages[] = "skinname-$skinKey";
92 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
93 * Useful for Special:Preferences and other places where you
94 * only want to show skins users _can_ use.
95 * @return array of strings
97 public static function getUsableSkins() {
100 $allowedSkins = self
::getSkinNames();
102 foreach ( $wgSkipSkins as $skip ) {
103 unset( $allowedSkins[$skip] );
106 return $allowedSkins;
110 * Normalize a skin preference value to a form that can be loaded.
111 * If a skin can't be found, it will fall back to the configured
112 * default (or the old 'Classic' skin if that's broken).
113 * @param string $key 'monobook', 'standard', etc.
116 static function normalizeKey( $key ) {
117 global $wgDefaultSkin;
119 $skinNames = Skin
::getSkinNames();
121 if ( $key == '' ||
$key == 'default' ) {
122 // Don't return the default immediately;
123 // in a misconfiguration we need to fall back.
124 $key = $wgDefaultSkin;
127 if ( isset( $skinNames[$key] ) ) {
131 // Older versions of the software used a numeric setting
132 // in the user preferences.
138 if ( isset( $fallback[$key] ) ) {
139 $key = $fallback[$key];
142 if ( isset( $skinNames[$key] ) ) {
144 } elseif ( isset( $skinNames[$wgDefaultSkin] ) ) {
145 return $wgDefaultSkin;
152 * Factory method for loading a skin of a given type
153 * @param string $key 'monobook', 'standard', etc.
156 static function &newFromKey( $key ) {
157 global $wgStyleDirectory;
159 $key = Skin
::normalizeKey( $key );
161 $skinNames = Skin
::getSkinNames();
162 $skinName = $skinNames[$key];
163 $className = "Skin{$skinName}";
165 # Grab the skin class and initialise it.
166 if ( !class_exists( $className ) ) {
168 require_once "{$wgStyleDirectory}/{$skinName}.php";
170 # Check if we got if not fallback to default skin
171 if ( !class_exists( $className ) ) {
172 # DO NOT die if the class isn't found. This breaks maintenance
173 # scripts and can cause a user account to be unrecoverable
174 # except by SQL manipulation if a previously valid skin name
175 # is no longer valid.
176 wfDebug( "Skin class does not exist: $className\n" );
177 $className = 'SkinVector';
178 require_once "{$wgStyleDirectory}/Vector.php";
181 $skin = new $className( $key );
185 /** @return string skin name */
186 public function getSkinName() {
187 return $this->skinname
;
191 * @param $out OutputPage
193 function initPage( OutputPage
$out ) {
194 wfProfileIn( __METHOD__
);
196 $this->preloadExistence();
198 wfProfileOut( __METHOD__
);
202 * Defines the ResourceLoader modules that should be added to the skin
203 * It is recommended that skins wishing to override call parent::getDefaultModules()
204 * and substitute out any modules they wish to change by using a key to look them up
205 * @return Array of modules with helper keys for easy overriding
207 public function getDefaultModules() {
208 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
209 $wgAjaxWatch, $wgEnableAPI, $wgEnableWriteAPI;
211 $out = $this->getOutput();
212 $user = $out->getUser();
214 // modules that enhance the page content in some way
216 'mediawiki.page.ready',
218 // modules that exist for legacy reasons
220 // modules relating to search functionality
222 // modules relating to functionality relating to watching an article
224 // modules which relate to the current users preferences
227 if ( $wgIncludeLegacyJavaScript ) {
228 $modules['legacy'][] = 'mediawiki.legacy.wikibits';
231 if ( $wgPreloadJavaScriptMwUtil ) {
232 $modules['legacy'][] = 'mediawiki.util';
235 // Add various resources if required
237 $modules['legacy'][] = 'mediawiki.legacy.ajax';
239 if ( $wgEnableAPI ) {
240 if ( $wgEnableWriteAPI && $wgAjaxWatch && $user->isLoggedIn()
241 && $user->isAllowed( 'writeapi' )
243 $modules['watch'][] = 'mediawiki.page.watch.ajax';
246 $modules['search'][] = 'mediawiki.searchSuggest';
250 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
251 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
254 // Crazy edit-on-double-click stuff
255 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
256 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
262 * Preload the existence of three commonly-requested pages in a single query
264 function preloadExistence() {
265 $user = $this->getUser();
268 $titles = array( $user->getUserPage(), $user->getTalkPage() );
271 if ( $this->getTitle()->isSpecialPage() ) {
273 } elseif ( $this->getTitle()->isTalkPage() ) {
274 $titles[] = $this->getTitle()->getSubjectPage();
276 $titles[] = $this->getTitle()->getTalkPage();
279 $lb = new LinkBatch( $titles );
280 $lb->setCaller( __METHOD__
);
285 * Get the current revision ID
289 public function getRevisionId() {
290 return $this->getOutput()->getRevisionId();
294 * Whether the revision displayed is the latest revision of the page
298 public function isRevisionCurrent() {
299 $revID = $this->getRevisionId();
300 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
304 * Set the "relevant" title
305 * @see self::getRelevantTitle()
306 * @param $t Title object to use
308 public function setRelevantTitle( $t ) {
309 $this->mRelevantTitle
= $t;
313 * Return the "relevant" title.
314 * A "relevant" title is not necessarily the actual title of the page.
315 * Special pages like Special:MovePage use set the page they are acting on
316 * as their "relevant" title, this allows the skin system to display things
317 * such as content tabs which belong to to that page instead of displaying
318 * a basic special page tab which has almost no meaning.
322 public function getRelevantTitle() {
323 if ( isset( $this->mRelevantTitle
) ) {
324 return $this->mRelevantTitle
;
326 return $this->getTitle();
330 * Set the "relevant" user
331 * @see self::getRelevantUser()
332 * @param $u User object to use
334 public function setRelevantUser( $u ) {
335 $this->mRelevantUser
= $u;
339 * Return the "relevant" user.
340 * A "relevant" user is similar to a relevant title. Special pages like
341 * Special:Contributions mark the user which they are relevant to so that
342 * things like the toolbox can display the information they usually are only
343 * able to display on a user's userpage and talkpage.
346 public function getRelevantUser() {
347 if ( isset( $this->mRelevantUser
) ) {
348 return $this->mRelevantUser
;
350 $title = $this->getRelevantTitle();
351 if ( $title->hasSubjectNamespace( NS_USER
) ) {
352 $rootUser = $title->getRootText();
353 if ( User
::isIP( $rootUser ) ) {
354 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
356 $user = User
::newFromName( $rootUser, false );
357 if ( $user && $user->isLoggedIn() ) {
358 $this->mRelevantUser
= $user;
361 return $this->mRelevantUser
;
367 * Outputs the HTML generated by other functions.
368 * @param $out OutputPage
370 abstract function outputPage( OutputPage
$out = null );
376 static function makeVariablesScript( $data ) {
378 return Html
::inlineScript(
379 ResourceLoader
::makeLoaderConditionalScript( ResourceLoader
::makeConfigSetScript( $data ) )
387 * Make a "<script>" tag containing global variables
389 * @deprecated in 1.19
391 * @return string HTML fragment
393 public static function makeGlobalVariablesScript( $unused ) {
396 wfDeprecated( __METHOD__
, '1.19' );
398 return self
::makeVariablesScript( $wgOut->getJSVars() );
402 * Get the query to generate a dynamic stylesheet
406 public static function getDynamicStylesheetQuery() {
407 global $wgSquidMaxage;
411 'maxage' => $wgSquidMaxage,
412 'usemsgcache' => 'yes',
413 'ctype' => 'text/css',
414 'smaxage' => $wgSquidMaxage,
419 * Add skin specific stylesheets
420 * Calling this method with an $out of anything but the same OutputPage
421 * inside ->getOutput() is deprecated. The $out arg is kept
422 * for compatibility purposes with skins.
423 * @param $out OutputPage
426 abstract function setupSkinUserCss( OutputPage
$out );
430 * @param $title Title
433 function getPageClasses( $title ) {
434 $numeric = 'ns-' . $title->getNamespace();
436 if ( $title->isSpecialPage() ) {
437 $type = 'ns-special';
438 // bug 23315: provide a class based on the canonical special page name without subpages
439 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
440 if ( $canonicalName ) {
441 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
443 $type .= ' mw-invalidspecialpage';
445 } elseif ( $title->isTalkPage() ) {
448 $type = 'ns-subject';
451 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
453 return "$numeric $type $name";
457 * This will be called by OutputPage::headElement when it is creating the
458 * "<body>" tag, skins can override it if they have a need to add in any
459 * body attributes or classes of their own.
460 * @param $out OutputPage
461 * @param $bodyAttrs Array
463 function addToBodyAttributes( $out, &$bodyAttrs ) {
464 // does nothing by default
479 function getCategoryLinks() {
480 global $wgUseCategoryBrowser;
482 $out = $this->getOutput();
483 $allCats = $out->getCategoryLinks();
485 if ( !count( $allCats ) ) {
493 $colon = $this->msg( 'colon-separator' )->escaped();
495 if ( !empty( $allCats['normal'] ) ) {
496 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
498 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
499 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
500 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
501 Linker
::link( Title
::newFromText( $linkPage ), $msg )
502 . $colon . '<ul>' . $t . '</ul>' . '</div>';
506 if ( isset( $allCats['hidden'] ) ) {
507 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
508 $class = ' mw-hidden-cats-user-shown';
509 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
510 $class = ' mw-hidden-cats-ns-shown';
512 $class = ' mw-hidden-cats-hidden';
515 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
516 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
517 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
521 # optional 'dmoz-like' category browser. Will be shown under the list
522 # of categories an article belong to
523 if ( $wgUseCategoryBrowser ) {
524 $s .= '<br /><hr />';
526 # get a big array of the parents tree
527 $parenttree = $this->getTitle()->getParentCategoryTree();
528 # Skin object passed by reference cause it can not be
529 # accessed under the method subfunction drawCategoryBrowser
530 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
531 # Clean out bogus first entry and sort them
532 unset( $tempout[0] );
534 # Output one per line
535 $s .= implode( "<br />\n", $tempout );
542 * Render the array as a series of links.
543 * @param array $tree categories tree returned by Title::getParentCategoryTree
544 * @return String separated by >, terminate with "\n"
546 function drawCategoryBrowser( $tree ) {
549 foreach ( $tree as $element => $parent ) {
550 if ( empty( $parent ) ) {
551 # element start a new list
554 # grab the others elements
555 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
558 # add our current element to the list
559 $eltitle = Title
::newFromText( $element );
560 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
569 function getCategories() {
570 $out = $this->getOutput();
572 $catlinks = $this->getCategoryLinks();
574 $classes = 'catlinks';
576 // Check what we're showing
577 $allCats = $out->getCategoryLinks();
578 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
579 $this->getTitle()->getNamespace() == NS_CATEGORY
;
581 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
582 $classes .= ' catlinks-allhidden';
585 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
589 * This runs a hook to allow extensions placing their stuff after content
590 * and article metadata (e.g. categories).
591 * Note: This function has nothing to do with afterContent().
593 * This hook is placed here in order to allow using the same hook for all
594 * skins, both the SkinTemplate based ones and the older ones, which directly
595 * use this class to get their data.
597 * The output of this function gets processed in SkinTemplate::outputPage() for
598 * the SkinTemplate based skins, all other skins should directly echo it.
600 * @return String, empty by default, if not changed by any hook function.
602 protected function afterContentHook() {
605 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
606 // adding just some spaces shouldn't toggle the output
607 // of the whole <div/>, so we use trim() here
608 if ( trim( $data ) != '' ) {
609 // Doing this here instead of in the skins to
610 // ensure that the div has the same ID in all
612 $data = "<div id='mw-data-after-content'>\n" .
617 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
624 * Generate debug data HTML for displaying at the bottom of the main content
626 * @return String HTML containing debug data, if enabled (otherwise empty).
628 protected function generateDebugHTML() {
629 return MWDebug
::getHTMLDebugLog();
633 * This gets called shortly before the "</body>" tag.
635 * @return String HTML-wrapped JS code to be put before "</body>"
637 function bottomScripts() {
638 // TODO and the suckage continues. This function is really just a wrapper around
639 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
641 $bottomScriptText = $this->getOutput()->getBottomScripts();
642 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
644 return $bottomScriptText;
648 * Text with the permalink to the source page,
649 * usually shown on the footer of a printed page
651 * @return string HTML text with an URL
653 function printSource() {
654 $oldid = $this->getRevisionId();
656 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid ) ) );
658 // oldid not available for non existing pages
659 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
661 return $this->msg( 'retrievedfrom', '<a href="' . $url . '">' . $url . '</a>' )->text();
667 function getUndeleteLink() {
668 $action = $this->getRequest()->getVal( 'action', 'view' );
670 if ( $this->getUser()->isAllowed( 'deletedhistory' ) &&
671 ( $this->getTitle()->getArticleID() == 0 ||
$action == 'history' ) ) {
672 $n = $this->getTitle()->isDeleted();
675 if ( $this->getUser()->isAllowed( 'undelete' ) ) {
676 $msg = 'thisisdeleted';
678 $msg = 'viewdeleted';
681 return $this->msg( $msg )->rawParams(
683 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
684 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
695 function subPageSubtitle() {
697 $out = $this->getOutput();
700 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
704 if ( $out->isArticle() && MWNamespace
::hasSubpages( $out->getTitle()->getNamespace() ) ) {
705 $ptext = $this->getTitle()->getPrefixedText();
706 if ( preg_match( '/\//', $ptext ) ) {
707 $links = explode( '/', $ptext );
713 foreach ( $links as $link ) {
714 $growinglink .= $link;
716 $linkObj = Title
::newFromText( $growinglink );
718 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
719 $getlink = Linker
::linkKnown(
721 htmlspecialchars( $display )
727 $subpages .= $wgLang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
729 $subpages .= '< ';
732 $subpages .= $getlink;
746 * Returns true if the IP should be shown in the header
749 function showIPinHeader() {
750 global $wgShowIPinHeader;
751 return $wgShowIPinHeader && session_id() != '';
757 function getSearchLink() {
758 $searchPage = SpecialPage
::getTitleFor( 'Search' );
759 return $searchPage->getLocalURL();
765 function escapeSearchLink() {
766 return htmlspecialchars( $this->getSearchLink() );
770 * @param $type string
773 function getCopyright( $type = 'detect' ) {
774 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgContLang;
776 if ( $type == 'detect' ) {
777 if ( !$this->isRevisionCurrent() && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled() ) {
784 if ( $type == 'history' ) {
785 $msg = 'history_copyright';
790 if ( $wgRightsPage ) {
791 $title = Title
::newFromText( $wgRightsPage );
792 $link = Linker
::linkKnown( $title, $wgRightsText );
793 } elseif ( $wgRightsUrl ) {
794 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
795 } elseif ( $wgRightsText ) {
796 $link = $wgRightsText;
802 // Allow for site and per-namespace customization of copyright notice.
805 wfRunHooks( 'SkinCopyrightFooter', array( $this->getTitle(), $type, &$msg, &$link, &$forContent ) );
807 $msgObj = $this->msg( $msg )->rawParams( $link );
809 $msg = $msgObj->inContentLanguage()->text();
810 if ( $this->getLanguage()->getCode() !== $wgContLang->getCode() ) {
811 $msg = Html
::rawElement( 'span', array( 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $msg );
815 return $msgObj->text();
820 * @return null|string
822 function getCopyrightIcon() {
823 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
827 if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
828 $out = $wgCopyrightIcon;
829 } elseif ( $wgRightsIcon ) {
830 $icon = htmlspecialchars( $wgRightsIcon );
832 if ( $wgRightsUrl ) {
833 $url = htmlspecialchars( $wgRightsUrl );
834 $out .= '<a href="' . $url . '">';
837 $text = htmlspecialchars( $wgRightsText );
838 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
840 if ( $wgRightsUrl ) {
849 * Gets the powered by MediaWiki icon.
852 function getPoweredBy() {
855 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
856 $text = '<a href="//www.mediawiki.org/"><img src="' . $url . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
857 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
862 * Get the timestamp of the latest revision, formatted in user language
866 protected function lastModified() {
867 $timestamp = $this->getOutput()->getRevisionTimestamp();
869 # No cached timestamp, load it from the database
870 if ( $timestamp === null ) {
871 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
875 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
876 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
877 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text();
882 if ( wfGetLB()->getLaggedSlaveMode() ) {
883 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->text() . '</strong>';
890 * @param $align string
893 function logoText( $align = '' ) {
894 if ( $align != '' ) {
895 $a = " style='float: {$align};'";
900 $mp = $this->msg( 'mainpage' )->escaped();
901 $mptitle = Title
::newMainPage();
902 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
904 $logourl = $this->getLogo();
905 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
911 * Renders a $wgFooterIcons icon according to the method's arguments
912 * @param array $icon The icon to build the html for, see $wgFooterIcons for the format of this array
913 * @param bool|String $withImage Whether to use the icon's image or output a text-only footericon
914 * @return String HTML
916 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
917 if ( is_string( $icon ) ) {
919 } else { // Assuming array
920 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
921 unset( $icon["url"] );
922 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
923 $html = Html
::element( 'img', $icon ); // do this the lazy way, just pass icon data as an attribute array
925 $html = htmlspecialchars( $icon["alt"] );
928 $html = Html
::rawElement( 'a', array( "href" => $url ), $html );
935 * Gets the link to the wiki's main page.
938 function mainPageLink() {
939 $s = Linker
::linkKnown(
940 Title
::newMainPage(),
941 $this->msg( 'mainpage' )->escaped()
952 public function footerLink( $desc, $page ) {
953 // if the link description has been set to "-" in the default language,
954 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
955 // then it is disabled, for all languages.
958 // Otherwise, we display the link for the user, described in their
959 // language (which may or may not be the same as the default language),
960 // but we make the link target be the one site-wide page.
961 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
963 return Linker
::linkKnown(
965 $this->msg( $desc )->escaped()
971 * Gets the link to the wiki's privacy policy page.
972 * @return String HTML
974 function privacyLink() {
975 return $this->footerLink( 'privacy', 'privacypage' );
979 * Gets the link to the wiki's about page.
980 * @return String HTML
982 function aboutLink() {
983 return $this->footerLink( 'aboutsite', 'aboutpage' );
987 * Gets the link to the wiki's general disclaimers page.
988 * @return String HTML
990 function disclaimerLink() {
991 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
995 * Return URL options for the 'edit page' link.
996 * This may include an 'oldid' specifier, if the current page view is such.
1001 function editUrlOptions() {
1002 $options = array( 'action' => 'edit' );
1004 if ( !$this->isRevisionCurrent() ) {
1005 $options['oldid'] = intval( $this->getRevisionId() );
1012 * @param $id User|int
1015 function showEmailUser( $id ) {
1016 if ( $id instanceof User
) {
1019 $targetUser = User
::newFromId( $id );
1021 return $this->getUser()->canSendEmail() && # the sending user must have a confirmed email address
1022 $targetUser->canReceiveEmail(); # the target user must have a confirmed email address and allow emails from users
1026 * Return a fully resolved style path url to images or styles stored in the common folder.
1027 * This method returns a url resolved using the configured skin style path
1028 * and includes the style version inside of the url.
1029 * @param string $name The name or path of a skin resource file
1030 * @return String The fully resolved style path url including styleversion
1032 function getCommonStylePath( $name ) {
1033 global $wgStylePath, $wgStyleVersion;
1034 return "$wgStylePath/common/$name?$wgStyleVersion";
1038 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1039 * This method returns a url resolved using the configured skin style path
1040 * and includes the style version inside of the url.
1041 * @param string $name The name or path of a skin resource file
1042 * @return String The fully resolved style path url including styleversion
1044 function getSkinStylePath( $name ) {
1045 global $wgStylePath, $wgStyleVersion;
1046 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1049 /* these are used extensively in SkinTemplate, but also some other places */
1052 * @param $urlaction string
1055 static function makeMainPageUrl( $urlaction = '' ) {
1056 $title = Title
::newMainPage();
1057 self
::checkTitle( $title, '' );
1059 return $title->getLocalURL( $urlaction );
1063 * Make a URL for a Special Page using the given query and protocol.
1065 * If $proto is set to null, make a local URL. Otherwise, make a full
1066 * URL with the protocol specified.
1068 * @param string $name Name of the Special page
1069 * @param string $urlaction Query to append
1070 * @param $proto Protocol to use or null for a local URL
1073 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1074 $title = SpecialPage
::getSafeTitleFor( $name );
1075 if ( is_null( $proto ) ) {
1076 return $title->getLocalURL( $urlaction );
1078 return $title->getFullURL( $urlaction, false, $proto );
1083 * @param $name string
1084 * @param $subpage string
1085 * @param $urlaction string
1088 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1089 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1090 return $title->getLocalURL( $urlaction );
1094 * @param $name string
1095 * @param $urlaction string
1098 static function makeI18nUrl( $name, $urlaction = '' ) {
1099 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1100 self
::checkTitle( $title, $name );
1101 return $title->getLocalURL( $urlaction );
1105 * @param $name string
1106 * @param $urlaction string
1109 static function makeUrl( $name, $urlaction = '' ) {
1110 $title = Title
::newFromText( $name );
1111 self
::checkTitle( $title, $name );
1113 return $title->getLocalURL( $urlaction );
1117 * If url string starts with http, consider as external URL, else
1119 * @param $name String
1120 * @return String URL
1122 static function makeInternalOrExternalUrl( $name ) {
1123 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1126 return self
::makeUrl( $name );
1131 * this can be passed the NS number as defined in Language.php
1133 * @param $urlaction string
1134 * @param $namespace int
1137 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1138 $title = Title
::makeTitleSafe( $namespace, $name );
1139 self
::checkTitle( $title, $name );
1141 return $title->getLocalURL( $urlaction );
1145 * these return an array with the 'href' and boolean 'exists'
1147 * @param $urlaction string
1150 static function makeUrlDetails( $name, $urlaction = '' ) {
1151 $title = Title
::newFromText( $name );
1152 self
::checkTitle( $title, $name );
1155 'href' => $title->getLocalURL( $urlaction ),
1156 'exists' => $title->getArticleID() != 0,
1161 * Make URL details where the article exists (or at least it's convenient to think so)
1162 * @param string $name Article name
1163 * @param $urlaction String
1166 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1167 $title = Title
::newFromText( $name );
1168 self
::checkTitle( $title, $name );
1171 'href' => $title->getLocalURL( $urlaction ),
1177 * make sure we have some title to operate on
1179 * @param $title Title
1180 * @param $name string
1182 static function checkTitle( &$title, $name ) {
1183 if ( !is_object( $title ) ) {
1184 $title = Title
::newFromText( $name );
1185 if ( !is_object( $title ) ) {
1186 $title = Title
::newFromText( '--error: link target missing--' );
1192 * Build an array that represents the sidebar(s), the navigation bar among them.
1194 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1196 * The format of the returned array is array( heading => content, ... ), where:
1197 * - heading is the heading of a navigation portlet. It is either:
1198 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1199 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1200 * - plain text, which should be HTML-escaped by the skin
1201 * - content is the contents of the portlet. It is either:
1202 * - HTML text (<ul><li>...</li>...</ul>)
1203 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1204 * - (for a magic string as a key, any value)
1206 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1207 * and can technically insert anything in here; skin creators are expected to handle
1208 * values described above.
1212 function buildSidebar() {
1213 global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1214 wfProfileIn( __METHOD__
);
1216 $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() );
1218 if ( $wgEnableSidebarCache ) {
1219 $cachedsidebar = $wgMemc->get( $key );
1220 if ( $cachedsidebar ) {
1221 wfProfileOut( __METHOD__
);
1222 return $cachedsidebar;
1227 $this->addToSidebar( $bar, 'sidebar' );
1229 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1230 if ( $wgEnableSidebarCache ) {
1231 $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1234 wfProfileOut( __METHOD__
);
1238 * Add content from a sidebar system message
1239 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1241 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1244 * @param $message String
1246 function addToSidebar( &$bar, $message ) {
1247 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1251 * Add content from plain text
1254 * @param $text string
1257 function addToSidebarPlain( &$bar, $text ) {
1258 $lines = explode( "\n", $text );
1262 foreach ( $lines as $line ) {
1263 if ( strpos( $line, '*' ) !== 0 ) {
1266 $line = rtrim( $line, "\r" ); // for Windows compat
1268 if ( strpos( $line, '**' ) !== 0 ) {
1269 $heading = trim( $line, '* ' );
1270 if ( !array_key_exists( $heading, $bar ) ) {
1271 $bar[$heading] = array();
1274 $line = trim( $line, '* ' );
1276 if ( strpos( $line, '|' ) !== false ) { // sanity check
1277 $line = MessageCache
::singleton()->transform( $line, false, null, $this->getTitle() );
1278 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1279 if ( count( $line ) !== 2 ) {
1280 // Second sanity check, could be hit by people doing
1281 // funky stuff with parserfuncs... (bug 33321)
1285 $extraAttribs = array();
1287 $msgLink = $this->msg( $line[0] )->inContentLanguage();
1288 if ( $msgLink->exists() ) {
1289 $link = $msgLink->text();
1290 if ( $link == '-' ) {
1296 $msgText = $this->msg( $line[1] );
1297 if ( $msgText->exists() ) {
1298 $text = $msgText->text();
1303 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1306 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1307 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1308 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1309 $extraAttribs['rel'] = 'nofollow';
1312 global $wgExternalLinkTarget;
1313 if ( $wgExternalLinkTarget ) {
1314 $extraAttribs['target'] = $wgExternalLinkTarget;
1317 $title = Title
::newFromText( $link );
1320 $title = $title->fixSpecialName();
1321 $href = $title->getLinkURL();
1323 $href = 'INVALID-TITLE';
1327 $bar[$heading][] = array_merge( array(
1330 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1343 * This function previously controlled whether the 'mediawiki.legacy.wikiprintable' module
1344 * should be loaded by OutputPage. That module no longer exists and the return value of this
1345 * method is ignored.
1347 * If your skin doesn't provide its own print styles, the 'mediawiki.legacy.commonPrint' module
1348 * can be used instead (SkinTemplate-based skins do it automatically).
1350 * @deprecated since 1.22
1353 public function commonPrintStylesheet() {
1354 wfDeprecated( __METHOD__
, '1.22' );
1359 * Gets new talk page messages for the current user and returns an
1360 * appropriate alert message (or an empty string if there are no messages)
1363 function getNewtalks() {
1365 $newMessagesAlert = '';
1366 $user = $this->getUser();
1367 $newtalks = $user->getNewMessageLinks();
1368 $out = $this->getOutput();
1370 // Allow extensions to disable or modify the new messages alert
1371 if ( !wfRunHooks( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) {
1374 if ( $newMessagesAlert ) {
1375 return $newMessagesAlert;
1378 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1379 $uTalkTitle = $user->getTalkPage();
1380 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1382 if ( $lastSeenRev !== null ) {
1383 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1384 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1385 if ( $latestRev !== null ) {
1386 // Singular if only 1 unseen revision, plural if several unseen revisions.
1387 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1388 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1389 $lastSeenRev, $latestRev, 10, 'include_new' );
1392 // Singular if no revision -> diff link will show latest change only in any case
1395 $plural = $plural ?
999 : 1;
1396 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1397 // the number of revisions or authors is not necessarily the same as the number of
1399 $newMessagesLink = Linker
::linkKnown(
1401 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1403 array( 'redirect' => 'no' )
1406 $newMessagesDiffLink = Linker
::linkKnown(
1408 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1410 $lastSeenRev !== null
1411 ?
array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' )
1412 : array( 'diff' => 'cur' )
1415 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1416 $newMessagesAlert = $this->msg(
1417 'youhavenewmessagesfromusers',
1419 $newMessagesDiffLink
1420 )->numParams( $nofAuthors, $plural );
1422 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1423 $newMessagesAlert = $this->msg(
1424 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1426 $newMessagesDiffLink
1427 )->numParams( $plural );
1429 $newMessagesAlert = $newMessagesAlert->text();
1430 # Disable Squid cache
1431 $out->setSquidMaxage( 0 );
1432 } elseif ( count( $newtalks ) ) {
1433 $sep = $this->msg( 'newtalkseparator' )->escaped();
1436 foreach ( $newtalks as $newtalk ) {
1437 $msgs[] = Xml
::element(
1439 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1442 $parts = implode( $sep, $msgs );
1443 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1444 $out->setSquidMaxage( 0 );
1447 return $newMessagesAlert;
1451 * Get a cached notice
1453 * @param string $name message name, or 'default' for $wgSiteNotice
1454 * @return String: HTML fragment
1456 private function getCachedNotice( $name ) {
1457 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1459 wfProfileIn( __METHOD__
);
1463 if ( $name === 'default' ) {
1465 global $wgSiteNotice;
1466 $notice = $wgSiteNotice;
1467 if ( empty( $notice ) ) {
1468 wfProfileOut( __METHOD__
);
1472 $msg = $this->msg( $name )->inContentLanguage();
1473 if ( $msg->isDisabled() ) {
1474 wfProfileOut( __METHOD__
);
1477 $notice = $msg->plain();
1480 // Use the extra hash appender to let eg SSL variants separately cache.
1481 $key = wfMemcKey( $name . $wgRenderHashAppend );
1482 $cachedNotice = $parserMemc->get( $key );
1483 if ( is_array( $cachedNotice ) ) {
1484 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1485 $notice = $cachedNotice['html'];
1494 $parsed = $this->getOutput()->parse( $notice );
1495 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1499 $notice = Html
::rawElement( 'div', array( 'id' => 'localNotice',
1500 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice );
1501 wfProfileOut( __METHOD__
);
1506 * Get a notice based on page's namespace
1508 * @return String: HTML fragment
1510 function getNamespaceNotice() {
1511 wfProfileIn( __METHOD__
);
1513 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1514 $namespaceNotice = $this->getCachedNotice( $key );
1515 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
1516 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1518 $namespaceNotice = '';
1521 wfProfileOut( __METHOD__
);
1522 return $namespaceNotice;
1526 * Get the site notice
1528 * @return String: HTML fragment
1530 function getSiteNotice() {
1531 wfProfileIn( __METHOD__
);
1534 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1535 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1536 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1538 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1539 if ( !$anonNotice ) {
1540 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1542 $siteNotice = $anonNotice;
1545 if ( !$siteNotice ) {
1546 $siteNotice = $this->getCachedNotice( 'default' );
1550 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1551 wfProfileOut( __METHOD__
);
1556 * Create a section edit link. This supersedes editSectionLink() and
1557 * editSectionLinkForOther().
1559 * @param $nt Title The title being linked to (may not be the same as
1560 * the current page, if the section is included from a template)
1561 * @param string $section The designation of the section being pointed to,
1562 * to be included in the link, like "§ion=$section"
1563 * @param string $tooltip The tooltip to use for the link: will be escaped
1564 * and wrapped in the 'editsectionhint' message
1565 * @param $lang string Language code
1566 * @return string HTML to use for edit link
1568 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1569 // HTML generated here should probably have userlangattributes
1570 // added to it for LTR text on RTL pages
1572 $lang = wfGetLangObj( $lang );
1575 if ( !is_null( $tooltip ) ) {
1576 # Bug 25462: undo double-escaping.
1577 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1578 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1579 ->inLanguage( $lang )->text();
1581 $link = Linker
::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(),
1583 array( 'action' => 'edit', 'section' => $section ),
1584 array( 'noclasses', 'known' )
1587 # Add the brackets and the span and run the hook.
1588 $result = '<span class="mw-editsection">'
1589 . '<span class="mw-editsection-bracket">[</span>'
1591 . '<span class="mw-editsection-bracket">]</span>'
1594 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1599 * Use PHP's magic __call handler to intercept legacy calls to the linker
1600 * for backwards compatibility.
1602 * @param string $fname Name of called method
1603 * @param array $args Arguments to the method
1604 * @throws MWException
1607 function __call( $fname, $args ) {
1608 $realFunction = array( 'Linker', $fname );
1609 if ( is_callable( $realFunction ) ) {
1610 wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' );
1611 return call_user_func_array( $realFunction, $args );
1613 $className = get_class( $this );
1614 throw new MWException( "Call to undefined method $className::$fname" );