Preserve Special:Preferences tab state across reload, open in new tab/window.
[mediawiki.git] / includes / Skin.php
blob6623d26650ea1bd1ec3544b3175476ee0deb1109
1 <?php
2 /**
3 * @defgroup Skins Skins
4 */
6 if ( !defined( 'MEDIAWIKI' ) ) {
7 die( 1 );
10 /**
11 * The main skin class that provide methods and properties for all other skins.
12 * This base class is also the "Standard" skin.
14 * See docs/skin.txt for more information.
16 * @ingroup Skins
18 abstract class Skin extends Linker {
19 /**#@+
20 * @private
22 var $mWatchLinkNum = 0; // Appended to end of watch link id's
23 /**#@-*/
24 protected $mRevisionId; // The revision ID we're looking at, null if not applicable.
25 protected $skinname = 'standard';
26 // @todo Fixme: should be protected :-\
27 var $mTitle = null;
28 protected $mRelevantTitle = null;
29 protected $mRelevantUser = null;
31 /** Constructor, call parent constructor */
32 function __construct() {
33 parent::__construct();
36 /**
37 * Fetch the set of available skins.
38 * @return array of strings
40 static function getSkinNames() {
41 global $wgValidSkinNames;
42 static $skinsInitialised = false;
44 if ( !$skinsInitialised || !count( $wgValidSkinNames ) ) {
45 # Get a list of available skins
46 # Build using the regular expression '^(.*).php$'
47 # Array keys are all lower case, array value keep the case used by filename
49 wfProfileIn( __METHOD__ . '-init' );
51 global $wgStyleDirectory;
53 $skinDir = dir( $wgStyleDirectory );
55 # while code from www.php.net
56 while ( false !== ( $file = $skinDir->read() ) ) {
57 // Skip non-PHP files, hidden files, and '.dep' includes
58 $matches = array();
60 if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
61 $aSkin = $matches[1];
62 $wgValidSkinNames[strtolower( $aSkin )] = $aSkin;
65 $skinDir->close();
66 $skinsInitialised = true;
67 wfProfileOut( __METHOD__ . '-init' );
69 return $wgValidSkinNames;
72 /**
73 * Fetch the list of usable skins in regards to $wgSkipSkins.
74 * Useful for Special:Preferences and other places where you
75 * only want to show skins users _can_ use.
76 * @return array of strings
78 public static function getUsableSkins() {
79 global $wgSkipSkins;
81 $usableSkins = self::getSkinNames();
83 foreach ( $wgSkipSkins as $skip ) {
84 unset( $usableSkins[$skip] );
87 return $usableSkins;
90 /**
91 * Normalize a skin preference value to a form that can be loaded.
92 * If a skin can't be found, it will fall back to the configured
93 * default (or the old 'Classic' skin if that's broken).
94 * @param $key String: 'monobook', 'standard', etc.
95 * @return string
97 static function normalizeKey( $key ) {
98 global $wgDefaultSkin;
100 $skinNames = Skin::getSkinNames();
102 if ( $key == '' ) {
103 // Don't return the default immediately;
104 // in a misconfiguration we need to fall back.
105 $key = $wgDefaultSkin;
108 if ( isset( $skinNames[$key] ) ) {
109 return $key;
112 // Older versions of the software used a numeric setting
113 // in the user preferences.
114 $fallback = array(
115 0 => $wgDefaultSkin,
116 1 => 'nostalgia',
117 2 => 'cologneblue'
120 if ( isset( $fallback[$key] ) ) {
121 $key = $fallback[$key];
124 if ( isset( $skinNames[$key] ) ) {
125 return $key;
126 } else if ( isset( $skinNames[$wgDefaultSkin] ) ) {
127 return $wgDefaultSkin;
128 } else {
129 return 'vector';
134 * Factory method for loading a skin of a given type
135 * @param $key String: 'monobook', 'standard', etc.
136 * @return Skin
138 static function &newFromKey( $key ) {
139 global $wgStyleDirectory;
141 $key = Skin::normalizeKey( $key );
143 $skinNames = Skin::getSkinNames();
144 $skinName = $skinNames[$key];
145 $className = "Skin{$skinName}";
147 # Grab the skin class and initialise it.
148 if ( !class_exists( $className ) ) {
149 // Preload base classes to work around APC/PHP5 bug
150 $deps = "{$wgStyleDirectory}/{$skinName}.deps.php";
152 if ( file_exists( $deps ) ) {
153 include_once( $deps );
155 require_once( "{$wgStyleDirectory}/{$skinName}.php" );
157 # Check if we got if not failback to default skin
158 if ( !class_exists( $className ) ) {
159 # DO NOT die if the class isn't found. This breaks maintenance
160 # scripts and can cause a user account to be unrecoverable
161 # except by SQL manipulation if a previously valid skin name
162 # is no longer valid.
163 wfDebug( "Skin class does not exist: $className\n" );
164 $className = 'SkinVector';
165 require_once( "{$wgStyleDirectory}/Vector.php" );
168 $skin = new $className;
169 return $skin;
172 /** @return string path to the skin stylesheet */
173 function getStylesheet() {
174 return 'common/wikistandard.css';
177 /** @return string skin name */
178 public function getSkinName() {
179 return $this->skinname;
182 function initPage( OutputPage $out ) {
183 global $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI;
185 wfProfileIn( __METHOD__ );
187 # Generally the order of the favicon and apple-touch-icon links
188 # should not matter, but Konqueror (3.5.9 at least) incorrectly
189 # uses whichever one appears later in the HTML source. Make sure
190 # apple-touch-icon is specified first to avoid this.
191 if ( false !== $wgAppleTouchIcon ) {
192 $out->addLink( array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
195 if ( false !== $wgFavicon ) {
196 $out->addLink( array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
199 # OpenSearch description link
200 $out->addLink( array(
201 'rel' => 'search',
202 'type' => 'application/opensearchdescription+xml',
203 'href' => wfScript( 'opensearch_desc' ),
204 'title' => wfMsgForContent( 'opensearch-desc' ),
205 ) );
207 if ( $wgEnableAPI ) {
208 # Real Simple Discovery link, provides auto-discovery information
209 # for the MediaWiki API (and potentially additional custom API
210 # support such as WordPress or Twitter-compatible APIs for a
211 # blogging extension, etc)
212 $out->addLink( array(
213 'rel' => 'EditURI',
214 'type' => 'application/rsd+xml',
215 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ) ),
216 ) );
219 $this->addMetadataLinks( $out );
221 $this->mRevisionId = $out->mRevisionId;
223 $this->preloadExistence();
225 wfProfileOut( __METHOD__ );
229 * Preload the existence of three commonly-requested pages in a single query
231 function preloadExistence() {
232 global $wgUser;
234 // User/talk link
235 $titles = array( $wgUser->getUserPage(), $wgUser->getTalkPage() );
237 // Other tab link
238 if ( $this->mTitle->getNamespace() == NS_SPECIAL ) {
239 // nothing
240 } elseif ( $this->mTitle->isTalkPage() ) {
241 $titles[] = $this->mTitle->getSubjectPage();
242 } else {
243 $titles[] = $this->mTitle->getTalkPage();
246 $lb = new LinkBatch( $titles );
247 $lb->setCaller( __METHOD__ );
248 $lb->execute();
252 * Adds metadata links below to the HTML output.
253 * <ol>
254 * <li>Creative Commons
255 * <br />See http://wiki.creativecommons.org/Extend_Metadata.
256 * </li>
257 * <li>Dublin Core</li>
258 * <li>Use hreflang to specify canonical and alternate links
259 * <br />See http://www.google.com/support/webmasters/bin/answer.py?answer=189077
260 * </li>
261 * <li>Copyright</li>
262 * <ol>
264 * @param $out Object: instance of OutputPage
266 function addMetadataLinks( OutputPage $out ) {
267 global $wgEnableDublinCoreRdf, $wgEnableCreativeCommonsRdf;
268 global $wgDisableLangConversion, $wgCanonicalLanguageLinks, $wgContLang;
269 global $wgRightsPage, $wgRightsUrl;
271 if ( $out->isArticleRelated() ) {
272 # note: buggy CC software only reads first "meta" link
273 if ( $wgEnableCreativeCommonsRdf ) {
274 $out->addMetadataLink( array(
275 'title' => 'Creative Commons',
276 'type' => 'application/rdf+xml',
277 'href' => $this->mTitle->getLocalURL( 'action=creativecommons' ) )
281 if ( $wgEnableDublinCoreRdf ) {
282 $out->addMetadataLink( array(
283 'title' => 'Dublin Core',
284 'type' => 'application/rdf+xml',
285 'href' => $this->mTitle->getLocalURL( 'action=dublincore' ) )
290 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
291 && $wgContLang->hasVariants() ) {
293 $urlvar = $wgContLang->getURLVariant();
295 if ( !$urlvar ) {
296 $variants = $wgContLang->getVariants();
297 foreach ( $variants as $_v ) {
298 $out->addLink( array(
299 'rel' => 'alternate',
300 'hreflang' => $_v,
301 'href' => $this->mTitle->getLocalURL( '', $_v ) )
304 } else {
305 $out->addLink( array(
306 'rel' => 'canonical',
307 'href' => $this->mTitle->getFullURL() )
312 $copyright = '';
313 if ( $wgRightsPage ) {
314 $copy = Title::newFromText( $wgRightsPage );
316 if ( $copy ) {
317 $copyright = $copy->getLocalURL();
321 if ( !$copyright && $wgRightsUrl ) {
322 $copyright = $wgRightsUrl;
325 if ( $copyright ) {
326 $out->addLink( array(
327 'rel' => 'copyright',
328 'href' => $copyright )
334 * Set some local variables
336 protected function setMembers() {
337 global $wgUser;
338 $this->mUser = $wgUser;
339 $this->userpage = $wgUser->getUserPage()->getPrefixedText();
340 $this->usercss = false;
344 * Whether the revision displayed is the latest revision of the page
346 * @return Boolean
348 public function isRevisionCurrent() {
349 return $this->mRevisionId == 0 || $this->mRevisionId == $this->mTitle->getLatestRevID();
353 * Set the title
354 * @param $t Title object to use
356 public function setTitle( $t ) {
357 $this->mTitle = $t;
360 /** Get the title */
361 public function getTitle() {
362 return $this->mTitle;
366 * Set the "relevant" title
367 * @see self::getRelevantTitle()
368 * @param $t Title object to use
370 public function setRelevantTitle( $t ) {
371 $this->mRelevantTitle = $t;
375 * Return the "relevant" title.
376 * A "relevant" title is not necessarily the actual title of the page.
377 * Special pages like Special:MovePage use set the page they are acting on
378 * as their "relevant" title, this allows the skin system to display things
379 * such as content tabs which belong to to that page instead of displaying
380 * a basic special page tab which has almost no meaning.
382 public function getRelevantTitle() {
383 if ( isset($this->mRelevantTitle) ) {
384 return $this->mRelevantTitle;
386 return $this->mTitle;
390 * Set the "relevant" user
391 * @see self::getRelevantUser()
392 * @param $u User object to use
394 public function setRelevantUser( $u ) {
395 $this->mRelevantUser = $u;
399 * Return the "relevant" user.
400 * A "relevant" user is similar to a relevant title. Special pages like
401 * Special:Contributions mark the user which they are relevant to so that
402 * things like the toolbox can display the information they usually are only
403 * able to display on a user's userpage and talkpage.
405 public function getRelevantUser() {
406 if ( isset($this->mRelevantUser) ) {
407 return $this->mRelevantUser;
409 $title = $this->getRelevantTitle();
410 if( $title->getNamespace() == NS_USER || $title->getNamespace() == NS_USER_TALK ) {
411 $rootUser = strtok( $title->getText(), '/' );
412 if ( User::isIP( $rootUser ) ) {
413 $this->mRelevantUser = User::newFromName( $rootUser, false );
414 } else {
415 $user = User::newFromName( $rootUser );
416 if ( $user->isLoggedIn() ) {
417 $this->mRelevantUser = $user;
420 return $this->mRelevantUser;
422 return null;
426 * Outputs the HTML generated by other functions.
427 * @param $out Object: instance of OutputPage
428 * @todo Exterminate!
430 function outputPage( OutputPage $out ) {
431 global $wgDebugComments;
432 wfProfileIn( __METHOD__ );
434 $this->setMembers();
435 $this->initPage( $out );
437 // See self::afterContentHook() for documentation
438 $afterContent = $this->afterContentHook();
440 $out->out( $out->headElement( $this ) );
442 if ( $wgDebugComments ) {
443 $out->out( "<!-- Debug output:\n" .
444 $out->mDebugtext . "-->\n" );
447 $out->out( $this->beforeContent() );
449 $out->out( $out->mBodytext . "\n" );
451 $out->out( $this->afterContent() );
453 $out->out( $afterContent );
455 $out->out( $this->bottomScripts( $out ) );
457 $out->out( wfReportTime() );
459 $out->out( "\n</body></html>" );
460 wfProfileOut( __METHOD__ );
463 static function makeVariablesScript( $data ) {
464 if ( $data ) {
465 return Html::inlineScript(
466 ResourceLoader::makeLoaderConditionalScript( ResourceLoader::makeConfigSetScript( $data ) )
468 } else {
469 return '';
474 * Make a <script> tag containing global variables
475 * @param $skinName string Name of the skin
476 * The odd calling convention is for backwards compatibility
477 * @todo FIXME: Make this not depend on $wgTitle!
479 * Do not add things here which can be evaluated in ResourceLoaderStartupScript - in other words, without state.
480 * You will only be adding bloat to the page and causing page caches to have to be purged on configuration changes.
482 static function makeGlobalVariablesScript( $skinName ) {
483 global $wgTitle, $wgUser, $wgRequest, $wgOut, $wgUseAjax, $wgEnableMWSuggest;
485 $ns = $wgTitle->getNamespace();
486 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $wgTitle->getNsText();
487 $vars = array(
488 'wgCanonicalNamespace' => $nsname,
489 'wgCanonicalSpecialPageName' => $ns == NS_SPECIAL ?
490 SpecialPage::resolveAlias( $wgTitle->getDBkey() ) : false, # bug 21115
491 'wgNamespaceNumber' => $wgTitle->getNamespace(),
492 'wgPageName' => $wgTitle->getPrefixedDBKey(),
493 'wgTitle' => $wgTitle->getText(),
494 'wgAction' => $wgRequest->getText( 'action', 'view' ),
495 'wgArticleId' => $wgTitle->getArticleId(),
496 'wgIsArticle' => $wgOut->isArticle(),
497 'wgUserName' => $wgUser->isAnon() ? null : $wgUser->getName(),
498 'wgUserGroups' => $wgUser->getEffectiveGroups(),
499 'wgCurRevisionId' => $wgTitle->getLatestRevID(),
500 'wgCategories' => $wgOut->getCategories(),
501 'wgBreakFrames' => $wgOut->getFrameOptions() == 'DENY',
503 foreach ( $wgTitle->getRestrictionTypes() as $type ) {
504 $vars['wgRestriction' . ucfirst( $type )] = $wgTitle->getRestrictions( $type );
506 if ( $wgUseAjax && $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
507 $vars['wgSearchNamespaces'] = SearchEngine::userNamespaces( $wgUser );
510 // Allow extensions to add their custom variables to the global JS variables
511 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
513 return self::makeVariablesScript( $vars );
517 * To make it harder for someone to slip a user a fake
518 * user-JavaScript or user-CSS preview, a random token
519 * is associated with the login session. If it's not
520 * passed back with the preview request, we won't render
521 * the code.
523 * @param $action String: 'edit', 'submit' etc.
524 * @return bool
526 public function userCanPreview( $action ) {
527 global $wgRequest, $wgUser;
529 if ( $action != 'submit' ) {
530 return false;
532 if ( !$wgRequest->wasPosted() ) {
533 return false;
535 if ( !$this->mTitle->userCanEditCssSubpage() ) {
536 return false;
538 if ( !$this->mTitle->userCanEditJsSubpage() ) {
539 return false;
542 return $wgUser->matchEditToken(
543 $wgRequest->getVal( 'wpEditToken' ) );
547 * Generated JavaScript action=raw&gen=js
548 * This returns MediaWiki:Common.js and MediaWiki:[Skinname].js concate-
549 * nated together. For some bizarre reason, it does *not* return any
550 * custom user JS from subpages. Huh?
552 * There's absolutely no reason to have separate Monobook/Common JSes.
553 * Any JS that cares can just check the skin variable generated at the
554 * top. For now Monobook.js will be maintained, but it should be consi-
555 * dered deprecated.
557 * @param $skinName String: If set, overrides the skin name
558 * @return string
560 public function generateUserJs( $skinName = null ) {
562 // Stub - see ResourceLoaderSiteModule, CologneBlue, Simple and Standard skins override this
564 return '';
568 * Generate user stylesheet for action=raw&gen=css
570 public function generateUserStylesheet() {
572 // Stub - see ResourceLoaderUserModule, CologneBlue, Simple and Standard skins override this
574 return '';
578 * Split for easier subclassing in SkinSimple, SkinStandard and SkinCologneBlue
579 * Anything in here won't be generated if $wgAllowUserCssPrefs is false.
581 protected function reallyGenerateUserStylesheet() {
583 // Stub - see ResourceLoaderUserModule, CologneBlue, Simple and Standard skins override this
585 return '';
589 * @private
591 function setupUserCss( OutputPage $out ) {
592 global $wgRequest;
593 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
595 wfProfileIn( __METHOD__ );
597 $this->setupSkinUserCss( $out );
598 // Add any extension CSS
599 foreach ( $out->getExtStyle() as $url ) {
600 $out->addStyle( $url );
603 // Per-site custom styles
604 if ( $wgUseSiteCss ) {
605 $out->addModuleStyles( 'site' );
608 // Per-user custom styles
609 if ( $wgAllowUserCss ) {
610 if ( $this->mTitle->isCssSubpage() && $this->userCanPreview( $wgRequest->getVal( 'action' ) ) ) {
611 // @FIXME: properly escape the cdata!
612 $out->addInlineStyle( $wgRequest->getText( 'wpTextbox1' ) );
613 } else {
614 $out->addModuleStyles( 'user' );
618 // Per-user preference styles
619 if ( $wgAllowUserCssPrefs ) {
620 $out->addModuleStyles( 'user.options' );
623 wfProfileOut( __METHOD__ );
627 * Get the query to generate a dynamic stylesheet
629 * @return array
631 public static function getDynamicStylesheetQuery() {
632 global $wgSquidMaxage;
634 return array(
635 'action' => 'raw',
636 'maxage' => $wgSquidMaxage,
637 'usemsgcache' => 'yes',
638 'ctype' => 'text/css',
639 'smaxage' => $wgSquidMaxage,
644 * Add skin specific stylesheets
645 * @param $out OutputPage
646 * @delete
648 abstract function setupSkinUserCss( OutputPage $out );
650 function getPageClasses( $title ) {
651 $numeric = 'ns-' . $title->getNamespace();
653 if ( $title->getNamespace() == NS_SPECIAL ) {
654 $type = 'ns-special';
655 } elseif ( $title->isTalkPage() ) {
656 $type = 'ns-talk';
657 } else {
658 $type = 'ns-subject';
661 $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() );
663 return "$numeric $type $name";
667 * This will be called by OutputPage::headElement when it is creating the
668 * <body> tag, skins can override it if they have a need to add in any
669 * body attributes or classes of their own.
671 function addToBodyAttributes( $out, &$bodyAttrs ) {
672 // does nothing by default
676 * URL to the logo
678 function getLogo() {
679 global $wgLogo;
680 return $wgLogo;
683 function getCategoryLinks() {
684 global $wgOut, $wgUseCategoryBrowser;
685 global $wgContLang, $wgUser;
687 if ( count( $wgOut->mCategoryLinks ) == 0 ) {
688 return '';
691 # Separator
692 $sep = wfMsgExt( 'catseparator', array( 'parsemag', 'escapenoentities' ) );
694 // Use Unicode bidi embedding override characters,
695 // to make sure links don't smash each other up in ugly ways.
696 $dir = $wgContLang->getDir();
697 $embed = "<span dir='$dir'>";
698 $pop = '</span>';
700 $allCats = $wgOut->getCategoryLinks();
701 $s = '';
702 $colon = wfMsgExt( 'colon-separator', 'escapenoentities' );
704 if ( !empty( $allCats['normal'] ) ) {
705 $t = $embed . implode( "{$pop} {$sep} {$embed}" , $allCats['normal'] ) . $pop;
707 $msg = wfMsgExt( 'pagecategories', array( 'parsemag', 'escapenoentities' ), count( $allCats['normal'] ) );
708 $s .= '<div id="mw-normal-catlinks">' .
709 $this->link( Title::newFromText( wfMsgForContent( 'pagecategorieslink' ) ), $msg )
710 . $colon . $t . '</div>';
713 # Hidden categories
714 if ( isset( $allCats['hidden'] ) ) {
715 if ( $wgUser->getBoolOption( 'showhiddencats' ) ) {
716 $class = 'mw-hidden-cats-user-shown';
717 } elseif ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
718 $class = 'mw-hidden-cats-ns-shown';
719 } else {
720 $class = 'mw-hidden-cats-hidden';
723 $s .= "<div id=\"mw-hidden-catlinks\" class=\"$class\">" .
724 wfMsgExt( 'hidden-categories', array( 'parsemag', 'escapenoentities' ), count( $allCats['hidden'] ) ) .
725 $colon . $embed . implode( "$pop $sep $embed", $allCats['hidden'] ) . $pop .
726 '</div>';
729 # optional 'dmoz-like' category browser. Will be shown under the list
730 # of categories an article belong to
731 if ( $wgUseCategoryBrowser ) {
732 $s .= '<br /><hr />';
734 # get a big array of the parents tree
735 $parenttree = $this->mTitle->getParentCategoryTree();
736 # Skin object passed by reference cause it can not be
737 # accessed under the method subfunction drawCategoryBrowser
738 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree, $this ) );
739 # Clean out bogus first entry and sort them
740 unset( $tempout[0] );
741 asort( $tempout );
742 # Output one per line
743 $s .= implode( "<br />\n", $tempout );
746 return $s;
750 * Render the array as a serie of links.
751 * @param $tree Array: categories tree returned by Title::getParentCategoryTree
752 * @param &skin Object: skin passed by reference
753 * @return String separated by &gt;, terminate with "\n"
755 function drawCategoryBrowser( $tree, &$skin ) {
756 $return = '';
758 foreach ( $tree as $element => $parent ) {
759 if ( empty( $parent ) ) {
760 # element start a new list
761 $return .= "\n";
762 } else {
763 # grab the others elements
764 $return .= $this->drawCategoryBrowser( $parent, $skin ) . ' &gt; ';
767 # add our current element to the list
768 $eltitle = Title::newFromText( $element );
769 $return .= $skin->link( $eltitle, $eltitle->getText() );
772 return $return;
775 function getCategories() {
776 $catlinks = $this->getCategoryLinks();
778 $classes = 'catlinks';
780 global $wgOut, $wgUser;
782 // Check what we're showing
783 $allCats = $wgOut->getCategoryLinks();
784 $showHidden = $wgUser->getBoolOption( 'showhiddencats' ) ||
785 $this->mTitle->getNamespace() == NS_CATEGORY;
787 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
788 $classes .= ' catlinks-allhidden';
791 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
795 * This runs a hook to allow extensions placing their stuff after content
796 * and article metadata (e.g. categories).
797 * Note: This function has nothing to do with afterContent().
799 * This hook is placed here in order to allow using the same hook for all
800 * skins, both the SkinTemplate based ones and the older ones, which directly
801 * use this class to get their data.
803 * The output of this function gets processed in SkinTemplate::outputPage() for
804 * the SkinTemplate based skins, all other skins should directly echo it.
806 * Returns an empty string by default, if not changed by any hook function.
808 protected function afterContentHook() {
809 $data = '';
811 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
812 // adding just some spaces shouldn't toggle the output
813 // of the whole <div/>, so we use trim() here
814 if ( trim( $data ) != '' ) {
815 // Doing this here instead of in the skins to
816 // ensure that the div has the same ID in all
817 // skins
818 $data = "<div id='mw-data-after-content'>\n" .
819 "\t$data\n" .
820 "</div>\n";
822 } else {
823 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
826 return $data;
830 * Generate debug data HTML for displaying at the bottom of the main content
831 * area.
832 * @return String HTML containing debug data, if enabled (otherwise empty).
834 protected function generateDebugHTML() {
835 global $wgShowDebug, $wgOut;
837 if ( $wgShowDebug ) {
838 $listInternals = $this->formatDebugHTML( $wgOut->mDebugtext );
839 return "\n<hr />\n<strong>Debug data:</strong><ul style=\"font-family:monospace;\" id=\"mw-debug-html\">" .
840 $listInternals . "</ul>\n";
843 return '';
846 private function formatDebugHTML( $debugText ) {
847 $lines = explode( "\n", $debugText );
848 $curIdent = 0;
849 $ret = '<li>';
851 foreach ( $lines as $line ) {
852 $display = ltrim( $line );
853 $ident = strlen( $line ) - strlen( $display );
854 $diff = $ident - $curIdent;
856 if ( $display == '' ) {
857 $display = "\xc2\xa0";
860 if ( !$ident && $diff < 0 && substr( $display, 0, 9 ) != 'Entering ' && substr( $display, 0, 8 ) != 'Exiting ' ) {
861 $ident = $curIdent;
862 $diff = 0;
863 $display = '<span style="background:yellow;">' . htmlspecialchars( $display ) . '</span>';
864 } else {
865 $display = htmlspecialchars( $display );
868 if ( $diff < 0 ) {
869 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
870 } elseif ( $diff == 0 ) {
871 $ret .= "</li><li>\n";
872 } else {
873 $ret .= str_repeat( "<ul><li>\n", $diff );
875 $ret .= $display . "\n";
877 $curIdent = $ident;
880 $ret .= str_repeat( '</li></ul>', $curIdent ) . '</li>';
882 return $ret;
886 * This gets called shortly before the </body> tag.
887 * @param $out OutputPage object
888 * @return String HTML-wrapped JS code to be put before </body>
890 function bottomScripts( $out ) {
891 $bottomScriptText = "\n" . $out->getHeadScripts( $this );
892 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
894 return $bottomScriptText;
897 /** @return string Retrievied from HTML text */
898 function printSource() {
899 $url = htmlspecialchars( $this->mTitle->getFullURL() );
900 return wfMsg( 'retrievedfrom', '<a href="' . $url . '">' . $url . '</a>' );
903 function getUndeleteLink() {
904 global $wgUser, $wgLang, $wgRequest;
906 $action = $wgRequest->getVal( 'action', 'view' );
908 if ( $wgUser->isAllowed( 'deletedhistory' ) &&
909 ( $this->mTitle->getArticleId() == 0 || $action == 'history' ) ) {
910 $n = $this->mTitle->isDeleted();
912 if ( $n ) {
913 if ( $wgUser->isAllowed( 'undelete' ) ) {
914 $msg = 'thisisdeleted';
915 } else {
916 $msg = 'viewdeleted';
919 return wfMsg(
920 $msg,
921 $this->link(
922 SpecialPage::getTitleFor( 'Undelete', $this->mTitle->getPrefixedDBkey() ),
923 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $wgLang->formatNum( $n ) ),
924 array(),
925 array(),
926 array( 'known', 'noclasses' )
932 return '';
935 function subPageSubtitle() {
936 $subpages = '';
938 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this ) ) ) {
939 return $subpages;
942 global $wgOut;
944 if ( $wgOut->isArticle() && MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
945 $ptext = $this->mTitle->getPrefixedText();
946 if ( preg_match( '/\//', $ptext ) ) {
947 $links = explode( '/', $ptext );
948 array_pop( $links );
949 $c = 0;
950 $growinglink = '';
951 $display = '';
953 foreach ( $links as $link ) {
954 $growinglink .= $link;
955 $display .= $link;
956 $linkObj = Title::newFromText( $growinglink );
958 if ( is_object( $linkObj ) && $linkObj->exists() ) {
959 $getlink = $this->link(
960 $linkObj,
961 htmlspecialchars( $display ),
962 array(),
963 array(),
964 array( 'known', 'noclasses' )
967 $c++;
969 if ( $c > 1 ) {
970 $subpages .= wfMsgExt( 'pipe-separator', 'escapenoentities' );
971 } else {
972 $subpages .= '&lt; ';
975 $subpages .= $getlink;
976 $display = '';
977 } else {
978 $display .= '/';
980 $growinglink .= '/';
985 return $subpages;
989 * Returns true if the IP should be shown in the header
991 function showIPinHeader() {
992 global $wgShowIPinHeader;
993 return $wgShowIPinHeader && session_id() != '';
996 function getSearchLink() {
997 $searchPage = SpecialPage::getTitleFor( 'Search' );
998 return $searchPage->getLocalURL();
1001 function escapeSearchLink() {
1002 return htmlspecialchars( $this->getSearchLink() );
1005 function getCopyright( $type = 'detect' ) {
1006 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgRequest;
1008 if ( $type == 'detect' ) {
1009 $diff = $wgRequest->getVal( 'diff' );
1011 if ( is_null( $diff ) && !$this->isRevisionCurrent() && wfMsgForContent( 'history_copyright' ) !== '-' ) {
1012 $type = 'history';
1013 } else {
1014 $type = 'normal';
1018 if ( $type == 'history' ) {
1019 $msg = 'history_copyright';
1020 } else {
1021 $msg = 'copyright';
1024 $out = '';
1026 if ( $wgRightsPage ) {
1027 $title = Title::newFromText( $wgRightsPage );
1028 $link = $this->linkKnown( $title, $wgRightsText );
1029 } elseif ( $wgRightsUrl ) {
1030 $link = $this->makeExternalLink( $wgRightsUrl, $wgRightsText );
1031 } elseif ( $wgRightsText ) {
1032 $link = $wgRightsText;
1033 } else {
1034 # Give up now
1035 return $out;
1038 // Allow for site and per-namespace customization of copyright notice.
1039 $forContent = true;
1041 wfRunHooks( 'SkinCopyrightFooter', array( $this->mTitle, $type, &$msg, &$link, &$forContent ) );
1043 if ( $forContent ) {
1044 $out .= wfMsgForContent( $msg, $link );
1045 } else {
1046 $out .= wfMsg( $msg, $link );
1049 return $out;
1052 function getCopyrightIcon() {
1053 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
1055 $out = '';
1057 if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
1058 $out = $wgCopyrightIcon;
1059 } elseif ( $wgRightsIcon ) {
1060 $icon = htmlspecialchars( $wgRightsIcon );
1062 if ( $wgRightsUrl ) {
1063 $url = htmlspecialchars( $wgRightsUrl );
1064 $out .= '<a href="' . $url . '">';
1067 $text = htmlspecialchars( $wgRightsText );
1068 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
1070 if ( $wgRightsUrl ) {
1071 $out .= '</a>';
1075 return $out;
1079 * Gets the powered by MediaWiki icon.
1080 * @return string
1082 function getPoweredBy() {
1083 global $wgStylePath;
1085 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
1086 $text = '<a href="http://www.mediawiki.org/"><img src="' . $url . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
1087 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
1088 return $text;
1092 * Get the timestamp of the latest revision, formatted in user language
1094 * @param $article Article object. Used if we're working with the current revision
1095 * @return String
1097 protected function lastModified( $article ) {
1098 global $wgLang;
1100 if ( !$this->isRevisionCurrent() ) {
1101 $timestamp = Revision::getTimestampFromId( $this->mTitle, $this->mRevisionId );
1102 } else {
1103 $timestamp = $article->getTimestamp();
1106 if ( $timestamp ) {
1107 $d = $wgLang->date( $timestamp, true );
1108 $t = $wgLang->time( $timestamp, true );
1109 $s = ' ' . wfMsg( 'lastmodifiedat', $d, $t );
1110 } else {
1111 $s = '';
1114 if ( wfGetLB()->getLaggedSlaveMode() ) {
1115 $s .= ' <strong>' . wfMsg( 'laggedslavemode' ) . '</strong>';
1118 return $s;
1121 function logoText( $align = '' ) {
1122 if ( $align != '' ) {
1123 $a = " align='{$align}'";
1124 } else {
1125 $a = '';
1128 $mp = wfMsg( 'mainpage' );
1129 $mptitle = Title::newMainPage();
1130 $url = ( is_object( $mptitle ) ? $mptitle->escapeLocalURL() : '' );
1132 $logourl = $this->getLogo();
1133 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
1135 return $s;
1139 * Renders a $wgFooterIcons icon acording to the method's arguments
1140 * @param $icon Array: The icon to build the html for, see $wgFooterIcons for the format of this array
1141 * @param $withImage Boolean: Whether to use the icon's image or output a text-only footericon
1143 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
1144 if ( is_string( $icon ) ) {
1145 $html = $icon;
1146 } else { // Assuming array
1147 $url = isset($icon["url"]) ? $icon["url"] : null;
1148 unset( $icon["url"] );
1149 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
1150 $html = Html::element( 'img', $icon ); // do this the lazy way, just pass icon data as an attribute array
1151 } else {
1152 $html = htmlspecialchars( $icon["alt"] );
1154 if ( $url ) {
1155 $html = Html::rawElement( 'a', array( "href" => $url ), $html );
1158 return $html;
1162 * Gets the link to the wiki's main page.
1163 * @return string
1165 function mainPageLink() {
1166 $s = $this->link(
1167 Title::newMainPage(),
1168 wfMsg( 'mainpage' ),
1169 array(),
1170 array(),
1171 array( 'known', 'noclasses' )
1174 return $s;
1177 public function footerLink( $desc, $page ) {
1178 // if the link description has been set to "-" in the default language,
1179 if ( wfMsgForContent( $desc ) == '-' ) {
1180 // then it is disabled, for all languages.
1181 return '';
1182 } else {
1183 // Otherwise, we display the link for the user, described in their
1184 // language (which may or may not be the same as the default language),
1185 // but we make the link target be the one site-wide page.
1186 $title = Title::newFromText( wfMsgForContent( $page ) );
1188 return $this->linkKnown(
1189 $title,
1190 wfMsgExt( $desc, array( 'parsemag', 'escapenoentities' ) )
1196 * Gets the link to the wiki's privacy policy page.
1198 function privacyLink() {
1199 return $this->footerLink( 'privacy', 'privacypage' );
1203 * Gets the link to the wiki's about page.
1205 function aboutLink() {
1206 return $this->footerLink( 'aboutsite', 'aboutpage' );
1210 * Gets the link to the wiki's general disclaimers page.
1212 function disclaimerLink() {
1213 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1217 * Return URL options for the 'edit page' link.
1218 * This may include an 'oldid' specifier, if the current page view is such.
1220 * @return array
1221 * @private
1223 function editUrlOptions() {
1224 $options = array( 'action' => 'edit' );
1226 if ( !$this->isRevisionCurrent() ) {
1227 $options['oldid'] = intval( $this->mRevisionId );
1230 return $options;
1233 function showEmailUser( $id ) {
1234 global $wgUser;
1235 $targetUser = User::newFromId( $id );
1236 return $wgUser->canSendEmail() && # the sending user must have a confirmed email address
1237 $targetUser->canReceiveEmail(); # the target user must have a confirmed email address and allow emails from users
1241 * Return a fully resolved style path url to images or styles stored in the common folder.
1242 * This method returns a url resolved using the configured skin style path
1243 * and includes the style version inside of the url.
1244 * @param $name String: The name or path of a skin resource file
1245 * @return String The fully resolved style path url including styleversion
1247 function getCommonStylePath( $name ) {
1248 global $wgStylePath, $wgStyleVersion;
1249 return "$wgStylePath/common/$name?$wgStyleVersion";
1253 * Return a fully resolved style path url to images or styles stored in the curent skins's folder.
1254 * This method returns a url resolved using the configured skin style path
1255 * and includes the style version inside of the url.
1256 * @param $name String: The name or path of a skin resource file
1257 * @return String The fully resolved style path url including styleversion
1259 function getSkinStylePath( $name ) {
1260 global $wgStylePath, $wgStyleVersion;
1261 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1264 /* these are used extensively in SkinTemplate, but also some other places */
1265 static function makeMainPageUrl( $urlaction = '' ) {
1266 $title = Title::newMainPage();
1267 self::checkTitle( $title, '' );
1269 return $title->getLocalURL( $urlaction );
1272 static function makeSpecialUrl( $name, $urlaction = '' ) {
1273 $title = SpecialPage::getTitleFor( $name );
1274 return $title->getLocalURL( $urlaction );
1277 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1278 $title = SpecialPage::getSafeTitleFor( $name, $subpage );
1279 return $title->getLocalURL( $urlaction );
1282 static function makeI18nUrl( $name, $urlaction = '' ) {
1283 $title = Title::newFromText( wfMsgForContent( $name ) );
1284 self::checkTitle( $title, $name );
1285 return $title->getLocalURL( $urlaction );
1288 static function makeUrl( $name, $urlaction = '' ) {
1289 $title = Title::newFromText( $name );
1290 self::checkTitle( $title, $name );
1292 return $title->getLocalURL( $urlaction );
1296 * If url string starts with http, consider as external URL, else
1297 * internal
1299 static function makeInternalOrExternalUrl( $name ) {
1300 if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $name ) ) {
1301 return $name;
1302 } else {
1303 return self::makeUrl( $name );
1307 # this can be passed the NS number as defined in Language.php
1308 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
1309 $title = Title::makeTitleSafe( $namespace, $name );
1310 self::checkTitle( $title, $name );
1312 return $title->getLocalURL( $urlaction );
1315 /* these return an array with the 'href' and boolean 'exists' */
1316 static function makeUrlDetails( $name, $urlaction = '' ) {
1317 $title = Title::newFromText( $name );
1318 self::checkTitle( $title, $name );
1320 return array(
1321 'href' => $title->getLocalURL( $urlaction ),
1322 'exists' => $title->getArticleID() != 0,
1327 * Make URL details where the article exists (or at least it's convenient to think so)
1329 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1330 $title = Title::newFromText( $name );
1331 self::checkTitle( $title, $name );
1333 return array(
1334 'href' => $title->getLocalURL( $urlaction ),
1335 'exists' => true
1339 # make sure we have some title to operate on
1340 static function checkTitle( &$title, $name ) {
1341 if ( !is_object( $title ) ) {
1342 $title = Title::newFromText( $name );
1343 if ( !is_object( $title ) ) {
1344 $title = Title::newFromText( '--error: link target missing--' );
1350 * Build an array that represents the sidebar(s), the navigation bar among them
1352 * @return array
1354 function buildSidebar() {
1355 global $parserMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1356 global $wgLang;
1357 wfProfileIn( __METHOD__ );
1359 $key = wfMemcKey( 'sidebar', $wgLang->getCode() );
1361 if ( $wgEnableSidebarCache ) {
1362 $cachedsidebar = $parserMemc->get( $key );
1363 if ( $cachedsidebar ) {
1364 wfProfileOut( __METHOD__ );
1365 return $cachedsidebar;
1369 $bar = array();
1370 $this->addToSidebar( $bar, 'sidebar' );
1372 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1373 if ( $wgEnableSidebarCache ) {
1374 $parserMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1377 wfProfileOut( __METHOD__ );
1378 return $bar;
1381 * Add content from a sidebar system message
1382 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1384 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1386 * @param &$bar array
1387 * @param $message String
1389 function addToSidebar( &$bar, $message ) {
1390 $this->addToSidebarPlain( $bar, wfMsgForContent( $message ) );
1394 * Add content from plain text
1395 * @since 1.17
1396 * @param &$bar array
1397 * @param $text string
1399 function addToSidebarPlain( &$bar, $text ) {
1400 $lines = explode( "\n", $text );
1401 $wikiBar = array(); # We need to handle the wikitext on a different variable, to avoid trying to do an array operation on text, which would be a fatal error.
1403 $heading = '';
1405 foreach ( $lines as $line ) {
1406 if ( strpos( $line, '*' ) !== 0 ) {
1407 continue;
1410 if ( strpos( $line, '**' ) !== 0 ) {
1411 $heading = trim( $line, '* ' );
1412 if ( !array_key_exists( $heading, $bar ) ) {
1413 $bar[$heading] = array();
1415 } else {
1416 $line = trim( $line, '* ' );
1418 if ( strpos( $line, '|' ) !== false ) { // sanity check
1419 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1420 $link = wfMsgForContent( $line[0] );
1422 if ( $link == '-' ) {
1423 continue;
1426 $text = wfMsgExt( $line[1], 'parsemag' );
1428 if ( wfEmptyMsg( $line[1], $text ) ) {
1429 $text = $line[1];
1432 if ( wfEmptyMsg( $line[0], $link ) ) {
1433 $link = $line[0];
1436 if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $link ) ) {
1437 $href = $link;
1438 } else {
1439 $title = Title::newFromText( $link );
1441 if ( $title ) {
1442 $title = $title->fixSpecialName();
1443 $href = $title->getLocalURL();
1444 } else {
1445 $href = 'INVALID-TITLE';
1449 $bar[$heading][] = array(
1450 'text' => $text,
1451 'href' => $href,
1452 'id' => 'n-' . strtr( $line[1], ' ', '-' ),
1453 'active' => false
1455 } else if ( ( substr( $line, 0, 2 ) == '{{' ) && ( substr( $line, -2 ) == '}}' ) ) {
1456 global $wgParser, $wgTitle;
1458 $line = substr( $line, 2, strlen( $line ) - 4 );
1460 $options = new ParserOptions();
1461 $options->setEditSection( false );
1462 $options->setInterfaceMessage( true );
1463 $wikiBar[$heading] = $wgParser->parse( wfMsgForContentNoTrans( $line ) , $wgTitle, $options )->getText();
1464 } else {
1465 continue;
1470 if ( count( $wikiBar ) > 0 ) {
1471 $bar = array_merge( $bar, $wikiBar );
1474 return $bar;
1478 * Should we include common/wikiprintable.css? Skins that have their own
1479 * print stylesheet should override this and return false. (This is an
1480 * ugly hack to get Monobook to play nicely with
1481 * OutputPage::headElement().)
1483 * @return bool
1485 public function commonPrintStylesheet() {
1486 return true;
1490 * Gets new talk page messages for the current user.
1491 * @return MediaWiki message or if no new talk page messages, nothing
1493 function getNewtalks() {
1494 global $wgUser, $wgOut;
1496 $newtalks = $wgUser->getNewMessageLinks();
1497 $ntl = '';
1499 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1500 $userTitle = $this->mUser->getUserPage();
1501 $userTalkTitle = $userTitle->getTalkPage();
1503 if ( !$userTalkTitle->equals( $this->mTitle ) ) {
1504 $newMessagesLink = $this->link(
1505 $userTalkTitle,
1506 wfMsgHtml( 'newmessageslink' ),
1507 array(),
1508 array( 'redirect' => 'no' ),
1509 array( 'known', 'noclasses' )
1512 $newMessagesDiffLink = $this->link(
1513 $userTalkTitle,
1514 wfMsgHtml( 'newmessagesdifflink' ),
1515 array(),
1516 array( 'diff' => 'cur' ),
1517 array( 'known', 'noclasses' )
1520 $ntl = wfMsg(
1521 'youhavenewmessages',
1522 $newMessagesLink,
1523 $newMessagesDiffLink
1525 # Disable Squid cache
1526 $wgOut->setSquidMaxage( 0 );
1528 } elseif ( count( $newtalks ) ) {
1529 // _>" " for BC <= 1.16
1530 $sep = str_replace( '_', ' ', wfMsgHtml( 'newtalkseparator' ) );
1531 $msgs = array();
1533 foreach ( $newtalks as $newtalk ) {
1534 $msgs[] = Xml::element(
1535 'a',
1536 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1539 $parts = implode( $sep, $msgs );
1540 $ntl = wfMsgHtml( 'youhavenewmessagesmulti', $parts );
1541 $wgOut->setSquidMaxage( 0 );
1544 return $ntl;