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.
30 * See docs/skin.txt for more information.
34 abstract class Skin
extends ContextSource
{
35 protected $skinname = null;
36 protected $mRelevantTitle = null;
37 protected $mRelevantUser = null;
40 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
41 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
43 public $stylename = null;
46 * Fetch the set of available skins.
47 * @return array Associative array of strings
49 static function getSkinNames() {
50 global $wgValidSkinNames;
51 static $skinsInitialised = false;
53 if ( !$skinsInitialised ||
!count( $wgValidSkinNames ) ) {
54 # Get a list of available skins
55 # Build using the regular expression '^(.*).php$'
56 # Array keys are all lower case, array value keep the case used by filename
58 wfProfileIn( __METHOD__
. '-init' );
60 global $wgStyleDirectory;
62 $skinDir = dir( $wgStyleDirectory );
64 if ( $skinDir !== false && $skinDir !== null ) {
65 # while code from www.php.net
66 while ( false !== ( $file = $skinDir->read() ) ) {
67 // Skip non-PHP files, hidden files, and '.dep' includes
70 if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
73 // Explicitly disallow loading core skins via the autodiscovery mechanism.
75 // They should be loaded already (in a non-autodicovery way), but old files might still
76 // exist on the server because our MW version upgrade process is widely documented as
77 // requiring just copying over all files, without removing old ones.
79 // This is one of the reasons we should have never used autodiscovery in the first
80 // place. This hack can be safely removed when autodiscovery is gone.
81 if ( in_array( $aSkin, array( 'CologneBlue', 'Modern', 'MonoBook', 'Vector' ) ) ) {
83 "An old copy of the $aSkin skin was found in your skins/ directory. " .
84 "You should remove it to avoid problems in the future." .
85 "See https://www.mediawiki.org/wiki/Manual:Skin_autodiscovery for details."
91 "A skin using autodiscovery mechanism, $aSkin, was found in your skins/ directory. " .
92 "The mechanism will be removed in MediaWiki 1.25 and the skin will no longer be recognized. " .
93 "See https://www.mediawiki.org/wiki/Manual:Skin_autodiscovery for information how to fix this."
95 $wgValidSkinNames[strtolower( $aSkin )] = $aSkin;
100 $skinsInitialised = true;
101 wfProfileOut( __METHOD__
. '-init' );
103 return $wgValidSkinNames;
107 * Fetch the skinname messages for available skins.
110 static function getSkinNameMessages() {
112 foreach ( self
::getSkinNames() as $skinKey => $skinName ) {
113 $messages[] = "skinname-$skinKey";
119 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
120 * Useful for Special:Preferences and other places where you
121 * only want to show skins users _can_ use.
125 public static function getAllowedSkins() {
128 $allowedSkins = self
::getSkinNames();
130 foreach ( $wgSkipSkins as $skip ) {
131 unset( $allowedSkins[$skip] );
134 return $allowedSkins;
138 * @deprecated since 1.23, use getAllowedSkins
141 public static function getUsableSkins() {
142 wfDeprecated( __METHOD__
, '1.23' );
143 return self
::getAllowedSkins();
147 * Normalize a skin preference value to a form that can be loaded.
148 * If a skin can't be found, it will fall back to the configured
149 * default, or the hardcoded default if that's broken.
150 * @param string $key 'monobook', 'vector', etc.
153 static function normalizeKey( $key ) {
154 global $wgDefaultSkin;
156 $skinNames = Skin
::getSkinNames();
158 if ( $key == '' ||
$key == 'default' ) {
159 // Don't return the default immediately;
160 // in a misconfiguration we need to fall back.
161 $key = $wgDefaultSkin;
164 if ( isset( $skinNames[$key] ) ) {
168 // Older versions of the software used a numeric setting
169 // in the user preferences.
175 if ( isset( $fallback[$key] ) ) {
176 $key = $fallback[$key];
179 if ( isset( $skinNames[$key] ) ) {
181 } elseif ( isset( $skinNames[$wgDefaultSkin] ) ) {
182 return $wgDefaultSkin;
189 * Factory method for loading a skin of a given type
190 * @param string $key 'monobook', 'vector', etc.
193 static function &newFromKey( $key ) {
194 global $wgStyleDirectory;
196 $key = Skin
::normalizeKey( $key );
198 $skinNames = Skin
::getSkinNames();
199 $skinName = $skinNames[$key];
200 $className = "Skin{$skinName}";
202 # Grab the skin class and initialise it.
203 if ( !class_exists( $className ) ) {
205 require_once "{$wgStyleDirectory}/{$skinName}.php";
207 # Check if we got if not fallback to default skin
208 if ( !class_exists( $className ) ) {
209 # DO NOT die if the class isn't found. This breaks maintenance
210 # scripts and can cause a user account to be unrecoverable
211 # except by SQL manipulation if a previously valid skin name
212 # is no longer valid.
213 wfDebug( "Skin class does not exist: $className\n" );
214 $className = 'SkinVector';
217 $skin = new $className( $key );
222 * @return string Skin name
224 public function getSkinName() {
225 return $this->skinname
;
229 * @param OutputPage $out
231 function initPage( OutputPage
$out ) {
232 wfProfileIn( __METHOD__
);
234 $this->preloadExistence();
236 wfProfileOut( __METHOD__
);
240 * Defines the ResourceLoader modules that should be added to the skin
241 * It is recommended that skins wishing to override call parent::getDefaultModules()
242 * and substitute out any modules they wish to change by using a key to look them up
243 * @return array Array of modules with helper keys for easy overriding
245 public function getDefaultModules() {
246 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
247 $wgAjaxWatch, $wgEnableAPI, $wgEnableWriteAPI;
249 $out = $this->getOutput();
250 $user = $out->getUser();
252 // modules that enhance the page content in some way
254 'mediawiki.page.ready',
256 // modules that exist for legacy reasons
258 // modules relating to search functionality
260 // modules relating to functionality relating to watching an article
262 // modules which relate to the current users preferences
265 if ( $wgIncludeLegacyJavaScript ) {
266 $modules['legacy'][] = 'mediawiki.legacy.wikibits';
269 if ( $wgPreloadJavaScriptMwUtil ) {
270 $modules['legacy'][] = 'mediawiki.util';
273 // Add various resources if required
275 $modules['legacy'][] = 'mediawiki.legacy.ajax';
277 if ( $wgEnableAPI ) {
278 if ( $wgEnableWriteAPI && $wgAjaxWatch && $user->isLoggedIn()
279 && $user->isAllowed( 'writeapi' )
281 $modules['watch'][] = 'mediawiki.page.watch.ajax';
284 $modules['search'][] = 'mediawiki.searchSuggest';
288 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
289 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
292 // Crazy edit-on-double-click stuff
293 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
294 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
300 * Preload the existence of three commonly-requested pages in a single query
302 function preloadExistence() {
303 $user = $this->getUser();
306 $titles = array( $user->getUserPage(), $user->getTalkPage() );
309 if ( $this->getTitle()->isSpecialPage() ) {
311 } elseif ( $this->getTitle()->isTalkPage() ) {
312 $titles[] = $this->getTitle()->getSubjectPage();
314 $titles[] = $this->getTitle()->getTalkPage();
317 $lb = new LinkBatch( $titles );
318 $lb->setCaller( __METHOD__
);
323 * Get the current revision ID
327 public function getRevisionId() {
328 return $this->getOutput()->getRevisionId();
332 * Whether the revision displayed is the latest revision of the page
336 public function isRevisionCurrent() {
337 $revID = $this->getRevisionId();
338 return $revID == 0 ||
$revID == $this->getTitle()->getLatestRevID();
342 * Set the "relevant" title
343 * @see self::getRelevantTitle()
346 public function setRelevantTitle( $t ) {
347 $this->mRelevantTitle
= $t;
351 * Return the "relevant" title.
352 * A "relevant" title is not necessarily the actual title of the page.
353 * Special pages like Special:MovePage use set the page they are acting on
354 * as their "relevant" title, this allows the skin system to display things
355 * such as content tabs which belong to to that page instead of displaying
356 * a basic special page tab which has almost no meaning.
360 public function getRelevantTitle() {
361 if ( isset( $this->mRelevantTitle
) ) {
362 return $this->mRelevantTitle
;
364 return $this->getTitle();
368 * Set the "relevant" user
369 * @see self::getRelevantUser()
372 public function setRelevantUser( $u ) {
373 $this->mRelevantUser
= $u;
377 * Return the "relevant" user.
378 * A "relevant" user is similar to a relevant title. Special pages like
379 * Special:Contributions mark the user which they are relevant to so that
380 * things like the toolbox can display the information they usually are only
381 * able to display on a user's userpage and talkpage.
384 public function getRelevantUser() {
385 if ( isset( $this->mRelevantUser
) ) {
386 return $this->mRelevantUser
;
388 $title = $this->getRelevantTitle();
389 if ( $title->hasSubjectNamespace( NS_USER
) ) {
390 $rootUser = $title->getRootText();
391 if ( User
::isIP( $rootUser ) ) {
392 $this->mRelevantUser
= User
::newFromName( $rootUser, false );
394 $user = User
::newFromName( $rootUser, false );
395 if ( $user && $user->isLoggedIn() ) {
396 $this->mRelevantUser
= $user;
399 return $this->mRelevantUser
;
405 * Outputs the HTML generated by other functions.
406 * @param OutputPage $out
408 abstract function outputPage( OutputPage
$out = null );
414 static function makeVariablesScript( $data ) {
416 return Html
::inlineScript(
417 ResourceLoader
::makeLoaderConditionalScript( ResourceLoader
::makeConfigSetScript( $data ) )
425 * Get the query to generate a dynamic stylesheet
429 public static function getDynamicStylesheetQuery() {
430 global $wgSquidMaxage;
434 'maxage' => $wgSquidMaxage,
435 'usemsgcache' => 'yes',
436 'ctype' => 'text/css',
437 'smaxage' => $wgSquidMaxage,
442 * Add skin specific stylesheets
443 * Calling this method with an $out of anything but the same OutputPage
444 * inside ->getOutput() is deprecated. The $out arg is kept
445 * for compatibility purposes with skins.
446 * @param OutputPage $out
449 abstract function setupSkinUserCss( OutputPage
$out );
453 * @param Title $title
456 function getPageClasses( $title ) {
457 $numeric = 'ns-' . $title->getNamespace();
459 if ( $title->isSpecialPage() ) {
460 $type = 'ns-special';
461 // bug 23315: provide a class based on the canonical special page name without subpages
462 list( $canonicalName ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
463 if ( $canonicalName ) {
464 $type .= ' ' . Sanitizer
::escapeClass( "mw-special-$canonicalName" );
466 $type .= ' mw-invalidspecialpage';
468 } elseif ( $title->isTalkPage() ) {
471 $type = 'ns-subject';
474 $name = Sanitizer
::escapeClass( 'page-' . $title->getPrefixedText() );
476 return "$numeric $type $name";
480 * Return values for <html> element
481 * @return array of associative name-to-value elements for <html> element
483 public function getHtmlElementAttributes() {
484 $lang = $this->getLanguage();
486 'lang' => $lang->getHtmlCode(),
487 'dir' => $lang->getDir(),
488 'class' => 'client-nojs',
493 * This will be called by OutputPage::headElement when it is creating the
494 * "<body>" tag, skins can override it if they have a need to add in any
495 * body attributes or classes of their own.
496 * @param OutputPage $out
497 * @param array $bodyAttrs
499 function addToBodyAttributes( $out, &$bodyAttrs ) {
500 // does nothing by default
515 function getCategoryLinks() {
516 global $wgUseCategoryBrowser;
518 $out = $this->getOutput();
519 $allCats = $out->getCategoryLinks();
521 if ( !count( $allCats ) ) {
529 $colon = $this->msg( 'colon-separator' )->escaped();
531 if ( !empty( $allCats['normal'] ) ) {
532 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
534 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
535 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
536 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
537 Linker
::link( Title
::newFromText( $linkPage ), $msg )
538 . $colon . '<ul>' . $t . '</ul>' . '</div>';
542 if ( isset( $allCats['hidden'] ) ) {
543 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
544 $class = ' mw-hidden-cats-user-shown';
545 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY
) {
546 $class = ' mw-hidden-cats-ns-shown';
548 $class = ' mw-hidden-cats-hidden';
551 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
552 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
553 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
557 # optional 'dmoz-like' category browser. Will be shown under the list
558 # of categories an article belong to
559 if ( $wgUseCategoryBrowser ) {
560 $s .= '<br /><hr />';
562 # get a big array of the parents tree
563 $parenttree = $this->getTitle()->getParentCategoryTree();
564 # Skin object passed by reference cause it can not be
565 # accessed under the method subfunction drawCategoryBrowser
566 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
567 # Clean out bogus first entry and sort them
568 unset( $tempout[0] );
570 # Output one per line
571 $s .= implode( "<br />\n", $tempout );
578 * Render the array as a series of links.
579 * @param array $tree Categories tree returned by Title::getParentCategoryTree
580 * @return string Separated by >, terminate with "\n"
582 function drawCategoryBrowser( $tree ) {
585 foreach ( $tree as $element => $parent ) {
586 if ( empty( $parent ) ) {
587 # element start a new list
590 # grab the others elements
591 $return .= $this->drawCategoryBrowser( $parent ) . ' > ';
594 # add our current element to the list
595 $eltitle = Title
::newFromText( $element );
596 $return .= Linker
::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
605 function getCategories() {
606 $out = $this->getOutput();
608 $catlinks = $this->getCategoryLinks();
610 $classes = 'catlinks';
612 // Check what we're showing
613 $allCats = $out->getCategoryLinks();
614 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
615 $this->getTitle()->getNamespace() == NS_CATEGORY
;
617 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
618 $classes .= ' catlinks-allhidden';
621 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
625 * This runs a hook to allow extensions placing their stuff after content
626 * and article metadata (e.g. categories).
627 * Note: This function has nothing to do with afterContent().
629 * This hook is placed here in order to allow using the same hook for all
630 * skins, both the SkinTemplate based ones and the older ones, which directly
631 * use this class to get their data.
633 * The output of this function gets processed in SkinTemplate::outputPage() for
634 * the SkinTemplate based skins, all other skins should directly echo it.
636 * @return string Empty by default, if not changed by any hook function.
638 protected function afterContentHook() {
641 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
642 // adding just some spaces shouldn't toggle the output
643 // of the whole <div/>, so we use trim() here
644 if ( trim( $data ) != '' ) {
645 // Doing this here instead of in the skins to
646 // ensure that the div has the same ID in all
648 $data = "<div id='mw-data-after-content'>\n" .
653 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
660 * Generate debug data HTML for displaying at the bottom of the main content
662 * @return string HTML containing debug data, if enabled (otherwise empty).
664 protected function generateDebugHTML() {
665 return MWDebug
::getHTMLDebugLog();
669 * This gets called shortly before the "</body>" tag.
671 * @return string HTML-wrapped JS code to be put before "</body>"
673 function bottomScripts() {
674 // TODO and the suckage continues. This function is really just a wrapper around
675 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
677 $bottomScriptText = $this->getOutput()->getBottomScripts();
678 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
680 return $bottomScriptText;
684 * Text with the permalink to the source page,
685 * usually shown on the footer of a printed page
687 * @return string HTML text with an URL
689 function printSource() {
690 $oldid = $this->getRevisionId();
692 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
693 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
695 // oldid not available for non existing pages
696 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
699 return $this->msg( 'retrievedfrom', '<a dir="ltr" href="' . $url
700 . '">' . $url . '</a>' )->text();
706 function getUndeleteLink() {
707 $action = $this->getRequest()->getVal( 'action', 'view' );
709 if ( $this->getUser()->isAllowed( 'deletedhistory' ) &&
710 ( $this->getTitle()->getArticleID() == 0 ||
$action == 'history' ) ) {
711 $n = $this->getTitle()->isDeleted();
714 if ( $this->getUser()->isAllowed( 'undelete' ) ) {
715 $msg = 'thisisdeleted';
717 $msg = 'viewdeleted';
720 return $this->msg( $msg )->rawParams(
722 SpecialPage
::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
723 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
734 function subPageSubtitle() {
735 $out = $this->getOutput();
738 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
742 if ( $out->isArticle() && MWNamespace
::hasSubpages( $out->getTitle()->getNamespace() ) ) {
743 $ptext = $this->getTitle()->getPrefixedText();
744 if ( preg_match( '/\//', $ptext ) ) {
745 $links = explode( '/', $ptext );
750 $lang = $this->getLanguage();
752 foreach ( $links as $link ) {
753 $growinglink .= $link;
755 $linkObj = Title
::newFromText( $growinglink );
757 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
758 $getlink = Linker
::linkKnown(
760 htmlspecialchars( $display )
766 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
768 $subpages .= '< ';
771 $subpages .= $getlink;
785 * Returns true if the IP should be shown in the header
788 function showIPinHeader() {
789 global $wgShowIPinHeader;
790 return $wgShowIPinHeader && session_id() != '';
796 function getSearchLink() {
797 $searchPage = SpecialPage
::getTitleFor( 'Search' );
798 return $searchPage->getLocalURL();
804 function escapeSearchLink() {
805 return htmlspecialchars( $this->getSearchLink() );
809 * @param string $type
812 function getCopyright( $type = 'detect' ) {
813 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgContLang;
815 if ( $type == 'detect' ) {
816 if ( !$this->isRevisionCurrent()
817 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
825 if ( $type == 'history' ) {
826 $msg = 'history_copyright';
831 if ( $wgRightsPage ) {
832 $title = Title
::newFromText( $wgRightsPage );
833 $link = Linker
::linkKnown( $title, $wgRightsText );
834 } elseif ( $wgRightsUrl ) {
835 $link = Linker
::makeExternalLink( $wgRightsUrl, $wgRightsText );
836 } elseif ( $wgRightsText ) {
837 $link = $wgRightsText;
843 // Allow for site and per-namespace customization of copyright notice.
844 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
848 'SkinCopyrightFooter',
849 array( $this->getTitle(), $type, &$msg, &$link, &$forContent )
852 return $this->msg( $msg )->rawParams( $link )->text();
856 * @return null|string
858 function getCopyrightIcon() {
859 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
863 if ( $wgCopyrightIcon ) {
864 $out = $wgCopyrightIcon;
865 } elseif ( $wgRightsIcon ) {
866 $icon = htmlspecialchars( $wgRightsIcon );
868 if ( $wgRightsUrl ) {
869 $url = htmlspecialchars( $wgRightsUrl );
870 $out .= '<a href="' . $url . '">';
873 $text = htmlspecialchars( $wgRightsText );
874 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
876 if ( $wgRightsUrl ) {
885 * Gets the powered by MediaWiki icon.
888 function getPoweredBy() {
891 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
892 $text = '<a href="//www.mediawiki.org/"><img src="' . $url
893 . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
894 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
899 * Get the timestamp of the latest revision, formatted in user language
903 protected function lastModified() {
904 $timestamp = $this->getOutput()->getRevisionTimestamp();
906 # No cached timestamp, load it from the database
907 if ( $timestamp === null ) {
908 $timestamp = Revision
::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
912 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
913 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
914 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text();
919 if ( wfGetLB()->getLaggedSlaveMode() ) {
920 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->text() . '</strong>';
927 * @param string $align
930 function logoText( $align = '' ) {
931 if ( $align != '' ) {
932 $a = " style='float: {$align};'";
937 $mp = $this->msg( 'mainpage' )->escaped();
938 $mptitle = Title
::newMainPage();
939 $url = ( is_object( $mptitle ) ?
htmlspecialchars( $mptitle->getLocalURL() ) : '' );
941 $logourl = $this->getLogo();
942 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
948 * Renders a $wgFooterIcons icon according to the method's arguments
949 * @param array $icon The icon to build the html for, see $wgFooterIcons
950 * for the format of this array.
951 * @param bool|string $withImage Whether to use the icon's image or output
952 * a text-only footericon.
953 * @return string HTML
955 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
956 if ( is_string( $icon ) ) {
958 } else { // Assuming array
959 $url = isset( $icon["url"] ) ?
$icon["url"] : null;
960 unset( $icon["url"] );
961 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
962 // do this the lazy way, just pass icon data as an attribute array
963 $html = Html
::element( 'img', $icon );
965 $html = htmlspecialchars( $icon["alt"] );
968 $html = Html
::rawElement( 'a', array( "href" => $url ), $html );
975 * Gets the link to the wiki's main page.
978 function mainPageLink() {
979 $s = Linker
::linkKnown(
980 Title
::newMainPage(),
981 $this->msg( 'mainpage' )->escaped()
988 * Returns an HTML link for use in the footer
989 * @param string $desc i18n message key for the link text
990 * @param string $page i18n message key for the page to link to
991 * @return string HTML anchor
993 public function footerLink( $desc, $page ) {
994 // if the link description has been set to "-" in the default language,
995 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
996 // then it is disabled, for all languages.
999 // Otherwise, we display the link for the user, described in their
1000 // language (which may or may not be the same as the default language),
1001 // but we make the link target be the one site-wide page.
1002 $title = Title
::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1004 return Linker
::linkKnown(
1006 $this->msg( $desc )->escaped()
1012 * Gets the link to the wiki's privacy policy page.
1013 * @return string HTML
1015 function privacyLink() {
1016 return $this->footerLink( 'privacy', 'privacypage' );
1020 * Gets the link to the wiki's about page.
1021 * @return string HTML
1023 function aboutLink() {
1024 return $this->footerLink( 'aboutsite', 'aboutpage' );
1028 * Gets the link to the wiki's general disclaimers page.
1029 * @return string HTML
1031 function disclaimerLink() {
1032 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1036 * Return URL options for the 'edit page' link.
1037 * This may include an 'oldid' specifier, if the current page view is such.
1042 function editUrlOptions() {
1043 $options = array( 'action' => 'edit' );
1045 if ( !$this->isRevisionCurrent() ) {
1046 $options['oldid'] = intval( $this->getRevisionId() );
1053 * @param User|int $id
1056 function showEmailUser( $id ) {
1057 if ( $id instanceof User
) {
1060 $targetUser = User
::newFromId( $id );
1063 # The sending user must have a confirmed email address and the target
1064 # user must have a confirmed email address and allow emails from users.
1065 return $this->getUser()->canSendEmail() &&
1066 $targetUser->canReceiveEmail();
1070 * Return a fully resolved style path url to images or styles stored in the common folder.
1071 * This method returns a url resolved using the configured skin style path
1072 * and includes the style version inside of the url.
1073 * @param string $name The name or path of a skin resource file
1074 * @return string The fully resolved style path url including styleversion
1076 function getCommonStylePath( $name ) {
1077 global $wgStylePath, $wgStyleVersion;
1078 return "$wgStylePath/common/$name?$wgStyleVersion";
1082 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1083 * This method returns a url resolved using the configured skin style path
1084 * and includes the style version inside of the url.
1086 * Requires $stylename to be set, otherwise throws MWException.
1088 * @param string $name The name or path of a skin resource file
1089 * @return string The fully resolved style path url including styleversion
1091 function getSkinStylePath( $name ) {
1092 global $wgStylePath, $wgStyleVersion;
1094 if ( $this->stylename
=== null ) {
1095 $class = get_class( $this );
1096 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1099 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1102 /* these are used extensively in SkinTemplate, but also some other places */
1105 * @param string $urlaction
1108 static function makeMainPageUrl( $urlaction = '' ) {
1109 $title = Title
::newMainPage();
1110 self
::checkTitle( $title, '' );
1112 return $title->getLocalURL( $urlaction );
1116 * Make a URL for a Special Page using the given query and protocol.
1118 * If $proto is set to null, make a local URL. Otherwise, make a full
1119 * URL with the protocol specified.
1121 * @param string $name Name of the Special page
1122 * @param string $urlaction Query to append
1123 * @param string|null $proto Protocol to use or null for a local URL
1126 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1127 $title = SpecialPage
::getSafeTitleFor( $name );
1128 if ( is_null( $proto ) ) {
1129 return $title->getLocalURL( $urlaction );
1131 return $title->getFullURL( $urlaction, false, $proto );
1136 * @param string $name
1137 * @param string $subpage
1138 * @param string $urlaction
1141 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1142 $title = SpecialPage
::getSafeTitleFor( $name, $subpage );
1143 return $title->getLocalURL( $urlaction );
1147 * @param string $name
1148 * @param string $urlaction
1151 static function makeI18nUrl( $name, $urlaction = '' ) {
1152 $title = Title
::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1153 self
::checkTitle( $title, $name );
1154 return $title->getLocalURL( $urlaction );
1158 * @param string $name
1159 * @param string $urlaction
1162 static function makeUrl( $name, $urlaction = '' ) {
1163 $title = Title
::newFromText( $name );
1164 self
::checkTitle( $title, $name );
1166 return $title->getLocalURL( $urlaction );
1170 * If url string starts with http, consider as external URL, else
1172 * @param string $name
1173 * @return string URL
1175 static function makeInternalOrExternalUrl( $name ) {
1176 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1179 return self
::makeUrl( $name );
1184 * this can be passed the NS number as defined in Language.php
1185 * @param string $name
1186 * @param string $urlaction
1187 * @param int $namespace
1190 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN
) {
1191 $title = Title
::makeTitleSafe( $namespace, $name );
1192 self
::checkTitle( $title, $name );
1194 return $title->getLocalURL( $urlaction );
1198 * these return an array with the 'href' and boolean 'exists'
1199 * @param string $name
1200 * @param string $urlaction
1203 static function makeUrlDetails( $name, $urlaction = '' ) {
1204 $title = Title
::newFromText( $name );
1205 self
::checkTitle( $title, $name );
1208 'href' => $title->getLocalURL( $urlaction ),
1209 'exists' => $title->getArticleID() != 0,
1214 * Make URL details where the article exists (or at least it's convenient to think so)
1215 * @param string $name Article name
1216 * @param string $urlaction
1219 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1220 $title = Title
::newFromText( $name );
1221 self
::checkTitle( $title, $name );
1224 'href' => $title->getLocalURL( $urlaction ),
1230 * make sure we have some title to operate on
1232 * @param Title $title
1233 * @param string $name
1235 static function checkTitle( &$title, $name ) {
1236 if ( !is_object( $title ) ) {
1237 $title = Title
::newFromText( $name );
1238 if ( !is_object( $title ) ) {
1239 $title = Title
::newFromText( '--error: link target missing--' );
1245 * Build an array that represents the sidebar(s), the navigation bar among them.
1247 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1249 * The format of the returned array is array( heading => content, ... ), where:
1250 * - heading is the heading of a navigation portlet. It is either:
1251 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1252 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1253 * - plain text, which should be HTML-escaped by the skin
1254 * - content is the contents of the portlet. It is either:
1255 * - HTML text (<ul><li>...</li>...</ul>)
1256 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1257 * - (for a magic string as a key, any value)
1259 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1260 * and can technically insert anything in here; skin creators are expected to handle
1261 * values described above.
1265 function buildSidebar() {
1266 global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1267 wfProfileIn( __METHOD__
);
1269 $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() );
1271 if ( $wgEnableSidebarCache ) {
1272 $cachedsidebar = $wgMemc->get( $key );
1273 if ( $cachedsidebar ) {
1274 wfRunHooks( 'SidebarBeforeOutput', array( $this, &$cachedsidebar ) );
1276 wfProfileOut( __METHOD__
);
1277 return $cachedsidebar;
1282 $this->addToSidebar( $bar, 'sidebar' );
1284 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1285 if ( $wgEnableSidebarCache ) {
1286 $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1289 wfRunHooks( 'SidebarBeforeOutput', array( $this, &$bar ) );
1291 wfProfileOut( __METHOD__
);
1296 * Add content from a sidebar system message
1297 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1299 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1302 * @param string $message
1304 function addToSidebar( &$bar, $message ) {
1305 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1309 * Add content from plain text
1312 * @param string $text
1315 function addToSidebarPlain( &$bar, $text ) {
1316 $lines = explode( "\n", $text );
1320 foreach ( $lines as $line ) {
1321 if ( strpos( $line, '*' ) !== 0 ) {
1324 $line = rtrim( $line, "\r" ); // for Windows compat
1326 if ( strpos( $line, '**' ) !== 0 ) {
1327 $heading = trim( $line, '* ' );
1328 if ( !array_key_exists( $heading, $bar ) ) {
1329 $bar[$heading] = array();
1332 $line = trim( $line, '* ' );
1334 if ( strpos( $line, '|' ) !== false ) { // sanity check
1335 $line = MessageCache
::singleton()->transform( $line, false, null, $this->getTitle() );
1336 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1337 if ( count( $line ) !== 2 ) {
1338 // Second sanity check, could be hit by people doing
1339 // funky stuff with parserfuncs... (bug 33321)
1343 $extraAttribs = array();
1345 $msgLink = $this->msg( $line[0] )->inContentLanguage();
1346 if ( $msgLink->exists() ) {
1347 $link = $msgLink->text();
1348 if ( $link == '-' ) {
1354 $msgText = $this->msg( $line[1] );
1355 if ( $msgText->exists() ) {
1356 $text = $msgText->text();
1361 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1364 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1365 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1366 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1367 $extraAttribs['rel'] = 'nofollow';
1370 global $wgExternalLinkTarget;
1371 if ( $wgExternalLinkTarget ) {
1372 $extraAttribs['target'] = $wgExternalLinkTarget;
1375 $title = Title
::newFromText( $link );
1378 $title = $title->fixSpecialName();
1379 $href = $title->getLinkURL();
1381 $href = 'INVALID-TITLE';
1385 $bar[$heading][] = array_merge( array(
1388 'id' => 'n-' . Sanitizer
::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1401 * This function previously controlled whether the 'mediawiki.legacy.wikiprintable' module
1402 * should be loaded by OutputPage. That module no longer exists and the return value of this
1403 * method is ignored.
1405 * If your skin doesn't provide its own print styles, the 'mediawiki.legacy.commonPrint' module
1406 * can be used instead (SkinTemplate-based skins do it automatically).
1408 * @deprecated since 1.22
1411 public function commonPrintStylesheet() {
1412 wfDeprecated( __METHOD__
, '1.22' );
1417 * Gets new talk page messages for the current user and returns an
1418 * appropriate alert message (or an empty string if there are no messages)
1421 function getNewtalks() {
1423 $newMessagesAlert = '';
1424 $user = $this->getUser();
1425 $newtalks = $user->getNewMessageLinks();
1426 $out = $this->getOutput();
1428 // Allow extensions to disable or modify the new messages alert
1429 if ( !wfRunHooks( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) {
1432 if ( $newMessagesAlert ) {
1433 return $newMessagesAlert;
1436 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1437 $uTalkTitle = $user->getTalkPage();
1438 $lastSeenRev = isset( $newtalks[0]['rev'] ) ?
$newtalks[0]['rev'] : null;
1440 if ( $lastSeenRev !== null ) {
1441 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1442 $latestRev = Revision
::newFromTitle( $uTalkTitle, false, Revision
::READ_NORMAL
);
1443 if ( $latestRev !== null ) {
1444 // Singular if only 1 unseen revision, plural if several unseen revisions.
1445 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1446 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1447 $lastSeenRev, $latestRev, 10, 'include_new' );
1450 // Singular if no revision -> diff link will show latest change only in any case
1453 $plural = $plural ?
999 : 1;
1454 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1455 // the number of revisions or authors is not necessarily the same as the number of
1457 $newMessagesLink = Linker
::linkKnown(
1459 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1461 array( 'redirect' => 'no' )
1464 $newMessagesDiffLink = Linker
::linkKnown(
1466 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1468 $lastSeenRev !== null
1469 ?
array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' )
1470 : array( 'diff' => 'cur' )
1473 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1474 $newMessagesAlert = $this->msg(
1475 'youhavenewmessagesfromusers',
1477 $newMessagesDiffLink
1478 )->numParams( $nofAuthors, $plural );
1480 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1481 $newMessagesAlert = $this->msg(
1482 $nofAuthors > 10 ?
'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1484 $newMessagesDiffLink
1485 )->numParams( $plural );
1487 $newMessagesAlert = $newMessagesAlert->text();
1488 # Disable Squid cache
1489 $out->setSquidMaxage( 0 );
1490 } elseif ( count( $newtalks ) ) {
1491 $sep = $this->msg( 'newtalkseparator' )->escaped();
1494 foreach ( $newtalks as $newtalk ) {
1495 $msgs[] = Xml
::element(
1497 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1500 $parts = implode( $sep, $msgs );
1501 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1502 $out->setSquidMaxage( 0 );
1505 return $newMessagesAlert;
1509 * Get a cached notice
1511 * @param string $name Message name, or 'default' for $wgSiteNotice
1512 * @return string HTML fragment
1514 private function getCachedNotice( $name ) {
1515 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1517 wfProfileIn( __METHOD__
);
1521 if ( $name === 'default' ) {
1523 global $wgSiteNotice;
1524 $notice = $wgSiteNotice;
1525 if ( empty( $notice ) ) {
1526 wfProfileOut( __METHOD__
);
1530 $msg = $this->msg( $name )->inContentLanguage();
1531 if ( $msg->isDisabled() ) {
1532 wfProfileOut( __METHOD__
);
1535 $notice = $msg->plain();
1538 // Use the extra hash appender to let eg SSL variants separately cache.
1539 $key = wfMemcKey( $name . $wgRenderHashAppend );
1540 $cachedNotice = $parserMemc->get( $key );
1541 if ( is_array( $cachedNotice ) ) {
1542 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1543 $notice = $cachedNotice['html'];
1552 $parsed = $this->getOutput()->parse( $notice );
1553 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1557 $notice = Html
::rawElement( 'div', array( 'id' => 'localNotice',
1558 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice );
1559 wfProfileOut( __METHOD__
);
1564 * Get a notice based on page's namespace
1566 * @return string HTML fragment
1568 function getNamespaceNotice() {
1569 wfProfileIn( __METHOD__
);
1571 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1572 $namespaceNotice = $this->getCachedNotice( $key );
1573 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p><' ) {
1574 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1576 $namespaceNotice = '';
1579 wfProfileOut( __METHOD__
);
1580 return $namespaceNotice;
1584 * Get the site notice
1586 * @return string HTML fragment
1588 function getSiteNotice() {
1589 wfProfileIn( __METHOD__
);
1592 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1593 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1594 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1596 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1597 if ( !$anonNotice ) {
1598 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1600 $siteNotice = $anonNotice;
1603 if ( !$siteNotice ) {
1604 $siteNotice = $this->getCachedNotice( 'default' );
1608 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1609 wfProfileOut( __METHOD__
);
1614 * Create a section edit link. This supersedes editSectionLink() and
1615 * editSectionLinkForOther().
1617 * @param Title $nt The title being linked to (may not be the same as
1618 * the current page, if the section is included from a template)
1619 * @param string $section The designation of the section being pointed to,
1620 * to be included in the link, like "§ion=$section"
1621 * @param string $tooltip The tooltip to use for the link: will be escaped
1622 * and wrapped in the 'editsectionhint' message
1623 * @param string $lang Language code
1624 * @return string HTML to use for edit link
1626 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1627 // HTML generated here should probably have userlangattributes
1628 // added to it for LTR text on RTL pages
1630 $lang = wfGetLangObj( $lang );
1633 if ( !is_null( $tooltip ) ) {
1634 # Bug 25462: undo double-escaping.
1635 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1636 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1637 ->inLanguage( $lang )->text();
1639 $link = Linker
::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(),
1641 array( 'action' => 'edit', 'section' => $section ),
1642 array( 'noclasses', 'known' )
1645 # Add the brackets and the span and run the hook.
1646 $result = '<span class="mw-editsection">'
1647 . '<span class="mw-editsection-bracket">[</span>'
1649 . '<span class="mw-editsection-bracket">]</span>'
1652 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1657 * Use PHP's magic __call handler to intercept legacy calls to the linker
1658 * for backwards compatibility.
1660 * @param string $fname Name of called method
1661 * @param array $args Arguments to the method
1662 * @throws MWException
1665 function __call( $fname, $args ) {
1666 $realFunction = array( 'Linker', $fname );
1667 if ( is_callable( $realFunction ) ) {
1668 wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' );
1669 return call_user_func_array( $realFunction, $args );
1671 $className = get_class( $this );
1672 throw new MWException( "Call to undefined method $className::$fname" );