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-$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.
94 * @return array of strings
96 public static function getUsableSkins() {
99 $allowedSkins = self
::getSkinNames();
101 foreach ( $wgSkipSkins as $skip ) {
102 unset( $allowedSkins[$skip] );
105 return $allowedSkins;
109 * Normalize a skin preference value to a form that can be loaded.
110 * If a skin can't be found, it will fall back to the configured
111 * default (or the old 'Classic' skin if that's broken).
112 * @param string $key 'monobook', 'standard', etc.
115 static function normalizeKey( $key ) {
116 global $wgDefaultSkin;
118 $skinNames = Skin
::getSkinNames();
120 if ( $key == '' ||
$key == 'default' ) {
121 // Don't return the default immediately;
122 // in a misconfiguration we need to fall back.
123 $key = $wgDefaultSkin;
126 if ( isset( $skinNames[$key] ) ) {
130 // Older versions of the software used a numeric setting
131 // in the user preferences.
137 if ( isset( $fallback[$key] ) ) {
138 $key = $fallback[$key];
141 if ( isset( $skinNames[$key] ) ) {
143 } elseif ( isset( $skinNames[$wgDefaultSkin] ) ) {
144 return $wgDefaultSkin;
151 * Factory method for loading a skin of a given type
152 * @param string $key 'monobook', 'standard', etc.
155 static function &newFromKey( $key ) {
156 global $wgStyleDirectory;
158 $key = Skin
::normalizeKey( $key );
160 $skinNames = Skin
::getSkinNames();
161 $skinName = $skinNames[$key];
162 $className = "Skin{$skinName}";
164 # Grab the skin class and initialise it.
165 if ( !class_exists( $className ) ) {
167 require_once "{$wgStyleDirectory}/{$skinName}.php";
169 # Check if we got if not fallback to default skin
170 if ( !class_exists( $className ) ) {
171 # DO NOT die if the class isn't found. This breaks maintenance
172 # scripts and can cause a user account to be unrecoverable
173 # except by SQL manipulation if a previously valid skin name
174 # is no longer valid.
175 wfDebug( "Skin class does not exist: $className\n" );
176 $className = 'SkinVector';
177 require_once "{$wgStyleDirectory}/Vector.php";
180 $skin = new $className( $key );
184 /** @return string skin name */
185 public function getSkinName() {
186 return $this->skinname
;
190 * @param $out OutputPage
192 function initPage( OutputPage
$out ) {
193 wfProfileIn( __METHOD__
);
195 $this->preloadExistence();
197 wfProfileOut( __METHOD__
);
201 * Defines the ResourceLoader modules that should be added to the skin
202 * It is recommended that skins wishing to override call parent::getDefaultModules()
203 * and substitute out any modules they wish to change by using a key to look them up
204 * @return Array of modules with helper keys for easy overriding
206 public function getDefaultModules() {
207 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
210 $out = $this->getOutput();
211 $user = $out->getUser();
213 // modules that enhance the page content in some way
215 'mediawiki.page.ready',
217 // modules that exist for legacy reasons
219 // modules relating to search functionality
221 // modules relating to functionality relating to watching an article
223 // modules which relate to the current users preferences
226 if ( $wgIncludeLegacyJavaScript ) {
227 $modules['legacy'][] = 'mediawiki.legacy.wikibits';
230 if ( $wgPreloadJavaScriptMwUtil ) {
231 $modules['legacy'][] = 'mediawiki.util';
234 // Add various resources if required
236 $modules['legacy'][] = 'mediawiki.legacy.ajax';
238 if ( $wgAjaxWatch && $user->isLoggedIn() ) {
239 $modules['watch'][] = 'mediawiki.page.watch.ajax';
242 if ( !$user->getOption( 'disablesuggest', false ) ) {
243 $modules['search'][] = 'mediawiki.searchSuggest';
247 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
248 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
251 // Crazy edit-on-double-click stuff
252 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
253 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
259 * Preload the existence of three commonly-requested pages in a single query
261 function preloadExistence() {
262 $user = $this->getUser();
265 $titles = array( $user->getUserPage(), $user->getTalkPage() );
268 if ( $this->getTitle()->isSpecialPage() ) {
270 } elseif ( $this->getTitle()->isTalkPage() ) {
271 $titles[] = $this->getTitle()->getSubjectPage();
273 $titles[] = $this->getTitle()->getTalkPage();
276 $lb = new LinkBatch( $titles );
277 $lb->setCaller( __METHOD__
);
282 * Get the current revision ID
286 public function getRevisionId() {
287 return $this->getOutput()->getRevisionId();
291 * Whether the revision displayed is the latest revision of the page
295 public function isRevisionCurrent() {
296 $revID = $this->getRevisionId();
297 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
301 * Set the "relevant" title
302 * @see self::getRelevantTitle()
303 * @param $t Title object to use
305 public function setRelevantTitle( $t ) {
306 $this->mRelevantTitle
= $t;
310 * Return the "relevant" title.
311 * A "relevant" title is not necessarily the actual title of the page.
312 * Special pages like Special:MovePage use set the page they are acting on
313 * as their "relevant" title, this allows the skin system to display things
314 * such as content tabs which belong to to that page instead of displaying
315 * a basic special page tab which has almost no meaning.
319 public function getRelevantTitle() {
320 if ( isset( $this->mRelevantTitle
) ) {
321 return $this->mRelevantTitle
;
323 return $this->getTitle();
327 * Set the "relevant" user
328 * @see self::getRelevantUser()
329 * @param $u User object to use
331 public function setRelevantUser( $u ) {
332 $this->mRelevantUser
= $u;
336 * Return the "relevant" user.
337 * A "relevant" user is similar to a relevant title. Special pages like
338 * Special:Contributions mark the user which they are relevant to so that
339 * things like the toolbox can display the information they usually are only
340 * able to display on a user's userpage and talkpage.
343 public function getRelevantUser() {
344 if ( isset( $this->mRelevantUser
) ) {
345 return $this->mRelevantUser
;
347 $title = $this->getRelevantTitle();
348 if ( $title->hasSubjectNamespace( NS_USER
) ) {
349 $rootUser = $title->getRootText();
350 if ( User
::isIP( $rootUser ) ) {
351 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
353 $user = User
::newFromName( $rootUser, false );
354 if ( $user && $user->isLoggedIn() ) {
355 $this->mRelevantUser
= $user;
358 return $this->mRelevantUser
;
364 * Outputs the HTML generated by other functions.
365 * @param $out OutputPage
367 abstract function outputPage( OutputPage
$out = null );
373 static function makeVariablesScript( $data ) {
375 return Html
::inlineScript(
376 ResourceLoader
::makeLoaderConditionalScript( ResourceLoader
::makeConfigSetScript( $data ) )
384 * Make a "<script>" tag containing global variables
386 * @deprecated in 1.19
388 * @return string HTML fragment
390 public static function makeGlobalVariablesScript( $unused ) {
393 wfDeprecated( __METHOD__
, '1.19' );
395 return self
::makeVariablesScript( $wgOut->getJSVars() );
399 * Get the query to generate a dynamic stylesheet
403 public static function getDynamicStylesheetQuery() {
404 global $wgSquidMaxage;
408 'maxage' => $wgSquidMaxage,
409 'usemsgcache' => 'yes',
410 'ctype' => 'text/css',
411 'smaxage' => $wgSquidMaxage,
416 * Add skin specific stylesheets
417 * Calling this method with an $out of anything but the same OutputPage
418 * inside ->getOutput() is deprecated. The $out arg is kept
419 * for compatibility purposes with skins.
420 * @param $out OutputPage
423 abstract function setupSkinUserCss( OutputPage
$out );
427 * @param $title Title
430 function getPageClasses( $title ) {
431 $numeric = 'ns-' . $title->getNamespace();
433 if ( $title->isSpecialPage() ) {
434 $type = 'ns-special';
435 // bug 23315: provide a class based on the canonical special page name without subpages
436 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
437 if ( $canonicalName ) {
438 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
440 $type .= ' mw-invalidspecialpage';
442 } elseif ( $title->isTalkPage() ) {
445 $type = 'ns-subject';
448 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
450 return "$numeric $type $name";
454 * This will be called by OutputPage::headElement when it is creating the
455 * "<body>" tag, skins can override it if they have a need to add in any
456 * body attributes or classes of their own.
457 * @param $out OutputPage
458 * @param $bodyAttrs Array
460 function addToBodyAttributes( $out, &$bodyAttrs ) {
461 // does nothing by default
476 function getCategoryLinks() {
477 global $wgUseCategoryBrowser;
479 $out = $this->getOutput();
480 $allCats = $out->getCategoryLinks();
482 if ( !count( $allCats ) ) {
490 $colon = $this->msg( 'colon-separator' )->escaped();
492 if ( !empty( $allCats['normal'] ) ) {
493 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
495 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
496 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
497 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
498 Linker
::link( Title
::newFromText( $linkPage ), $msg )
499 . $colon . '<ul>' . $t . '</ul>' . '</div>';
503 if ( isset( $allCats['hidden'] ) ) {
504 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
505 $class = ' mw-hidden-cats-user-shown';
506 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
507 $class = ' mw-hidden-cats-ns-shown';
509 $class = ' mw-hidden-cats-hidden';
512 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
513 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
514 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
518 # optional 'dmoz-like' category browser. Will be shown under the list
519 # of categories an article belong to
520 if ( $wgUseCategoryBrowser ) {
521 $s .= '<br /><hr />';
523 # get a big array of the parents tree
524 $parenttree = $this->getTitle()->getParentCategoryTree();
525 # Skin object passed by reference cause it can not be
526 # accessed under the method subfunction drawCategoryBrowser
527 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
528 # Clean out bogus first entry and sort them
529 unset( $tempout[0] );
531 # Output one per line
532 $s .= implode( "<br />\n", $tempout );
539 * Render the array as a series of links.
540 * @param array $tree categories tree returned by Title::getParentCategoryTree
541 * @return String separated by >, terminate with "\n"
543 function drawCategoryBrowser( $tree ) {
546 foreach ( $tree as $element => $parent ) {
547 if ( empty( $parent ) ) {
548 # element start a new list
551 # grab the others elements
552 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
555 # add our current element to the list
556 $eltitle = Title
::newFromText( $element );
557 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
566 function getCategories() {
567 $out = $this->getOutput();
569 $catlinks = $this->getCategoryLinks();
571 $classes = 'catlinks';
573 // Check what we're showing
574 $allCats = $out->getCategoryLinks();
575 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
576 $this->getTitle()->getNamespace() == NS_CATEGORY
;
578 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
579 $classes .= ' catlinks-allhidden';
582 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
586 * This runs a hook to allow extensions placing their stuff after content
587 * and article metadata (e.g. categories).
588 * Note: This function has nothing to do with afterContent().
590 * This hook is placed here in order to allow using the same hook for all
591 * skins, both the SkinTemplate based ones and the older ones, which directly
592 * use this class to get their data.
594 * The output of this function gets processed in SkinTemplate::outputPage() for
595 * the SkinTemplate based skins, all other skins should directly echo it.
597 * @return String, empty by default, if not changed by any hook function.
599 protected function afterContentHook() {
602 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
603 // adding just some spaces shouldn't toggle the output
604 // of the whole <div/>, so we use trim() here
605 if ( trim( $data ) != '' ) {
606 // Doing this here instead of in the skins to
607 // ensure that the div has the same ID in all
609 $data = "<div id='mw-data-after-content'>\n" .
614 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
621 * Generate debug data HTML for displaying at the bottom of the main content
623 * @return String HTML containing debug data, if enabled (otherwise empty).
625 protected function generateDebugHTML() {
626 return MWDebug
::getHTMLDebugLog();
630 * This gets called shortly before the "</body>" tag.
632 * @return String HTML-wrapped JS code to be put before "</body>"
634 function bottomScripts() {
635 // TODO and the suckage continues. This function is really just a wrapper around
636 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
638 $bottomScriptText = $this->getOutput()->getBottomScripts();
639 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
641 return $bottomScriptText;
645 * Text with the permalink to the source page,
646 * usually shown on the footer of a printed page
648 * @return string HTML text with an URL
650 function printSource() {
651 $oldid = $this->getRevisionId();
653 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid ) ) );
655 // oldid not available for non existing pages
656 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
658 return $this->msg( 'retrievedfrom', '<a href="' . $url . '">' . $url . '</a>' )->text();
664 function getUndeleteLink() {
665 $action = $this->getRequest()->getVal( 'action', 'view' );
667 if ( $this->getUser()->isAllowed( 'deletedhistory' ) &&
668 ( $this->getTitle()->getArticleID() == 0 ||
$action == 'history' ) ) {
669 $n = $this->getTitle()->isDeleted();
672 if ( $this->getUser()->isAllowed( 'undelete' ) ) {
673 $msg = 'thisisdeleted';
675 $msg = 'viewdeleted';
678 return $this->msg( $msg )->rawParams(
680 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
681 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
692 function subPageSubtitle() {
694 $out = $this->getOutput();
697 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
701 if ( $out->isArticle() && MWNamespace
::hasSubpages( $out->getTitle()->getNamespace() ) ) {
702 $ptext = $this->getTitle()->getPrefixedText();
703 if ( preg_match( '/\//', $ptext ) ) {
704 $links = explode( '/', $ptext );
710 foreach ( $links as $link ) {
711 $growinglink .= $link;
713 $linkObj = Title
::newFromText( $growinglink );
715 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
716 $getlink = Linker
::linkKnown(
718 htmlspecialchars( $display )
724 $subpages .= $wgLang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
726 $subpages .= '< ';
729 $subpages .= $getlink;
743 * Returns true if the IP should be shown in the header
746 function showIPinHeader() {
747 global $wgShowIPinHeader;
748 return $wgShowIPinHeader && session_id() != '';
754 function getSearchLink() {
755 $searchPage = SpecialPage
::getTitleFor( 'Search' );
756 return $searchPage->getLocalURL();
762 function escapeSearchLink() {
763 return htmlspecialchars( $this->getSearchLink() );
767 * @param $type string
770 function getCopyright( $type = 'detect' ) {
771 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgContLang;
773 if ( $type == 'detect' ) {
774 if ( !$this->isRevisionCurrent() && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled() ) {
781 if ( $type == 'history' ) {
782 $msg = 'history_copyright';
787 if ( $wgRightsPage ) {
788 $title = Title
::newFromText( $wgRightsPage );
789 $link = Linker
::linkKnown( $title, $wgRightsText );
790 } elseif ( $wgRightsUrl ) {
791 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
792 } elseif ( $wgRightsText ) {
793 $link = $wgRightsText;
799 // Allow for site and per-namespace customization of copyright notice.
802 wfRunHooks( 'SkinCopyrightFooter', array( $this->getTitle(), $type, &$msg, &$link, &$forContent ) );
804 $msgObj = $this->msg( $msg )->rawParams( $link );
806 $msg = $msgObj->inContentLanguage()->text();
807 if ( $this->getLanguage()->getCode() !== $wgContLang->getCode() ) {
808 $msg = Html
::rawElement( 'span', array( 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $msg );
812 return $msgObj->text();
817 * @return null|string
819 function getCopyrightIcon() {
820 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
824 if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
825 $out = $wgCopyrightIcon;
826 } elseif ( $wgRightsIcon ) {
827 $icon = htmlspecialchars( $wgRightsIcon );
829 if ( $wgRightsUrl ) {
830 $url = htmlspecialchars( $wgRightsUrl );
831 $out .= '<a href="' . $url . '">';
834 $text = htmlspecialchars( $wgRightsText );
835 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
837 if ( $wgRightsUrl ) {
846 * Gets the powered by MediaWiki icon.
849 function getPoweredBy() {
852 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
853 $text = '<a href="//www.mediawiki.org/"><img src="' . $url . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
854 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
859 * Get the timestamp of the latest revision, formatted in user language
863 protected function lastModified() {
864 $timestamp = $this->getOutput()->getRevisionTimestamp();
866 # No cached timestamp, load it from the database
867 if ( $timestamp === null ) {
868 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
872 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
873 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
874 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text();
879 if ( wfGetLB()->getLaggedSlaveMode() ) {
880 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->text() . '</strong>';
887 * @param $align string
890 function logoText( $align = '' ) {
891 if ( $align != '' ) {
892 $a = " style='float: {$align};'";
897 $mp = $this->msg( 'mainpage' )->escaped();
898 $mptitle = Title
::newMainPage();
899 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
901 $logourl = $this->getLogo();
902 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
908 * Renders a $wgFooterIcons icon according to the method's arguments
909 * @param array $icon The icon to build the html for, see $wgFooterIcons for the format of this array
910 * @param bool|String $withImage Whether to use the icon's image or output a text-only footericon
911 * @return String HTML
913 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
914 if ( is_string( $icon ) ) {
916 } else { // Assuming array
917 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
918 unset( $icon["url"] );
919 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
920 $html = Html
::element( 'img', $icon ); // do this the lazy way, just pass icon data as an attribute array
922 $html = htmlspecialchars( $icon["alt"] );
925 $html = Html
::rawElement( 'a', array( "href" => $url ), $html );
932 * Gets the link to the wiki's main page.
935 function mainPageLink() {
936 $s = Linker
::linkKnown(
937 Title
::newMainPage(),
938 $this->msg( 'mainpage' )->escaped()
949 public function footerLink( $desc, $page ) {
950 // if the link description has been set to "-" in the default language,
951 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
952 // then it is disabled, for all languages.
955 // Otherwise, we display the link for the user, described in their
956 // language (which may or may not be the same as the default language),
957 // but we make the link target be the one site-wide page.
958 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
960 return Linker
::linkKnown(
962 $this->msg( $desc )->escaped()
968 * Gets the link to the wiki's privacy policy page.
969 * @return String HTML
971 function privacyLink() {
972 return $this->footerLink( 'privacy', 'privacypage' );
976 * Gets the link to the wiki's about page.
977 * @return String HTML
979 function aboutLink() {
980 return $this->footerLink( 'aboutsite', 'aboutpage' );
984 * Gets the link to the wiki's general disclaimers page.
985 * @return String HTML
987 function disclaimerLink() {
988 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
992 * Return URL options for the 'edit page' link.
993 * This may include an 'oldid' specifier, if the current page view is such.
998 function editUrlOptions() {
999 $options = array( 'action' => 'edit' );
1001 if ( !$this->isRevisionCurrent() ) {
1002 $options['oldid'] = intval( $this->getRevisionId() );
1009 * @param $id User|int
1012 function showEmailUser( $id ) {
1013 if ( $id instanceof User
) {
1016 $targetUser = User
::newFromId( $id );
1018 return $this->getUser()->canSendEmail() && # the sending user must have a confirmed email address
1019 $targetUser->canReceiveEmail(); # the target user must have a confirmed email address and allow emails from users
1023 * Return a fully resolved style path url to images or styles stored in the common folder.
1024 * This method returns a url resolved using the configured skin style path
1025 * and includes the style version inside of the url.
1026 * @param string $name The name or path of a skin resource file
1027 * @return String The fully resolved style path url including styleversion
1029 function getCommonStylePath( $name ) {
1030 global $wgStylePath, $wgStyleVersion;
1031 return "$wgStylePath/common/$name?$wgStyleVersion";
1035 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1036 * This method returns a url resolved using the configured skin style path
1037 * and includes the style version inside of the url.
1038 * @param string $name The name or path of a skin resource file
1039 * @return String The fully resolved style path url including styleversion
1041 function getSkinStylePath( $name ) {
1042 global $wgStylePath, $wgStyleVersion;
1043 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1046 /* these are used extensively in SkinTemplate, but also some other places */
1049 * @param $urlaction string
1052 static function makeMainPageUrl( $urlaction = '' ) {
1053 $title = Title
::newMainPage();
1054 self
::checkTitle( $title, '' );
1056 return $title->getLocalURL( $urlaction );
1060 * Make a URL for a Special Page using the given query and protocol.
1062 * If $proto is set to null, make a local URL. Otherwise, make a full
1063 * URL with the protocol specified.
1065 * @param string $name Name of the Special page
1066 * @param string $urlaction Query to append
1067 * @param $proto Protocol to use or null for a local URL
1070 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1071 $title = SpecialPage
::getSafeTitleFor( $name );
1072 if ( is_null( $proto ) ) {
1073 return $title->getLocalURL( $urlaction );
1075 return $title->getFullURL( $urlaction, false, $proto );
1080 * @param $name string
1081 * @param $subpage string
1082 * @param $urlaction string
1085 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1086 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1087 return $title->getLocalURL( $urlaction );
1091 * @param $name string
1092 * @param $urlaction string
1095 static function makeI18nUrl( $name, $urlaction = '' ) {
1096 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1097 self
::checkTitle( $title, $name );
1098 return $title->getLocalURL( $urlaction );
1102 * @param $name string
1103 * @param $urlaction string
1106 static function makeUrl( $name, $urlaction = '' ) {
1107 $title = Title
::newFromText( $name );
1108 self
::checkTitle( $title, $name );
1110 return $title->getLocalURL( $urlaction );
1114 * If url string starts with http, consider as external URL, else
1116 * @param $name String
1117 * @return String URL
1119 static function makeInternalOrExternalUrl( $name ) {
1120 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1123 return self
::makeUrl( $name );
1128 * this can be passed the NS number as defined in Language.php
1130 * @param $urlaction string
1131 * @param $namespace int
1134 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1135 $title = Title
::makeTitleSafe( $namespace, $name );
1136 self
::checkTitle( $title, $name );
1138 return $title->getLocalURL( $urlaction );
1142 * these return an array with the 'href' and boolean 'exists'
1144 * @param $urlaction string
1147 static function makeUrlDetails( $name, $urlaction = '' ) {
1148 $title = Title
::newFromText( $name );
1149 self
::checkTitle( $title, $name );
1152 'href' => $title->getLocalURL( $urlaction ),
1153 'exists' => $title->getArticleID() != 0,
1158 * Make URL details where the article exists (or at least it's convenient to think so)
1159 * @param string $name Article name
1160 * @param $urlaction String
1163 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1164 $title = Title
::newFromText( $name );
1165 self
::checkTitle( $title, $name );
1168 'href' => $title->getLocalURL( $urlaction ),
1174 * make sure we have some title to operate on
1176 * @param $title Title
1177 * @param $name string
1179 static function checkTitle( &$title, $name ) {
1180 if ( !is_object( $title ) ) {
1181 $title = Title
::newFromText( $name );
1182 if ( !is_object( $title ) ) {
1183 $title = Title
::newFromText( '--error: link target missing--' );
1189 * Build an array that represents the sidebar(s), the navigation bar among them.
1191 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1193 * The format of the returned array is array( heading => content, ... ), where:
1194 * - heading is the heading of a navigation portlet. It is either:
1195 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1196 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1197 * - plain text, which should be HTML-escaped by the skin
1198 * - content is the contents of the portlet. It is either:
1199 * - HTML text (<ul><li>...</li>...</ul>)
1200 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1201 * - (for a magic string as a key, any value)
1203 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1204 * and can technically insert anything in here; skin creators are expected to handle
1205 * values described above.
1209 function buildSidebar() {
1210 global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1211 wfProfileIn( __METHOD__
);
1213 $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() );
1215 if ( $wgEnableSidebarCache ) {
1216 $cachedsidebar = $wgMemc->get( $key );
1217 if ( $cachedsidebar ) {
1218 wfProfileOut( __METHOD__
);
1219 return $cachedsidebar;
1224 $this->addToSidebar( $bar, 'sidebar' );
1226 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1227 if ( $wgEnableSidebarCache ) {
1228 $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1231 wfProfileOut( __METHOD__
);
1235 * Add content from a sidebar system message
1236 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1238 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1241 * @param $message String
1243 function addToSidebar( &$bar, $message ) {
1244 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1248 * Add content from plain text
1251 * @param $text string
1254 function addToSidebarPlain( &$bar, $text ) {
1255 $lines = explode( "\n", $text );
1259 foreach ( $lines as $line ) {
1260 if ( strpos( $line, '*' ) !== 0 ) {
1263 $line = rtrim( $line, "\r" ); // for Windows compat
1265 if ( strpos( $line, '**' ) !== 0 ) {
1266 $heading = trim( $line, '* ' );
1267 if ( !array_key_exists( $heading, $bar ) ) {
1268 $bar[$heading] = array();
1271 $line = trim( $line, '* ' );
1273 if ( strpos( $line, '|' ) !== false ) { // sanity check
1274 $line = MessageCache
::singleton()->transform( $line, false, null, $this->getTitle() );
1275 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1276 if ( count( $line ) !== 2 ) {
1277 // Second sanity check, could be hit by people doing
1278 // funky stuff with parserfuncs... (bug 33321)
1282 $extraAttribs = array();
1284 $msgLink = $this->msg( $line[0] )->inContentLanguage();
1285 if ( $msgLink->exists() ) {
1286 $link = $msgLink->text();
1287 if ( $link == '-' ) {
1293 $msgText = $this->msg( $line[1] );
1294 if ( $msgText->exists() ) {
1295 $text = $msgText->text();
1300 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1303 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1304 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1305 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1306 $extraAttribs['rel'] = 'nofollow';
1309 global $wgExternalLinkTarget;
1310 if ( $wgExternalLinkTarget ) {
1311 $extraAttribs['target'] = $wgExternalLinkTarget;
1314 $title = Title
::newFromText( $link );
1317 $title = $title->fixSpecialName();
1318 $href = $title->getLinkURL();
1320 $href = 'INVALID-TITLE';
1324 $bar[$heading][] = array_merge( array(
1327 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1340 * Should we load mediawiki.legacy.wikiprintable? Skins that have their own
1341 * print stylesheet should override this and return false. (This is an
1342 * ugly hack to get Monobook to play nicely with OutputPage::headElement().)
1346 public function commonPrintStylesheet() {
1351 * Gets new talk page messages for the current user and returns an
1352 * appropriate alert message (or an empty string if there are no messages)
1355 function getNewtalks() {
1357 $newMessagesAlert = '';
1358 $user = $this->getUser();
1359 $newtalks = $user->getNewMessageLinks();
1360 $out = $this->getOutput();
1362 // Allow extensions to disable or modify the new messages alert
1363 if ( !wfRunHooks( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) {
1366 if ( $newMessagesAlert ) {
1367 return $newMessagesAlert;
1370 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1371 $uTalkTitle = $user->getTalkPage();
1373 if ( !$uTalkTitle->equals( $out->getTitle() ) ) {
1374 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1376 if ( $lastSeenRev !== null ) {
1377 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1378 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1379 if ( $latestRev !== null ) {
1380 // Singular if only 1 unseen revision, plural if several unseen revisions.
1381 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1382 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1383 $lastSeenRev, $latestRev, 10, 'include_new' );
1386 // Singular if no revision -> diff link will show latest change only in any case
1389 $plural = $plural ?
2 : 1;
1390 // 2 signifies "more than one revision". We don't know how many, and even if we did,
1391 // the number of revisions or authors is not necessarily the same as the number of
1393 $newMessagesLink = Linker
::linkKnown(
1395 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1397 array( 'redirect' => 'no' )
1400 $newMessagesDiffLink = Linker
::linkKnown(
1402 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1404 $lastSeenRev !== null
1405 ?
array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' )
1406 : array( 'diff' => 'cur' )
1409 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1410 $newMessagesAlert = $this->msg(
1411 'youhavenewmessagesfromusers',
1413 $newMessagesDiffLink
1414 )->numParams( $nofAuthors );
1416 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1417 $newMessagesAlert = $this->msg(
1418 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1420 $newMessagesDiffLink
1423 $newMessagesAlert = $newMessagesAlert->text();
1424 # Disable Squid cache
1425 $out->setSquidMaxage( 0 );
1427 } elseif ( count( $newtalks ) ) {
1428 $sep = $this->msg( 'newtalkseparator' )->escaped();
1431 foreach ( $newtalks as $newtalk ) {
1432 $msgs[] = Xml
::element(
1434 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1437 $parts = implode( $sep, $msgs );
1438 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1439 $out->setSquidMaxage( 0 );
1442 return $newMessagesAlert;
1446 * Get a cached notice
1448 * @param string $name message name, or 'default' for $wgSiteNotice
1449 * @return String: HTML fragment
1451 private function getCachedNotice( $name ) {
1452 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1454 wfProfileIn( __METHOD__
);
1458 if ( $name === 'default' ) {
1460 global $wgSiteNotice;
1461 $notice = $wgSiteNotice;
1462 if ( empty( $notice ) ) {
1463 wfProfileOut( __METHOD__
);
1467 $msg = $this->msg( $name )->inContentLanguage();
1468 if ( $msg->isDisabled() ) {
1469 wfProfileOut( __METHOD__
);
1472 $notice = $msg->plain();
1475 // Use the extra hash appender to let eg SSL variants separately cache.
1476 $key = wfMemcKey( $name . $wgRenderHashAppend );
1477 $cachedNotice = $parserMemc->get( $key );
1478 if ( is_array( $cachedNotice ) ) {
1479 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1480 $notice = $cachedNotice['html'];
1489 $parsed = $this->getOutput()->parse( $notice );
1490 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1494 $notice = Html
::rawElement( 'div', array( 'id' => 'localNotice',
1495 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice );
1496 wfProfileOut( __METHOD__
);
1501 * Get a notice based on page's namespace
1503 * @return String: HTML fragment
1505 function getNamespaceNotice() {
1506 wfProfileIn( __METHOD__
);
1508 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1509 $namespaceNotice = $this->getCachedNotice( $key );
1510 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
1511 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1513 $namespaceNotice = '';
1516 wfProfileOut( __METHOD__
);
1517 return $namespaceNotice;
1521 * Get the site notice
1523 * @return String: HTML fragment
1525 function getSiteNotice() {
1526 wfProfileIn( __METHOD__
);
1529 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1530 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1531 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1533 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1534 if ( !$anonNotice ) {
1535 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1537 $siteNotice = $anonNotice;
1540 if ( !$siteNotice ) {
1541 $siteNotice = $this->getCachedNotice( 'default' );
1545 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1546 wfProfileOut( __METHOD__
);
1551 * Create a section edit link. This supersedes editSectionLink() and
1552 * editSectionLinkForOther().
1554 * @param $nt Title The title being linked to (may not be the same as
1555 * $wgTitle, if the section is included from a template)
1556 * @param string $section The designation of the section being pointed to,
1557 * to be included in the link, like "§ion=$section"
1558 * @param string $tooltip The tooltip to use for the link: will be escaped
1559 * and wrapped in the 'editsectionhint' message
1560 * @param $lang string Language code
1561 * @return string HTML to use for edit link
1563 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1564 // HTML generated here should probably have userlangattributes
1565 // added to it for LTR text on RTL pages
1567 $lang = wfGetLangObj( $lang );
1570 if ( !is_null( $tooltip ) ) {
1571 # Bug 25462: undo double-escaping.
1572 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1573 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1574 ->inLanguage( $lang )->text();
1576 $link = Linker
::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(),
1578 array( 'action' => 'edit', 'section' => $section ),
1579 array( 'noclasses', 'known' )
1582 # Run the old hook. This takes up half of the function . . . hopefully
1583 # we can rid of it someday.
1586 $attribs = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1587 ->inLanguage( $lang )->escaped();
1588 $attribs = " title=\"$attribs\"";
1591 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result, $lang ) );
1592 if ( !is_null( $result ) ) {
1593 # For reverse compatibility, add the brackets *after* the hook is
1594 # run, and even add them to hook-provided text. (This is the main
1595 # reason that the EditSectionLink hook is deprecated in favor of
1596 # DoEditSectionLink: it can't change the brackets or the span.)
1597 $result = wfMessage( 'editsection-brackets' )->rawParams( $result )
1598 ->inLanguage( $lang )->escaped();
1599 return "<span class=\"mw-editsection\">$result</span>";
1602 # Add the brackets and the span, and *then* run the nice new hook, with
1603 # clean and non-redundant arguments.
1604 $result = wfMessage( 'editsection-brackets' )->rawParams( $link )
1605 ->inLanguage( $lang )->escaped();
1606 $result = "<span class=\"mw-editsection\">$result</span>";
1608 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1613 * Use PHP's magic __call handler to intercept legacy calls to the linker
1614 * for backwards compatibility.
1616 * @param string $fname Name of called method
1617 * @param array $args Arguments to the method
1618 * @throws MWException
1621 function __call( $fname, $args ) {
1622 $realFunction = array( 'Linker', $fname );
1623 if ( is_callable( $realFunction ) ) {
1624 wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' );
1625 return call_user_func_array( $realFunction, $args );
1627 $className = get_class( $this );
1628 throw new MWException( "Call to undefined method $className::$fname" );