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 that provide 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 usable 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 $usableSkins = self
::getSkinNames();
101 foreach ( $wgSkipSkins as $skip ) {
102 unset( $usableSkins[$skip] );
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.
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 ( !MWInit
::classExists( $className ) ) {
168 if ( !defined( 'MW_COMPILED' ) ) {
169 require_once( "{$wgStyleDirectory}/{$skinName}.php" );
172 # Check if we got if not fallback to default skin
173 if ( !MWInit
::classExists( $className ) ) {
174 # DO NOT die if the class isn't found. This breaks maintenance
175 # scripts and can cause a user account to be unrecoverable
176 # except by SQL manipulation if a previously valid skin name
177 # is no longer valid.
178 wfDebug( "Skin class does not exist: $className\n" );
179 $className = 'SkinVector';
180 if ( !defined( 'MW_COMPILED' ) ) {
181 require_once( "{$wgStyleDirectory}/Vector.php" );
185 $skin = new $className( $key );
189 /** @return string skin name */
190 public function getSkinName() {
191 return $this->skinname
;
195 * @param $out OutputPage
197 function initPage( OutputPage
$out ) {
198 wfProfileIn( __METHOD__
);
200 $this->preloadExistence();
202 wfProfileOut( __METHOD__
);
206 * Preload the existence of three commonly-requested pages in a single query
208 function preloadExistence() {
209 $user = $this->getUser();
212 $titles = array( $user->getUserPage(), $user->getTalkPage() );
215 if ( $this->getTitle()->isSpecialPage() ) {
217 } elseif ( $this->getTitle()->isTalkPage() ) {
218 $titles[] = $this->getTitle()->getSubjectPage();
220 $titles[] = $this->getTitle()->getTalkPage();
223 $lb = new LinkBatch( $titles );
224 $lb->setCaller( __METHOD__
);
229 * Get the current revision ID
233 public function getRevisionId() {
234 return $this->getOutput()->getRevisionId();
238 * Whether the revision displayed is the latest revision of the page
242 public function isRevisionCurrent() {
243 $revID = $this->getRevisionId();
244 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
248 * Set the "relevant" title
249 * @see self::getRelevantTitle()
250 * @param $t Title object to use
252 public function setRelevantTitle( $t ) {
253 $this->mRelevantTitle
= $t;
257 * Return the "relevant" title.
258 * A "relevant" title is not necessarily the actual title of the page.
259 * Special pages like Special:MovePage use set the page they are acting on
260 * as their "relevant" title, this allows the skin system to display things
261 * such as content tabs which belong to to that page instead of displaying
262 * a basic special page tab which has almost no meaning.
266 public function getRelevantTitle() {
267 if ( isset( $this->mRelevantTitle
) ) {
268 return $this->mRelevantTitle
;
270 return $this->getTitle();
274 * Set the "relevant" user
275 * @see self::getRelevantUser()
276 * @param $u User object to use
278 public function setRelevantUser( $u ) {
279 $this->mRelevantUser
= $u;
283 * Return the "relevant" user.
284 * A "relevant" user is similar to a relevant title. Special pages like
285 * Special:Contributions mark the user which they are relevant to so that
286 * things like the toolbox can display the information they usually are only
287 * able to display on a user's userpage and talkpage.
290 public function getRelevantUser() {
291 if ( isset( $this->mRelevantUser
) ) {
292 return $this->mRelevantUser
;
294 $title = $this->getRelevantTitle();
295 if( $title->hasSubjectNamespace( NS_USER
) ) {
296 $rootUser = $title->getRootText();
297 if ( User
::isIP( $rootUser ) ) {
298 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
300 $user = User
::newFromName( $rootUser, false );
301 if ( $user && $user->isLoggedIn() ) {
302 $this->mRelevantUser
= $user;
305 return $this->mRelevantUser
;
311 * Outputs the HTML generated by other functions.
312 * @param $out OutputPage
314 abstract function outputPage( OutputPage
$out = null );
320 static function makeVariablesScript( $data ) {
322 return Html
::inlineScript(
323 ResourceLoader
::makeLoaderConditionalScript( ResourceLoader
::makeConfigSetScript( $data ) )
331 * Make a "<script>" tag containing global variables
333 * @deprecated in 1.19
335 * @return string HTML fragment
337 public static function makeGlobalVariablesScript( $unused ) {
340 wfDeprecated( __METHOD__
, '1.19' );
342 return self
::makeVariablesScript( $wgOut->getJSVars() );
346 * Get the query to generate a dynamic stylesheet
350 public static function getDynamicStylesheetQuery() {
351 global $wgSquidMaxage;
355 'maxage' => $wgSquidMaxage,
356 'usemsgcache' => 'yes',
357 'ctype' => 'text/css',
358 'smaxage' => $wgSquidMaxage,
363 * Add skin specific stylesheets
364 * Calling this method with an $out of anything but the same OutputPage
365 * inside ->getOutput() is deprecated. The $out arg is kept
366 * for compatibility purposes with skins.
367 * @param $out OutputPage
370 abstract function setupSkinUserCss( OutputPage
$out );
374 * @param $title Title
377 function getPageClasses( $title ) {
378 $numeric = 'ns-' . $title->getNamespace();
380 if ( $title->isSpecialPage() ) {
381 $type = 'ns-special';
382 // bug 23315: provide a class based on the canonical special page name without subpages
383 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
384 if ( $canonicalName ) {
385 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
387 $type .= ' mw-invalidspecialpage';
389 } elseif ( $title->isTalkPage() ) {
392 $type = 'ns-subject';
395 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
397 return "$numeric $type $name";
401 * This will be called by OutputPage::headElement when it is creating the
402 * "<body>" tag, skins can override it if they have a need to add in any
403 * body attributes or classes of their own.
404 * @param $out OutputPage
405 * @param $bodyAttrs Array
407 function addToBodyAttributes( $out, &$bodyAttrs ) {
408 // does nothing by default
423 function getCategoryLinks() {
424 global $wgUseCategoryBrowser;
426 $out = $this->getOutput();
427 $allCats = $out->getCategoryLinks();
429 if ( !count( $allCats ) ) {
437 $colon = $this->msg( 'colon-separator' )->escaped();
439 if ( !empty( $allCats['normal'] ) ) {
440 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
442 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
443 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
444 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
445 Linker
::link( Title
::newFromText( $linkPage ), $msg )
446 . $colon . '<ul>' . $t . '</ul>' . '</div>';
450 if ( isset( $allCats['hidden'] ) ) {
451 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
452 $class = ' mw-hidden-cats-user-shown';
453 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
454 $class = ' mw-hidden-cats-ns-shown';
456 $class = ' mw-hidden-cats-hidden';
459 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
460 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
461 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
465 # optional 'dmoz-like' category browser. Will be shown under the list
466 # of categories an article belong to
467 if ( $wgUseCategoryBrowser ) {
468 $s .= '<br /><hr />';
470 # get a big array of the parents tree
471 $parenttree = $this->getTitle()->getParentCategoryTree();
472 # Skin object passed by reference cause it can not be
473 # accessed under the method subfunction drawCategoryBrowser
474 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
475 # Clean out bogus first entry and sort them
476 unset( $tempout[0] );
478 # Output one per line
479 $s .= implode( "<br />\n", $tempout );
486 * Render the array as a series of links.
487 * @param array $tree categories tree returned by Title::getParentCategoryTree
488 * @return String separated by >, terminate with "\n"
490 function drawCategoryBrowser( $tree ) {
493 foreach ( $tree as $element => $parent ) {
494 if ( empty( $parent ) ) {
495 # element start a new list
498 # grab the others elements
499 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
502 # add our current element to the list
503 $eltitle = Title
::newFromText( $element );
504 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
513 function getCategories() {
514 $out = $this->getOutput();
516 $catlinks = $this->getCategoryLinks();
518 $classes = 'catlinks';
520 // Check what we're showing
521 $allCats = $out->getCategoryLinks();
522 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
523 $this->getTitle()->getNamespace() == NS_CATEGORY
;
525 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
526 $classes .= ' catlinks-allhidden';
529 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
533 * This runs a hook to allow extensions placing their stuff after content
534 * and article metadata (e.g. categories).
535 * Note: This function has nothing to do with afterContent().
537 * This hook is placed here in order to allow using the same hook for all
538 * skins, both the SkinTemplate based ones and the older ones, which directly
539 * use this class to get their data.
541 * The output of this function gets processed in SkinTemplate::outputPage() for
542 * the SkinTemplate based skins, all other skins should directly echo it.
544 * @return String, empty by default, if not changed by any hook function.
546 protected function afterContentHook() {
549 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
550 // adding just some spaces shouldn't toggle the output
551 // of the whole <div/>, so we use trim() here
552 if ( trim( $data ) != '' ) {
553 // Doing this here instead of in the skins to
554 // ensure that the div has the same ID in all
556 $data = "<div id='mw-data-after-content'>\n" .
561 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
568 * Generate debug data HTML for displaying at the bottom of the main content
570 * @return String HTML containing debug data, if enabled (otherwise empty).
572 protected function generateDebugHTML() {
573 return MWDebug
::getHTMLDebugLog();
577 * This gets called shortly before the "</body>" tag.
579 * @return String HTML-wrapped JS code to be put before "</body>"
581 function bottomScripts() {
582 // TODO and the suckage continues. This function is really just a wrapper around
583 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
585 $bottomScriptText = $this->getOutput()->getBottomScripts();
586 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
588 return $bottomScriptText;
592 * Text with the permalink to the source page,
593 * usually shown on the footer of a printed page
595 * @return string HTML text with an URL
597 function printSource() {
598 $oldid = $this->getRevisionId();
600 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid ) ) );
602 // oldid not available for non existing pages
603 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
605 return $this->msg( 'retrievedfrom', '<a href="' . $url . '">' . $url . '</a>' )->text();
611 function getUndeleteLink() {
612 $action = $this->getRequest()->getVal( 'action', 'view' );
614 if ( $this->getUser()->isAllowed( 'deletedhistory' ) &&
615 ( $this->getTitle()->getArticleID() == 0 ||
$action == 'history' ) ) {
616 $n = $this->getTitle()->isDeleted();
619 if ( $this->getUser()->isAllowed( 'undelete' ) ) {
620 $msg = 'thisisdeleted';
622 $msg = 'viewdeleted';
625 return $this->msg( $msg )->rawParams(
627 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
628 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
639 function subPageSubtitle() {
641 $out = $this->getOutput();
644 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
648 if ( $out->isArticle() && MWNamespace
::hasSubpages( $out->getTitle()->getNamespace() ) ) {
649 $ptext = $this->getTitle()->getPrefixedText();
650 if ( preg_match( '/\//', $ptext ) ) {
651 $links = explode( '/', $ptext );
657 foreach ( $links as $link ) {
658 $growinglink .= $link;
660 $linkObj = Title
::newFromText( $growinglink );
662 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
663 $getlink = Linker
::linkKnown(
665 htmlspecialchars( $display )
671 $subpages .= $wgLang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
673 $subpages .= '< ';
676 $subpages .= $getlink;
690 * Returns true if the IP should be shown in the header
693 function showIPinHeader() {
694 global $wgShowIPinHeader;
695 return $wgShowIPinHeader && session_id() != '';
701 function getSearchLink() {
702 $searchPage = SpecialPage
::getTitleFor( 'Search' );
703 return $searchPage->getLocalURL();
709 function escapeSearchLink() {
710 return htmlspecialchars( $this->getSearchLink() );
714 * @param $type string
717 function getCopyright( $type = 'detect' ) {
718 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgContLang;
720 if ( $type == 'detect' ) {
721 if ( !$this->isRevisionCurrent() && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled() ) {
728 if ( $type == 'history' ) {
729 $msg = 'history_copyright';
734 if ( $wgRightsPage ) {
735 $title = Title
::newFromText( $wgRightsPage );
736 $link = Linker
::linkKnown( $title, $wgRightsText );
737 } elseif ( $wgRightsUrl ) {
738 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
739 } elseif ( $wgRightsText ) {
740 $link = $wgRightsText;
746 // Allow for site and per-namespace customization of copyright notice.
749 wfRunHooks( 'SkinCopyrightFooter', array( $this->getTitle(), $type, &$msg, &$link, &$forContent ) );
751 $msgObj = $this->msg( $msg )->rawParams( $link );
753 $msg = $msgObj->inContentLanguage()->text();
754 if ( $this->getLanguage()->getCode() !== $wgContLang->getCode() ) {
755 $msg = Html
::rawElement( 'span', array( 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $msg );
759 return $msgObj->text();
764 * @return null|string
766 function getCopyrightIcon() {
767 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
771 if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
772 $out = $wgCopyrightIcon;
773 } elseif ( $wgRightsIcon ) {
774 $icon = htmlspecialchars( $wgRightsIcon );
776 if ( $wgRightsUrl ) {
777 $url = htmlspecialchars( $wgRightsUrl );
778 $out .= '<a href="' . $url . '">';
781 $text = htmlspecialchars( $wgRightsText );
782 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
784 if ( $wgRightsUrl ) {
793 * Gets the powered by MediaWiki icon.
796 function getPoweredBy() {
799 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
800 $text = '<a href="//www.mediawiki.org/"><img src="' . $url . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
801 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
806 * Get the timestamp of the latest revision, formatted in user language
810 protected function lastModified() {
811 $timestamp = $this->getOutput()->getRevisionTimestamp();
813 # No cached timestamp, load it from the database
814 if ( $timestamp === null ) {
815 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
819 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
820 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
821 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text();
826 if ( wfGetLB()->getLaggedSlaveMode() ) {
827 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->text() . '</strong>';
834 * @param $align string
837 function logoText( $align = '' ) {
838 if ( $align != '' ) {
839 $a = " style='float: {$align};'";
844 $mp = $this->msg( 'mainpage' )->escaped();
845 $mptitle = Title
::newMainPage();
846 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
848 $logourl = $this->getLogo();
849 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
855 * Renders a $wgFooterIcons icon according to the method's arguments
856 * @param array $icon The icon to build the html for, see $wgFooterIcons for the format of this array
857 * @param bool|String $withImage Whether to use the icon's image or output a text-only footericon
858 * @return String HTML
860 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
861 if ( is_string( $icon ) ) {
863 } else { // Assuming array
864 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
865 unset( $icon["url"] );
866 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
867 $html = Html
::element( 'img', $icon ); // do this the lazy way, just pass icon data as an attribute array
869 $html = htmlspecialchars( $icon["alt"] );
872 $html = Html
::rawElement( 'a', array( "href" => $url ), $html );
879 * Gets the link to the wiki's main page.
882 function mainPageLink() {
883 $s = Linker
::linkKnown(
884 Title
::newMainPage(),
885 $this->msg( 'mainpage' )->escaped()
896 public function footerLink( $desc, $page ) {
897 // if the link description has been set to "-" in the default language,
898 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
899 // then it is disabled, for all languages.
902 // Otherwise, we display the link for the user, described in their
903 // language (which may or may not be the same as the default language),
904 // but we make the link target be the one site-wide page.
905 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
907 return Linker
::linkKnown(
909 $this->msg( $desc )->escaped()
915 * Gets the link to the wiki's privacy policy page.
916 * @return String HTML
918 function privacyLink() {
919 return $this->footerLink( 'privacy', 'privacypage' );
923 * Gets the link to the wiki's about page.
924 * @return String HTML
926 function aboutLink() {
927 return $this->footerLink( 'aboutsite', 'aboutpage' );
931 * Gets the link to the wiki's general disclaimers page.
932 * @return String HTML
934 function disclaimerLink() {
935 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
939 * Return URL options for the 'edit page' link.
940 * This may include an 'oldid' specifier, if the current page view is such.
945 function editUrlOptions() {
946 $options = array( 'action' => 'edit' );
948 if ( !$this->isRevisionCurrent() ) {
949 $options['oldid'] = intval( $this->getRevisionId() );
956 * @param $id User|int
959 function showEmailUser( $id ) {
960 if ( $id instanceof User
) {
963 $targetUser = User
::newFromId( $id );
965 return $this->getUser()->canSendEmail() && # the sending user must have a confirmed email address
966 $targetUser->canReceiveEmail(); # the target user must have a confirmed email address and allow emails from users
970 * Return a fully resolved style path url to images or styles stored in the common folder.
971 * This method returns a url resolved using the configured skin style path
972 * and includes the style version inside of the url.
973 * @param string $name The name or path of a skin resource file
974 * @return String The fully resolved style path url including styleversion
976 function getCommonStylePath( $name ) {
977 global $wgStylePath, $wgStyleVersion;
978 return "$wgStylePath/common/$name?$wgStyleVersion";
982 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
983 * This method returns a url resolved using the configured skin style path
984 * and includes the style version inside of the url.
985 * @param string $name The name or path of a skin resource file
986 * @return String The fully resolved style path url including styleversion
988 function getSkinStylePath( $name ) {
989 global $wgStylePath, $wgStyleVersion;
990 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
993 /* these are used extensively in SkinTemplate, but also some other places */
996 * @param $urlaction string
999 static function makeMainPageUrl( $urlaction = '' ) {
1000 $title = Title
::newMainPage();
1001 self
::checkTitle( $title, '' );
1003 return $title->getLocalURL( $urlaction );
1007 * Make a URL for a Special Page using the given query and protocol.
1009 * If $proto is set to null, make a local URL. Otherwise, make a full
1010 * URL with the protocol specified.
1012 * @param string $name Name of the Special page
1013 * @param string $urlaction Query to append
1014 * @param $proto Protocol to use or null for a local URL
1017 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1018 $title = SpecialPage
::getSafeTitleFor( $name );
1019 if( is_null( $proto ) ) {
1020 return $title->getLocalURL( $urlaction );
1022 return $title->getFullURL( $urlaction, false, $proto );
1027 * @param $name string
1028 * @param $subpage string
1029 * @param $urlaction string
1032 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1033 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1034 return $title->getLocalURL( $urlaction );
1038 * @param $name string
1039 * @param $urlaction string
1042 static function makeI18nUrl( $name, $urlaction = '' ) {
1043 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1044 self
::checkTitle( $title, $name );
1045 return $title->getLocalURL( $urlaction );
1049 * @param $name string
1050 * @param $urlaction string
1053 static function makeUrl( $name, $urlaction = '' ) {
1054 $title = Title
::newFromText( $name );
1055 self
::checkTitle( $title, $name );
1057 return $title->getLocalURL( $urlaction );
1061 * If url string starts with http, consider as external URL, else
1063 * @param $name String
1064 * @return String URL
1066 static function makeInternalOrExternalUrl( $name ) {
1067 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1070 return self
::makeUrl( $name );
1075 * this can be passed the NS number as defined in Language.php
1077 * @param $urlaction string
1078 * @param $namespace int
1081 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1082 $title = Title
::makeTitleSafe( $namespace, $name );
1083 self
::checkTitle( $title, $name );
1085 return $title->getLocalURL( $urlaction );
1089 * these return an array with the 'href' and boolean 'exists'
1091 * @param $urlaction string
1094 static function makeUrlDetails( $name, $urlaction = '' ) {
1095 $title = Title
::newFromText( $name );
1096 self
::checkTitle( $title, $name );
1099 'href' => $title->getLocalURL( $urlaction ),
1100 'exists' => $title->getArticleID() != 0,
1105 * Make URL details where the article exists (or at least it's convenient to think so)
1106 * @param string $name Article name
1107 * @param $urlaction String
1110 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1111 $title = Title
::newFromText( $name );
1112 self
::checkTitle( $title, $name );
1115 'href' => $title->getLocalURL( $urlaction ),
1121 * make sure we have some title to operate on
1123 * @param $title Title
1124 * @param $name string
1126 static function checkTitle( &$title, $name ) {
1127 if ( !is_object( $title ) ) {
1128 $title = Title
::newFromText( $name );
1129 if ( !is_object( $title ) ) {
1130 $title = Title
::newFromText( '--error: link target missing--' );
1136 * Build an array that represents the sidebar(s), the navigation bar among them.
1138 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1140 * The format of the returned array is array( heading => content, ... ), where:
1141 * - heading is the heading of a navigation portlet. It is either:
1142 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1143 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1144 * - plain text, which should be HTML-escaped by the skin
1145 * - content is the contents of the portlet. It is either:
1146 * - HTML text (<ul><li>...</li>...</ul>)
1147 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1148 * - (for a magic string as a key, any value)
1150 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1151 * and can technically insert anything in here; skin creators are expected to handle
1152 * values described above.
1156 function buildSidebar() {
1157 global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1158 wfProfileIn( __METHOD__
);
1160 $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() );
1162 if ( $wgEnableSidebarCache ) {
1163 $cachedsidebar = $wgMemc->get( $key );
1164 if ( $cachedsidebar ) {
1165 wfProfileOut( __METHOD__
);
1166 return $cachedsidebar;
1171 $this->addToSidebar( $bar, 'sidebar' );
1173 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1174 if ( $wgEnableSidebarCache ) {
1175 $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1178 wfProfileOut( __METHOD__
);
1182 * Add content from a sidebar system message
1183 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1185 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1188 * @param $message String
1190 function addToSidebar( &$bar, $message ) {
1191 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1195 * Add content from plain text
1198 * @param $text string
1201 function addToSidebarPlain( &$bar, $text ) {
1202 $lines = explode( "\n", $text );
1206 foreach ( $lines as $line ) {
1207 if ( strpos( $line, '*' ) !== 0 ) {
1210 $line = rtrim( $line, "\r" ); // for Windows compat
1212 if ( strpos( $line, '**' ) !== 0 ) {
1213 $heading = trim( $line, '* ' );
1214 if ( !array_key_exists( $heading, $bar ) ) {
1215 $bar[$heading] = array();
1218 $line = trim( $line, '* ' );
1220 if ( strpos( $line, '|' ) !== false ) { // sanity check
1221 $line = MessageCache
::singleton()->transform( $line, false, null, $this->getTitle() );
1222 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1223 if ( count( $line ) !== 2 ) {
1224 // Second sanity check, could be hit by people doing
1225 // funky stuff with parserfuncs... (bug 33321)
1229 $extraAttribs = array();
1231 $msgLink = $this->msg( $line[0] )->inContentLanguage();
1232 if ( $msgLink->exists() ) {
1233 $link = $msgLink->text();
1234 if ( $link == '-' ) {
1240 $msgText = $this->msg( $line[1] );
1241 if ( $msgText->exists() ) {
1242 $text = $msgText->text();
1247 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1250 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1251 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1252 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1253 $extraAttribs['rel'] = 'nofollow';
1256 global $wgExternalLinkTarget;
1257 if ( $wgExternalLinkTarget ) {
1258 $extraAttribs['target'] = $wgExternalLinkTarget;
1261 $title = Title
::newFromText( $link );
1264 $title = $title->fixSpecialName();
1265 $href = $title->getLinkURL();
1267 $href = 'INVALID-TITLE';
1271 $bar[$heading][] = array_merge( array(
1274 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1287 * Should we load mediawiki.legacy.wikiprintable? Skins that have their own
1288 * print stylesheet should override this and return false. (This is an
1289 * ugly hack to get Monobook to play nicely with OutputPage::headElement().)
1293 public function commonPrintStylesheet() {
1298 * Gets new talk page messages for the current user.
1299 * @return MediaWiki message or if no new talk page messages, nothing
1301 function getNewtalks() {
1302 $out = $this->getOutput();
1304 $newtalks = $this->getUser()->getNewMessageLinks();
1307 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1308 $uTalkTitle = $this->getUser()->getTalkPage();
1310 if ( !$uTalkTitle->equals( $out->getTitle() ) ) {
1311 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1313 if ( $lastSeenRev !== null ) {
1314 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1315 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1316 if ( $latestRev !== null ) {
1317 // Singular if only 1 unseen revision, plural if several unseen revisions.
1318 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1319 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1320 $lastSeenRev, $latestRev, 10, 'include_new' );
1323 // Singular if no revision -> diff link will show latest change only in any case
1326 $plural = $plural ?
2 : 1;
1327 // 2 signifies "more than one revision". We don't know how many, and even if we did,
1328 // the number of revisions or authors is not necessarily the same as the number of
1330 $newMessagesLink = Linker
::linkKnown(
1332 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1334 array( 'redirect' => 'no' )
1337 $newMessagesDiffLink = Linker
::linkKnown(
1339 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1341 $lastSeenRev !== null
1342 ?
array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' )
1343 : array( 'diff' => 'cur' )
1346 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1348 'youhavenewmessagesfromusers',
1350 $newMessagesDiffLink
1351 )->numParams( $nofAuthors );
1353 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1355 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1357 $newMessagesDiffLink
1360 $ntl = $ntl->text();
1361 # Disable Squid cache
1362 $out->setSquidMaxage( 0 );
1364 } elseif ( count( $newtalks ) ) {
1365 // _>" " for BC <= 1.16
1366 $sep = str_replace( '_', ' ', $this->msg( 'newtalkseparator' )->escaped() );
1369 foreach ( $newtalks as $newtalk ) {
1370 $msgs[] = Xml
::element(
1372 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1375 $parts = implode( $sep, $msgs );
1376 $ntl = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1377 $out->setSquidMaxage( 0 );
1384 * Get a cached notice
1386 * @param string $name message name, or 'default' for $wgSiteNotice
1387 * @return String: HTML fragment
1389 private function getCachedNotice( $name ) {
1390 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1392 wfProfileIn( __METHOD__
);
1396 if( $name === 'default' ) {
1398 global $wgSiteNotice;
1399 $notice = $wgSiteNotice;
1400 if( empty( $notice ) ) {
1401 wfProfileOut( __METHOD__
);
1405 $msg = $this->msg( $name )->inContentLanguage();
1406 if( $msg->isDisabled() ) {
1407 wfProfileOut( __METHOD__
);
1410 $notice = $msg->plain();
1413 // Use the extra hash appender to let eg SSL variants separately cache.
1414 $key = wfMemcKey( $name . $wgRenderHashAppend );
1415 $cachedNotice = $parserMemc->get( $key );
1416 if( is_array( $cachedNotice ) ) {
1417 if( md5( $notice ) == $cachedNotice['hash'] ) {
1418 $notice = $cachedNotice['html'];
1427 $parsed = $this->getOutput()->parse( $notice );
1428 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1432 $notice = Html
::rawElement( 'div', array( 'id' => 'localNotice',
1433 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice );
1434 wfProfileOut( __METHOD__
);
1439 * Get a notice based on page's namespace
1441 * @return String: HTML fragment
1443 function getNamespaceNotice() {
1444 wfProfileIn( __METHOD__
);
1446 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1447 $namespaceNotice = $this->getCachedNotice( $key );
1448 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
1449 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1451 $namespaceNotice = '';
1454 wfProfileOut( __METHOD__
);
1455 return $namespaceNotice;
1459 * Get the site notice
1461 * @return String: HTML fragment
1463 function getSiteNotice() {
1464 wfProfileIn( __METHOD__
);
1467 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1468 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1469 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1471 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1472 if ( !$anonNotice ) {
1473 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1475 $siteNotice = $anonNotice;
1478 if ( !$siteNotice ) {
1479 $siteNotice = $this->getCachedNotice( 'default' );
1483 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1484 wfProfileOut( __METHOD__
);
1489 * Create a section edit link. This supersedes editSectionLink() and
1490 * editSectionLinkForOther().
1492 * @param $nt Title The title being linked to (may not be the same as
1493 * $wgTitle, if the section is included from a template)
1494 * @param string $section The designation of the section being pointed to,
1495 * to be included in the link, like "§ion=$section"
1496 * @param string $tooltip The tooltip to use for the link: will be escaped
1497 * and wrapped in the 'editsectionhint' message
1498 * @param $lang string Language code
1499 * @return string HTML to use for edit link
1501 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1502 // HTML generated here should probably have userlangattributes
1503 // added to it for LTR text on RTL pages
1505 $lang = wfGetLangObj( $lang );
1508 if ( !is_null( $tooltip ) ) {
1509 # Bug 25462: undo double-escaping.
1510 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1511 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1512 ->inLanguage( $lang )->text();
1514 $link = Linker
::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(),
1516 array( 'action' => 'edit', 'section' => $section ),
1517 array( 'noclasses', 'known' )
1520 # Run the old hook. This takes up half of the function . . . hopefully
1521 # we can rid of it someday.
1524 $attribs = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1525 ->inLanguage( $lang )->escaped();
1526 $attribs = " title=\"$attribs\"";
1529 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result, $lang ) );
1530 if ( !is_null( $result ) ) {
1531 # For reverse compatibility, add the brackets *after* the hook is
1532 # run, and even add them to hook-provided text. (This is the main
1533 # reason that the EditSectionLink hook is deprecated in favor of
1534 # DoEditSectionLink: it can't change the brackets or the span.)
1535 $result = wfMessage( 'editsection-brackets' )->rawParams( $result )
1536 ->inLanguage( $lang )->escaped();
1537 return "<span class=\"editsection\">$result</span>";
1540 # Add the brackets and the span, and *then* run the nice new hook, with
1541 # clean and non-redundant arguments.
1542 $result = wfMessage( 'editsection-brackets' )->rawParams( $link )
1543 ->inLanguage( $lang )->escaped();
1544 $result = "<span class=\"editsection\">$result</span>";
1546 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1551 * Use PHP's magic __call handler to intercept legacy calls to the linker
1552 * for backwards compatibility.
1554 * @param string $fname Name of called method
1555 * @param array $args Arguments to the method
1556 * @throws MWException
1559 function __call( $fname, $args ) {
1560 $realFunction = array( 'Linker', $fname );
1561 if ( is_callable( $realFunction ) ) {
1562 wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' );
1563 return call_user_func_array( $realFunction, $args );
1565 $className = get_class( $this );
1566 throw new MWException( "Call to undefined method $className::$fname" );