3 * Base class for all skins.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * @defgroup Skins Skins
28 * The main skin class which provides methods and properties for all other skins.
29 * This base class is also the "Standard" skin.
31 * See docs/skin.txt for more information.
35 abstract class Skin
extends ContextSource
{
36 protected $skinname = 'standard';
37 protected $mRelevantTitle = null;
38 protected $mRelevantUser = null;
41 * Fetch the set of available skins.
42 * @return array associative array of strings
44 static function getSkinNames() {
45 global $wgValidSkinNames;
46 static $skinsInitialised = false;
48 if ( !$skinsInitialised ||
!count( $wgValidSkinNames ) ) {
49 # Get a list of available skins
50 # Build using the regular expression '^(.*).php$'
51 # Array keys are all lower case, array value keep the case used by filename
53 wfProfileIn( __METHOD__
. '-init' );
55 global $wgStyleDirectory;
57 $skinDir = dir( $wgStyleDirectory );
59 if ( $skinDir !== false && $skinDir !== null ) {
60 # while code from www.php.net
61 while ( false !== ( $file = $skinDir->read() ) ) {
62 // Skip non-PHP files, hidden files, and '.dep' includes
65 if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
67 $wgValidSkinNames[strtolower( $aSkin )] = $aSkin;
72 $skinsInitialised = true;
73 wfProfileOut( __METHOD__
. '-init' );
75 return $wgValidSkinNames;
79 * Fetch the skinname messages for available skins.
80 * @return array of strings
82 static function getSkinNameMessages() {
84 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
85 // Messages: skinname-cologneblue, skinname-monobook, skinname-modern, skinname-vector
86 $messages[] = "skinname-$skinKey";
92 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
93 * Useful for Special:Preferences and other places where you
94 * only want to show skins users _can_ use.
97 public static function getAllowedSkins() {
100 $allowedSkins = self
::getSkinNames();
102 foreach ( $wgSkipSkins as $skip ) {
103 unset( $allowedSkins[$skip] );
106 return $allowedSkins;
110 * @deprecated since 1.22, use getAllowedSkins
113 public static function getUsableSkins() {
114 wfDeprecated( __METHOD__
, '1.22' );
115 return self
::getAllowedSkins();
119 * Normalize a skin preference value to a form that can be loaded.
120 * If a skin can't be found, it will fall back to the configured
121 * default (or the old 'Classic' skin if that's broken).
122 * @param string $key 'monobook', 'standard', etc.
125 static function normalizeKey( $key ) {
126 global $wgDefaultSkin;
128 $skinNames = Skin
::getSkinNames();
130 if ( $key == '' ||
$key == 'default' ) {
131 // Don't return the default immediately;
132 // in a misconfiguration we need to fall back.
133 $key = $wgDefaultSkin;
136 if ( isset( $skinNames[$key] ) ) {
140 // Older versions of the software used a numeric setting
141 // in the user preferences.
147 if ( isset( $fallback[$key] ) ) {
148 $key = $fallback[$key];
151 if ( isset( $skinNames[$key] ) ) {
153 } elseif ( isset( $skinNames[$wgDefaultSkin] ) ) {
154 return $wgDefaultSkin;
161 * Factory method for loading a skin of a given type
162 * @param string $key 'monobook', 'standard', etc.
165 static function &newFromKey( $key ) {
166 global $wgStyleDirectory;
168 $key = Skin
::normalizeKey( $key );
170 $skinNames = Skin
::getSkinNames();
171 $skinName = $skinNames[$key];
172 $className = "Skin{$skinName}";
174 # Grab the skin class and initialise it.
175 if ( !class_exists( $className ) ) {
177 require_once "{$wgStyleDirectory}/{$skinName}.php";
179 # Check if we got if not fallback to default skin
180 if ( !class_exists( $className ) ) {
181 # DO NOT die if the class isn't found. This breaks maintenance
182 # scripts and can cause a user account to be unrecoverable
183 # except by SQL manipulation if a previously valid skin name
184 # is no longer valid.
185 wfDebug( "Skin class does not exist: $className\n" );
186 $className = 'SkinVector';
187 require_once "{$wgStyleDirectory}/Vector.php";
190 $skin = new $className( $key );
195 * @return string skin name
197 public function getSkinName() {
198 return $this->skinname
;
202 * @param $out OutputPage
204 function initPage( OutputPage
$out ) {
205 wfProfileIn( __METHOD__
);
207 $this->preloadExistence();
209 wfProfileOut( __METHOD__
);
213 * Defines the ResourceLoader modules that should be added to the skin
214 * It is recommended that skins wishing to override call parent::getDefaultModules()
215 * and substitute out any modules they wish to change by using a key to look them up
216 * @return Array of modules with helper keys for easy overriding
218 public function getDefaultModules() {
219 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
220 $wgAjaxWatch, $wgEnableAPI, $wgEnableWriteAPI;
222 $out = $this->getOutput();
223 $user = $out->getUser();
225 // modules that enhance the page content in some way
227 'mediawiki.page.ready',
229 // modules that exist for legacy reasons
231 // modules relating to search functionality
233 // modules relating to functionality relating to watching an article
235 // modules which relate to the current users preferences
238 if ( $wgIncludeLegacyJavaScript ) {
239 $modules['legacy'][] = 'mediawiki.legacy.wikibits';
242 if ( $wgPreloadJavaScriptMwUtil ) {
243 $modules['legacy'][] = 'mediawiki.util';
246 // Add various resources if required
248 $modules['legacy'][] = 'mediawiki.legacy.ajax';
250 if ( $wgEnableAPI ) {
251 if ( $wgEnableWriteAPI && $wgAjaxWatch && $user->isLoggedIn()
252 && $user->isAllowed( 'writeapi' )
254 $modules['watch'][] = 'mediawiki.page.watch.ajax';
257 $modules['search'][] = 'mediawiki.searchSuggest';
261 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
262 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
265 // Crazy edit-on-double-click stuff
266 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
267 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
273 * Preload the existence of three commonly-requested pages in a single query
275 function preloadExistence() {
276 $user = $this->getUser();
279 $titles = array( $user->getUserPage(), $user->getTalkPage() );
282 if ( $this->getTitle()->isSpecialPage() ) {
284 } elseif ( $this->getTitle()->isTalkPage() ) {
285 $titles[] = $this->getTitle()->getSubjectPage();
287 $titles[] = $this->getTitle()->getTalkPage();
290 $lb = new LinkBatch( $titles );
291 $lb->setCaller( __METHOD__
);
296 * Get the current revision ID
300 public function getRevisionId() {
301 return $this->getOutput()->getRevisionId();
305 * Whether the revision displayed is the latest revision of the page
309 public function isRevisionCurrent() {
310 $revID = $this->getRevisionId();
311 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
315 * Set the "relevant" title
316 * @see self::getRelevantTitle()
317 * @param $t Title object to use
319 public function setRelevantTitle( $t ) {
320 $this->mRelevantTitle
= $t;
324 * Return the "relevant" title.
325 * A "relevant" title is not necessarily the actual title of the page.
326 * Special pages like Special:MovePage use set the page they are acting on
327 * as their "relevant" title, this allows the skin system to display things
328 * such as content tabs which belong to to that page instead of displaying
329 * a basic special page tab which has almost no meaning.
333 public function getRelevantTitle() {
334 if ( isset( $this->mRelevantTitle
) ) {
335 return $this->mRelevantTitle
;
337 return $this->getTitle();
341 * Set the "relevant" user
342 * @see self::getRelevantUser()
343 * @param $u User object to use
345 public function setRelevantUser( $u ) {
346 $this->mRelevantUser
= $u;
350 * Return the "relevant" user.
351 * A "relevant" user is similar to a relevant title. Special pages like
352 * Special:Contributions mark the user which they are relevant to so that
353 * things like the toolbox can display the information they usually are only
354 * able to display on a user's userpage and talkpage.
357 public function getRelevantUser() {
358 if ( isset( $this->mRelevantUser
) ) {
359 return $this->mRelevantUser
;
361 $title = $this->getRelevantTitle();
362 if ( $title->hasSubjectNamespace( NS_USER
) ) {
363 $rootUser = $title->getRootText();
364 if ( User
::isIP( $rootUser ) ) {
365 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
367 $user = User
::newFromName( $rootUser, false );
368 if ( $user && $user->isLoggedIn() ) {
369 $this->mRelevantUser
= $user;
372 return $this->mRelevantUser
;
378 * Outputs the HTML generated by other functions.
379 * @param $out OutputPage
381 abstract function outputPage( OutputPage
$out = null );
387 static function makeVariablesScript( $data ) {
389 return Html
::inlineScript(
390 ResourceLoader
::makeLoaderConditionalScript( ResourceLoader
::makeConfigSetScript( $data ) )
398 * Make a "<script>" tag containing global variables
400 * @deprecated in 1.19
402 * @return string HTML fragment
404 public static function makeGlobalVariablesScript( $unused ) {
407 wfDeprecated( __METHOD__
, '1.19' );
409 return self
::makeVariablesScript( $wgOut->getJSVars() );
413 * Get the query to generate a dynamic stylesheet
417 public static function getDynamicStylesheetQuery() {
418 global $wgSquidMaxage;
422 'maxage' => $wgSquidMaxage,
423 'usemsgcache' => 'yes',
424 'ctype' => 'text/css',
425 'smaxage' => $wgSquidMaxage,
430 * Add skin specific stylesheets
431 * Calling this method with an $out of anything but the same OutputPage
432 * inside ->getOutput() is deprecated. The $out arg is kept
433 * for compatibility purposes with skins.
434 * @param $out OutputPage
437 abstract function setupSkinUserCss( OutputPage
$out );
441 * @param $title Title
444 function getPageClasses( $title ) {
445 $numeric = 'ns-' . $title->getNamespace();
447 if ( $title->isSpecialPage() ) {
448 $type = 'ns-special';
449 // bug 23315: provide a class based on the canonical special page name without subpages
450 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
451 if ( $canonicalName ) {
452 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
454 $type .= ' mw-invalidspecialpage';
456 } elseif ( $title->isTalkPage() ) {
459 $type = 'ns-subject';
462 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
464 return "$numeric $type $name";
468 * Return values for <html> element
469 * @return array of associative name-to-value elements for <html> element
471 public function getHtmlElementAttributes() {
472 $lang = $this->getLanguage();
474 'lang' => $lang->getHtmlCode(),
475 'dir' => $lang->getDir(),
476 'class' => 'client-nojs',
481 * This will be called by OutputPage::headElement when it is creating the
482 * "<body>" tag, skins can override it if they have a need to add in any
483 * body attributes or classes of their own.
484 * @param $out OutputPage
485 * @param $bodyAttrs Array
487 function addToBodyAttributes( $out, &$bodyAttrs ) {
488 // does nothing by default
503 function getCategoryLinks() {
504 global $wgUseCategoryBrowser;
506 $out = $this->getOutput();
507 $allCats = $out->getCategoryLinks();
509 if ( !count( $allCats ) ) {
517 $colon = $this->msg( 'colon-separator' )->escaped();
519 if ( !empty( $allCats['normal'] ) ) {
520 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
522 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
523 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
524 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
525 Linker
::link( Title
::newFromText( $linkPage ), $msg )
526 . $colon . '<ul>' . $t . '</ul>' . '</div>';
530 if ( isset( $allCats['hidden'] ) ) {
531 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
532 $class = ' mw-hidden-cats-user-shown';
533 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
534 $class = ' mw-hidden-cats-ns-shown';
536 $class = ' mw-hidden-cats-hidden';
539 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
540 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
541 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
545 # optional 'dmoz-like' category browser. Will be shown under the list
546 # of categories an article belong to
547 if ( $wgUseCategoryBrowser ) {
548 $s .= '<br /><hr />';
550 # get a big array of the parents tree
551 $parenttree = $this->getTitle()->getParentCategoryTree();
552 # Skin object passed by reference cause it can not be
553 # accessed under the method subfunction drawCategoryBrowser
554 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
555 # Clean out bogus first entry and sort them
556 unset( $tempout[0] );
558 # Output one per line
559 $s .= implode( "<br />\n", $tempout );
566 * Render the array as a series of links.
567 * @param array $tree categories tree returned by Title::getParentCategoryTree
568 * @return String separated by >, terminate with "\n"
570 function drawCategoryBrowser( $tree ) {
573 foreach ( $tree as $element => $parent ) {
574 if ( empty( $parent ) ) {
575 # element start a new list
578 # grab the others elements
579 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
582 # add our current element to the list
583 $eltitle = Title
::newFromText( $element );
584 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
593 function getCategories() {
594 $out = $this->getOutput();
596 $catlinks = $this->getCategoryLinks();
598 $classes = 'catlinks';
600 // Check what we're showing
601 $allCats = $out->getCategoryLinks();
602 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
603 $this->getTitle()->getNamespace() == NS_CATEGORY
;
605 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
606 $classes .= ' catlinks-allhidden';
609 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
613 * This runs a hook to allow extensions placing their stuff after content
614 * and article metadata (e.g. categories).
615 * Note: This function has nothing to do with afterContent().
617 * This hook is placed here in order to allow using the same hook for all
618 * skins, both the SkinTemplate based ones and the older ones, which directly
619 * use this class to get their data.
621 * The output of this function gets processed in SkinTemplate::outputPage() for
622 * the SkinTemplate based skins, all other skins should directly echo it.
624 * @return String, empty by default, if not changed by any hook function.
626 protected function afterContentHook() {
629 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
630 // adding just some spaces shouldn't toggle the output
631 // of the whole <div/>, so we use trim() here
632 if ( trim( $data ) != '' ) {
633 // Doing this here instead of in the skins to
634 // ensure that the div has the same ID in all
636 $data = "<div id='mw-data-after-content'>\n" .
641 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
648 * Generate debug data HTML for displaying at the bottom of the main content
650 * @return String HTML containing debug data, if enabled (otherwise empty).
652 protected function generateDebugHTML() {
653 return MWDebug
::getHTMLDebugLog();
657 * This gets called shortly before the "</body>" tag.
659 * @return String HTML-wrapped JS code to be put before "</body>"
661 function bottomScripts() {
662 // TODO and the suckage continues. This function is really just a wrapper around
663 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
665 $bottomScriptText = $this->getOutput()->getBottomScripts();
666 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
668 return $bottomScriptText;
672 * Text with the permalink to the source page,
673 * usually shown on the footer of a printed page
675 * @return string HTML text with an URL
677 function printSource() {
678 $oldid = $this->getRevisionId();
680 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid ) ) );
682 // oldid not available for non existing pages
683 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
685 return $this->msg( 'retrievedfrom', '<a href="' . $url . '">' . $url . '</a>' )->text();
691 function getUndeleteLink() {
692 $action = $this->getRequest()->getVal( 'action', 'view' );
694 if ( $this->getUser()->isAllowed( 'deletedhistory' ) &&
695 ( $this->getTitle()->getArticleID() == 0 ||
$action == 'history' ) ) {
696 $n = $this->getTitle()->isDeleted();
699 if ( $this->getUser()->isAllowed( 'undelete' ) ) {
700 $msg = 'thisisdeleted';
702 $msg = 'viewdeleted';
705 return $this->msg( $msg )->rawParams(
707 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
708 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
719 function subPageSubtitle() {
721 $out = $this->getOutput();
724 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
728 if ( $out->isArticle() && MWNamespace
::hasSubpages( $out->getTitle()->getNamespace() ) ) {
729 $ptext = $this->getTitle()->getPrefixedText();
730 if ( preg_match( '/\//', $ptext ) ) {
731 $links = explode( '/', $ptext );
737 foreach ( $links as $link ) {
738 $growinglink .= $link;
740 $linkObj = Title
::newFromText( $growinglink );
742 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
743 $getlink = Linker
::linkKnown(
745 htmlspecialchars( $display )
751 $subpages .= $wgLang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
753 $subpages .= '< ';
756 $subpages .= $getlink;
770 * Returns true if the IP should be shown in the header
773 function showIPinHeader() {
774 global $wgShowIPinHeader;
775 return $wgShowIPinHeader && session_id() != '';
781 function getSearchLink() {
782 $searchPage = SpecialPage
::getTitleFor( 'Search' );
783 return $searchPage->getLocalURL();
789 function escapeSearchLink() {
790 return htmlspecialchars( $this->getSearchLink() );
794 * @param $type string
797 function getCopyright( $type = 'detect' ) {
798 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgContLang;
800 if ( $type == 'detect' ) {
801 if ( !$this->isRevisionCurrent() && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled() ) {
808 if ( $type == 'history' ) {
809 $msg = 'history_copyright';
814 if ( $wgRightsPage ) {
815 $title = Title
::newFromText( $wgRightsPage );
816 $link = Linker
::linkKnown( $title, $wgRightsText );
817 } elseif ( $wgRightsUrl ) {
818 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
819 } elseif ( $wgRightsText ) {
820 $link = $wgRightsText;
826 // Allow for site and per-namespace customization of copyright notice.
829 wfRunHooks( 'SkinCopyrightFooter', array( $this->getTitle(), $type, &$msg, &$link, &$forContent ) );
831 $msgObj = $this->msg( $msg )->rawParams( $link );
833 $msg = $msgObj->inContentLanguage()->text();
834 if ( $this->getLanguage()->getCode() !== $wgContLang->getCode() ) {
835 $msg = Html
::rawElement( 'span', array( 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $msg );
839 return $msgObj->text();
844 * @return null|string
846 function getCopyrightIcon() {
847 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
851 if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
852 $out = $wgCopyrightIcon;
853 } elseif ( $wgRightsIcon ) {
854 $icon = htmlspecialchars( $wgRightsIcon );
856 if ( $wgRightsUrl ) {
857 $url = htmlspecialchars( $wgRightsUrl );
858 $out .= '<a href="' . $url . '">';
861 $text = htmlspecialchars( $wgRightsText );
862 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
864 if ( $wgRightsUrl ) {
873 * Gets the powered by MediaWiki icon.
876 function getPoweredBy() {
879 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
880 $text = '<a href="//www.mediawiki.org/"><img src="' . $url . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
881 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
886 * Get the timestamp of the latest revision, formatted in user language
890 protected function lastModified() {
891 $timestamp = $this->getOutput()->getRevisionTimestamp();
893 # No cached timestamp, load it from the database
894 if ( $timestamp === null ) {
895 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
899 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
900 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
901 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text();
906 if ( wfGetLB()->getLaggedSlaveMode() ) {
907 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->text() . '</strong>';
914 * @param $align string
917 function logoText( $align = '' ) {
918 if ( $align != '' ) {
919 $a = " style='float: {$align};'";
924 $mp = $this->msg( 'mainpage' )->escaped();
925 $mptitle = Title
::newMainPage();
926 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
928 $logourl = $this->getLogo();
929 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
935 * Renders a $wgFooterIcons icon according to the method's arguments
936 * @param array $icon The icon to build the html for, see $wgFooterIcons for the format of this array
937 * @param bool|String $withImage Whether to use the icon's image or output a text-only footericon
938 * @return String HTML
940 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
941 if ( is_string( $icon ) ) {
943 } else { // Assuming array
944 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
945 unset( $icon["url"] );
946 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
947 $html = Html
::element( 'img', $icon ); // do this the lazy way, just pass icon data as an attribute array
949 $html = htmlspecialchars( $icon["alt"] );
952 $html = Html
::rawElement( 'a', array( "href" => $url ), $html );
959 * Gets the link to the wiki's main page.
962 function mainPageLink() {
963 $s = Linker
::linkKnown(
964 Title
::newMainPage(),
965 $this->msg( 'mainpage' )->escaped()
972 * Returns an HTML link for use in the footer
973 * @param string $desc i18n message key for the link text
974 * @param string $page i18n message key for the page to link to
975 * @return string HTML anchor
977 public function footerLink( $desc, $page ) {
978 // if the link description has been set to "-" in the default language,
979 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
980 // then it is disabled, for all languages.
983 // Otherwise, we display the link for the user, described in their
984 // language (which may or may not be the same as the default language),
985 // but we make the link target be the one site-wide page.
986 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
988 return Linker
::linkKnown(
990 $this->msg( $desc )->escaped()
996 * Gets the link to the wiki's privacy policy page.
997 * @return String HTML
999 function privacyLink() {
1000 return $this->footerLink( 'privacy', 'privacypage' );
1004 * Gets the link to the wiki's about page.
1005 * @return String HTML
1007 function aboutLink() {
1008 return $this->footerLink( 'aboutsite', 'aboutpage' );
1012 * Gets the link to the wiki's general disclaimers page.
1013 * @return String HTML
1015 function disclaimerLink() {
1016 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1020 * Return URL options for the 'edit page' link.
1021 * This may include an 'oldid' specifier, if the current page view is such.
1026 function editUrlOptions() {
1027 $options = array( 'action' => 'edit' );
1029 if ( !$this->isRevisionCurrent() ) {
1030 $options['oldid'] = intval( $this->getRevisionId() );
1037 * @param $id User|int
1040 function showEmailUser( $id ) {
1041 if ( $id instanceof User
) {
1044 $targetUser = User
::newFromId( $id );
1046 return $this->getUser()->canSendEmail() && # the sending user must have a confirmed email address
1047 $targetUser->canReceiveEmail(); # the target user must have a confirmed email address and allow emails from users
1051 * Return a fully resolved style path url to images or styles stored in the common folder.
1052 * This method returns a url resolved using the configured skin style path
1053 * and includes the style version inside of the url.
1054 * @param string $name The name or path of a skin resource file
1055 * @return String The fully resolved style path url including styleversion
1057 function getCommonStylePath( $name ) {
1058 global $wgStylePath, $wgStyleVersion;
1059 return "$wgStylePath/common/$name?$wgStyleVersion";
1063 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1064 * This method returns a url resolved using the configured skin style path
1065 * and includes the style version inside of the url.
1066 * @param string $name The name or path of a skin resource file
1067 * @return String The fully resolved style path url including styleversion
1069 function getSkinStylePath( $name ) {
1070 global $wgStylePath, $wgStyleVersion;
1071 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1074 /* these are used extensively in SkinTemplate, but also some other places */
1077 * @param $urlaction string
1080 static function makeMainPageUrl( $urlaction = '' ) {
1081 $title = Title
::newMainPage();
1082 self
::checkTitle( $title, '' );
1084 return $title->getLocalURL( $urlaction );
1088 * Make a URL for a Special Page using the given query and protocol.
1090 * If $proto is set to null, make a local URL. Otherwise, make a full
1091 * URL with the protocol specified.
1093 * @param string $name Name of the Special page
1094 * @param string $urlaction Query to append
1095 * @param $proto Protocol to use or null for a local URL
1098 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1099 $title = SpecialPage
::getSafeTitleFor( $name );
1100 if ( is_null( $proto ) ) {
1101 return $title->getLocalURL( $urlaction );
1103 return $title->getFullURL( $urlaction, false, $proto );
1108 * @param $name string
1109 * @param $subpage string
1110 * @param $urlaction string
1113 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1114 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1115 return $title->getLocalURL( $urlaction );
1119 * @param $name string
1120 * @param $urlaction string
1123 static function makeI18nUrl( $name, $urlaction = '' ) {
1124 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1125 self
::checkTitle( $title, $name );
1126 return $title->getLocalURL( $urlaction );
1130 * @param $name string
1131 * @param $urlaction string
1134 static function makeUrl( $name, $urlaction = '' ) {
1135 $title = Title
::newFromText( $name );
1136 self
::checkTitle( $title, $name );
1138 return $title->getLocalURL( $urlaction );
1142 * If url string starts with http, consider as external URL, else
1144 * @param $name String
1145 * @return String URL
1147 static function makeInternalOrExternalUrl( $name ) {
1148 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1151 return self
::makeUrl( $name );
1156 * this can be passed the NS number as defined in Language.php
1158 * @param $urlaction string
1159 * @param $namespace int
1162 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1163 $title = Title
::makeTitleSafe( $namespace, $name );
1164 self
::checkTitle( $title, $name );
1166 return $title->getLocalURL( $urlaction );
1170 * these return an array with the 'href' and boolean 'exists'
1172 * @param $urlaction string
1175 static function makeUrlDetails( $name, $urlaction = '' ) {
1176 $title = Title
::newFromText( $name );
1177 self
::checkTitle( $title, $name );
1180 'href' => $title->getLocalURL( $urlaction ),
1181 'exists' => $title->getArticleID() != 0,
1186 * Make URL details where the article exists (or at least it's convenient to think so)
1187 * @param string $name Article name
1188 * @param $urlaction String
1191 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1192 $title = Title
::newFromText( $name );
1193 self
::checkTitle( $title, $name );
1196 'href' => $title->getLocalURL( $urlaction ),
1202 * make sure we have some title to operate on
1204 * @param $title Title
1205 * @param $name string
1207 static function checkTitle( &$title, $name ) {
1208 if ( !is_object( $title ) ) {
1209 $title = Title
::newFromText( $name );
1210 if ( !is_object( $title ) ) {
1211 $title = Title
::newFromText( '--error: link target missing--' );
1217 * Build an array that represents the sidebar(s), the navigation bar among them.
1219 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1221 * The format of the returned array is array( heading => content, ... ), where:
1222 * - heading is the heading of a navigation portlet. It is either:
1223 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1224 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1225 * - plain text, which should be HTML-escaped by the skin
1226 * - content is the contents of the portlet. It is either:
1227 * - HTML text (<ul><li>...</li>...</ul>)
1228 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1229 * - (for a magic string as a key, any value)
1231 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1232 * and can technically insert anything in here; skin creators are expected to handle
1233 * values described above.
1237 function buildSidebar() {
1238 global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1239 wfProfileIn( __METHOD__
);
1241 $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() );
1243 if ( $wgEnableSidebarCache ) {
1244 $cachedsidebar = $wgMemc->get( $key );
1245 if ( $cachedsidebar ) {
1246 wfProfileOut( __METHOD__
);
1247 return $cachedsidebar;
1252 $this->addToSidebar( $bar, 'sidebar' );
1254 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1255 if ( $wgEnableSidebarCache ) {
1256 $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1259 wfProfileOut( __METHOD__
);
1264 * Add content from a sidebar system message
1265 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1267 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1270 * @param $message String
1272 function addToSidebar( &$bar, $message ) {
1273 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1277 * Add content from plain text
1280 * @param $text string
1283 function addToSidebarPlain( &$bar, $text ) {
1284 $lines = explode( "\n", $text );
1288 foreach ( $lines as $line ) {
1289 if ( strpos( $line, '*' ) !== 0 ) {
1292 $line = rtrim( $line, "\r" ); // for Windows compat
1294 if ( strpos( $line, '**' ) !== 0 ) {
1295 $heading = trim( $line, '* ' );
1296 if ( !array_key_exists( $heading, $bar ) ) {
1297 $bar[$heading] = array();
1300 $line = trim( $line, '* ' );
1302 if ( strpos( $line, '|' ) !== false ) { // sanity check
1303 $line = MessageCache
::singleton()->transform( $line, false, null, $this->getTitle() );
1304 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1305 if ( count( $line ) !== 2 ) {
1306 // Second sanity check, could be hit by people doing
1307 // funky stuff with parserfuncs... (bug 33321)
1311 $extraAttribs = array();
1313 $msgLink = $this->msg( $line[0] )->inContentLanguage();
1314 if ( $msgLink->exists() ) {
1315 $link = $msgLink->text();
1316 if ( $link == '-' ) {
1322 $msgText = $this->msg( $line[1] );
1323 if ( $msgText->exists() ) {
1324 $text = $msgText->text();
1329 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1332 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1333 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1334 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1335 $extraAttribs['rel'] = 'nofollow';
1338 global $wgExternalLinkTarget;
1339 if ( $wgExternalLinkTarget ) {
1340 $extraAttribs['target'] = $wgExternalLinkTarget;
1343 $title = Title
::newFromText( $link );
1346 $title = $title->fixSpecialName();
1347 $href = $title->getLinkURL();
1349 $href = 'INVALID-TITLE';
1353 $bar[$heading][] = array_merge( array(
1356 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1369 * This function previously controlled whether the 'mediawiki.legacy.wikiprintable' module
1370 * should be loaded by OutputPage. That module no longer exists and the return value of this
1371 * method is ignored.
1373 * If your skin doesn't provide its own print styles, the 'mediawiki.legacy.commonPrint' module
1374 * can be used instead (SkinTemplate-based skins do it automatically).
1376 * @deprecated since 1.22
1379 public function commonPrintStylesheet() {
1380 wfDeprecated( __METHOD__
, '1.22' );
1385 * Gets new talk page messages for the current user and returns an
1386 * appropriate alert message (or an empty string if there are no messages)
1389 function getNewtalks() {
1391 $newMessagesAlert = '';
1392 $user = $this->getUser();
1393 $newtalks = $user->getNewMessageLinks();
1394 $out = $this->getOutput();
1396 // Allow extensions to disable or modify the new messages alert
1397 if ( !wfRunHooks( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) {
1400 if ( $newMessagesAlert ) {
1401 return $newMessagesAlert;
1404 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1405 $uTalkTitle = $user->getTalkPage();
1406 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1408 if ( $lastSeenRev !== null ) {
1409 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1410 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1411 if ( $latestRev !== null ) {
1412 // Singular if only 1 unseen revision, plural if several unseen revisions.
1413 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1414 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1415 $lastSeenRev, $latestRev, 10, 'include_new' );
1418 // Singular if no revision -> diff link will show latest change only in any case
1421 $plural = $plural ?
999 : 1;
1422 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1423 // the number of revisions or authors is not necessarily the same as the number of
1425 $newMessagesLink = Linker
::linkKnown(
1427 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1429 array( 'redirect' => 'no' )
1432 $newMessagesDiffLink = Linker
::linkKnown(
1434 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1436 $lastSeenRev !== null
1437 ?
array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' )
1438 : array( 'diff' => 'cur' )
1441 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1442 $newMessagesAlert = $this->msg(
1443 'youhavenewmessagesfromusers',
1445 $newMessagesDiffLink
1446 )->numParams( $nofAuthors, $plural );
1448 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1449 $newMessagesAlert = $this->msg(
1450 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1452 $newMessagesDiffLink
1453 )->numParams( $plural );
1455 $newMessagesAlert = $newMessagesAlert->text();
1456 # Disable Squid cache
1457 $out->setSquidMaxage( 0 );
1458 } elseif ( count( $newtalks ) ) {
1459 $sep = $this->msg( 'newtalkseparator' )->escaped();
1462 foreach ( $newtalks as $newtalk ) {
1463 $msgs[] = Xml
::element(
1465 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1468 $parts = implode( $sep, $msgs );
1469 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1470 $out->setSquidMaxage( 0 );
1473 return $newMessagesAlert;
1477 * Get a cached notice
1479 * @param string $name message name, or 'default' for $wgSiteNotice
1480 * @return String: HTML fragment
1482 private function getCachedNotice( $name ) {
1483 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1485 wfProfileIn( __METHOD__
);
1489 if ( $name === 'default' ) {
1491 global $wgSiteNotice;
1492 $notice = $wgSiteNotice;
1493 if ( empty( $notice ) ) {
1494 wfProfileOut( __METHOD__
);
1498 $msg = $this->msg( $name )->inContentLanguage();
1499 if ( $msg->isDisabled() ) {
1500 wfProfileOut( __METHOD__
);
1503 $notice = $msg->plain();
1506 // Use the extra hash appender to let eg SSL variants separately cache.
1507 $key = wfMemcKey( $name . $wgRenderHashAppend );
1508 $cachedNotice = $parserMemc->get( $key );
1509 if ( is_array( $cachedNotice ) ) {
1510 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1511 $notice = $cachedNotice['html'];
1520 $parsed = $this->getOutput()->parse( $notice );
1521 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1525 $notice = Html
::rawElement( 'div', array( 'id' => 'localNotice',
1526 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice );
1527 wfProfileOut( __METHOD__
);
1532 * Get a notice based on page's namespace
1534 * @return String: HTML fragment
1536 function getNamespaceNotice() {
1537 wfProfileIn( __METHOD__
);
1539 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1540 $namespaceNotice = $this->getCachedNotice( $key );
1541 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
1542 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1544 $namespaceNotice = '';
1547 wfProfileOut( __METHOD__
);
1548 return $namespaceNotice;
1552 * Get the site notice
1554 * @return String: HTML fragment
1556 function getSiteNotice() {
1557 wfProfileIn( __METHOD__
);
1560 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1561 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1562 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1564 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1565 if ( !$anonNotice ) {
1566 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1568 $siteNotice = $anonNotice;
1571 if ( !$siteNotice ) {
1572 $siteNotice = $this->getCachedNotice( 'default' );
1576 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1577 wfProfileOut( __METHOD__
);
1582 * Create a section edit link. This supersedes editSectionLink() and
1583 * editSectionLinkForOther().
1585 * @param $nt Title The title being linked to (may not be the same as
1586 * the current page, if the section is included from a template)
1587 * @param string $section The designation of the section being pointed to,
1588 * to be included in the link, like "§ion=$section"
1589 * @param string $tooltip The tooltip to use for the link: will be escaped
1590 * and wrapped in the 'editsectionhint' message
1591 * @param $lang string Language code
1592 * @return string HTML to use for edit link
1594 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1595 // HTML generated here should probably have userlangattributes
1596 // added to it for LTR text on RTL pages
1598 $lang = wfGetLangObj( $lang );
1601 if ( !is_null( $tooltip ) ) {
1602 # Bug 25462: undo double-escaping.
1603 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1604 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1605 ->inLanguage( $lang )->text();
1607 $link = Linker
::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(),
1609 array( 'action' => 'edit', 'section' => $section ),
1610 array( 'noclasses', 'known' )
1613 # Add the brackets and the span and run the hook.
1614 $result = '<span class="mw-editsection">'
1615 . '<span class="mw-editsection-bracket">[</span>'
1617 . '<span class="mw-editsection-bracket">]</span>'
1620 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1625 * Use PHP's magic __call handler to intercept legacy calls to the linker
1626 * for backwards compatibility.
1628 * @param string $fname Name of called method
1629 * @param array $args Arguments to the method
1630 * @throws MWException
1633 function __call( $fname, $args ) {
1634 $realFunction = array( 'Linker', $fname );
1635 if ( is_callable( $realFunction ) ) {
1636 wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' );
1637 return call_user_func_array( $realFunction, $args );
1639 $className = get_class( $this );
1640 throw new MWException( "Call to undefined method $className::$fname" );