From: Kunal Mehta Date: Sat, 9 Aug 2014 12:36:35 +0000 (+0100) Subject: Introduce SkinFactory X-Git-Tag: 1.31.0-rc.0~14492^2 X-Git-Url: http://git.cyclocoop.org/data/%24oldEdit?a=commitdiff_plain;h=eb37e9d1ffb2ebf3e847ae948b8f30455b1f3176;p=lhc%2Fweb%2Fwiklou.git Introduce SkinFactory Modeled similar to ConfigFactory, this lets skins register themselves via a callback, allowing for proper dependency injection. Loading via $wgValidSkinNames is still supported, but considered "legacy", not deprecated though. Skin::newFromKey is now deprecated (and had only one caller in an extension, which I'll update afterwards). Change-Id: I1960483f87c2ef55c994545239b728fa376f17f4 --- diff --git a/includes/AutoLoader.php b/includes/AutoLoader.php index 872e89b7cc..c535ca0c30 100644 --- a/includes/AutoLoader.php +++ b/includes/AutoLoader.php @@ -36,7 +36,6 @@ $wgAutoloadLocalClasses = array( 'AuthPlugin' => 'includes/AuthPlugin.php', 'AuthPluginUser' => 'includes/AuthPlugin.php', 'Autopromote' => 'includes/Autopromote.php', - 'BaseTemplate' => 'includes/SkinTemplate.php', 'Block' => 'includes/Block.php', 'Category' => 'includes/Category.php', 'Categoryfinder' => 'includes/Categoryfinder.php', @@ -120,7 +119,6 @@ $wgAutoloadLocalClasses = array( 'MagicWordArray' => 'includes/MagicWord.php', 'MailAddress' => 'includes/UserMailer.php', 'MediaWiki' => 'includes/MediaWiki.php', - 'MediaWikiI18N' => 'includes/SkinTemplate.php', 'MediaWikiVersionFetcher' => 'includes/MediaWikiVersionFetcher.php', 'Message' => 'includes/Message.php', 'MessageBlobStore' => 'includes/MessageBlobStore.php', @@ -143,7 +141,6 @@ $wgAutoloadLocalClasses = array( 'PreferencesForm' => 'includes/Preferences.php', 'PrefixSearch' => 'includes/PrefixSearch.php', 'ProtectionForm' => 'includes/ProtectionForm.php', - 'QuickTemplate' => 'includes/SkinTemplate.php', 'RawMessage' => 'includes/Message.php', 'ReverseChronologicalPager' => 'includes/Pager.php', 'RevisionItem' => 'includes/RevisionList.php', @@ -156,10 +153,6 @@ $wgAutoloadLocalClasses = array( 'SiteConfiguration' => 'includes/SiteConfiguration.php', 'SiteStats' => 'includes/SiteStats.php', 'SiteStatsInit' => 'includes/SiteStats.php', - 'Skin' => 'includes/Skin.php', - 'SkinTemplate' => 'includes/SkinTemplate.php', - 'SkinFallback' => 'includes/SkinFallback.php', - 'SkinFallbackTemplate' => 'includes/SkinFallbackTemplate.php', 'SquidPurgeClient' => 'includes/SquidPurgeClient.php', 'SquidPurgeClientPool' => 'includes/SquidPurgeClient.php', 'StatCounter' => 'includes/StatCounter.php', @@ -933,6 +926,17 @@ $wgAutoloadLocalClasses = array( 'Sites' => 'includes/site/SiteSQLStore.php', 'SiteStore' => 'includes/site/SiteStore.php', + # includes/skins + 'BaseTemplate' => 'includes/skins/SkinTemplate.php', + 'MediaWikiI18N' => 'includes/skins/SkinTemplate.php', + 'QuickTemplate' => 'includes/skins/SkinTemplate.php', + 'Skin' => 'includes/skins/Skin.php', + 'SkinException' => 'includes/skins/SkinException.php', + 'SkinFactory' => 'includes/skins/SkinFactory.php', + 'SkinFallback' => 'includes/skins/SkinFallback.php', + 'SkinFallbackTemplate' => 'includes/skins/SkinFallbackTemplate.php', + 'SkinTemplate' => 'includes/skins/SkinTemplate.php', + # includes/specialpage 'ChangesListSpecialPage' => 'includes/specialpage/ChangesListSpecialPage.php', 'FormSpecialPage' => 'includes/specialpage/FormSpecialPage.php', diff --git a/includes/Skin.php b/includes/Skin.php deleted file mode 100644 index a59d5678a3..0000000000 --- a/includes/Skin.php +++ /dev/null @@ -1,1686 +0,0 @@ -read() ) ) { - // Skip non-PHP files, hidden files, and '.dep' includes - $matches = array(); - - if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) { - $aSkin = $matches[1]; - - // Explicitly disallow loading core skins via the autodiscovery mechanism. - // - // They should be loaded already (in a non-autodicovery way), but old files might still - // exist on the server because our MW version upgrade process is widely documented as - // requiring just copying over all files, without removing old ones. - // - // This is one of the reasons we should have never used autodiscovery in the first - // place. This hack can be safely removed when autodiscovery is gone. - if ( in_array( $aSkin, array( 'CologneBlue', 'Modern', 'MonoBook', 'Vector' ) ) ) { - wfLogWarning( - "An old copy of the $aSkin skin was found in your skins/ directory. " . - "You should remove it to avoid problems in the future." . - "See https://www.mediawiki.org/wiki/Manual:Skin_autodiscovery for details." - ); - continue; - } - - wfLogWarning( - "A skin using autodiscovery mechanism, $aSkin, was found in your skins/ directory. " . - "The mechanism will be removed in MediaWiki 1.25 and the skin will no longer be recognized. " . - "See https://www.mediawiki.org/wiki/Manual:Skin_autodiscovery for information how to fix this." - ); - $wgValidSkinNames[strtolower( $aSkin )] = $aSkin; - } - } - $skinDir->close(); - } - $skinsInitialised = true; - wfProfileOut( __METHOD__ . '-init' ); - } - return $wgValidSkinNames; - } - - /** - * Fetch the skinname messages for available skins. - * @return string[] - */ - static function getSkinNameMessages() { - $messages = array(); - foreach ( self::getSkinNames() as $skinKey => $skinName ) { - $messages[] = "skinname-$skinKey"; - } - return $messages; - } - - /** - * Fetch the list of user-selectable skins in regards to $wgSkipSkins. - * Useful for Special:Preferences and other places where you - * only want to show skins users _can_ use. - * @return string[] - * @since 1.23 - */ - public static function getAllowedSkins() { - global $wgSkipSkins; - - $allowedSkins = self::getSkinNames(); - - foreach ( $wgSkipSkins as $skip ) { - unset( $allowedSkins[$skip] ); - } - - return $allowedSkins; - } - - /** - * @deprecated since 1.23, use getAllowedSkins - * @return string[] - */ - public static function getUsableSkins() { - wfDeprecated( __METHOD__, '1.23' ); - return self::getAllowedSkins(); - } - - /** - * Normalize a skin preference value to a form that can be loaded. - * - * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the - * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too. - * - * @param string $key 'monobook', 'vector', etc. - * @return string - */ - static function normalizeKey( $key ) { - global $wgDefaultSkin, $wgFallbackSkin; - - $skinNames = Skin::getSkinNames(); - - // Make keys lowercase for case-insensitive matching. - $skinNames = array_change_key_case( $skinNames, CASE_LOWER ); - $key = strtolower( $key ); - $defaultSkin = strtolower( $wgDefaultSkin ); - $fallbackSkin = strtolower( $wgFallbackSkin ); - - if ( $key == '' || $key == 'default' ) { - // Don't return the default immediately; - // in a misconfiguration we need to fall back. - $key = $defaultSkin; - } - - if ( isset( $skinNames[$key] ) ) { - return $key; - } - - // Older versions of the software used a numeric setting - // in the user preferences. - $fallback = array( - 0 => $defaultSkin, - 2 => 'cologneblue' - ); - - if ( isset( $fallback[$key] ) ) { - $key = $fallback[$key]; - } - - if ( isset( $skinNames[$key] ) ) { - return $key; - } elseif ( isset( $skinNames[$defaultSkin] ) ) { - return $defaultSkin; - } else { - return $fallbackSkin; - } - } - - /** - * Factory method for loading a skin of a given type - * @param string $key 'monobook', 'vector', etc. - * @return Skin - */ - static function &newFromKey( $key ) { - global $wgStyleDirectory, $wgFallbackSkin; - - $key = Skin::normalizeKey( $key ); - - $skinNames = Skin::getSkinNames(); - $skinName = $skinNames[$key]; - $className = "Skin{$skinName}"; - - # Grab the skin class and initialise it. - if ( !class_exists( $className ) ) { - - require_once "{$wgStyleDirectory}/{$skinName}.php"; - - # Check if we got if not fallback to default skin - if ( !class_exists( $className ) ) { - # DO NOT die if the class isn't found. This breaks maintenance - # scripts and can cause a user account to be unrecoverable - # except by SQL manipulation if a previously valid skin name - # is no longer valid. - wfDebug( "Skin class does not exist: $className\n" ); - - $fallback = $skinNames[Skin::normalizeKey( $wgFallbackSkin )]; - $className = "Skin{$fallback}"; - } - } - $skin = new $className( $key ); - return $skin; - } - - /** - * @return string Skin name - */ - public function getSkinName() { - return $this->skinname; - } - - /** - * @param OutputPage $out - */ - function initPage( OutputPage $out ) { - wfProfileIn( __METHOD__ ); - - $this->preloadExistence(); - - wfProfileOut( __METHOD__ ); - } - - /** - * Defines the ResourceLoader modules that should be added to the skin - * It is recommended that skins wishing to override call parent::getDefaultModules() - * and substitute out any modules they wish to change by using a key to look them up - * @return array Array of modules with helper keys for easy overriding - */ - public function getDefaultModules() { - global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax, - $wgAjaxWatch, $wgEnableAPI, $wgEnableWriteAPI; - - $out = $this->getOutput(); - $user = $out->getUser(); - $modules = array( - // modules that enhance the page content in some way - 'content' => array( - 'mediawiki.page.ready', - ), - // modules that exist for legacy reasons - 'legacy' => array(), - // modules relating to search functionality - 'search' => array(), - // modules relating to functionality relating to watching an article - 'watch' => array(), - // modules which relate to the current users preferences - 'user' => array(), - ); - if ( $wgIncludeLegacyJavaScript ) { - $modules['legacy'][] = 'mediawiki.legacy.wikibits'; - } - - if ( $wgPreloadJavaScriptMwUtil ) { - $modules['legacy'][] = 'mediawiki.util'; - } - - // Add various resources if required - if ( $wgUseAjax ) { - $modules['legacy'][] = 'mediawiki.legacy.ajax'; - - if ( $wgEnableAPI ) { - if ( $wgEnableWriteAPI && $wgAjaxWatch && $user->isLoggedIn() - && $user->isAllowed( 'writeapi' ) - ) { - $modules['watch'][] = 'mediawiki.page.watch.ajax'; - } - - $modules['search'][] = 'mediawiki.searchSuggest'; - } - } - - if ( $user->getBoolOption( 'editsectiononrightclick' ) ) { - $modules['user'][] = 'mediawiki.action.view.rightClickEdit'; - } - - // Crazy edit-on-double-click stuff - if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) { - $modules['user'][] = 'mediawiki.action.view.dblClickEdit'; - } - return $modules; - } - - /** - * Preload the existence of three commonly-requested pages in a single query - */ - function preloadExistence() { - $user = $this->getUser(); - - // User/talk link - $titles = array( $user->getUserPage(), $user->getTalkPage() ); - - // Other tab link - if ( $this->getTitle()->isSpecialPage() ) { - // nothing - } elseif ( $this->getTitle()->isTalkPage() ) { - $titles[] = $this->getTitle()->getSubjectPage(); - } else { - $titles[] = $this->getTitle()->getTalkPage(); - } - - $lb = new LinkBatch( $titles ); - $lb->setCaller( __METHOD__ ); - $lb->execute(); - } - - /** - * Get the current revision ID - * - * @return int - */ - public function getRevisionId() { - return $this->getOutput()->getRevisionId(); - } - - /** - * Whether the revision displayed is the latest revision of the page - * - * @return bool - */ - public function isRevisionCurrent() { - $revID = $this->getRevisionId(); - return $revID == 0 || $revID == $this->getTitle()->getLatestRevID(); - } - - /** - * Set the "relevant" title - * @see self::getRelevantTitle() - * @param Title $t - */ - public function setRelevantTitle( $t ) { - $this->mRelevantTitle = $t; - } - - /** - * Return the "relevant" title. - * A "relevant" title is not necessarily the actual title of the page. - * Special pages like Special:MovePage use set the page they are acting on - * as their "relevant" title, this allows the skin system to display things - * such as content tabs which belong to to that page instead of displaying - * a basic special page tab which has almost no meaning. - * - * @return Title - */ - public function getRelevantTitle() { - if ( isset( $this->mRelevantTitle ) ) { - return $this->mRelevantTitle; - } - return $this->getTitle(); - } - - /** - * Set the "relevant" user - * @see self::getRelevantUser() - * @param User $u - */ - public function setRelevantUser( $u ) { - $this->mRelevantUser = $u; - } - - /** - * Return the "relevant" user. - * A "relevant" user is similar to a relevant title. Special pages like - * Special:Contributions mark the user which they are relevant to so that - * things like the toolbox can display the information they usually are only - * able to display on a user's userpage and talkpage. - * @return User - */ - public function getRelevantUser() { - if ( isset( $this->mRelevantUser ) ) { - return $this->mRelevantUser; - } - $title = $this->getRelevantTitle(); - if ( $title->hasSubjectNamespace( NS_USER ) ) { - $rootUser = $title->getRootText(); - if ( User::isIP( $rootUser ) ) { - $this->mRelevantUser = User::newFromName( $rootUser, false ); - } else { - $user = User::newFromName( $rootUser, false ); - if ( $user && $user->isLoggedIn() ) { - $this->mRelevantUser = $user; - } - } - return $this->mRelevantUser; - } - return null; - } - - /** - * Outputs the HTML generated by other functions. - * @param OutputPage $out - */ - abstract function outputPage( OutputPage $out = null ); - - /** - * @param array $data - * @return string - */ - static function makeVariablesScript( $data ) { - if ( $data ) { - return Html::inlineScript( - ResourceLoader::makeLoaderConditionalScript( ResourceLoader::makeConfigSetScript( $data ) ) - ); - } else { - return ''; - } - } - - /** - * Get the query to generate a dynamic stylesheet - * - * @return array - */ - public static function getDynamicStylesheetQuery() { - global $wgSquidMaxage; - - return array( - 'action' => 'raw', - 'maxage' => $wgSquidMaxage, - 'usemsgcache' => 'yes', - 'ctype' => 'text/css', - 'smaxage' => $wgSquidMaxage, - ); - } - - /** - * Add skin specific stylesheets - * Calling this method with an $out of anything but the same OutputPage - * inside ->getOutput() is deprecated. The $out arg is kept - * for compatibility purposes with skins. - * @param OutputPage $out - * @todo delete - */ - abstract function setupSkinUserCss( OutputPage $out ); - - /** - * TODO: document - * @param Title $title - * @return string - */ - function getPageClasses( $title ) { - $numeric = 'ns-' . $title->getNamespace(); - - if ( $title->isSpecialPage() ) { - $type = 'ns-special'; - // bug 23315: provide a class based on the canonical special page name without subpages - list( $canonicalName ) = SpecialPageFactory::resolveAlias( $title->getDBkey() ); - if ( $canonicalName ) { - $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" ); - } else { - $type .= ' mw-invalidspecialpage'; - } - } elseif ( $title->isTalkPage() ) { - $type = 'ns-talk'; - } else { - $type = 'ns-subject'; - } - - $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() ); - - return "$numeric $type $name"; - } - - /* - * Return values for element - * @return array of associative name-to-value elements for element - */ - public function getHtmlElementAttributes() { - $lang = $this->getLanguage(); - return array( - 'lang' => $lang->getHtmlCode(), - 'dir' => $lang->getDir(), - 'class' => 'client-nojs', - ); - } - - /** - * This will be called by OutputPage::headElement when it is creating the - * "" tag, skins can override it if they have a need to add in any - * body attributes or classes of their own. - * @param OutputPage $out - * @param array $bodyAttrs - */ - function addToBodyAttributes( $out, &$bodyAttrs ) { - // does nothing by default - } - - /** - * URL to the logo - * @return string - */ - function getLogo() { - global $wgLogo; - return $wgLogo; - } - - /** - * @return string - */ - function getCategoryLinks() { - global $wgUseCategoryBrowser; - - $out = $this->getOutput(); - $allCats = $out->getCategoryLinks(); - - if ( !count( $allCats ) ) { - return ''; - } - - $embed = "
  • "; - $pop = "
  • "; - - $s = ''; - $colon = $this->msg( 'colon-separator' )->escaped(); - - if ( !empty( $allCats['normal'] ) ) { - $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop; - - $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped(); - $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text(); - $s .= ''; - } - - # Hidden categories - if ( isset( $allCats['hidden'] ) ) { - if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) { - $class = ' mw-hidden-cats-user-shown'; - } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY ) { - $class = ' mw-hidden-cats-ns-shown'; - } else { - $class = ' mw-hidden-cats-hidden'; - } - - $s .= "
    " . - $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() . - $colon . '' . - '
    '; - } - - # optional 'dmoz-like' category browser. Will be shown under the list - # of categories an article belong to - if ( $wgUseCategoryBrowser ) { - $s .= '

    '; - - # get a big array of the parents tree - $parenttree = $this->getTitle()->getParentCategoryTree(); - # Skin object passed by reference cause it can not be - # accessed under the method subfunction drawCategoryBrowser - $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) ); - # Clean out bogus first entry and sort them - unset( $tempout[0] ); - asort( $tempout ); - # Output one per line - $s .= implode( "
    \n", $tempout ); - } - - return $s; - } - - /** - * Render the array as a series of links. - * @param array $tree Categories tree returned by Title::getParentCategoryTree - * @return string Separated by >, terminate with "\n" - */ - function drawCategoryBrowser( $tree ) { - $return = ''; - - foreach ( $tree as $element => $parent ) { - if ( empty( $parent ) ) { - # element start a new list - $return .= "\n"; - } else { - # grab the others elements - $return .= $this->drawCategoryBrowser( $parent ) . ' > '; - } - - # add our current element to the list - $eltitle = Title::newFromText( $element ); - $return .= Linker::link( $eltitle, htmlspecialchars( $eltitle->getText() ) ); - } - - return $return; - } - - /** - * @return string - */ - function getCategories() { - $out = $this->getOutput(); - - $catlinks = $this->getCategoryLinks(); - - $classes = 'catlinks'; - - // Check what we're showing - $allCats = $out->getCategoryLinks(); - $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) || - $this->getTitle()->getNamespace() == NS_CATEGORY; - - if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) { - $classes .= ' catlinks-allhidden'; - } - - return ""; - } - - /** - * This runs a hook to allow extensions placing their stuff after content - * and article metadata (e.g. categories). - * Note: This function has nothing to do with afterContent(). - * - * This hook is placed here in order to allow using the same hook for all - * skins, both the SkinTemplate based ones and the older ones, which directly - * use this class to get their data. - * - * The output of this function gets processed in SkinTemplate::outputPage() for - * the SkinTemplate based skins, all other skins should directly echo it. - * - * @return string Empty by default, if not changed by any hook function. - */ - protected function afterContentHook() { - $data = ''; - - if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) { - // adding just some spaces shouldn't toggle the output - // of the whole
    , so we use trim() here - if ( trim( $data ) != '' ) { - // Doing this here instead of in the skins to - // ensure that the div has the same ID in all - // skins - $data = "
    \n" . - "\t$data\n" . - "
    \n"; - } - } else { - wfDebug( "Hook SkinAfterContent changed output processing.\n" ); - } - - return $data; - } - - /** - * Generate debug data HTML for displaying at the bottom of the main content - * area. - * @return string HTML containing debug data, if enabled (otherwise empty). - */ - protected function generateDebugHTML() { - return MWDebug::getHTMLDebugLog(); - } - - /** - * This gets called shortly before the "" tag. - * - * @return string HTML-wrapped JS code to be put before "" - */ - function bottomScripts() { - // TODO and the suckage continues. This function is really just a wrapper around - // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned - // up at some point - $bottomScriptText = $this->getOutput()->getBottomScripts(); - wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) ); - - return $bottomScriptText; - } - - /** - * Text with the permalink to the source page, - * usually shown on the footer of a printed page - * - * @return string HTML text with an URL - */ - function printSource() { - $oldid = $this->getRevisionId(); - if ( $oldid ) { - $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid ); - $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) ); - } else { - // oldid not available for non existing pages - $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) ); - } - - return $this->msg( 'retrievedfrom', '' . $url . '' )->text(); - } - - /** - * @return string - */ - function getUndeleteLink() { - $action = $this->getRequest()->getVal( 'action', 'view' ); - - if ( $this->getUser()->isAllowed( 'deletedhistory' ) && - ( $this->getTitle()->getArticleID() == 0 || $action == 'history' ) ) { - $n = $this->getTitle()->isDeleted(); - - if ( $n ) { - if ( $this->getUser()->isAllowed( 'undelete' ) ) { - $msg = 'thisisdeleted'; - } else { - $msg = 'viewdeleted'; - } - - return $this->msg( $msg )->rawParams( - Linker::linkKnown( - SpecialPage::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ), - $this->msg( 'restorelink' )->numParams( $n )->escaped() ) - )->text(); - } - } - - return ''; - } - - /** - * @return string - */ - function subPageSubtitle() { - $out = $this->getOutput(); - $subpages = ''; - - if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) { - return $subpages; - } - - if ( $out->isArticle() && MWNamespace::hasSubpages( $out->getTitle()->getNamespace() ) ) { - $ptext = $this->getTitle()->getPrefixedText(); - if ( preg_match( '/\//', $ptext ) ) { - $links = explode( '/', $ptext ); - array_pop( $links ); - $c = 0; - $growinglink = ''; - $display = ''; - $lang = $this->getLanguage(); - - foreach ( $links as $link ) { - $growinglink .= $link; - $display .= $link; - $linkObj = Title::newFromText( $growinglink ); - - if ( is_object( $linkObj ) && $linkObj->isKnown() ) { - $getlink = Linker::linkKnown( - $linkObj, - htmlspecialchars( $display ) - ); - - $c++; - - if ( $c > 1 ) { - $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped(); - } else { - $subpages .= '< '; - } - - $subpages .= $getlink; - $display = ''; - } else { - $display .= '/'; - } - $growinglink .= '/'; - } - } - } - - return $subpages; - } - - /** - * Returns true if the IP should be shown in the header - * @return bool - */ - function showIPinHeader() { - global $wgShowIPinHeader; - return $wgShowIPinHeader && session_id() != ''; - } - - /** - * @return string - */ - function getSearchLink() { - $searchPage = SpecialPage::getTitleFor( 'Search' ); - return $searchPage->getLocalURL(); - } - - /** - * @return string - */ - function escapeSearchLink() { - return htmlspecialchars( $this->getSearchLink() ); - } - - /** - * @param string $type - * @return string - */ - function getCopyright( $type = 'detect' ) { - global $wgRightsPage, $wgRightsUrl, $wgRightsText; - - if ( $type == 'detect' ) { - if ( !$this->isRevisionCurrent() - && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled() - ) { - $type = 'history'; - } else { - $type = 'normal'; - } - } - - if ( $type == 'history' ) { - $msg = 'history_copyright'; - } else { - $msg = 'copyright'; - } - - if ( $wgRightsPage ) { - $title = Title::newFromText( $wgRightsPage ); - $link = Linker::linkKnown( $title, $wgRightsText ); - } elseif ( $wgRightsUrl ) { - $link = Linker::makeExternalLink( $wgRightsUrl, $wgRightsText ); - } elseif ( $wgRightsText ) { - $link = $wgRightsText; - } else { - # Give up now - return ''; - } - - // Allow for site and per-namespace customization of copyright notice. - // @todo Remove deprecated $forContent param from hook handlers and then remove here. - $forContent = true; - - wfRunHooks( - 'SkinCopyrightFooter', - array( $this->getTitle(), $type, &$msg, &$link, &$forContent ) - ); - - return $this->msg( $msg )->rawParams( $link )->text(); - } - - /** - * @return null|string - */ - function getCopyrightIcon() { - global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon; - - $out = ''; - - if ( $wgCopyrightIcon ) { - $out = $wgCopyrightIcon; - } elseif ( $wgRightsIcon ) { - $icon = htmlspecialchars( $wgRightsIcon ); - - if ( $wgRightsUrl ) { - $url = htmlspecialchars( $wgRightsUrl ); - $out .= ''; - } - - $text = htmlspecialchars( $wgRightsText ); - $out .= "\"$text\""; - - if ( $wgRightsUrl ) { - $out .= ''; - } - } - - return $out; - } - - /** - * Gets the powered by MediaWiki icon. - * @return string - */ - function getPoweredBy() { - global $wgStylePath; - - $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" ); - $text = 'Powered by MediaWiki'; - wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) ); - return $text; - } - - /** - * Get the timestamp of the latest revision, formatted in user language - * - * @return string - */ - protected function lastModified() { - $timestamp = $this->getOutput()->getRevisionTimestamp(); - - # No cached timestamp, load it from the database - if ( $timestamp === null ) { - $timestamp = Revision::getTimestampFromId( $this->getTitle(), $this->getRevisionId() ); - } - - if ( $timestamp ) { - $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() ); - $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() ); - $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text(); - } else { - $s = ''; - } - - if ( wfGetLB()->getLaggedSlaveMode() ) { - $s .= ' ' . $this->msg( 'laggedslavemode' )->text() . ''; - } - - return $s; - } - - /** - * @param string $align - * @return string - */ - function logoText( $align = '' ) { - if ( $align != '' ) { - $a = " style='float: {$align};'"; - } else { - $a = ''; - } - - $mp = $this->msg( 'mainpage' )->escaped(); - $mptitle = Title::newMainPage(); - $url = ( is_object( $mptitle ) ? htmlspecialchars( $mptitle->getLocalURL() ) : '' ); - - $logourl = $this->getLogo(); - $s = ""; - - return $s; - } - - /** - * Renders a $wgFooterIcons icon according to the method's arguments - * @param array $icon The icon to build the html for, see $wgFooterIcons - * for the format of this array. - * @param bool|string $withImage Whether to use the icon's image or output - * a text-only footericon. - * @return string HTML - */ - function makeFooterIcon( $icon, $withImage = 'withImage' ) { - if ( is_string( $icon ) ) { - $html = $icon; - } else { // Assuming array - $url = isset( $icon["url"] ) ? $icon["url"] : null; - unset( $icon["url"] ); - if ( isset( $icon["src"] ) && $withImage === 'withImage' ) { - // do this the lazy way, just pass icon data as an attribute array - $html = Html::element( 'img', $icon ); - } else { - $html = htmlspecialchars( $icon["alt"] ); - } - if ( $url ) { - $html = Html::rawElement( 'a', array( "href" => $url ), $html ); - } - } - return $html; - } - - /** - * Gets the link to the wiki's main page. - * @return string - */ - function mainPageLink() { - $s = Linker::linkKnown( - Title::newMainPage(), - $this->msg( 'mainpage' )->escaped() - ); - - return $s; - } - - /** - * Returns an HTML link for use in the footer - * @param string $desc The i18n message key for the link text - * @param string $page The i18n message key for the page to link to - * @return string HTML anchor - */ - public function footerLink( $desc, $page ) { - // if the link description has been set to "-" in the default language, - if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) { - // then it is disabled, for all languages. - return ''; - } else { - // Otherwise, we display the link for the user, described in their - // language (which may or may not be the same as the default language), - // but we make the link target be the one site-wide page. - $title = Title::newFromText( $this->msg( $page )->inContentLanguage()->text() ); - - return Linker::linkKnown( - $title, - $this->msg( $desc )->escaped() - ); - } - } - - /** - * Gets the link to the wiki's privacy policy page. - * @return string HTML - */ - function privacyLink() { - return $this->footerLink( 'privacy', 'privacypage' ); - } - - /** - * Gets the link to the wiki's about page. - * @return string HTML - */ - function aboutLink() { - return $this->footerLink( 'aboutsite', 'aboutpage' ); - } - - /** - * Gets the link to the wiki's general disclaimers page. - * @return string HTML - */ - function disclaimerLink() { - return $this->footerLink( 'disclaimers', 'disclaimerpage' ); - } - - /** - * Return URL options for the 'edit page' link. - * This may include an 'oldid' specifier, if the current page view is such. - * - * @return array - * @private - */ - function editUrlOptions() { - $options = array( 'action' => 'edit' ); - - if ( !$this->isRevisionCurrent() ) { - $options['oldid'] = intval( $this->getRevisionId() ); - } - - return $options; - } - - /** - * @param User|int $id - * @return bool - */ - function showEmailUser( $id ) { - if ( $id instanceof User ) { - $targetUser = $id; - } else { - $targetUser = User::newFromId( $id ); - } - - # The sending user must have a confirmed email address and the target - # user must have a confirmed email address and allow emails from users. - return $this->getUser()->canSendEmail() && - $targetUser->canReceiveEmail(); - } - - /** - * Return a fully resolved style path url to images or styles stored in the common folder. - * This method returns a url resolved using the configured skin style path - * and includes the style version inside of the url. - * @param string $name The name or path of a skin resource file - * @return string The fully resolved style path url including styleversion - */ - function getCommonStylePath( $name ) { - global $wgStylePath, $wgStyleVersion; - return "$wgStylePath/common/$name?$wgStyleVersion"; - } - - /** - * Return a fully resolved style path url to images or styles stored in the current skins's folder. - * This method returns a url resolved using the configured skin style path - * and includes the style version inside of the url. - * - * Requires $stylename to be set, otherwise throws MWException. - * - * @param string $name The name or path of a skin resource file - * @return string The fully resolved style path url including styleversion - */ - function getSkinStylePath( $name ) { - global $wgStylePath, $wgStyleVersion; - - if ( $this->stylename === null ) { - $class = get_class( $this ); - throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" ); - } - - return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion"; - } - - /* these are used extensively in SkinTemplate, but also some other places */ - - /** - * @param string $urlaction - * @return string - */ - static function makeMainPageUrl( $urlaction = '' ) { - $title = Title::newMainPage(); - self::checkTitle( $title, '' ); - - return $title->getLocalURL( $urlaction ); - } - - /** - * Make a URL for a Special Page using the given query and protocol. - * - * If $proto is set to null, make a local URL. Otherwise, make a full - * URL with the protocol specified. - * - * @param string $name Name of the Special page - * @param string $urlaction Query to append - * @param string|null $proto Protocol to use or null for a local URL - * @return string - */ - static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) { - $title = SpecialPage::getSafeTitleFor( $name ); - if ( is_null( $proto ) ) { - return $title->getLocalURL( $urlaction ); - } else { - return $title->getFullURL( $urlaction, false, $proto ); - } - } - - /** - * @param string $name - * @param string $subpage - * @param string $urlaction - * @return string - */ - static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) { - $title = SpecialPage::getSafeTitleFor( $name, $subpage ); - return $title->getLocalURL( $urlaction ); - } - - /** - * @param string $name - * @param string $urlaction - * @return string - */ - static function makeI18nUrl( $name, $urlaction = '' ) { - $title = Title::newFromText( wfMessage( $name )->inContentLanguage()->text() ); - self::checkTitle( $title, $name ); - return $title->getLocalURL( $urlaction ); - } - - /** - * @param string $name - * @param string $urlaction - * @return string - */ - static function makeUrl( $name, $urlaction = '' ) { - $title = Title::newFromText( $name ); - self::checkTitle( $title, $name ); - - return $title->getLocalURL( $urlaction ); - } - - /** - * If url string starts with http, consider as external URL, else - * internal - * @param string $name - * @return string URL - */ - static function makeInternalOrExternalUrl( $name ) { - if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) { - return $name; - } else { - return self::makeUrl( $name ); - } - } - - /** - * this can be passed the NS number as defined in Language.php - * @param string $name - * @param string $urlaction - * @param int $namespace - * @return string - */ - static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) { - $title = Title::makeTitleSafe( $namespace, $name ); - self::checkTitle( $title, $name ); - - return $title->getLocalURL( $urlaction ); - } - - /** - * these return an array with the 'href' and boolean 'exists' - * @param string $name - * @param string $urlaction - * @return array - */ - static function makeUrlDetails( $name, $urlaction = '' ) { - $title = Title::newFromText( $name ); - self::checkTitle( $title, $name ); - - return array( - 'href' => $title->getLocalURL( $urlaction ), - 'exists' => $title->getArticleID() != 0, - ); - } - - /** - * Make URL details where the article exists (or at least it's convenient to think so) - * @param string $name Article name - * @param string $urlaction - * @return array - */ - static function makeKnownUrlDetails( $name, $urlaction = '' ) { - $title = Title::newFromText( $name ); - self::checkTitle( $title, $name ); - - return array( - 'href' => $title->getLocalURL( $urlaction ), - 'exists' => true - ); - } - - /** - * make sure we have some title to operate on - * - * @param Title $title - * @param string $name - */ - static function checkTitle( &$title, $name ) { - if ( !is_object( $title ) ) { - $title = Title::newFromText( $name ); - if ( !is_object( $title ) ) { - $title = Title::newFromText( '--error: link target missing--' ); - } - } - } - - /** - * Build an array that represents the sidebar(s), the navigation bar among them. - * - * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins. - * - * The format of the returned array is array( heading => content, ... ), where: - * - heading is the heading of a navigation portlet. It is either: - * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...) - * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin - * - plain text, which should be HTML-escaped by the skin - * - content is the contents of the portlet. It is either: - * - HTML text () - * - array of link data in a format accepted by BaseTemplate::makeListItem() - * - (for a magic string as a key, any value) - * - * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook - * and can technically insert anything in here; skin creators are expected to handle - * values described above. - * - * @return array - */ - function buildSidebar() { - global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry; - wfProfileIn( __METHOD__ ); - - $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() ); - - if ( $wgEnableSidebarCache ) { - $cachedsidebar = $wgMemc->get( $key ); - if ( $cachedsidebar ) { - wfRunHooks( 'SidebarBeforeOutput', array( $this, &$cachedsidebar ) ); - - wfProfileOut( __METHOD__ ); - return $cachedsidebar; - } - } - - $bar = array(); - $this->addToSidebar( $bar, 'sidebar' ); - - wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) ); - if ( $wgEnableSidebarCache ) { - $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry ); - } - - wfRunHooks( 'SidebarBeforeOutput', array( $this, &$bar ) ); - - wfProfileOut( __METHOD__ ); - return $bar; - } - - /** - * Add content from a sidebar system message - * Currently only used for MediaWiki:Sidebar (but may be used by Extensions) - * - * This is just a wrapper around addToSidebarPlain() for backwards compatibility - * - * @param array $bar - * @param string $message - */ - function addToSidebar( &$bar, $message ) { - $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() ); - } - - /** - * Add content from plain text - * @since 1.17 - * @param array $bar - * @param string $text - * @return array - */ - function addToSidebarPlain( &$bar, $text ) { - $lines = explode( "\n", $text ); - - $heading = ''; - - foreach ( $lines as $line ) { - if ( strpos( $line, '*' ) !== 0 ) { - continue; - } - $line = rtrim( $line, "\r" ); // for Windows compat - - if ( strpos( $line, '**' ) !== 0 ) { - $heading = trim( $line, '* ' ); - if ( !array_key_exists( $heading, $bar ) ) { - $bar[$heading] = array(); - } - } else { - $line = trim( $line, '* ' ); - - if ( strpos( $line, '|' ) !== false ) { // sanity check - $line = MessageCache::singleton()->transform( $line, false, null, $this->getTitle() ); - $line = array_map( 'trim', explode( '|', $line, 2 ) ); - if ( count( $line ) !== 2 ) { - // Second sanity check, could be hit by people doing - // funky stuff with parserfuncs... (bug 33321) - continue; - } - - $extraAttribs = array(); - - $msgLink = $this->msg( $line[0] )->inContentLanguage(); - if ( $msgLink->exists() ) { - $link = $msgLink->text(); - if ( $link == '-' ) { - continue; - } - } else { - $link = $line[0]; - } - $msgText = $this->msg( $line[1] ); - if ( $msgText->exists() ) { - $text = $msgText->text(); - } else { - $text = $line[1]; - } - - if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) { - $href = $link; - - // Parser::getExternalLinkAttribs won't work here because of the Namespace things - global $wgNoFollowLinks, $wgNoFollowDomainExceptions; - if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) { - $extraAttribs['rel'] = 'nofollow'; - } - - global $wgExternalLinkTarget; - if ( $wgExternalLinkTarget ) { - $extraAttribs['target'] = $wgExternalLinkTarget; - } - } else { - $title = Title::newFromText( $link ); - - if ( $title ) { - $title = $title->fixSpecialName(); - $href = $title->getLinkURL(); - } else { - $href = 'INVALID-TITLE'; - } - } - - $bar[$heading][] = array_merge( array( - 'text' => $text, - 'href' => $href, - 'id' => 'n-' . Sanitizer::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ), - 'active' => false - ), $extraAttribs ); - } else { - continue; - } - } - } - - return $bar; - } - - /** - * This function previously controlled whether the 'mediawiki.legacy.wikiprintable' module - * should be loaded by OutputPage. That module no longer exists and the return value of this - * method is ignored. - * - * If your skin doesn't provide its own print styles, the 'mediawiki.legacy.commonPrint' module - * can be used instead (SkinTemplate-based skins do it automatically). - * - * @deprecated since 1.22 - * @return bool - */ - public function commonPrintStylesheet() { - wfDeprecated( __METHOD__, '1.22' ); - return false; - } - - /** - * Gets new talk page messages for the current user and returns an - * appropriate alert message (or an empty string if there are no messages) - * @return string - */ - function getNewtalks() { - - $newMessagesAlert = ''; - $user = $this->getUser(); - $newtalks = $user->getNewMessageLinks(); - $out = $this->getOutput(); - - // Allow extensions to disable or modify the new messages alert - if ( !wfRunHooks( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) { - return ''; - } - if ( $newMessagesAlert ) { - return $newMessagesAlert; - } - - if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) { - $uTalkTitle = $user->getTalkPage(); - $lastSeenRev = isset( $newtalks[0]['rev'] ) ? $newtalks[0]['rev'] : null; - $nofAuthors = 0; - if ( $lastSeenRev !== null ) { - $plural = true; // Default if we have a last seen revision: if unknown, use plural - $latestRev = Revision::newFromTitle( $uTalkTitle, false, Revision::READ_NORMAL ); - if ( $latestRev !== null ) { - // Singular if only 1 unseen revision, plural if several unseen revisions. - $plural = $latestRev->getParentId() !== $lastSeenRev->getId(); - $nofAuthors = $uTalkTitle->countAuthorsBetween( - $lastSeenRev, $latestRev, 10, 'include_new' ); - } - } else { - // Singular if no revision -> diff link will show latest change only in any case - $plural = false; - } - $plural = $plural ? 999 : 1; - // 999 signifies "more than one revision". We don't know how many, and even if we did, - // the number of revisions or authors is not necessarily the same as the number of - // "messages". - $newMessagesLink = Linker::linkKnown( - $uTalkTitle, - $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(), - array(), - array( 'redirect' => 'no' ) - ); - - $newMessagesDiffLink = Linker::linkKnown( - $uTalkTitle, - $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(), - array(), - $lastSeenRev !== null - ? array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ) - : array( 'diff' => 'cur' ) - ); - - if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) { - $newMessagesAlert = $this->msg( - 'youhavenewmessagesfromusers', - $newMessagesLink, - $newMessagesDiffLink - )->numParams( $nofAuthors, $plural ); - } else { - // $nofAuthors === 11 signifies "11 or more" ("more than 10") - $newMessagesAlert = $this->msg( - $nofAuthors > 10 ? 'youhavenewmessagesmanyusers' : 'youhavenewmessages', - $newMessagesLink, - $newMessagesDiffLink - )->numParams( $plural ); - } - $newMessagesAlert = $newMessagesAlert->text(); - # Disable Squid cache - $out->setSquidMaxage( 0 ); - } elseif ( count( $newtalks ) ) { - $sep = $this->msg( 'newtalkseparator' )->escaped(); - $msgs = array(); - - foreach ( $newtalks as $newtalk ) { - $msgs[] = Xml::element( - 'a', - array( 'href' => $newtalk['link'] ), $newtalk['wiki'] - ); - } - $parts = implode( $sep, $msgs ); - $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped(); - $out->setSquidMaxage( 0 ); - } - - return $newMessagesAlert; - } - - /** - * Get a cached notice - * - * @param string $name Message name, or 'default' for $wgSiteNotice - * @return string HTML fragment - */ - private function getCachedNotice( $name ) { - global $wgRenderHashAppend, $parserMemc, $wgContLang; - - wfProfileIn( __METHOD__ ); - - $needParse = false; - - if ( $name === 'default' ) { - // special case - global $wgSiteNotice; - $notice = $wgSiteNotice; - if ( empty( $notice ) ) { - wfProfileOut( __METHOD__ ); - return false; - } - } else { - $msg = $this->msg( $name )->inContentLanguage(); - if ( $msg->isDisabled() ) { - wfProfileOut( __METHOD__ ); - return false; - } - $notice = $msg->plain(); - } - - // Use the extra hash appender to let eg SSL variants separately cache. - $key = wfMemcKey( $name . $wgRenderHashAppend ); - $cachedNotice = $parserMemc->get( $key ); - if ( is_array( $cachedNotice ) ) { - if ( md5( $notice ) == $cachedNotice['hash'] ) { - $notice = $cachedNotice['html']; - } else { - $needParse = true; - } - } else { - $needParse = true; - } - - if ( $needParse ) { - $parsed = $this->getOutput()->parse( $notice ); - $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 ); - $notice = $parsed; - } - - $notice = Html::rawElement( 'div', array( 'id' => 'localNotice', - 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice ); - wfProfileOut( __METHOD__ ); - return $notice; - } - - /** - * Get a notice based on page's namespace - * - * @return string HTML fragment - */ - function getNamespaceNotice() { - wfProfileIn( __METHOD__ ); - - $key = 'namespacenotice-' . $this->getTitle()->getNsText(); - $namespaceNotice = $this->getCachedNotice( $key ); - if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '

    <' ) { - $namespaceNotice = '

    ' . $namespaceNotice . '
    '; - } else { - $namespaceNotice = ''; - } - - wfProfileOut( __METHOD__ ); - return $namespaceNotice; - } - - /** - * Get the site notice - * - * @return string HTML fragment - */ - function getSiteNotice() { - wfProfileIn( __METHOD__ ); - $siteNotice = ''; - - if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) { - if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) { - $siteNotice = $this->getCachedNotice( 'sitenotice' ); - } else { - $anonNotice = $this->getCachedNotice( 'anonnotice' ); - if ( !$anonNotice ) { - $siteNotice = $this->getCachedNotice( 'sitenotice' ); - } else { - $siteNotice = $anonNotice; - } - } - if ( !$siteNotice ) { - $siteNotice = $this->getCachedNotice( 'default' ); - } - } - - wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) ); - wfProfileOut( __METHOD__ ); - return $siteNotice; - } - - /** - * Create a section edit link. This supersedes editSectionLink() and - * editSectionLinkForOther(). - * - * @param Title $nt The title being linked to (may not be the same as - * the current page, if the section is included from a template) - * @param string $section The designation of the section being pointed to, - * to be included in the link, like "§ion=$section" - * @param string $tooltip The tooltip to use for the link: will be escaped - * and wrapped in the 'editsectionhint' message - * @param string $lang Language code - * @return string HTML to use for edit link - */ - public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) { - // HTML generated here should probably have userlangattributes - // added to it for LTR text on RTL pages - - $lang = wfGetLangObj( $lang ); - - $attribs = array(); - if ( !is_null( $tooltip ) ) { - # Bug 25462: undo double-escaping. - $tooltip = Sanitizer::decodeCharReferences( $tooltip ); - $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip ) - ->inLanguage( $lang )->text(); - } - $link = Linker::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(), - $attribs, - array( 'action' => 'edit', 'section' => $section ), - array( 'noclasses', 'known' ) - ); - - # Add the brackets and the span and run the hook. - $result = '' - . '[' - . $link - . ']' - . ''; - - wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) ); - return $result; - } - - /** - * Use PHP's magic __call handler to intercept legacy calls to the linker - * for backwards compatibility. - * - * @param string $fname Name of called method - * @param array $args Arguments to the method - * @throws MWException - * @return mixed - */ - function __call( $fname, $args ) { - $realFunction = array( 'Linker', $fname ); - if ( is_callable( $realFunction ) ) { - wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' ); - return call_user_func_array( $realFunction, $args ); - } else { - $className = get_class( $this ); - throw new MWException( "Call to undefined method $className::$fname" ); - } - } - -} diff --git a/includes/SkinFallback.php b/includes/SkinFallback.php deleted file mode 100644 index 6055473b44..0000000000 --- a/includes/SkinFallback.php +++ /dev/null @@ -1,26 +0,0 @@ -addModuleStyles( 'mediawiki.skinning.interface' ); - } -} diff --git a/includes/SkinFallbackTemplate.php b/includes/SkinFallbackTemplate.php deleted file mode 100644 index 0703b0eee3..0000000000 --- a/includes/SkinFallbackTemplate.php +++ /dev/null @@ -1,109 +0,0 @@ -config->get( 'StyleDirectory' ); // @todo we should inject this directly? - // Get all subdirectories which might contains skins - $possibleSkins = scandir( $styleDirectory ); - $possibleSkins = array_filter( $possibleSkins, function ( $maybeDir ) use ( $styleDirectory ) { - return $maybeDir !== '.' && $maybeDir !== '..' && is_dir( "$styleDirectory/$maybeDir" ); - } ); - - // Only keep the ones that contain a .php file with the same name inside - $possibleSkins = array_filter( $possibleSkins, function ( $skinDir ) use ( $styleDirectory ) { - return is_file( "$styleDirectory/$skinDir/$skinDir.php" ); - } ); - - return $possibleSkins; - } - - /** - * Inform the user why they are seeing this skin. - * - * @return string - */ - private function buildHelpfulInformationMessage() { - $defaultSkin = $this->config->get( 'DefaultSkin' ); - $installedSkins = $this->findInstalledSkins(); - $enabledSkins = $this->config->get( 'ValidSkinNames' ); - $enabledSkins = array_change_key_case( $enabledSkins, CASE_LOWER ); - - if ( $installedSkins ) { - $skinsInstalledText = array(); - $skinsInstalledSnippet = array(); - - foreach ( $installedSkins as $skin ) { - $normalizedKey = strtolower( $skin ); - $isEnabled = array_key_exists( $normalizedKey, $enabledSkins ); - if ( $isEnabled ) { - $skinsInstalledText[] = $this->getMsg( 'default-skin-not-found-row-enabled' ) - ->params( $normalizedKey, $skin )->plain(); - } else { - $skinsInstalledText[] = $this->getMsg( 'default-skin-not-found-row-disabled' ) - ->params( $normalizedKey, $skin )->plain(); - $skinsInstalledSnippet[] = "require_once \"\$IP/skins/$skin/$skin.php\";"; - } - } - - return $this->getMsg( 'default-skin-not-found' )->params( - $defaultSkin, - implode( "\n", $skinsInstalledText ), - implode( "\n", $skinsInstalledSnippet ) - )->parseAsBlock(); - } else { - return $this->getMsg( 'default-skin-not-found-no-skins' )->params( - $defaultSkin - )->parseAsBlock(); - } - } - - /** - * Outputs the entire contents of the page. No navigation (other than search box), just the big - * warning message and page content. - */ - public function execute() { - $this->html( 'headelement' ) ?> - -
    - buildHelpfulInformationMessage() ?> -
    - -
    - -

    - makeSearchInput( array( "id" => "searchInput" ) ) ?> - makeSearchButton( 'go' ) ?> -
    - -
    -

    - html( 'title' ) ?> -

    - -
    - html( 'bodytext' ) ?> - html( 'catlinks' ) ?> -
    -
    - - printTrail() ?> - - - context[$varName] = $value; - } - - function translate( $value ) { - wfProfileIn( __METHOD__ ); - - // Hack for i18n:attributes in PHPTAL 1.0.0 dev version as of 2004-10-23 - $value = preg_replace( '/^string:/', '', $value ); - - $value = wfMessage( $value )->text(); - // interpolate variables - $m = array(); - while ( preg_match( '/\$([0-9]*?)/sm', $value, $m ) ) { - list( $src, $var ) = $m; - wfSuppressWarnings(); - $varValue = $this->context[$var]; - wfRestoreWarnings(); - $value = str_replace( $src, $varValue, $value ); - } - wfProfileOut( __METHOD__ ); - return $value; - } -} - -/** - * Template-filler skin base class - * Formerly generic PHPTal (http://phptal.sourceforge.net/) skin - * Based on Brion's smarty skin - * @copyright Copyright © Gabriel Wicke -- http://www.aulinx.de/ - * - * @todo Needs some serious refactoring into functions that correspond - * to the computations individual esi snippets need. Most importantly no body - * parsing for most of those of course. - * - * @ingroup Skins - */ -class SkinTemplate extends Skin { - /** - * @var string Name of our skin, it probably needs to be all lower case. - * Child classes should override the default. - */ - public $skinname = 'monobook'; - - /** - * @var string For QuickTemplate, the name of the subclass which will - * actually fill the template. Child classes should override the default. - */ - public $template = 'QuickTemplate'; - - /** - * Add specific styles for this skin - * - * @param OutputPage $out - */ - function setupSkinUserCss( OutputPage $out ) { - $out->addModuleStyles( array( - 'mediawiki.legacy.shared', - 'mediawiki.legacy.commonPrint', - 'mediawiki.ui.button' - ) ); - } - - /** - * Create the template engine object; we feed it a bunch of data - * and eventually it spits out some HTML. Should have interface - * roughly equivalent to PHPTAL 0.7. - * - * @param string $classname - * @param bool|string $repository Subdirectory where we keep template files - * @param bool|string $cache_dir - * @return QuickTemplate - * @private - */ - function setupTemplate( $classname, $repository = false, $cache_dir = false ) { - return new $classname( $this->getConfig() ); - } - - /** - * Generates array of language links for the current page - * - * @return array - */ - public function getLanguages() { - global $wgHideInterlanguageLinks; - if ( $wgHideInterlanguageLinks ) { - return array(); - } - - $userLang = $this->getLanguage(); - $languageLinks = array(); - - foreach ( $this->getOutput()->getLanguageLinks() as $languageLinkText ) { - $languageLinkParts = explode( ':', $languageLinkText, 2 ); - $class = 'interlanguage-link interwiki-' . $languageLinkParts[0]; - unset( $languageLinkParts ); - - $languageLinkTitle = Title::newFromText( $languageLinkText ); - if ( $languageLinkTitle ) { - $ilInterwikiCode = $languageLinkTitle->getInterwiki(); - $ilLangName = Language::fetchLanguageName( $ilInterwikiCode ); - - if ( strval( $ilLangName ) === '' ) { - $ilDisplayTextMsg = wfMessage( "interlanguage-link-$ilInterwikiCode" ); - if ( !$ilDisplayTextMsg->isDisabled() ) { - // Use custom MW message for the display text - $ilLangName = $ilDisplayTextMsg->text(); - } else { - // Last resort: fallback to the language link target - $ilLangName = $languageLinkText; - } - } else { - // Use the language autonym as display text - $ilLangName = $this->formatLanguageName( $ilLangName ); - } - - // CLDR extension or similar is required to localize the language name; - // otherwise we'll end up with the autonym again. - $ilLangLocalName = Language::fetchLanguageName( - $ilInterwikiCode, - $userLang->getCode() - ); - - $languageLinkTitleText = $languageLinkTitle->getText(); - if ( $ilLangLocalName === '' ) { - $ilFriendlySiteName = wfMessage( "interlanguage-link-sitename-$ilInterwikiCode" ); - if ( !$ilFriendlySiteName->isDisabled() ) { - if ( $languageLinkTitleText === '' ) { - $ilTitle = wfMessage( - 'interlanguage-link-title-nonlangonly', - $ilFriendlySiteName->text() - )->text(); - } else { - $ilTitle = wfMessage( - 'interlanguage-link-title-nonlang', - $languageLinkTitleText, - $ilFriendlySiteName->text() - )->text(); - } - } else { - // we have nothing friendly to put in the title, so fall back to - // displaying the interlanguage link itself in the title text - // (similar to what is done in page content) - $ilTitle = $languageLinkTitle->getInterwiki() . - ":$languageLinkTitleText"; - } - } elseif ( $languageLinkTitleText === '' ) { - $ilTitle = wfMessage( - 'interlanguage-link-title-langonly', - $ilLangLocalName - )->text(); - } else { - $ilTitle = wfMessage( - 'interlanguage-link-title', - $languageLinkTitleText, - $ilLangLocalName - )->text(); - } - - $ilInterwikiCodeBCP47 = wfBCP47( $ilInterwikiCode ); - $languageLink = array( - 'href' => $languageLinkTitle->getFullURL(), - 'text' => $ilLangName, - 'title' => $ilTitle, - 'class' => $class, - 'lang' => $ilInterwikiCodeBCP47, - 'hreflang' => $ilInterwikiCodeBCP47, - ); - wfRunHooks( - 'SkinTemplateGetLanguageLink', - array( &$languageLink, $languageLinkTitle, $this->getTitle() ) - ); - $languageLinks[] = $languageLink; - } - } - - return $languageLinks; - } - - protected function setupTemplateForOutput() { - wfProfileIn( __METHOD__ ); - - $request = $this->getRequest(); - $user = $this->getUser(); - $title = $this->getTitle(); - - wfProfileIn( __METHOD__ . '-init' ); - $tpl = $this->setupTemplate( $this->template, 'skins' ); - wfProfileOut( __METHOD__ . '-init' ); - - wfProfileIn( __METHOD__ . '-stuff' ); - $this->thispage = $title->getPrefixedDBkey(); - $this->titletxt = $title->getPrefixedText(); - $this->userpage = $user->getUserPage()->getPrefixedText(); - $query = array(); - if ( !$request->wasPosted() ) { - $query = $request->getValues(); - unset( $query['title'] ); - unset( $query['returnto'] ); - unset( $query['returntoquery'] ); - } - $this->thisquery = wfArrayToCgi( $query ); - $this->loggedin = $user->isLoggedIn(); - $this->username = $user->getName(); - - if ( $this->loggedin || $this->showIPinHeader() ) { - $this->userpageUrlDetails = self::makeUrlDetails( $this->userpage ); - } else { - # This won't be used in the standard skins, but we define it to preserve the interface - # To save time, we check for existence - $this->userpageUrlDetails = self::makeKnownUrlDetails( $this->userpage ); - } - - wfProfileOut( __METHOD__ . '-stuff' ); - - wfProfileOut( __METHOD__ ); - - return $tpl; - } - - /** - * initialize various variables and generate the template - * - * @param OutputPage $out - */ - function outputPage( OutputPage $out = null ) { - wfProfileIn( __METHOD__ ); - Profiler::instance()->setTemplated( true ); - - $oldContext = null; - if ( $out !== null ) { - // @todo Add wfDeprecated in 1.20 - $oldContext = $this->getContext(); - $this->setContext( $out->getContext() ); - } - - $out = $this->getOutput(); - - wfProfileIn( __METHOD__ . '-init' ); - $this->initPage( $out ); - wfProfileOut( __METHOD__ . '-init' ); - $tpl = $this->prepareQuickTemplate( $out ); - // execute template - wfProfileIn( __METHOD__ . '-execute' ); - $res = $tpl->execute(); - wfProfileOut( __METHOD__ . '-execute' ); - - // result may be an error - $this->printOrError( $res ); - - if ( $oldContext ) { - $this->setContext( $oldContext ); - } - - wfProfileOut( __METHOD__ ); - } - - /** - * initialize various variables and generate the template - * - * @since 1.23 - * @return QuickTemplate The template to be executed by outputPage - */ - protected function prepareQuickTemplate() { - global $wgContLang, $wgScript, $wgStylePath, $wgMimeType, $wgJsMimeType, - $wgDisableCounters, $wgSitename, $wgLogo, $wgMaxCredits, - $wgShowCreditsIfMax, $wgPageShowWatchingUsers, $wgArticlePath, - $wgScriptPath, $wgServer; - - wfProfileIn( __METHOD__ ); - - $title = $this->getTitle(); - $request = $this->getRequest(); - $out = $this->getOutput(); - $tpl = $this->setupTemplateForOutput(); - - wfProfileIn( __METHOD__ . '-stuff2' ); - $tpl->set( 'title', $out->getPageTitle() ); - $tpl->set( 'pagetitle', $out->getHTMLTitle() ); - $tpl->set( 'displaytitle', $out->mPageLinkTitle ); - - $tpl->setRef( 'thispage', $this->thispage ); - $tpl->setRef( 'titleprefixeddbkey', $this->thispage ); - $tpl->set( 'titletext', $title->getText() ); - $tpl->set( 'articleid', $title->getArticleID() ); - - $tpl->set( 'isarticle', $out->isArticle() ); - - $subpagestr = $this->subPageSubtitle(); - if ( $subpagestr !== '' ) { - $subpagestr = '' . $subpagestr . ''; - } - $tpl->set( 'subtitle', $subpagestr . $out->getSubtitle() ); - - $undelete = $this->getUndeleteLink(); - if ( $undelete === '' ) { - $tpl->set( 'undelete', '' ); - } else { - $tpl->set( 'undelete', '' . $undelete . '' ); - } - - $tpl->set( 'catlinks', $this->getCategories() ); - if ( $out->isSyndicated() ) { - $feeds = array(); - foreach ( $out->getSyndicationLinks() as $format => $link ) { - $feeds[$format] = array( - // Messages: feed-atom, feed-rss - 'text' => $this->msg( "feed-$format" )->text(), - 'href' => $link - ); - } - $tpl->setRef( 'feeds', $feeds ); - } else { - $tpl->set( 'feeds', false ); - } - - $tpl->setRef( 'mimetype', $wgMimeType ); - $tpl->setRef( 'jsmimetype', $wgJsMimeType ); - $tpl->set( 'charset', 'UTF-8' ); - $tpl->setRef( 'wgScript', $wgScript ); - $tpl->setRef( 'skinname', $this->skinname ); - $tpl->set( 'skinclass', get_class( $this ) ); - $tpl->setRef( 'skin', $this ); - $tpl->setRef( 'stylename', $this->stylename ); - $tpl->set( 'printable', $out->isPrintable() ); - $tpl->set( 'handheld', $request->getBool( 'handheld' ) ); - $tpl->setRef( 'loggedin', $this->loggedin ); - $tpl->set( 'notspecialpage', !$title->isSpecialPage() ); - $tpl->set( 'searchaction', $this->escapeSearchLink() ); - $tpl->set( 'searchtitle', SpecialPage::getTitleFor( 'Search' )->getPrefixedDBkey() ); - $tpl->set( 'search', trim( $request->getVal( 'search' ) ) ); - $tpl->setRef( 'stylepath', $wgStylePath ); - $tpl->setRef( 'articlepath', $wgArticlePath ); - $tpl->setRef( 'scriptpath', $wgScriptPath ); - $tpl->setRef( 'serverurl', $wgServer ); - $tpl->setRef( 'logopath', $wgLogo ); - $tpl->setRef( 'sitename', $wgSitename ); - - $userLang = $this->getLanguage(); - $userLangCode = $userLang->getHtmlCode(); - $userLangDir = $userLang->getDir(); - - $tpl->set( 'lang', $userLangCode ); - $tpl->set( 'dir', $userLangDir ); - $tpl->set( 'rtl', $userLang->isRTL() ); - - $tpl->set( 'capitalizeallnouns', $userLang->capitalizeAllNouns() ? ' capitalize-all-nouns' : '' ); - $tpl->set( 'showjumplinks', true ); // showjumplinks preference has been removed - $tpl->set( 'username', $this->loggedin ? $this->username : null ); - $tpl->setRef( 'userpage', $this->userpage ); - $tpl->setRef( 'userpageurl', $this->userpageUrlDetails['href'] ); - $tpl->set( 'userlang', $userLangCode ); - - // Users can have their language set differently than the - // content of the wiki. For these users, tell the web browser - // that interface elements are in a different language. - $tpl->set( 'userlangattributes', '' ); - $tpl->set( 'specialpageattributes', '' ); # obsolete - // Used by VectorBeta to insert HTML before content but after the - // heading for the page title. Defaults to empty string. - $tpl->set( 'prebodyhtml', '' ); - - if ( $userLangCode !== $wgContLang->getHtmlCode() || $userLangDir !== $wgContLang->getDir() ) { - $escUserlang = htmlspecialchars( $userLangCode ); - $escUserdir = htmlspecialchars( $userLangDir ); - // Attributes must be in double quotes because htmlspecialchars() doesn't - // escape single quotes - $attrs = " lang=\"$escUserlang\" dir=\"$escUserdir\""; - $tpl->set( 'userlangattributes', $attrs ); - } - - wfProfileOut( __METHOD__ . '-stuff2' ); - - wfProfileIn( __METHOD__ . '-stuff3' ); - $tpl->set( 'newtalk', $this->getNewtalks() ); - $tpl->set( 'logo', $this->logoText() ); - - $tpl->set( 'copyright', false ); - $tpl->set( 'viewcount', false ); - $tpl->set( 'lastmod', false ); - $tpl->set( 'credits', false ); - $tpl->set( 'numberofwatchingusers', false ); - if ( $out->isArticle() && $title->exists() ) { - if ( $this->isRevisionCurrent() ) { - if ( !$wgDisableCounters ) { - $viewcount = $this->getWikiPage()->getCount(); - if ( $viewcount ) { - $tpl->set( 'viewcount', $this->msg( 'viewcount' )->numParams( $viewcount )->parse() ); - } - } - - if ( $wgPageShowWatchingUsers ) { - $dbr = wfGetDB( DB_SLAVE ); - $num = $dbr->selectField( 'watchlist', 'COUNT(*)', - array( 'wl_title' => $title->getDBkey(), 'wl_namespace' => $title->getNamespace() ), - __METHOD__ - ); - if ( $num > 0 ) { - $tpl->set( 'numberofwatchingusers', - $this->msg( 'number_of_watching_users_pageview' )->numParams( $num )->parse() - ); - } - } - - if ( $wgMaxCredits != 0 ) { - $tpl->set( 'credits', Action::factory( 'credits', $this->getWikiPage(), - $this->getContext() )->getCredits( $wgMaxCredits, $wgShowCreditsIfMax ) ); - } else { - $tpl->set( 'lastmod', $this->lastModified() ); - } - } - $tpl->set( 'copyright', $this->getCopyright() ); - } - wfProfileOut( __METHOD__ . '-stuff3' ); - - wfProfileIn( __METHOD__ . '-stuff4' ); - $tpl->set( 'copyrightico', $this->getCopyrightIcon() ); - $tpl->set( 'poweredbyico', $this->getPoweredBy() ); - $tpl->set( 'disclaimer', $this->disclaimerLink() ); - $tpl->set( 'privacy', $this->privacyLink() ); - $tpl->set( 'about', $this->aboutLink() ); - - $tpl->set( 'footerlinks', array( - 'info' => array( - 'lastmod', - 'viewcount', - 'numberofwatchingusers', - 'credits', - 'copyright', - ), - 'places' => array( - 'privacy', - 'about', - 'disclaimer', - ), - ) ); - - global $wgFooterIcons; - $tpl->set( 'footericons', $wgFooterIcons ); - foreach ( $tpl->data['footericons'] as $footerIconsKey => &$footerIconsBlock ) { - if ( count( $footerIconsBlock ) > 0 ) { - foreach ( $footerIconsBlock as &$footerIcon ) { - if ( isset( $footerIcon['src'] ) ) { - if ( !isset( $footerIcon['width'] ) ) { - $footerIcon['width'] = 88; - } - if ( !isset( $footerIcon['height'] ) ) { - $footerIcon['height'] = 31; - } - } - } - } else { - unset( $tpl->data['footericons'][$footerIconsKey] ); - } - } - - $tpl->set( 'sitenotice', $this->getSiteNotice() ); - $tpl->set( 'bottomscripts', $this->bottomScripts() ); - $tpl->set( 'printfooter', $this->printSource() ); - - # An ID that includes the actual body text; without categories, contentSub, ... - $realBodyAttribs = array( 'id' => 'mw-content-text' ); - - # Add a mw-content-ltr/rtl class to be able to style based on text direction - # when the content is different from the UI language, i.e.: - # not for special pages or file pages AND only when viewing AND if the page exists - # (or is in MW namespace, because that has default content) - if ( !in_array( $title->getNamespace(), array( NS_SPECIAL, NS_FILE ) ) && - Action::getActionName( $this ) === 'view' && - ( $title->exists() || $title->getNamespace() == NS_MEDIAWIKI ) ) { - $pageLang = $title->getPageViewLanguage(); - $realBodyAttribs['lang'] = $pageLang->getHtmlCode(); - $realBodyAttribs['dir'] = $pageLang->getDir(); - $realBodyAttribs['class'] = 'mw-content-' . $pageLang->getDir(); - } - - $out->mBodytext = Html::rawElement( 'div', $realBodyAttribs, $out->mBodytext ); - $tpl->setRef( 'bodytext', $out->mBodytext ); - - $language_urls = $this->getLanguages(); - if ( count( $language_urls ) ) { - $tpl->setRef( 'language_urls', $language_urls ); - } else { - $tpl->set( 'language_urls', false ); - } - wfProfileOut( __METHOD__ . '-stuff4' ); - - wfProfileIn( __METHOD__ . '-stuff5' ); - # Personal toolbar - $tpl->set( 'personal_urls', $this->buildPersonalUrls() ); - $content_navigation = $this->buildContentNavigationUrls(); - $content_actions = $this->buildContentActionUrls( $content_navigation ); - $tpl->setRef( 'content_navigation', $content_navigation ); - $tpl->setRef( 'content_actions', $content_actions ); - - $tpl->set( 'sidebar', $this->buildSidebar() ); - $tpl->set( 'nav_urls', $this->buildNavUrls() ); - - // Set the head scripts near the end, in case the above actions resulted in added scripts - $tpl->set( 'headelement', $out->headElement( $this ) ); - - $tpl->set( 'debug', '' ); - $tpl->set( 'debughtml', $this->generateDebugHTML() ); - $tpl->set( 'reporttime', wfReportTime() ); - - // original version by hansm - if ( !wfRunHooks( 'SkinTemplateOutputPageBeforeExec', array( &$this, &$tpl ) ) ) { - wfDebug( __METHOD__ . ": Hook SkinTemplateOutputPageBeforeExec broke outputPage execution!\n" ); - } - - // Set the bodytext to another key so that skins can just output it on it's own - // and output printfooter and debughtml separately - $tpl->set( 'bodycontent', $tpl->data['bodytext'] ); - - // Append printfooter and debughtml onto bodytext so that skins that - // were already using bodytext before they were split out don't suddenly - // start not outputting information. - $tpl->data['bodytext'] .= Html::rawElement( - 'div', - array( 'class' => 'printfooter' ), - "\n{$tpl->data['printfooter']}" - ) . "\n"; - $tpl->data['bodytext'] .= $tpl->data['debughtml']; - - // allow extensions adding stuff after the page content. - // See Skin::afterContentHook() for further documentation. - $tpl->set( 'dataAfterContent', $this->afterContentHook() ); - wfProfileOut( __METHOD__ . '-stuff5' ); - - wfProfileOut( __METHOD__ ); - return $tpl; - } - - /** - * Get the HTML for the p-personal list - * @return string - */ - public function getPersonalToolsList() { - $tpl = $this->setupTemplateForOutput(); - $tpl->set( 'personal_urls', $this->buildPersonalUrls() ); - $html = ''; - foreach ( $tpl->getPersonalTools() as $key => $item ) { - $html .= $tpl->makeListItem( $key, $item ); - } - return $html; - } - - /** - * Format language name for use in sidebar interlanguage links list. - * By default it is capitalized. - * - * @param string $name Language name, e.g. "English" or "español" - * @return string - * @private - */ - function formatLanguageName( $name ) { - return $this->getLanguage()->ucfirst( $name ); - } - - /** - * Output the string, or print error message if it's - * an error object of the appropriate type. - * For the base class, assume strings all around. - * - * @param string $str - * @private - */ - function printOrError( $str ) { - echo $str; - } - - /** - * Output a boolean indicating if buildPersonalUrls should output separate - * login and create account links or output a combined link - * By default we simply return a global config setting that affects most skins - * This is setup as a method so that like with $wgLogo and getLogo() a skin - * can override this setting and always output one or the other if it has - * a reason it can't output one of the two modes. - * @return bool - */ - function useCombinedLoginLink() { - global $wgUseCombinedLoginLink; - return $wgUseCombinedLoginLink; - } - - /** - * build array of urls for personal toolbar - * @return array - */ - protected function buildPersonalUrls() { - $title = $this->getTitle(); - $request = $this->getRequest(); - $pageurl = $title->getLocalURL(); - wfProfileIn( __METHOD__ ); - - /* set up the default links for the personal toolbar */ - $personal_urls = array(); - - # Due to bug 32276, if a user does not have read permissions, - # $this->getTitle() will just give Special:Badtitle, which is - # not especially useful as a returnto parameter. Use the title - # from the request instead, if there was one. - if ( $this->getUser()->isAllowed( 'read' ) ) { - $page = $this->getTitle(); - } else { - $page = Title::newFromText( $request->getVal( 'title', '' ) ); - } - $page = $request->getVal( 'returnto', $page ); - $a = array(); - if ( strval( $page ) !== '' ) { - $a['returnto'] = $page; - $query = $request->getVal( 'returntoquery', $this->thisquery ); - if ( $query != '' ) { - $a['returntoquery'] = $query; - } - } - - $returnto = wfArrayToCgi( $a ); - if ( $this->loggedin ) { - $personal_urls['userpage'] = array( - 'text' => $this->username, - 'href' => &$this->userpageUrlDetails['href'], - 'class' => $this->userpageUrlDetails['exists'] ? false : 'new', - 'active' => ( $this->userpageUrlDetails['href'] == $pageurl ), - 'dir' => 'auto' - ); - $usertalkUrlDetails = $this->makeTalkUrlDetails( $this->userpage ); - $personal_urls['mytalk'] = array( - 'text' => $this->msg( 'mytalk' )->text(), - 'href' => &$usertalkUrlDetails['href'], - 'class' => $usertalkUrlDetails['exists'] ? false : 'new', - 'active' => ( $usertalkUrlDetails['href'] == $pageurl ) - ); - $href = self::makeSpecialUrl( 'Preferences' ); - $personal_urls['preferences'] = array( - 'text' => $this->msg( 'mypreferences' )->text(), - 'href' => $href, - 'active' => ( $href == $pageurl ) - ); - - if ( $this->getUser()->isAllowed( 'viewmywatchlist' ) ) { - $href = self::makeSpecialUrl( 'Watchlist' ); - $personal_urls['watchlist'] = array( - 'text' => $this->msg( 'mywatchlist' )->text(), - 'href' => $href, - 'active' => ( $href == $pageurl ) - ); - } - - # We need to do an explicit check for Special:Contributions, as we - # have to match both the title, and the target, which could come - # from request values (Special:Contributions?target=Jimbo_Wales) - # or be specified in "sub page" form - # (Special:Contributions/Jimbo_Wales). The plot - # thickens, because the Title object is altered for special pages, - # so it doesn't contain the original alias-with-subpage. - $origTitle = Title::newFromText( $request->getText( 'title' ) ); - if ( $origTitle instanceof Title && $origTitle->isSpecialPage() ) { - list( $spName, $spPar ) = SpecialPageFactory::resolveAlias( $origTitle->getText() ); - $active = $spName == 'Contributions' - && ( ( $spPar && $spPar == $this->username ) - || $request->getText( 'target' ) == $this->username ); - } else { - $active = false; - } - - $href = self::makeSpecialUrlSubpage( 'Contributions', $this->username ); - $personal_urls['mycontris'] = array( - 'text' => $this->msg( 'mycontris' )->text(), - 'href' => $href, - 'active' => $active - ); - $personal_urls['logout'] = array( - 'text' => $this->msg( 'pt-userlogout' )->text(), - 'href' => self::makeSpecialUrl( 'Userlogout', - // userlogout link must always contain an & character, otherwise we might not be able - // to detect a buggy precaching proxy (bug 17790) - $title->isSpecial( 'Preferences' ) ? 'noreturnto' : $returnto - ), - 'active' => false - ); - } else { - $useCombinedLoginLink = $this->useCombinedLoginLink(); - $loginlink = $this->getUser()->isAllowed( 'createaccount' ) && $useCombinedLoginLink - ? 'nav-login-createaccount' - : 'pt-login'; - $is_signup = $request->getText( 'type' ) == 'signup'; - - $login_url = array( - 'text' => $this->msg( $loginlink )->text(), - 'href' => self::makeSpecialUrl( 'Userlogin', $returnto ), - 'active' => $title->isSpecial( 'Userlogin' ) - && ( $loginlink == 'nav-login-createaccount' || !$is_signup ), - ); - $createaccount_url = array( - 'text' => $this->msg( 'pt-createaccount' )->text(), - 'href' => self::makeSpecialUrl( 'Userlogin', "$returnto&type=signup" ), - 'active' => $title->isSpecial( 'Userlogin' ) && $is_signup, - ); - - if ( $this->showIPinHeader() ) { - $href = &$this->userpageUrlDetails['href']; - $personal_urls['anonuserpage'] = array( - 'text' => $this->username, - 'href' => $href, - 'class' => $this->userpageUrlDetails['exists'] ? false : 'new', - 'active' => ( $pageurl == $href ) - ); - $usertalkUrlDetails = $this->makeTalkUrlDetails( $this->userpage ); - $href = &$usertalkUrlDetails['href']; - $personal_urls['anontalk'] = array( - 'text' => $this->msg( 'anontalk' )->text(), - 'href' => $href, - 'class' => $usertalkUrlDetails['exists'] ? false : 'new', - 'active' => ( $pageurl == $href ) - ); - } - - if ( $this->getUser()->isAllowed( 'createaccount' ) && !$useCombinedLoginLink ) { - $personal_urls['createaccount'] = $createaccount_url; - } - - $personal_urls['login'] = $login_url; - } - - wfRunHooks( 'PersonalUrls', array( &$personal_urls, &$title, $this ) ); - wfProfileOut( __METHOD__ ); - return $personal_urls; - } - - /** - * Builds an array with tab definition - * - * @param Title $title Page Where the tab links to - * @param string|array $message Message key or an array of message keys (will fall back) - * @param bool $selected Display the tab as selected - * @param string $query Query string attached to tab URL - * @param bool $checkEdit Check if $title exists and mark with .new if one doesn't - * - * @return array - */ - function tabAction( $title, $message, $selected, $query = '', $checkEdit = false ) { - $classes = array(); - if ( $selected ) { - $classes[] = 'selected'; - } - if ( $checkEdit && !$title->isKnown() ) { - $classes[] = 'new'; - if ( $query !== '' ) { - $query = 'action=edit&redlink=1&' . $query; - } else { - $query = 'action=edit&redlink=1'; - } - } - - // wfMessageFallback will nicely accept $message as an array of fallbacks - // or just a single key - $msg = wfMessageFallback( $message )->setContext( $this->getContext() ); - if ( is_array( $message ) ) { - // for hook compatibility just keep the last message name - $message = end( $message ); - } - if ( $msg->exists() ) { - $text = $msg->text(); - } else { - global $wgContLang; - $text = $wgContLang->getFormattedNsText( - MWNamespace::getSubject( $title->getNamespace() ) ); - } - - $result = array(); - if ( !wfRunHooks( 'SkinTemplateTabAction', array( &$this, - $title, $message, $selected, $checkEdit, - &$classes, &$query, &$text, &$result ) ) ) { - return $result; - } - - return array( - 'class' => implode( ' ', $classes ), - 'text' => $text, - 'href' => $title->getLocalURL( $query ), - 'primary' => true ); - } - - function makeTalkUrlDetails( $name, $urlaction = '' ) { - $title = Title::newFromText( $name ); - if ( !is_object( $title ) ) { - throw new MWException( __METHOD__ . " given invalid pagename $name" ); - } - $title = $title->getTalkPage(); - self::checkTitle( $title, $name ); - return array( - 'href' => $title->getLocalURL( $urlaction ), - 'exists' => $title->getArticleID() != 0, - ); - } - - function makeArticleUrlDetails( $name, $urlaction = '' ) { - $title = Title::newFromText( $name ); - $title = $title->getSubjectPage(); - self::checkTitle( $title, $name ); - return array( - 'href' => $title->getLocalURL( $urlaction ), - 'exists' => $title->getArticleID() != 0, - ); - } - - /** - * a structured array of links usually used for the tabs in a skin - * - * There are 4 standard sections - * namespaces: Used for namespace tabs like special, page, and talk namespaces - * views: Used for primary page views like read, edit, history - * actions: Used for most extra page actions like deletion, protection, etc... - * variants: Used to list the language variants for the page - * - * Each section's value is a key/value array of links for that section. - * The links themselves have these common keys: - * - class: The css classes to apply to the tab - * - text: The text to display on the tab - * - href: The href for the tab to point to - * - rel: An optional rel= for the tab's link - * - redundant: If true the tab will be dropped in skins using content_actions - * this is useful for tabs like "Read" which only have meaning in skins that - * take special meaning from the grouped structure of content_navigation - * - * Views also have an extra key which can be used: - * - primary: If this is not true skins like vector may try to hide the tab - * when the user has limited space in their browser window - * - * content_navigation using code also expects these ids to be present on the - * links, however these are usually automatically generated by SkinTemplate - * itself and are not necessary when using a hook. The only things these may - * matter to are people modifying content_navigation after it's initial creation: - * - id: A "preferred" id, most skins are best off outputting this preferred - * id for best compatibility. - * - tooltiponly: This is set to true for some tabs in cases where the system - * believes that the accesskey should not be added to the tab. - * - * @return array - */ - protected function buildContentNavigationUrls() { - global $wgDisableLangConversion; - - wfProfileIn( __METHOD__ ); - - // Display tabs for the relevant title rather than always the title itself - $title = $this->getRelevantTitle(); - $onPage = $title->equals( $this->getTitle() ); - - $out = $this->getOutput(); - $request = $this->getRequest(); - $user = $this->getUser(); - - $content_navigation = array( - 'namespaces' => array(), - 'views' => array(), - 'actions' => array(), - 'variants' => array() - ); - - // parameters - $action = $request->getVal( 'action', 'view' ); - - $userCanRead = $title->quickUserCan( 'read', $user ); - - $preventActiveTabs = false; - wfRunHooks( 'SkinTemplatePreventOtherActiveTabs', array( &$this, &$preventActiveTabs ) ); - - // Checks if page is some kind of content - if ( $title->canExist() ) { - // Gets page objects for the related namespaces - $subjectPage = $title->getSubjectPage(); - $talkPage = $title->getTalkPage(); - - // Determines if this is a talk page - $isTalk = $title->isTalkPage(); - - // Generates XML IDs from namespace names - $subjectId = $title->getNamespaceKey( '' ); - - if ( $subjectId == 'main' ) { - $talkId = 'talk'; - } else { - $talkId = "{$subjectId}_talk"; - } - - $skname = $this->skinname; - - // Adds namespace links - $subjectMsg = array( "nstab-$subjectId" ); - if ( $subjectPage->isMainPage() ) { - array_unshift( $subjectMsg, 'mainpage-nstab' ); - } - $content_navigation['namespaces'][$subjectId] = $this->tabAction( - $subjectPage, $subjectMsg, !$isTalk && !$preventActiveTabs, '', $userCanRead - ); - $content_navigation['namespaces'][$subjectId]['context'] = 'subject'; - $content_navigation['namespaces'][$talkId] = $this->tabAction( - $talkPage, array( "nstab-$talkId", 'talk' ), $isTalk && !$preventActiveTabs, '', $userCanRead - ); - $content_navigation['namespaces'][$talkId]['context'] = 'talk'; - - if ( $userCanRead ) { - $isForeignFile = $title->inNamespace( NS_FILE ) && $this->canUseWikiPage() && - $this->getWikiPage() instanceof WikiFilePage && !$this->getWikiPage()->isLocal(); - - // Adds view view link - if ( $title->exists() || $isForeignFile ) { - $content_navigation['views']['view'] = $this->tabAction( - $isTalk ? $talkPage : $subjectPage, - array( "$skname-view-view", 'view' ), - ( $onPage && ( $action == 'view' || $action == 'purge' ) ), '', true - ); - // signal to hide this from simple content_actions - $content_navigation['views']['view']['redundant'] = true; - } - - // If it is a non-local file, show a link to the file in its own repository - if ( $isForeignFile ) { - $file = $this->getWikiPage()->getFile(); - $content_navigation['views']['view-foreign'] = array( - 'class' => '', - 'text' => wfMessageFallback( "$skname-view-foreign", 'view-foreign' )-> - setContext( $this->getContext() )-> - params( $file->getRepo()->getDisplayName() )->text(), - 'href' => $file->getDescriptionUrl(), - 'primary' => false, - ); - } - - wfProfileIn( __METHOD__ . '-edit' ); - - // Checks if user can edit the current page if it exists or create it otherwise - if ( $title->quickUserCan( 'edit', $user ) - && ( $title->exists() || $title->quickUserCan( 'create', $user ) ) - ) { - // Builds CSS class for talk page links - $isTalkClass = $isTalk ? ' istalk' : ''; - // Whether the user is editing the page - $isEditing = $onPage && ( $action == 'edit' || $action == 'submit' ); - // Whether to show the "Add a new section" tab - // Checks if this is a current rev of talk page and is not forced to be hidden - $showNewSection = !$out->forceHideNewSectionLink() - && ( ( $isTalk && $this->isRevisionCurrent() ) || $out->showNewSectionLink() ); - $section = $request->getVal( 'section' ); - - if ( $title->exists() - || ( $title->getNamespace() == NS_MEDIAWIKI - && $title->getDefaultMessageText() !== false - ) - ) { - $msgKey = $isForeignFile ? 'edit-local' : 'edit'; - } else { - $msgKey = $isForeignFile ? 'create-local' : 'create'; - } - $content_navigation['views']['edit'] = array( - 'class' => ( $isEditing && ( $section !== 'new' || !$showNewSection ) - ? 'selected' - : '' - ) . $isTalkClass, - 'text' => wfMessageFallback( "$skname-view-$msgKey", $msgKey ) - ->setContext( $this->getContext() )->text(), - 'href' => $title->getLocalURL( $this->editUrlOptions() ), - 'primary' => !$isForeignFile, // don't collapse this in vector - ); - - // section link - if ( $showNewSection ) { - // Adds new section link - //$content_navigation['actions']['addsection'] - $content_navigation['views']['addsection'] = array( - 'class' => ( $isEditing && $section == 'new' ) ? 'selected' : false, - 'text' => wfMessageFallback( "$skname-action-addsection", 'addsection' ) - ->setContext( $this->getContext() )->text(), - 'href' => $title->getLocalURL( 'action=edit§ion=new' ) - ); - } - // Checks if the page has some kind of viewable content - } elseif ( $title->hasSourceText() ) { - // Adds view source view link - $content_navigation['views']['viewsource'] = array( - 'class' => ( $onPage && $action == 'edit' ) ? 'selected' : false, - 'text' => wfMessageFallback( "$skname-action-viewsource", 'viewsource' ) - ->setContext( $this->getContext() )->text(), - 'href' => $title->getLocalURL( $this->editUrlOptions() ), - 'primary' => true, // don't collapse this in vector - ); - } - wfProfileOut( __METHOD__ . '-edit' ); - - wfProfileIn( __METHOD__ . '-live' ); - // Checks if the page exists - if ( $title->exists() ) { - // Adds history view link - $content_navigation['views']['history'] = array( - 'class' => ( $onPage && $action == 'history' ) ? 'selected' : false, - 'text' => wfMessageFallback( "$skname-view-history", 'history_short' ) - ->setContext( $this->getContext() )->text(), - 'href' => $title->getLocalURL( 'action=history' ), - 'rel' => 'archives', - ); - - if ( $title->quickUserCan( 'delete', $user ) ) { - $content_navigation['actions']['delete'] = array( - 'class' => ( $onPage && $action == 'delete' ) ? 'selected' : false, - 'text' => wfMessageFallback( "$skname-action-delete", 'delete' ) - ->setContext( $this->getContext() )->text(), - 'href' => $title->getLocalURL( 'action=delete' ) - ); - } - - if ( $title->quickUserCan( 'move', $user ) ) { - $moveTitle = SpecialPage::getTitleFor( 'Movepage', $title->getPrefixedDBkey() ); - $content_navigation['actions']['move'] = array( - 'class' => $this->getTitle()->isSpecial( 'Movepage' ) ? 'selected' : false, - 'text' => wfMessageFallback( "$skname-action-move", 'move' ) - ->setContext( $this->getContext() )->text(), - 'href' => $moveTitle->getLocalURL() - ); - } - } else { - // article doesn't exist or is deleted - if ( $user->isAllowed( 'deletedhistory' ) ) { - $n = $title->isDeleted(); - if ( $n ) { - $undelTitle = SpecialPage::getTitleFor( 'Undelete' ); - // If the user can't undelete but can view deleted - // history show them a "View .. deleted" tab instead. - $msgKey = $user->isAllowed( 'undelete' ) ? 'undelete' : 'viewdeleted'; - $content_navigation['actions']['undelete'] = array( - 'class' => $this->getTitle()->isSpecial( 'Undelete' ) ? 'selected' : false, - 'text' => wfMessageFallback( "$skname-action-$msgKey", "{$msgKey}_short" ) - ->setContext( $this->getContext() )->numParams( $n )->text(), - 'href' => $undelTitle->getLocalURL( array( 'target' => $title->getPrefixedDBkey() ) ) - ); - } - } - } - - if ( $title->quickUserCan( 'protect', $user ) && $title->getRestrictionTypes() && - MWNamespace::getRestrictionLevels( $title->getNamespace(), $user ) !== array( '' ) - ) { - $mode = $title->isProtected() ? 'unprotect' : 'protect'; - $content_navigation['actions'][$mode] = array( - 'class' => ( $onPage && $action == $mode ) ? 'selected' : false, - 'text' => wfMessageFallback( "$skname-action-$mode", $mode ) - ->setContext( $this->getContext() )->text(), - 'href' => $title->getLocalURL( "action=$mode" ) - ); - } - - wfProfileOut( __METHOD__ . '-live' ); - - // Checks if the user is logged in - if ( $this->loggedin && $user->isAllowedAll( 'viewmywatchlist', 'editmywatchlist' ) ) { - /** - * The following actions use messages which, if made particular to - * the any specific skins, would break the Ajax code which makes this - * action happen entirely inline. OutputPage::getJSVars - * defines a set of messages in a javascript object - and these - * messages are assumed to be global for all skins. Without making - * a change to that procedure these messages will have to remain as - * the global versions. - */ - $mode = $user->isWatched( $title ) ? 'unwatch' : 'watch'; - $token = WatchAction::getWatchToken( $title, $user, $mode ); - $content_navigation['actions'][$mode] = array( - 'class' => $onPage && ( $action == 'watch' || $action == 'unwatch' ) ? 'selected' : false, - // uses 'watch' or 'unwatch' message - 'text' => $this->msg( $mode )->text(), - 'href' => $title->getLocalURL( array( 'action' => $mode, 'token' => $token ) ) - ); - } - } - - wfRunHooks( 'SkinTemplateNavigation', array( &$this, &$content_navigation ) ); - - if ( $userCanRead && !$wgDisableLangConversion ) { - $pageLang = $title->getPageLanguage(); - // Gets list of language variants - $variants = $pageLang->getVariants(); - // Checks that language conversion is enabled and variants exist - // And if it is not in the special namespace - if ( count( $variants ) > 1 ) { - // Gets preferred variant (note that user preference is - // only possible for wiki content language variant) - $preferred = $pageLang->getPreferredVariant(); - if ( Action::getActionName( $this ) === 'view' ) { - $params = $request->getQueryValues(); - unset( $params['title'] ); - } else { - $params = array(); - } - // Loops over each variant - foreach ( $variants as $code ) { - // Gets variant name from language code - $varname = $pageLang->getVariantname( $code ); - // Appends variant link - $content_navigation['variants'][] = array( - 'class' => ( $code == $preferred ) ? 'selected' : false, - 'text' => $varname, - 'href' => $title->getLocalURL( array( 'variant' => $code ) + $params ), - 'lang' => wfBCP47( $code ), - 'hreflang' => wfBCP47( $code ), - ); - } - } - } - } else { - // If it's not content, it's got to be a special page - $content_navigation['namespaces']['special'] = array( - 'class' => 'selected', - 'text' => $this->msg( 'nstab-special' )->text(), - 'href' => $request->getRequestURL(), // @see: bug 2457, bug 2510 - 'context' => 'subject' - ); - - wfRunHooks( 'SkinTemplateNavigation::SpecialPage', - array( &$this, &$content_navigation ) ); - } - - // Equiv to SkinTemplateContentActions - wfRunHooks( 'SkinTemplateNavigation::Universal', array( &$this, &$content_navigation ) ); - - // Setup xml ids and tooltip info - foreach ( $content_navigation as $section => &$links ) { - foreach ( $links as $key => &$link ) { - $xmlID = $key; - if ( isset( $link['context'] ) && $link['context'] == 'subject' ) { - $xmlID = 'ca-nstab-' . $xmlID; - } elseif ( isset( $link['context'] ) && $link['context'] == 'talk' ) { - $xmlID = 'ca-talk'; - } elseif ( $section == 'variants' ) { - $xmlID = 'ca-varlang-' . $xmlID; - } else { - $xmlID = 'ca-' . $xmlID; - } - $link['id'] = $xmlID; - } - } - - # We don't want to give the watch tab an accesskey if the - # page is being edited, because that conflicts with the - # accesskey on the watch checkbox. We also don't want to - # give the edit tab an accesskey, because that's fairly - # superfluous and conflicts with an accesskey (Ctrl-E) often - # used for editing in Safari. - if ( in_array( $action, array( 'edit', 'submit' ) ) ) { - if ( isset( $content_navigation['views']['edit'] ) ) { - $content_navigation['views']['edit']['tooltiponly'] = true; - } - if ( isset( $content_navigation['actions']['watch'] ) ) { - $content_navigation['actions']['watch']['tooltiponly'] = true; - } - if ( isset( $content_navigation['actions']['unwatch'] ) ) { - $content_navigation['actions']['unwatch']['tooltiponly'] = true; - } - } - - wfProfileOut( __METHOD__ ); - - return $content_navigation; - } - - /** - * an array of edit links by default used for the tabs - * @param array $content_navigation - * @return array - */ - private function buildContentActionUrls( $content_navigation ) { - - wfProfileIn( __METHOD__ ); - - // content_actions has been replaced with content_navigation for backwards - // compatibility and also for skins that just want simple tabs content_actions - // is now built by flattening the content_navigation arrays into one - - $content_actions = array(); - - foreach ( $content_navigation as $links ) { - foreach ( $links as $key => $value ) { - if ( isset( $value['redundant'] ) && $value['redundant'] ) { - // Redundant tabs are dropped from content_actions - continue; - } - - // content_actions used to have ids built using the "ca-$key" pattern - // so the xmlID based id is much closer to the actual $key that we want - // for that reason we'll just strip out the ca- if present and use - // the latter potion of the "id" as the $key - if ( isset( $value['id'] ) && substr( $value['id'], 0, 3 ) == 'ca-' ) { - $key = substr( $value['id'], 3 ); - } - - if ( isset( $content_actions[$key] ) ) { - wfDebug( __METHOD__ . ": Found a duplicate key for $key while flattening " . - "content_navigation into content_actions.\n" ); - continue; - } - - $content_actions[$key] = $value; - } - } - - wfProfileOut( __METHOD__ ); - - return $content_actions; - } - - /** - * build array of common navigation links - * @return array - */ - protected function buildNavUrls() { - global $wgUploadNavigationUrl; - - wfProfileIn( __METHOD__ ); - - $out = $this->getOutput(); - $request = $this->getRequest(); - - $nav_urls = array(); - $nav_urls['mainpage'] = array( 'href' => self::makeMainPageUrl() ); - if ( $wgUploadNavigationUrl ) { - $nav_urls['upload'] = array( 'href' => $wgUploadNavigationUrl ); - } elseif ( UploadBase::isEnabled() && UploadBase::isAllowed( $this->getUser() ) === true ) { - $nav_urls['upload'] = array( 'href' => self::makeSpecialUrl( 'Upload' ) ); - } else { - $nav_urls['upload'] = false; - } - $nav_urls['specialpages'] = array( 'href' => self::makeSpecialUrl( 'Specialpages' ) ); - - $nav_urls['print'] = false; - $nav_urls['permalink'] = false; - $nav_urls['info'] = false; - $nav_urls['whatlinkshere'] = false; - $nav_urls['recentchangeslinked'] = false; - $nav_urls['contributions'] = false; - $nav_urls['log'] = false; - $nav_urls['blockip'] = false; - $nav_urls['emailuser'] = false; - $nav_urls['userrights'] = false; - - // A print stylesheet is attached to all pages, but nobody ever - // figures that out. :) Add a link... - if ( !$out->isPrintable() && ( $out->isArticle() || $this->getTitle()->isSpecialPage() ) ) { - $nav_urls['print'] = array( - 'text' => $this->msg( 'printableversion' )->text(), - 'href' => $this->getTitle()->getLocalURL( - $request->appendQueryValue( 'printable', 'yes', true ) ) - ); - } - - if ( $out->isArticle() ) { - // Also add a "permalink" while we're at it - $revid = $this->getRevisionId(); - if ( $revid ) { - $nav_urls['permalink'] = array( - 'text' => $this->msg( 'permalink' )->text(), - 'href' => $this->getTitle()->getLocalURL( "oldid=$revid" ) - ); - } - - // Use the copy of revision ID in case this undocumented, shady hook tries to mess with internals - wfRunHooks( 'SkinTemplateBuildNavUrlsNav_urlsAfterPermalink', - array( &$this, &$nav_urls, &$revid, &$revid ) ); - } - - if ( $out->isArticleRelated() ) { - $nav_urls['whatlinkshere'] = array( - 'href' => SpecialPage::getTitleFor( 'Whatlinkshere', $this->thispage )->getLocalURL() - ); - - $nav_urls['info'] = array( - 'text' => $this->msg( 'pageinfo-toolboxlink' )->text(), - 'href' => $this->getTitle()->getLocalURL( "action=info" ) - ); - - if ( $this->getTitle()->getArticleID() ) { - $nav_urls['recentchangeslinked'] = array( - 'href' => SpecialPage::getTitleFor( 'Recentchangeslinked', $this->thispage )->getLocalURL() - ); - } - } - - $user = $this->getRelevantUser(); - if ( $user ) { - $rootUser = $user->getName(); - - $nav_urls['contributions'] = array( - 'text' => $this->msg( 'contributions', $rootUser )->text(), - 'href' => self::makeSpecialUrlSubpage( 'Contributions', $rootUser ) - ); - - $nav_urls['log'] = array( - 'href' => self::makeSpecialUrlSubpage( 'Log', $rootUser ) - ); - - if ( $this->getUser()->isAllowed( 'block' ) ) { - $nav_urls['blockip'] = array( - 'text' => $this->msg( 'blockip', $rootUser )->text(), - 'href' => self::makeSpecialUrlSubpage( 'Block', $rootUser ) - ); - } - - if ( $this->showEmailUser( $user ) ) { - $nav_urls['emailuser'] = array( - 'href' => self::makeSpecialUrlSubpage( 'Emailuser', $rootUser ) - ); - } - - if ( !$user->isAnon() ) { - $sur = new UserrightsPage; - $sur->setContext( $this->getContext() ); - if ( $sur->userCanExecute( $this->getUser() ) ) { - $nav_urls['userrights'] = array( - 'href' => self::makeSpecialUrlSubpage( 'Userrights', $rootUser ) - ); - } - } - } - - wfProfileOut( __METHOD__ ); - return $nav_urls; - } - - /** - * Generate strings used for xml 'id' names - * @return string - */ - protected function getNameSpaceKey() { - return $this->getTitle()->getNamespaceKey(); - } -} - -/** - * Generic wrapper for template functions, with interface - * compatible with what we use of PHPTAL 0.7. - * @ingroup Skins - */ -abstract class QuickTemplate { - - /** @var Config $config */ - protected $config; - /** - * @var Config $config - */ - function __construct( Config $config = null ) { - $this->data = array(); - $this->translator = new MediaWikiI18N(); - if ( $config === null ) { - wfDebug( __METHOD__ . ' was called with no Config instance passed to it' ); - $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' ); - } - $this->config = $config; - } - - /** - * Sets the value $value to $name - * @param string $name - * @param mixed $value - */ - public function set( $name, $value ) { - $this->data[$name] = $value; - } - - /** - * Gets the template data requested - * @since 1.22 - * @param string $name Key for the data - * @param mixed $default Optional default (or null) - * @return mixed The value of the data requested or the deafult - */ - public function get( $name, $default = null ) { - if ( isset( $this->data[$name] ) ) { - return $this->data[$name]; - } else { - return $default; - } - } - - /** - * @param string $name - * @param mixed $value - */ - public function setRef( $name, &$value ) { - $this->data[$name] =& $value; - } - - /** - * @param MediaWikiI18N $t - */ - public function setTranslator( &$t ) { - $this->translator = &$t; - } - - /** - * Main function, used by classes that subclass QuickTemplate - * to show the actual HTML output - */ - abstract public function execute(); - - /** - * @private - * @param string $str - * @return string - */ - function text( $str ) { - echo htmlspecialchars( $this->data[$str] ); - } - - /** - * @private - * @param string $str - * @return string - */ - function html( $str ) { - echo $this->data[$str]; - } - - /** - * @private - * @param string $str - * @return string - */ - function msg( $str ) { - echo htmlspecialchars( $this->translator->translate( $str ) ); - } - - /** - * @private - * @param string $str - * @return string - */ - function msgHtml( $str ) { - echo $this->translator->translate( $str ); - } - - /** - * An ugly, ugly hack. - * @private - * @param string $str - * @return string - */ - function msgWiki( $str ) { - global $wgOut; - - $text = $this->translator->translate( $str ); - echo $wgOut->parse( $text ); - } - - /** - * @private - * @param string $str - * @return bool - */ - function haveData( $str ) { - return isset( $this->data[$str] ); - } - - /** - * @private - * - * @param string $str - * @return bool - */ - function haveMsg( $str ) { - $msg = $this->translator->translate( $str ); - return ( $msg != '-' ) && ( $msg != '' ); # ???? - } - - /** - * Get the Skin object related to this object - * - * @return Skin - */ - public function getSkin() { - return $this->data['skin']; - } - - /** - * Fetch the output of a QuickTemplate and return it - * - * @since 1.23 - * @return string - */ - public function getHTML() { - ob_start(); - $this->execute(); - $html = ob_get_contents(); - ob_end_clean(); - return $html; - } -} - -/** - * New base template for a skin's template extended from QuickTemplate - * this class features helper methods that provide common ways of interacting - * with the data stored in the QuickTemplate - */ -abstract class BaseTemplate extends QuickTemplate { - - /** - * Get a Message object with its context set - * - * @param string $name Message name - * @return Message - */ - public function getMsg( $name ) { - return $this->getSkin()->msg( $name ); - } - - function msg( $str ) { - echo $this->getMsg( $str )->escaped(); - } - - function msgHtml( $str ) { - echo $this->getMsg( $str )->text(); - } - - function msgWiki( $str ) { - echo $this->getMsg( $str )->parseAsBlock(); - } - - /** - * Create an array of common toolbox items from the data in the quicktemplate - * stored by SkinTemplate. - * The resulting array is built according to a format intended to be passed - * through makeListItem to generate the html. - * @return array - */ - function getToolbox() { - wfProfileIn( __METHOD__ ); - - $toolbox = array(); - if ( isset( $this->data['nav_urls']['whatlinkshere'] ) - && $this->data['nav_urls']['whatlinkshere'] - ) { - $toolbox['whatlinkshere'] = $this->data['nav_urls']['whatlinkshere']; - $toolbox['whatlinkshere']['id'] = 't-whatlinkshere'; - } - if ( isset( $this->data['nav_urls']['recentchangeslinked'] ) - && $this->data['nav_urls']['recentchangeslinked'] - ) { - $toolbox['recentchangeslinked'] = $this->data['nav_urls']['recentchangeslinked']; - $toolbox['recentchangeslinked']['msg'] = 'recentchangeslinked-toolbox'; - $toolbox['recentchangeslinked']['id'] = 't-recentchangeslinked'; - } - if ( isset( $this->data['feeds'] ) && $this->data['feeds'] ) { - $toolbox['feeds']['id'] = 'feedlinks'; - $toolbox['feeds']['links'] = array(); - foreach ( $this->data['feeds'] as $key => $feed ) { - $toolbox['feeds']['links'][$key] = $feed; - $toolbox['feeds']['links'][$key]['id'] = "feed-$key"; - $toolbox['feeds']['links'][$key]['rel'] = 'alternate'; - $toolbox['feeds']['links'][$key]['type'] = "application/{$key}+xml"; - $toolbox['feeds']['links'][$key]['class'] = 'feedlink'; - } - } - foreach ( array( 'contributions', 'log', 'blockip', 'emailuser', - 'userrights', 'upload', 'specialpages' ) as $special - ) { - if ( isset( $this->data['nav_urls'][$special] ) && $this->data['nav_urls'][$special] ) { - $toolbox[$special] = $this->data['nav_urls'][$special]; - $toolbox[$special]['id'] = "t-$special"; - } - } - if ( isset( $this->data['nav_urls']['print'] ) && $this->data['nav_urls']['print'] ) { - $toolbox['print'] = $this->data['nav_urls']['print']; - $toolbox['print']['id'] = 't-print'; - $toolbox['print']['rel'] = 'alternate'; - $toolbox['print']['msg'] = 'printableversion'; - } - if ( isset( $this->data['nav_urls']['permalink'] ) && $this->data['nav_urls']['permalink'] ) { - $toolbox['permalink'] = $this->data['nav_urls']['permalink']; - if ( $toolbox['permalink']['href'] === '' ) { - unset( $toolbox['permalink']['href'] ); - $toolbox['ispermalink']['tooltiponly'] = true; - $toolbox['ispermalink']['id'] = 't-ispermalink'; - $toolbox['ispermalink']['msg'] = 'permalink'; - } else { - $toolbox['permalink']['id'] = 't-permalink'; - } - } - if ( isset( $this->data['nav_urls']['info'] ) && $this->data['nav_urls']['info'] ) { - $toolbox['info'] = $this->data['nav_urls']['info']; - $toolbox['info']['id'] = 't-info'; - } - - wfRunHooks( 'BaseTemplateToolbox', array( &$this, &$toolbox ) ); - wfProfileOut( __METHOD__ ); - return $toolbox; - } - - /** - * Create an array of personal tools items from the data in the quicktemplate - * stored by SkinTemplate. - * The resulting array is built according to a format intended to be passed - * through makeListItem to generate the html. - * This is in reality the same list as already stored in personal_urls - * however it is reformatted so that you can just pass the individual items - * to makeListItem instead of hardcoding the element creation boilerplate. - * @return array - */ - function getPersonalTools() { - $personal_tools = array(); - foreach ( $this->get( 'personal_urls' ) as $key => $plink ) { - # The class on a personal_urls item is meant to go on the instead - # of the
  • so we have to use a single item "links" array instead - # of using most of the personal_url's keys directly. - $ptool = array( - 'links' => array( - array( 'single-id' => "pt-$key" ), - ), - 'id' => "pt-$key", - ); - if ( isset( $plink['active'] ) ) { - $ptool['active'] = $plink['active']; - } - foreach ( array( 'href', 'class', 'text', 'dir' ) as $k ) { - if ( isset( $plink[$k] ) ) { - $ptool['links'][0][$k] = $plink[$k]; - } - } - $personal_tools[$key] = $ptool; - } - return $personal_tools; - } - - function getSidebar( $options = array() ) { - // Force the rendering of the following portals - $sidebar = $this->data['sidebar']; - if ( !isset( $sidebar['SEARCH'] ) ) { - $sidebar['SEARCH'] = true; - } - if ( !isset( $sidebar['TOOLBOX'] ) ) { - $sidebar['TOOLBOX'] = true; - } - if ( !isset( $sidebar['LANGUAGES'] ) ) { - $sidebar['LANGUAGES'] = true; - } - - if ( !isset( $options['search'] ) || $options['search'] !== true ) { - unset( $sidebar['SEARCH'] ); - } - if ( isset( $options['toolbox'] ) && $options['toolbox'] === false ) { - unset( $sidebar['TOOLBOX'] ); - } - if ( isset( $options['languages'] ) && $options['languages'] === false ) { - unset( $sidebar['LANGUAGES'] ); - } - - $boxes = array(); - foreach ( $sidebar as $boxName => $content ) { - if ( $content === false ) { - continue; - } - switch ( $boxName ) { - case 'SEARCH': - // Search is a special case, skins should custom implement this - $boxes[$boxName] = array( - 'id' => 'p-search', - 'header' => $this->getMsg( 'search' )->text(), - 'generated' => false, - 'content' => true, - ); - break; - case 'TOOLBOX': - $msgObj = $this->getMsg( 'toolbox' ); - $boxes[$boxName] = array( - 'id' => 'p-tb', - 'header' => $msgObj->exists() ? $msgObj->text() : 'toolbox', - 'generated' => false, - 'content' => $this->getToolbox(), - ); - break; - case 'LANGUAGES': - if ( $this->data['language_urls'] ) { - $msgObj = $this->getMsg( 'otherlanguages' ); - $boxes[$boxName] = array( - 'id' => 'p-lang', - 'header' => $msgObj->exists() ? $msgObj->text() : 'otherlanguages', - 'generated' => false, - 'content' => $this->data['language_urls'], - ); - } - break; - default: - $msgObj = $this->getMsg( $boxName ); - $boxes[$boxName] = array( - 'id' => "p-$boxName", - 'header' => $msgObj->exists() ? $msgObj->text() : $boxName, - 'generated' => true, - 'content' => $content, - ); - break; - } - } - - // HACK: Compatibility with extensions still using SkinTemplateToolboxEnd - $hookContents = null; - if ( isset( $boxes['TOOLBOX'] ) ) { - ob_start(); - // We pass an extra 'true' at the end so extensions using BaseTemplateToolbox - // can abort and avoid outputting double toolbox links - wfRunHooks( 'SkinTemplateToolboxEnd', array( &$this, true ) ); - $hookContents = ob_get_contents(); - ob_end_clean(); - if ( !trim( $hookContents ) ) { - $hookContents = null; - } - } - // END hack - - if ( isset( $options['htmlOnly'] ) && $options['htmlOnly'] === true ) { - foreach ( $boxes as $boxName => $box ) { - if ( is_array( $box['content'] ) ) { - $content = '
      '; - foreach ( $box['content'] as $key => $val ) { - $content .= "\n " . $this->makeListItem( $key, $val ); - } - // HACK, shove the toolbox end onto the toolbox if we're rendering itself - if ( $hookContents ) { - $content .= "\n $hookContents"; - } - // END hack - $content .= "\n
    \n"; - $boxes[$boxName]['content'] = $content; - } - } - } else { - if ( $hookContents ) { - $boxes['TOOLBOXEND'] = array( - 'id' => 'p-toolboxend', - 'header' => $boxes['TOOLBOX']['header'], - 'generated' => false, - 'content' => "
      {$hookContents}
    ", - ); - // HACK: Make sure that TOOLBOXEND is sorted next to TOOLBOX - $boxes2 = array(); - foreach ( $boxes as $key => $box ) { - if ( $key === 'TOOLBOXEND' ) { - continue; - } - $boxes2[$key] = $box; - if ( $key === 'TOOLBOX' ) { - $boxes2['TOOLBOXEND'] = $boxes['TOOLBOXEND']; - } - } - $boxes = $boxes2; - // END hack - } - } - - return $boxes; - } - - /** - * @param string $name - */ - protected function renderAfterPortlet( $name ) { - $content = ''; - wfRunHooks( 'BaseTemplateAfterPortlet', array( $this, $name, &$content ) ); - - if ( $content !== '' ) { - echo "
    $content
    "; - } - - } - - /** - * Makes a link, usually used by makeListItem to generate a link for an item - * in a list used in navigation lists, portlets, portals, sidebars, etc... - * - * @param string $key Usually a key from the list you are generating this - * link from. - * @param array $item Contains some of a specific set of keys. - * - * The text of the link will be generated either from the contents of the - * "text" key in the $item array, if a "msg" key is present a message by - * that name will be used, and if neither of those are set the $key will be - * used as a message name. - * - * If a "href" key is not present makeLink will just output htmlescaped text. - * The "href", "id", "class", "rel", and "type" keys are used as attributes - * for the link if present. - * - * If an "id" or "single-id" (if you don't want the actual id to be output - * on the link) is present it will be used to generate a tooltip and - * accesskey for the link. - * - * The keys "context" and "primary" are ignored; these keys are used - * internally by skins and are not supposed to be included in the HTML - * output. - * - * If you don't want an accesskey, set $item['tooltiponly'] = true; - * - * @param array $options Can be used to affect the output of a link. - * Possible options are: - * - 'text-wrapper' key to specify a list of elements to wrap the text of - * a link in. This should be an array of arrays containing a 'tag' and - * optionally an 'attributes' key. If you only have one element you don't - * need to wrap it in another array. eg: To use
    ... - * in all links use array( 'text-wrapper' => array( 'tag' => 'span' ) ) - * for your options. - * - 'link-class' key can be used to specify additional classes to apply - * to all links. - * - 'link-fallback' can be used to specify a tag to use instead of "" - * if there is no link. eg: If you specify 'link-fallback' => 'span' than - * any non-link will output a "" instead of just text. - * - * @return string - */ - function makeLink( $key, $item, $options = array() ) { - if ( isset( $item['text'] ) ) { - $text = $item['text']; - } else { - $text = $this->translator->translate( isset( $item['msg'] ) ? $item['msg'] : $key ); - } - - $html = htmlspecialchars( $text ); - - if ( isset( $options['text-wrapper'] ) ) { - $wrapper = $options['text-wrapper']; - if ( isset( $wrapper['tag'] ) ) { - $wrapper = array( $wrapper ); - } - while ( count( $wrapper ) > 0 ) { - $element = array_pop( $wrapper ); - $html = Html::rawElement( $element['tag'], isset( $element['attributes'] ) - ? $element['attributes'] - : null, $html ); - } - } - - if ( isset( $item['href'] ) || isset( $options['link-fallback'] ) ) { - $attrs = $item; - foreach ( array( 'single-id', 'text', 'msg', 'tooltiponly', 'context', 'primary' ) as $k ) { - unset( $attrs[$k] ); - } - - if ( isset( $item['id'] ) && !isset( $item['single-id'] ) ) { - $item['single-id'] = $item['id']; - } - if ( isset( $item['single-id'] ) ) { - if ( isset( $item['tooltiponly'] ) && $item['tooltiponly'] ) { - $title = Linker::titleAttrib( $item['single-id'] ); - if ( $title !== false ) { - $attrs['title'] = $title; - } - } else { - $tip = Linker::tooltipAndAccesskeyAttribs( $item['single-id'] ); - if ( isset( $tip['title'] ) && $tip['title'] !== false ) { - $attrs['title'] = $tip['title']; - } - if ( isset( $tip['accesskey'] ) && $tip['accesskey'] !== false ) { - $attrs['accesskey'] = $tip['accesskey']; - } - } - } - if ( isset( $options['link-class'] ) ) { - if ( isset( $attrs['class'] ) ) { - $attrs['class'] .= " {$options['link-class']}"; - } else { - $attrs['class'] = $options['link-class']; - } - } - $html = Html::rawElement( isset( $attrs['href'] ) - ? 'a' - : $options['link-fallback'], $attrs, $html ); - } - - return $html; - } - - /** - * Generates a list item for a navigation, portlet, portal, sidebar... list - * - * @param string $key Usually a key from the list you are generating this link from. - * @param array $item Array of list item data containing some of a specific set of keys. - * The "id", "class" and "itemtitle" keys will be used as attributes for the list item, - * if "active" contains a value of true a "active" class will also be appended to class. - * - * @param array $options - * - * If you want something other than a "
  • " you can pass a tag name such as - * "tag" => "span" in the $options array to change the tag used. - * link/content data for the list item may come in one of two forms - * A "links" key may be used, in which case it should contain an array with - * a list of links to include inside the list item, see makeLink for the - * format of individual links array items. - * - * Otherwise the relevant keys from the list item $item array will be passed - * to makeLink instead. Note however that "id" and "class" are used by the - * list item directly so they will not be passed to makeLink - * (however the link will still support a tooltip and accesskey from it) - * If you need an id or class on a single link you should include a "links" - * array with just one link item inside of it. If you want to add a title - * to the list item itself, you can set "itemtitle" to the value. - * $options is also passed on to makeLink calls - * - * @return string - */ - function makeListItem( $key, $item, $options = array() ) { - if ( isset( $item['links'] ) ) { - $links = array(); - foreach ( $item['links'] as $linkKey => $link ) { - $links[] = $this->makeLink( $linkKey, $link, $options ); - } - $html = implode( ' ', $links ); - } else { - $link = $item; - // These keys are used by makeListItem and shouldn't be passed on to the link - foreach ( array( 'id', 'class', 'active', 'tag', 'itemtitle' ) as $k ) { - unset( $link[$k] ); - } - if ( isset( $item['id'] ) && !isset( $item['single-id'] ) ) { - // The id goes on the
  • not on the for single links - // but makeSidebarLink still needs to know what id to use when - // generating tooltips and accesskeys. - $link['single-id'] = $item['id']; - } - $html = $this->makeLink( $key, $link, $options ); - } - - $attrs = array(); - foreach ( array( 'id', 'class' ) as $attr ) { - if ( isset( $item[$attr] ) ) { - $attrs[$attr] = $item[$attr]; - } - } - if ( isset( $item['active'] ) && $item['active'] ) { - if ( !isset( $attrs['class'] ) ) { - $attrs['class'] = ''; - } - $attrs['class'] .= ' active'; - $attrs['class'] = trim( $attrs['class'] ); - } - if ( isset( $item['itemtitle'] ) ) { - $attrs['title'] = $item['itemtitle']; - } - return Html::rawElement( isset( $options['tag'] ) ? $options['tag'] : 'li', $attrs, $html ); - } - - function makeSearchInput( $attrs = array() ) { - $realAttrs = array( - 'type' => 'search', - 'name' => 'search', - 'placeholder' => wfMessage( 'searchsuggest-search' )->text(), - 'value' => $this->get( 'search', '' ), - ); - $realAttrs = array_merge( $realAttrs, Linker::tooltipAndAccesskeyAttribs( 'search' ), $attrs ); - return Html::element( 'input', $realAttrs ); - } - - function makeSearchButton( $mode, $attrs = array() ) { - switch ( $mode ) { - case 'go': - case 'fulltext': - $realAttrs = array( - 'type' => 'submit', - 'name' => $mode, - 'value' => $this->translator->translate( - $mode == 'go' ? 'searcharticle' : 'searchbutton' ), - ); - $realAttrs = array_merge( - $realAttrs, - Linker::tooltipAndAccesskeyAttribs( "search-$mode" ), - $attrs - ); - return Html::element( 'input', $realAttrs ); - case 'image': - $buttonAttrs = array( - 'type' => 'submit', - 'name' => 'button', - ); - $buttonAttrs = array_merge( - $buttonAttrs, - Linker::tooltipAndAccesskeyAttribs( 'search-fulltext' ), - $attrs - ); - unset( $buttonAttrs['src'] ); - unset( $buttonAttrs['alt'] ); - unset( $buttonAttrs['width'] ); - unset( $buttonAttrs['height'] ); - $imgAttrs = array( - 'src' => $attrs['src'], - 'alt' => isset( $attrs['alt'] ) - ? $attrs['alt'] - : $this->translator->translate( 'searchbutton' ), - 'width' => isset( $attrs['width'] ) ? $attrs['width'] : null, - 'height' => isset( $attrs['height'] ) ? $attrs['height'] : null, - ); - return Html::rawElement( 'button', $buttonAttrs, Html::element( 'img', $imgAttrs ) ); - default: - throw new MWException( 'Unknown mode passed to BaseTemplate::makeSearchButton' ); - } - } - - /** - * Returns an array of footerlinks trimmed down to only those footer links that - * are valid. - * If you pass "flat" as an option then the returned array will be a flat array - * of footer icons instead of a key/value array of footerlinks arrays broken - * up into categories. - * @param string $option - * @return array|mixed - */ - function getFooterLinks( $option = null ) { - $footerlinks = $this->get( 'footerlinks' ); - - // Reduce footer links down to only those which are being used - $validFooterLinks = array(); - foreach ( $footerlinks as $category => $links ) { - $validFooterLinks[$category] = array(); - foreach ( $links as $link ) { - if ( isset( $this->data[$link] ) && $this->data[$link] ) { - $validFooterLinks[$category][] = $link; - } - } - if ( count( $validFooterLinks[$category] ) <= 0 ) { - unset( $validFooterLinks[$category] ); - } - } - - if ( $option == 'flat' ) { - // fold footerlinks into a single array using a bit of trickery - $validFooterLinks = call_user_func_array( - 'array_merge', - array_values( $validFooterLinks ) - ); - } - - return $validFooterLinks; - } - - /** - * Returns an array of footer icons filtered down by options relevant to how - * the skin wishes to display them. - * If you pass "icononly" as the option all footer icons which do not have an - * image icon set will be filtered out. - * If you pass "nocopyright" then MediaWiki's copyright icon will not be included - * in the list of footer icons. This is mostly useful for skins which only - * display the text from footericons instead of the images and don't want a - * duplicate copyright statement because footerlinks already rendered one. - * @param string $option - * @return string - */ - function getFooterIcons( $option = null ) { - // Generate additional footer icons - $footericons = $this->get( 'footericons' ); - - if ( $option == 'icononly' ) { - // Unset any icons which don't have an image - foreach ( $footericons as &$footerIconsBlock ) { - foreach ( $footerIconsBlock as $footerIconKey => $footerIcon ) { - if ( !is_string( $footerIcon ) && !isset( $footerIcon['src'] ) ) { - unset( $footerIconsBlock[$footerIconKey] ); - } - } - } - // Redo removal of any empty blocks - foreach ( $footericons as $footerIconsKey => &$footerIconsBlock ) { - if ( count( $footerIconsBlock ) <= 0 ) { - unset( $footericons[$footerIconsKey] ); - } - } - } elseif ( $option == 'nocopyright' ) { - unset( $footericons['copyright']['copyright'] ); - if ( count( $footericons['copyright'] ) <= 0 ) { - unset( $footericons['copyright'] ); - } - } - - return $footericons; - } - - /** - * Output the basic end-page trail including bottomscripts, reporttime, and - * debug stuff. This should be called right before outputting the closing - * body and html tags. - */ - function printTrail() { ?> -getSkin()->getContext() ); ?> -html( 'bottomscripts' ); /* JS call to runBodyOnloadHook */ ?> -html( 'reporttime' ) ?> -getConfig()->get( 'FallbackSkin' ); + $factory = SkinFactory::getDefaultInstance(); // If the hook worked try to set a skin from it if ( $skin instanceof Skin ) { $this->skin = $skin; } elseif ( is_string( $skin ) ) { - $this->skin = Skin::newFromKey( $skin ); + try { + $this->skin = $factory->makeSkin( $skin ); + } catch ( SkinException $e ) { + $this->skin = $factory->makeSkin( $fallback ); + } + } // If this is still null (the hook didn't run or didn't work) @@ -372,7 +379,12 @@ class RequestContext implements IContextSource { $userSkin = $this->getConfig()->get( 'DefaultSkin' ); } - $this->skin = Skin::newFromKey( $userSkin ); + try { + $this->skin = $factory->makeSkin( $userSkin ); + } catch ( SkinException $e ) { + $this->skin = $factory->makeSkin( $fallback ); + } + } // After all that set a context on whatever skin got created diff --git a/includes/skins/Skin.php b/includes/skins/Skin.php new file mode 100644 index 0000000000..6ba1efd992 --- /dev/null +++ b/includes/skins/Skin.php @@ -0,0 +1,1619 @@ +getSkinNames(); + } + + /** + * Fetch the skinname messages for available skins. + * @return string[] + */ + static function getSkinNameMessages() { + $messages = array(); + foreach ( self::getSkinNames() as $skinKey => $skinName ) { + $messages[] = "skinname-$skinKey"; + } + return $messages; + } + + /** + * Fetch the list of user-selectable skins in regards to $wgSkipSkins. + * Useful for Special:Preferences and other places where you + * only want to show skins users _can_ use. + * @return string[] + * @since 1.23 + */ + public static function getAllowedSkins() { + global $wgSkipSkins; + + $allowedSkins = self::getSkinNames(); + + foreach ( $wgSkipSkins as $skip ) { + unset( $allowedSkins[$skip] ); + } + + return $allowedSkins; + } + + /** + * @deprecated since 1.23, use getAllowedSkins + * @return string[] + */ + public static function getUsableSkins() { + wfDeprecated( __METHOD__, '1.23' ); + return self::getAllowedSkins(); + } + + /** + * Normalize a skin preference value to a form that can be loaded. + * + * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the + * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too. + * + * @param string $key 'monobook', 'vector', etc. + * @return string + */ + static function normalizeKey( $key ) { + global $wgDefaultSkin, $wgFallbackSkin; + + $skinNames = Skin::getSkinNames(); + + // Make keys lowercase for case-insensitive matching. + $skinNames = array_change_key_case( $skinNames, CASE_LOWER ); + $key = strtolower( $key ); + $defaultSkin = strtolower( $wgDefaultSkin ); + $fallbackSkin = strtolower( $wgFallbackSkin ); + + if ( $key == '' || $key == 'default' ) { + // Don't return the default immediately; + // in a misconfiguration we need to fall back. + $key = $defaultSkin; + } + + if ( isset( $skinNames[$key] ) ) { + return $key; + } + + // Older versions of the software used a numeric setting + // in the user preferences. + $fallback = array( + 0 => $defaultSkin, + 2 => 'cologneblue' + ); + + if ( isset( $fallback[$key] ) ) { + $key = $fallback[$key]; + } + + if ( isset( $skinNames[$key] ) ) { + return $key; + } elseif ( isset( $skinNames[$defaultSkin] ) ) { + return $defaultSkin; + } else { + return $fallbackSkin; + } + } + + /** + * Factory method for loading a skin of a given type + * @param string $key 'monobook', 'vector', etc. + * @return Skin + * @deprecated Use SkinFactory instead + */ + static function &newFromKey( $key ) { + wfDeprecated( __METHOD__, '1.24' ); + global $wgFallbackSkin; + + $key = Skin::normalizeKey( $key ); + $factory = SkinFactory::getDefaultInstance(); + try { + $skin = $factory->makeSkin( $key ); + } catch ( SkinException $e ) { + $skin = $factory->makeSkin( $wgFallbackSkin ); + } + + return $skin; + } + + /** + * @return string Skin name + */ + public function getSkinName() { + return $this->skinname; + } + + /** + * @param OutputPage $out + */ + function initPage( OutputPage $out ) { + wfProfileIn( __METHOD__ ); + + $this->preloadExistence(); + + wfProfileOut( __METHOD__ ); + } + + /** + * Defines the ResourceLoader modules that should be added to the skin + * It is recommended that skins wishing to override call parent::getDefaultModules() + * and substitute out any modules they wish to change by using a key to look them up + * @return array Array of modules with helper keys for easy overriding + */ + public function getDefaultModules() { + global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax, + $wgAjaxWatch, $wgEnableAPI, $wgEnableWriteAPI; + + $out = $this->getOutput(); + $user = $out->getUser(); + $modules = array( + // modules that enhance the page content in some way + 'content' => array( + 'mediawiki.page.ready', + ), + // modules that exist for legacy reasons + 'legacy' => array(), + // modules relating to search functionality + 'search' => array(), + // modules relating to functionality relating to watching an article + 'watch' => array(), + // modules which relate to the current users preferences + 'user' => array(), + ); + if ( $wgIncludeLegacyJavaScript ) { + $modules['legacy'][] = 'mediawiki.legacy.wikibits'; + } + + if ( $wgPreloadJavaScriptMwUtil ) { + $modules['legacy'][] = 'mediawiki.util'; + } + + // Add various resources if required + if ( $wgUseAjax ) { + $modules['legacy'][] = 'mediawiki.legacy.ajax'; + + if ( $wgEnableAPI ) { + if ( $wgEnableWriteAPI && $wgAjaxWatch && $user->isLoggedIn() + && $user->isAllowed( 'writeapi' ) + ) { + $modules['watch'][] = 'mediawiki.page.watch.ajax'; + } + + $modules['search'][] = 'mediawiki.searchSuggest'; + } + } + + if ( $user->getBoolOption( 'editsectiononrightclick' ) ) { + $modules['user'][] = 'mediawiki.action.view.rightClickEdit'; + } + + // Crazy edit-on-double-click stuff + if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) { + $modules['user'][] = 'mediawiki.action.view.dblClickEdit'; + } + return $modules; + } + + /** + * Preload the existence of three commonly-requested pages in a single query + */ + function preloadExistence() { + $user = $this->getUser(); + + // User/talk link + $titles = array( $user->getUserPage(), $user->getTalkPage() ); + + // Other tab link + if ( $this->getTitle()->isSpecialPage() ) { + // nothing + } elseif ( $this->getTitle()->isTalkPage() ) { + $titles[] = $this->getTitle()->getSubjectPage(); + } else { + $titles[] = $this->getTitle()->getTalkPage(); + } + + $lb = new LinkBatch( $titles ); + $lb->setCaller( __METHOD__ ); + $lb->execute(); + } + + /** + * Get the current revision ID + * + * @return int + */ + public function getRevisionId() { + return $this->getOutput()->getRevisionId(); + } + + /** + * Whether the revision displayed is the latest revision of the page + * + * @return bool + */ + public function isRevisionCurrent() { + $revID = $this->getRevisionId(); + return $revID == 0 || $revID == $this->getTitle()->getLatestRevID(); + } + + /** + * Set the "relevant" title + * @see self::getRelevantTitle() + * @param Title $t + */ + public function setRelevantTitle( $t ) { + $this->mRelevantTitle = $t; + } + + /** + * Return the "relevant" title. + * A "relevant" title is not necessarily the actual title of the page. + * Special pages like Special:MovePage use set the page they are acting on + * as their "relevant" title, this allows the skin system to display things + * such as content tabs which belong to to that page instead of displaying + * a basic special page tab which has almost no meaning. + * + * @return Title + */ + public function getRelevantTitle() { + if ( isset( $this->mRelevantTitle ) ) { + return $this->mRelevantTitle; + } + return $this->getTitle(); + } + + /** + * Set the "relevant" user + * @see self::getRelevantUser() + * @param User $u + */ + public function setRelevantUser( $u ) { + $this->mRelevantUser = $u; + } + + /** + * Return the "relevant" user. + * A "relevant" user is similar to a relevant title. Special pages like + * Special:Contributions mark the user which they are relevant to so that + * things like the toolbox can display the information they usually are only + * able to display on a user's userpage and talkpage. + * @return User + */ + public function getRelevantUser() { + if ( isset( $this->mRelevantUser ) ) { + return $this->mRelevantUser; + } + $title = $this->getRelevantTitle(); + if ( $title->hasSubjectNamespace( NS_USER ) ) { + $rootUser = $title->getRootText(); + if ( User::isIP( $rootUser ) ) { + $this->mRelevantUser = User::newFromName( $rootUser, false ); + } else { + $user = User::newFromName( $rootUser, false ); + if ( $user && $user->isLoggedIn() ) { + $this->mRelevantUser = $user; + } + } + return $this->mRelevantUser; + } + return null; + } + + /** + * Outputs the HTML generated by other functions. + * @param OutputPage $out + */ + abstract function outputPage( OutputPage $out = null ); + + /** + * @param array $data + * @return string + */ + static function makeVariablesScript( $data ) { + if ( $data ) { + return Html::inlineScript( + ResourceLoader::makeLoaderConditionalScript( ResourceLoader::makeConfigSetScript( $data ) ) + ); + } else { + return ''; + } + } + + /** + * Get the query to generate a dynamic stylesheet + * + * @return array + */ + public static function getDynamicStylesheetQuery() { + global $wgSquidMaxage; + + return array( + 'action' => 'raw', + 'maxage' => $wgSquidMaxage, + 'usemsgcache' => 'yes', + 'ctype' => 'text/css', + 'smaxage' => $wgSquidMaxage, + ); + } + + /** + * Add skin specific stylesheets + * Calling this method with an $out of anything but the same OutputPage + * inside ->getOutput() is deprecated. The $out arg is kept + * for compatibility purposes with skins. + * @param OutputPage $out + * @todo delete + */ + abstract function setupSkinUserCss( OutputPage $out ); + + /** + * TODO: document + * @param Title $title + * @return string + */ + function getPageClasses( $title ) { + $numeric = 'ns-' . $title->getNamespace(); + + if ( $title->isSpecialPage() ) { + $type = 'ns-special'; + // bug 23315: provide a class based on the canonical special page name without subpages + list( $canonicalName ) = SpecialPageFactory::resolveAlias( $title->getDBkey() ); + if ( $canonicalName ) { + $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" ); + } else { + $type .= ' mw-invalidspecialpage'; + } + } elseif ( $title->isTalkPage() ) { + $type = 'ns-talk'; + } else { + $type = 'ns-subject'; + } + + $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() ); + + return "$numeric $type $name"; + } + + /* + * Return values for element + * @return array of associative name-to-value elements for element + */ + public function getHtmlElementAttributes() { + $lang = $this->getLanguage(); + return array( + 'lang' => $lang->getHtmlCode(), + 'dir' => $lang->getDir(), + 'class' => 'client-nojs', + ); + } + + /** + * This will be called by OutputPage::headElement when it is creating the + * "" tag, skins can override it if they have a need to add in any + * body attributes or classes of their own. + * @param OutputPage $out + * @param array $bodyAttrs + */ + function addToBodyAttributes( $out, &$bodyAttrs ) { + // does nothing by default + } + + /** + * URL to the logo + * @return string + */ + function getLogo() { + global $wgLogo; + return $wgLogo; + } + + /** + * @return string + */ + function getCategoryLinks() { + global $wgUseCategoryBrowser; + + $out = $this->getOutput(); + $allCats = $out->getCategoryLinks(); + + if ( !count( $allCats ) ) { + return ''; + } + + $embed = "
  • "; + $pop = "
  • "; + + $s = ''; + $colon = $this->msg( 'colon-separator' )->escaped(); + + if ( !empty( $allCats['normal'] ) ) { + $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop; + + $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped(); + $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text(); + $s .= ''; + } + + # Hidden categories + if ( isset( $allCats['hidden'] ) ) { + if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) { + $class = ' mw-hidden-cats-user-shown'; + } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY ) { + $class = ' mw-hidden-cats-ns-shown'; + } else { + $class = ' mw-hidden-cats-hidden'; + } + + $s .= "
    " . + $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() . + $colon . '
      ' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '
    ' . + '
    '; + } + + # optional 'dmoz-like' category browser. Will be shown under the list + # of categories an article belong to + if ( $wgUseCategoryBrowser ) { + $s .= '

    '; + + # get a big array of the parents tree + $parenttree = $this->getTitle()->getParentCategoryTree(); + # Skin object passed by reference cause it can not be + # accessed under the method subfunction drawCategoryBrowser + $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) ); + # Clean out bogus first entry and sort them + unset( $tempout[0] ); + asort( $tempout ); + # Output one per line + $s .= implode( "
    \n", $tempout ); + } + + return $s; + } + + /** + * Render the array as a series of links. + * @param array $tree Categories tree returned by Title::getParentCategoryTree + * @return string Separated by >, terminate with "\n" + */ + function drawCategoryBrowser( $tree ) { + $return = ''; + + foreach ( $tree as $element => $parent ) { + if ( empty( $parent ) ) { + # element start a new list + $return .= "\n"; + } else { + # grab the others elements + $return .= $this->drawCategoryBrowser( $parent ) . ' > '; + } + + # add our current element to the list + $eltitle = Title::newFromText( $element ); + $return .= Linker::link( $eltitle, htmlspecialchars( $eltitle->getText() ) ); + } + + return $return; + } + + /** + * @return string + */ + function getCategories() { + $out = $this->getOutput(); + + $catlinks = $this->getCategoryLinks(); + + $classes = 'catlinks'; + + // Check what we're showing + $allCats = $out->getCategoryLinks(); + $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) || + $this->getTitle()->getNamespace() == NS_CATEGORY; + + if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) { + $classes .= ' catlinks-allhidden'; + } + + return ""; + } + + /** + * This runs a hook to allow extensions placing their stuff after content + * and article metadata (e.g. categories). + * Note: This function has nothing to do with afterContent(). + * + * This hook is placed here in order to allow using the same hook for all + * skins, both the SkinTemplate based ones and the older ones, which directly + * use this class to get their data. + * + * The output of this function gets processed in SkinTemplate::outputPage() for + * the SkinTemplate based skins, all other skins should directly echo it. + * + * @return string Empty by default, if not changed by any hook function. + */ + protected function afterContentHook() { + $data = ''; + + if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) { + // adding just some spaces shouldn't toggle the output + // of the whole
    , so we use trim() here + if ( trim( $data ) != '' ) { + // Doing this here instead of in the skins to + // ensure that the div has the same ID in all + // skins + $data = "
    \n" . + "\t$data\n" . + "
    \n"; + } + } else { + wfDebug( "Hook SkinAfterContent changed output processing.\n" ); + } + + return $data; + } + + /** + * Generate debug data HTML for displaying at the bottom of the main content + * area. + * @return string HTML containing debug data, if enabled (otherwise empty). + */ + protected function generateDebugHTML() { + return MWDebug::getHTMLDebugLog(); + } + + /** + * This gets called shortly before the "" tag. + * + * @return string HTML-wrapped JS code to be put before "" + */ + function bottomScripts() { + // TODO and the suckage continues. This function is really just a wrapper around + // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned + // up at some point + $bottomScriptText = $this->getOutput()->getBottomScripts(); + wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) ); + + return $bottomScriptText; + } + + /** + * Text with the permalink to the source page, + * usually shown on the footer of a printed page + * + * @return string HTML text with an URL + */ + function printSource() { + $oldid = $this->getRevisionId(); + if ( $oldid ) { + $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid ); + $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) ); + } else { + // oldid not available for non existing pages + $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) ); + } + + return $this->msg( 'retrievedfrom', '
    ' . $url . '' )->text(); + } + + /** + * @return string + */ + function getUndeleteLink() { + $action = $this->getRequest()->getVal( 'action', 'view' ); + + if ( $this->getUser()->isAllowed( 'deletedhistory' ) && + ( $this->getTitle()->getArticleID() == 0 || $action == 'history' ) ) { + $n = $this->getTitle()->isDeleted(); + + if ( $n ) { + if ( $this->getUser()->isAllowed( 'undelete' ) ) { + $msg = 'thisisdeleted'; + } else { + $msg = 'viewdeleted'; + } + + return $this->msg( $msg )->rawParams( + Linker::linkKnown( + SpecialPage::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ), + $this->msg( 'restorelink' )->numParams( $n )->escaped() ) + )->text(); + } + } + + return ''; + } + + /** + * @return string + */ + function subPageSubtitle() { + $out = $this->getOutput(); + $subpages = ''; + + if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) { + return $subpages; + } + + if ( $out->isArticle() && MWNamespace::hasSubpages( $out->getTitle()->getNamespace() ) ) { + $ptext = $this->getTitle()->getPrefixedText(); + if ( preg_match( '/\//', $ptext ) ) { + $links = explode( '/', $ptext ); + array_pop( $links ); + $c = 0; + $growinglink = ''; + $display = ''; + $lang = $this->getLanguage(); + + foreach ( $links as $link ) { + $growinglink .= $link; + $display .= $link; + $linkObj = Title::newFromText( $growinglink ); + + if ( is_object( $linkObj ) && $linkObj->isKnown() ) { + $getlink = Linker::linkKnown( + $linkObj, + htmlspecialchars( $display ) + ); + + $c++; + + if ( $c > 1 ) { + $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped(); + } else { + $subpages .= '< '; + } + + $subpages .= $getlink; + $display = ''; + } else { + $display .= '/'; + } + $growinglink .= '/'; + } + } + } + + return $subpages; + } + + /** + * Returns true if the IP should be shown in the header + * @return bool + */ + function showIPinHeader() { + global $wgShowIPinHeader; + return $wgShowIPinHeader && session_id() != ''; + } + + /** + * @return string + */ + function getSearchLink() { + $searchPage = SpecialPage::getTitleFor( 'Search' ); + return $searchPage->getLocalURL(); + } + + /** + * @return string + */ + function escapeSearchLink() { + return htmlspecialchars( $this->getSearchLink() ); + } + + /** + * @param string $type + * @return string + */ + function getCopyright( $type = 'detect' ) { + global $wgRightsPage, $wgRightsUrl, $wgRightsText; + + if ( $type == 'detect' ) { + if ( !$this->isRevisionCurrent() + && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled() + ) { + $type = 'history'; + } else { + $type = 'normal'; + } + } + + if ( $type == 'history' ) { + $msg = 'history_copyright'; + } else { + $msg = 'copyright'; + } + + if ( $wgRightsPage ) { + $title = Title::newFromText( $wgRightsPage ); + $link = Linker::linkKnown( $title, $wgRightsText ); + } elseif ( $wgRightsUrl ) { + $link = Linker::makeExternalLink( $wgRightsUrl, $wgRightsText ); + } elseif ( $wgRightsText ) { + $link = $wgRightsText; + } else { + # Give up now + return ''; + } + + // Allow for site and per-namespace customization of copyright notice. + // @todo Remove deprecated $forContent param from hook handlers and then remove here. + $forContent = true; + + wfRunHooks( + 'SkinCopyrightFooter', + array( $this->getTitle(), $type, &$msg, &$link, &$forContent ) + ); + + return $this->msg( $msg )->rawParams( $link )->text(); + } + + /** + * @return null|string + */ + function getCopyrightIcon() { + global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon; + + $out = ''; + + if ( $wgCopyrightIcon ) { + $out = $wgCopyrightIcon; + } elseif ( $wgRightsIcon ) { + $icon = htmlspecialchars( $wgRightsIcon ); + + if ( $wgRightsUrl ) { + $url = htmlspecialchars( $wgRightsUrl ); + $out .= ''; + } + + $text = htmlspecialchars( $wgRightsText ); + $out .= "\"$text\""; + + if ( $wgRightsUrl ) { + $out .= ''; + } + } + + return $out; + } + + /** + * Gets the powered by MediaWiki icon. + * @return string + */ + function getPoweredBy() { + global $wgStylePath; + + $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" ); + $text = 'Powered by MediaWiki'; + wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) ); + return $text; + } + + /** + * Get the timestamp of the latest revision, formatted in user language + * + * @return string + */ + protected function lastModified() { + $timestamp = $this->getOutput()->getRevisionTimestamp(); + + # No cached timestamp, load it from the database + if ( $timestamp === null ) { + $timestamp = Revision::getTimestampFromId( $this->getTitle(), $this->getRevisionId() ); + } + + if ( $timestamp ) { + $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() ); + $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() ); + $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text(); + } else { + $s = ''; + } + + if ( wfGetLB()->getLaggedSlaveMode() ) { + $s .= ' ' . $this->msg( 'laggedslavemode' )->text() . ''; + } + + return $s; + } + + /** + * @param string $align + * @return string + */ + function logoText( $align = '' ) { + if ( $align != '' ) { + $a = " style='float: {$align};'"; + } else { + $a = ''; + } + + $mp = $this->msg( 'mainpage' )->escaped(); + $mptitle = Title::newMainPage(); + $url = ( is_object( $mptitle ) ? htmlspecialchars( $mptitle->getLocalURL() ) : '' ); + + $logourl = $this->getLogo(); + $s = ""; + + return $s; + } + + /** + * Renders a $wgFooterIcons icon according to the method's arguments + * @param array $icon The icon to build the html for, see $wgFooterIcons + * for the format of this array. + * @param bool|string $withImage Whether to use the icon's image or output + * a text-only footericon. + * @return string HTML + */ + function makeFooterIcon( $icon, $withImage = 'withImage' ) { + if ( is_string( $icon ) ) { + $html = $icon; + } else { // Assuming array + $url = isset( $icon["url"] ) ? $icon["url"] : null; + unset( $icon["url"] ); + if ( isset( $icon["src"] ) && $withImage === 'withImage' ) { + // do this the lazy way, just pass icon data as an attribute array + $html = Html::element( 'img', $icon ); + } else { + $html = htmlspecialchars( $icon["alt"] ); + } + if ( $url ) { + $html = Html::rawElement( 'a', array( "href" => $url ), $html ); + } + } + return $html; + } + + /** + * Gets the link to the wiki's main page. + * @return string + */ + function mainPageLink() { + $s = Linker::linkKnown( + Title::newMainPage(), + $this->msg( 'mainpage' )->escaped() + ); + + return $s; + } + + /** + * Returns an HTML link for use in the footer + * @param string $desc The i18n message key for the link text + * @param string $page The i18n message key for the page to link to + * @return string HTML anchor + */ + public function footerLink( $desc, $page ) { + // if the link description has been set to "-" in the default language, + if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) { + // then it is disabled, for all languages. + return ''; + } else { + // Otherwise, we display the link for the user, described in their + // language (which may or may not be the same as the default language), + // but we make the link target be the one site-wide page. + $title = Title::newFromText( $this->msg( $page )->inContentLanguage()->text() ); + + return Linker::linkKnown( + $title, + $this->msg( $desc )->escaped() + ); + } + } + + /** + * Gets the link to the wiki's privacy policy page. + * @return string HTML + */ + function privacyLink() { + return $this->footerLink( 'privacy', 'privacypage' ); + } + + /** + * Gets the link to the wiki's about page. + * @return string HTML + */ + function aboutLink() { + return $this->footerLink( 'aboutsite', 'aboutpage' ); + } + + /** + * Gets the link to the wiki's general disclaimers page. + * @return string HTML + */ + function disclaimerLink() { + return $this->footerLink( 'disclaimers', 'disclaimerpage' ); + } + + /** + * Return URL options for the 'edit page' link. + * This may include an 'oldid' specifier, if the current page view is such. + * + * @return array + * @private + */ + function editUrlOptions() { + $options = array( 'action' => 'edit' ); + + if ( !$this->isRevisionCurrent() ) { + $options['oldid'] = intval( $this->getRevisionId() ); + } + + return $options; + } + + /** + * @param User|int $id + * @return bool + */ + function showEmailUser( $id ) { + if ( $id instanceof User ) { + $targetUser = $id; + } else { + $targetUser = User::newFromId( $id ); + } + + # The sending user must have a confirmed email address and the target + # user must have a confirmed email address and allow emails from users. + return $this->getUser()->canSendEmail() && + $targetUser->canReceiveEmail(); + } + + /** + * Return a fully resolved style path url to images or styles stored in the common folder. + * This method returns a url resolved using the configured skin style path + * and includes the style version inside of the url. + * @param string $name The name or path of a skin resource file + * @return string The fully resolved style path url including styleversion + */ + function getCommonStylePath( $name ) { + global $wgStylePath, $wgStyleVersion; + return "$wgStylePath/common/$name?$wgStyleVersion"; + } + + /** + * Return a fully resolved style path url to images or styles stored in the current skins's folder. + * This method returns a url resolved using the configured skin style path + * and includes the style version inside of the url. + * + * Requires $stylename to be set, otherwise throws MWException. + * + * @param string $name The name or path of a skin resource file + * @return string The fully resolved style path url including styleversion + */ + function getSkinStylePath( $name ) { + global $wgStylePath, $wgStyleVersion; + + if ( $this->stylename === null ) { + $class = get_class( $this ); + throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" ); + } + + return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion"; + } + + /* these are used extensively in SkinTemplate, but also some other places */ + + /** + * @param string $urlaction + * @return string + */ + static function makeMainPageUrl( $urlaction = '' ) { + $title = Title::newMainPage(); + self::checkTitle( $title, '' ); + + return $title->getLocalURL( $urlaction ); + } + + /** + * Make a URL for a Special Page using the given query and protocol. + * + * If $proto is set to null, make a local URL. Otherwise, make a full + * URL with the protocol specified. + * + * @param string $name Name of the Special page + * @param string $urlaction Query to append + * @param string|null $proto Protocol to use or null for a local URL + * @return string + */ + static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) { + $title = SpecialPage::getSafeTitleFor( $name ); + if ( is_null( $proto ) ) { + return $title->getLocalURL( $urlaction ); + } else { + return $title->getFullURL( $urlaction, false, $proto ); + } + } + + /** + * @param string $name + * @param string $subpage + * @param string $urlaction + * @return string + */ + static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) { + $title = SpecialPage::getSafeTitleFor( $name, $subpage ); + return $title->getLocalURL( $urlaction ); + } + + /** + * @param string $name + * @param string $urlaction + * @return string + */ + static function makeI18nUrl( $name, $urlaction = '' ) { + $title = Title::newFromText( wfMessage( $name )->inContentLanguage()->text() ); + self::checkTitle( $title, $name ); + return $title->getLocalURL( $urlaction ); + } + + /** + * @param string $name + * @param string $urlaction + * @return string + */ + static function makeUrl( $name, $urlaction = '' ) { + $title = Title::newFromText( $name ); + self::checkTitle( $title, $name ); + + return $title->getLocalURL( $urlaction ); + } + + /** + * If url string starts with http, consider as external URL, else + * internal + * @param string $name + * @return string URL + */ + static function makeInternalOrExternalUrl( $name ) { + if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) { + return $name; + } else { + return self::makeUrl( $name ); + } + } + + /** + * this can be passed the NS number as defined in Language.php + * @param string $name + * @param string $urlaction + * @param int $namespace + * @return string + */ + static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) { + $title = Title::makeTitleSafe( $namespace, $name ); + self::checkTitle( $title, $name ); + + return $title->getLocalURL( $urlaction ); + } + + /** + * these return an array with the 'href' and boolean 'exists' + * @param string $name + * @param string $urlaction + * @return array + */ + static function makeUrlDetails( $name, $urlaction = '' ) { + $title = Title::newFromText( $name ); + self::checkTitle( $title, $name ); + + return array( + 'href' => $title->getLocalURL( $urlaction ), + 'exists' => $title->getArticleID() != 0, + ); + } + + /** + * Make URL details where the article exists (or at least it's convenient to think so) + * @param string $name Article name + * @param string $urlaction + * @return array + */ + static function makeKnownUrlDetails( $name, $urlaction = '' ) { + $title = Title::newFromText( $name ); + self::checkTitle( $title, $name ); + + return array( + 'href' => $title->getLocalURL( $urlaction ), + 'exists' => true + ); + } + + /** + * make sure we have some title to operate on + * + * @param Title $title + * @param string $name + */ + static function checkTitle( &$title, $name ) { + if ( !is_object( $title ) ) { + $title = Title::newFromText( $name ); + if ( !is_object( $title ) ) { + $title = Title::newFromText( '--error: link target missing--' ); + } + } + } + + /** + * Build an array that represents the sidebar(s), the navigation bar among them. + * + * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins. + * + * The format of the returned array is array( heading => content, ... ), where: + * - heading is the heading of a navigation portlet. It is either: + * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...) + * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin + * - plain text, which should be HTML-escaped by the skin + * - content is the contents of the portlet. It is either: + * - HTML text (
    • ...
    • ...
    ) + * - array of link data in a format accepted by BaseTemplate::makeListItem() + * - (for a magic string as a key, any value) + * + * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook + * and can technically insert anything in here; skin creators are expected to handle + * values described above. + * + * @return array + */ + function buildSidebar() { + global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry; + wfProfileIn( __METHOD__ ); + + $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() ); + + if ( $wgEnableSidebarCache ) { + $cachedsidebar = $wgMemc->get( $key ); + if ( $cachedsidebar ) { + wfRunHooks( 'SidebarBeforeOutput', array( $this, &$cachedsidebar ) ); + + wfProfileOut( __METHOD__ ); + return $cachedsidebar; + } + } + + $bar = array(); + $this->addToSidebar( $bar, 'sidebar' ); + + wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) ); + if ( $wgEnableSidebarCache ) { + $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry ); + } + + wfRunHooks( 'SidebarBeforeOutput', array( $this, &$bar ) ); + + wfProfileOut( __METHOD__ ); + return $bar; + } + + /** + * Add content from a sidebar system message + * Currently only used for MediaWiki:Sidebar (but may be used by Extensions) + * + * This is just a wrapper around addToSidebarPlain() for backwards compatibility + * + * @param array $bar + * @param string $message + */ + function addToSidebar( &$bar, $message ) { + $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() ); + } + + /** + * Add content from plain text + * @since 1.17 + * @param array $bar + * @param string $text + * @return array + */ + function addToSidebarPlain( &$bar, $text ) { + $lines = explode( "\n", $text ); + + $heading = ''; + + foreach ( $lines as $line ) { + if ( strpos( $line, '*' ) !== 0 ) { + continue; + } + $line = rtrim( $line, "\r" ); // for Windows compat + + if ( strpos( $line, '**' ) !== 0 ) { + $heading = trim( $line, '* ' ); + if ( !array_key_exists( $heading, $bar ) ) { + $bar[$heading] = array(); + } + } else { + $line = trim( $line, '* ' ); + + if ( strpos( $line, '|' ) !== false ) { // sanity check + $line = MessageCache::singleton()->transform( $line, false, null, $this->getTitle() ); + $line = array_map( 'trim', explode( '|', $line, 2 ) ); + if ( count( $line ) !== 2 ) { + // Second sanity check, could be hit by people doing + // funky stuff with parserfuncs... (bug 33321) + continue; + } + + $extraAttribs = array(); + + $msgLink = $this->msg( $line[0] )->inContentLanguage(); + if ( $msgLink->exists() ) { + $link = $msgLink->text(); + if ( $link == '-' ) { + continue; + } + } else { + $link = $line[0]; + } + $msgText = $this->msg( $line[1] ); + if ( $msgText->exists() ) { + $text = $msgText->text(); + } else { + $text = $line[1]; + } + + if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) { + $href = $link; + + // Parser::getExternalLinkAttribs won't work here because of the Namespace things + global $wgNoFollowLinks, $wgNoFollowDomainExceptions; + if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) { + $extraAttribs['rel'] = 'nofollow'; + } + + global $wgExternalLinkTarget; + if ( $wgExternalLinkTarget ) { + $extraAttribs['target'] = $wgExternalLinkTarget; + } + } else { + $title = Title::newFromText( $link ); + + if ( $title ) { + $title = $title->fixSpecialName(); + $href = $title->getLinkURL(); + } else { + $href = 'INVALID-TITLE'; + } + } + + $bar[$heading][] = array_merge( array( + 'text' => $text, + 'href' => $href, + 'id' => 'n-' . Sanitizer::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ), + 'active' => false + ), $extraAttribs ); + } else { + continue; + } + } + } + + return $bar; + } + + /** + * This function previously controlled whether the 'mediawiki.legacy.wikiprintable' module + * should be loaded by OutputPage. That module no longer exists and the return value of this + * method is ignored. + * + * If your skin doesn't provide its own print styles, the 'mediawiki.legacy.commonPrint' module + * can be used instead (SkinTemplate-based skins do it automatically). + * + * @deprecated since 1.22 + * @return bool + */ + public function commonPrintStylesheet() { + wfDeprecated( __METHOD__, '1.22' ); + return false; + } + + /** + * Gets new talk page messages for the current user and returns an + * appropriate alert message (or an empty string if there are no messages) + * @return string + */ + function getNewtalks() { + + $newMessagesAlert = ''; + $user = $this->getUser(); + $newtalks = $user->getNewMessageLinks(); + $out = $this->getOutput(); + + // Allow extensions to disable or modify the new messages alert + if ( !wfRunHooks( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) { + return ''; + } + if ( $newMessagesAlert ) { + return $newMessagesAlert; + } + + if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) { + $uTalkTitle = $user->getTalkPage(); + $lastSeenRev = isset( $newtalks[0]['rev'] ) ? $newtalks[0]['rev'] : null; + $nofAuthors = 0; + if ( $lastSeenRev !== null ) { + $plural = true; // Default if we have a last seen revision: if unknown, use plural + $latestRev = Revision::newFromTitle( $uTalkTitle, false, Revision::READ_NORMAL ); + if ( $latestRev !== null ) { + // Singular if only 1 unseen revision, plural if several unseen revisions. + $plural = $latestRev->getParentId() !== $lastSeenRev->getId(); + $nofAuthors = $uTalkTitle->countAuthorsBetween( + $lastSeenRev, $latestRev, 10, 'include_new' ); + } + } else { + // Singular if no revision -> diff link will show latest change only in any case + $plural = false; + } + $plural = $plural ? 999 : 1; + // 999 signifies "more than one revision". We don't know how many, and even if we did, + // the number of revisions or authors is not necessarily the same as the number of + // "messages". + $newMessagesLink = Linker::linkKnown( + $uTalkTitle, + $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(), + array(), + array( 'redirect' => 'no' ) + ); + + $newMessagesDiffLink = Linker::linkKnown( + $uTalkTitle, + $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(), + array(), + $lastSeenRev !== null + ? array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ) + : array( 'diff' => 'cur' ) + ); + + if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) { + $newMessagesAlert = $this->msg( + 'youhavenewmessagesfromusers', + $newMessagesLink, + $newMessagesDiffLink + )->numParams( $nofAuthors, $plural ); + } else { + // $nofAuthors === 11 signifies "11 or more" ("more than 10") + $newMessagesAlert = $this->msg( + $nofAuthors > 10 ? 'youhavenewmessagesmanyusers' : 'youhavenewmessages', + $newMessagesLink, + $newMessagesDiffLink + )->numParams( $plural ); + } + $newMessagesAlert = $newMessagesAlert->text(); + # Disable Squid cache + $out->setSquidMaxage( 0 ); + } elseif ( count( $newtalks ) ) { + $sep = $this->msg( 'newtalkseparator' )->escaped(); + $msgs = array(); + + foreach ( $newtalks as $newtalk ) { + $msgs[] = Xml::element( + 'a', + array( 'href' => $newtalk['link'] ), $newtalk['wiki'] + ); + } + $parts = implode( $sep, $msgs ); + $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped(); + $out->setSquidMaxage( 0 ); + } + + return $newMessagesAlert; + } + + /** + * Get a cached notice + * + * @param string $name Message name, or 'default' for $wgSiteNotice + * @return string HTML fragment + */ + private function getCachedNotice( $name ) { + global $wgRenderHashAppend, $parserMemc, $wgContLang; + + wfProfileIn( __METHOD__ ); + + $needParse = false; + + if ( $name === 'default' ) { + // special case + global $wgSiteNotice; + $notice = $wgSiteNotice; + if ( empty( $notice ) ) { + wfProfileOut( __METHOD__ ); + return false; + } + } else { + $msg = $this->msg( $name )->inContentLanguage(); + if ( $msg->isDisabled() ) { + wfProfileOut( __METHOD__ ); + return false; + } + $notice = $msg->plain(); + } + + // Use the extra hash appender to let eg SSL variants separately cache. + $key = wfMemcKey( $name . $wgRenderHashAppend ); + $cachedNotice = $parserMemc->get( $key ); + if ( is_array( $cachedNotice ) ) { + if ( md5( $notice ) == $cachedNotice['hash'] ) { + $notice = $cachedNotice['html']; + } else { + $needParse = true; + } + } else { + $needParse = true; + } + + if ( $needParse ) { + $parsed = $this->getOutput()->parse( $notice ); + $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 ); + $notice = $parsed; + } + + $notice = Html::rawElement( 'div', array( 'id' => 'localNotice', + 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice ); + wfProfileOut( __METHOD__ ); + return $notice; + } + + /** + * Get a notice based on page's namespace + * + * @return string HTML fragment + */ + function getNamespaceNotice() { + wfProfileIn( __METHOD__ ); + + $key = 'namespacenotice-' . $this->getTitle()->getNsText(); + $namespaceNotice = $this->getCachedNotice( $key ); + if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '

    <' ) { + $namespaceNotice = '

    ' . $namespaceNotice . '
    '; + } else { + $namespaceNotice = ''; + } + + wfProfileOut( __METHOD__ ); + return $namespaceNotice; + } + + /** + * Get the site notice + * + * @return string HTML fragment + */ + function getSiteNotice() { + wfProfileIn( __METHOD__ ); + $siteNotice = ''; + + if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) { + if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) { + $siteNotice = $this->getCachedNotice( 'sitenotice' ); + } else { + $anonNotice = $this->getCachedNotice( 'anonnotice' ); + if ( !$anonNotice ) { + $siteNotice = $this->getCachedNotice( 'sitenotice' ); + } else { + $siteNotice = $anonNotice; + } + } + if ( !$siteNotice ) { + $siteNotice = $this->getCachedNotice( 'default' ); + } + } + + wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) ); + wfProfileOut( __METHOD__ ); + return $siteNotice; + } + + /** + * Create a section edit link. This supersedes editSectionLink() and + * editSectionLinkForOther(). + * + * @param Title $nt The title being linked to (may not be the same as + * the current page, if the section is included from a template) + * @param string $section The designation of the section being pointed to, + * to be included in the link, like "§ion=$section" + * @param string $tooltip The tooltip to use for the link: will be escaped + * and wrapped in the 'editsectionhint' message + * @param string $lang Language code + * @return string HTML to use for edit link + */ + public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) { + // HTML generated here should probably have userlangattributes + // added to it for LTR text on RTL pages + + $lang = wfGetLangObj( $lang ); + + $attribs = array(); + if ( !is_null( $tooltip ) ) { + # Bug 25462: undo double-escaping. + $tooltip = Sanitizer::decodeCharReferences( $tooltip ); + $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip ) + ->inLanguage( $lang )->text(); + } + $link = Linker::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(), + $attribs, + array( 'action' => 'edit', 'section' => $section ), + array( 'noclasses', 'known' ) + ); + + # Add the brackets and the span and run the hook. + $result = '' + . '[' + . $link + . ']' + . ''; + + wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) ); + return $result; + } + + /** + * Use PHP's magic __call handler to intercept legacy calls to the linker + * for backwards compatibility. + * + * @param string $fname Name of called method + * @param array $args Arguments to the method + * @throws MWException + * @return mixed + */ + function __call( $fname, $args ) { + $realFunction = array( 'Linker', $fname ); + if ( is_callable( $realFunction ) ) { + wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' ); + return call_user_func_array( $realFunction, $args ); + } else { + $className = get_class( $this ); + throw new MWException( "Call to undefined method $className::$fname" ); + } + } + +} diff --git a/includes/skins/SkinException.php b/includes/skins/SkinException.php new file mode 100644 index 0000000000..31ff1437e8 --- /dev/null +++ b/includes/skins/SkinException.php @@ -0,0 +1,29 @@ + callback + * @var array + */ + private $factoryFunctions = array(); + /** + * Map of name => human readable name + * @var array + */ + private $displayNames = array(); + + /** + * @var SkinFactory + */ + private static $self; + + public static function getDefaultInstance() { + if ( !self::$self ) { + self::$self = new self; + } + + return self::$self; + } + + /** + * Register a new Skin factory function + * Will override if it's already registered + * @param string $name + * @param string $displayName + * @param callable $callback That takes the skin name as an argument + * @throws InvalidArgumentException If an invalid callback is provided + */ + public function register( $name, $displayName, $callback ) { + if ( !is_callable( $callback ) ) { + throw new InvalidArgumentException( 'Invalid callback provided' ); + } + $this->factoryFunctions[$name] = $callback; + $this->displayNames[$name] = $displayName; + } + + /** + * @return array + */ + private function getLegacySkinNames() { + global $wgValidSkinNames; + static $skinsInitialised = false; + + if ( !$skinsInitialised || !count( $wgValidSkinNames ) ) { + # Get a list of available skins + # Build using the regular expression '^(.*).php$' + # Array keys are all lower case, array value keep the case used by filename + # + wfProfileIn( __METHOD__ . '-init' ); + + global $wgStyleDirectory; + + $skinDir = dir( $wgStyleDirectory ); + + if ( $skinDir !== false && $skinDir !== null ) { + # while code from www.php.net + while ( false !== ( $file = $skinDir->read() ) ) { + // Skip non-PHP files, hidden files, and '.dep' includes + $matches = array(); + + if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) { + $aSkin = $matches[1]; + + // Explicitly disallow loading core skins via the autodiscovery mechanism. + // + // They should be loaded already (in a non-autodicovery way), but old files might still + // exist on the server because our MW version upgrade process is widely documented as + // requiring just copying over all files, without removing old ones. + // + // This is one of the reasons we should have never used autodiscovery in the first + // place. This hack can be safely removed when autodiscovery is gone. + if ( in_array( $aSkin, array( 'CologneBlue', 'Modern', 'MonoBook', 'Vector' ) ) ) { + wfLogWarning( + "An old copy of the $aSkin skin was found in your skins/ directory. " . + "You should remove it to avoid problems in the future." . + "See https://www.mediawiki.org/wiki/Manual:Skin_autodiscovery for details." + ); + continue; + } + + wfLogWarning( + "A skin using autodiscovery mechanism, $aSkin, was found in your skins/ directory. " . + "The mechanism will be removed in MediaWiki 1.25 and the skin will no longer be recognized. " . + "See https://www.mediawiki.org/wiki/Manual:Skin_autodiscovery for information how to fix this." + ); + $wgValidSkinNames[strtolower( $aSkin )] = $aSkin; + } + } + $skinDir->close(); + } + $skinsInitialised = true; + wfProfileOut( __METHOD__ . '-init' ); + } + return $wgValidSkinNames; + + } + + /** + * Returns an associative array of: + * skin name => human readable name + * + * @return array + */ + public function getSkinNames() { + return array_merge( + $this->getLegacySkinNames(), + $this->displayNames + ); + } + + /** + * Get a legacy skin which uses $wgValidSkinNames + * or autoloading + * + * @param string $name + * @return Skin|bool false if the skin couldn't be constructed + */ + private function getLegacySkin( $name ) { + $skinNames = $this->getLegacySkinNames(); + if ( !isset( $skinNames[$name] ) ) { + return false; + } + $skinName = $skinNames[$name]; + $className = "Skin{$skinName}"; + + # Grab the skin class and initialise it. + if ( !class_exists( $className ) ) { + global $wgStyleDirectory; + require_once "{$wgStyleDirectory}/{$skinName}.php"; + + # Check if we got it + if ( !class_exists( $className ) ) { + # DO NOT die if the class isn't found. This breaks maintenance + # scripts and can cause a user account to be unrecoverable + # except by SQL manipulation if a previously valid skin name + # is no longer valid. + return false; + } + } + $skin = new $className( $name ); + return $skin; + + } + + /** + * Create a given Skin using the registered callback for $name. + * @param string $name Name of the skin you want + * @throws SkinException If a factory function isn't registered for $name + * @throws UnexpectedValueException If the factory function returns a non-Skin object + * @return Skin + */ + public function makeSkin( $name ) { + if ( !isset( $this->factoryFunctions[$name] ) ) { + // Check the legacy method of skin loading + $legacy = $this->getLegacySkin( $name ); + if ( $legacy ) { + return $legacy; + } + throw new SkinException( "No registered builder available for $name." ); + } + $skin = call_user_func( $this->factoryFunctions[$name], $name ); + if ( $skin instanceof Skin ) { + return $skin; + } else { + throw new UnexpectedValueException( "The builder for $name returned a non-Skin object." ); + } + } +} diff --git a/includes/skins/SkinFallback.php b/includes/skins/SkinFallback.php new file mode 100644 index 0000000000..6055473b44 --- /dev/null +++ b/includes/skins/SkinFallback.php @@ -0,0 +1,26 @@ +addModuleStyles( 'mediawiki.skinning.interface' ); + } +} diff --git a/includes/skins/SkinFallbackTemplate.php b/includes/skins/SkinFallbackTemplate.php new file mode 100644 index 0000000000..0703b0eee3 --- /dev/null +++ b/includes/skins/SkinFallbackTemplate.php @@ -0,0 +1,109 @@ +config->get( 'StyleDirectory' ); // @todo we should inject this directly? + // Get all subdirectories which might contains skins + $possibleSkins = scandir( $styleDirectory ); + $possibleSkins = array_filter( $possibleSkins, function ( $maybeDir ) use ( $styleDirectory ) { + return $maybeDir !== '.' && $maybeDir !== '..' && is_dir( "$styleDirectory/$maybeDir" ); + } ); + + // Only keep the ones that contain a .php file with the same name inside + $possibleSkins = array_filter( $possibleSkins, function ( $skinDir ) use ( $styleDirectory ) { + return is_file( "$styleDirectory/$skinDir/$skinDir.php" ); + } ); + + return $possibleSkins; + } + + /** + * Inform the user why they are seeing this skin. + * + * @return string + */ + private function buildHelpfulInformationMessage() { + $defaultSkin = $this->config->get( 'DefaultSkin' ); + $installedSkins = $this->findInstalledSkins(); + $enabledSkins = $this->config->get( 'ValidSkinNames' ); + $enabledSkins = array_change_key_case( $enabledSkins, CASE_LOWER ); + + if ( $installedSkins ) { + $skinsInstalledText = array(); + $skinsInstalledSnippet = array(); + + foreach ( $installedSkins as $skin ) { + $normalizedKey = strtolower( $skin ); + $isEnabled = array_key_exists( $normalizedKey, $enabledSkins ); + if ( $isEnabled ) { + $skinsInstalledText[] = $this->getMsg( 'default-skin-not-found-row-enabled' ) + ->params( $normalizedKey, $skin )->plain(); + } else { + $skinsInstalledText[] = $this->getMsg( 'default-skin-not-found-row-disabled' ) + ->params( $normalizedKey, $skin )->plain(); + $skinsInstalledSnippet[] = "require_once \"\$IP/skins/$skin/$skin.php\";"; + } + } + + return $this->getMsg( 'default-skin-not-found' )->params( + $defaultSkin, + implode( "\n", $skinsInstalledText ), + implode( "\n", $skinsInstalledSnippet ) + )->parseAsBlock(); + } else { + return $this->getMsg( 'default-skin-not-found-no-skins' )->params( + $defaultSkin + )->parseAsBlock(); + } + } + + /** + * Outputs the entire contents of the page. No navigation (other than search box), just the big + * warning message and page content. + */ + public function execute() { + $this->html( 'headelement' ) ?> + +
    + buildHelpfulInformationMessage() ?> +
    + +
    + +

    + makeSearchInput( array( "id" => "searchInput" ) ) ?> + makeSearchButton( 'go' ) ?> +
    + +
    +

    + html( 'title' ) ?> +

    + +
    + html( 'bodytext' ) ?> + html( 'catlinks' ) ?> +
    +
    + + printTrail() ?> + + + context[$varName] = $value; + } + + function translate( $value ) { + wfProfileIn( __METHOD__ ); + + // Hack for i18n:attributes in PHPTAL 1.0.0 dev version as of 2004-10-23 + $value = preg_replace( '/^string:/', '', $value ); + + $value = wfMessage( $value )->text(); + // interpolate variables + $m = array(); + while ( preg_match( '/\$([0-9]*?)/sm', $value, $m ) ) { + list( $src, $var ) = $m; + wfSuppressWarnings(); + $varValue = $this->context[$var]; + wfRestoreWarnings(); + $value = str_replace( $src, $varValue, $value ); + } + wfProfileOut( __METHOD__ ); + return $value; + } +} + +/** + * Template-filler skin base class + * Formerly generic PHPTal (http://phptal.sourceforge.net/) skin + * Based on Brion's smarty skin + * @copyright Copyright © Gabriel Wicke -- http://www.aulinx.de/ + * + * @todo Needs some serious refactoring into functions that correspond + * to the computations individual esi snippets need. Most importantly no body + * parsing for most of those of course. + * + * @ingroup Skins + */ +class SkinTemplate extends Skin { + /** + * @var string Name of our skin, it probably needs to be all lower case. + * Child classes should override the default. + */ + public $skinname = 'monobook'; + + /** + * @var string For QuickTemplate, the name of the subclass which will + * actually fill the template. Child classes should override the default. + */ + public $template = 'QuickTemplate'; + + /** + * Add specific styles for this skin + * + * @param OutputPage $out + */ + function setupSkinUserCss( OutputPage $out ) { + $out->addModuleStyles( array( + 'mediawiki.legacy.shared', + 'mediawiki.legacy.commonPrint', + 'mediawiki.ui.button' + ) ); + } + + /** + * Create the template engine object; we feed it a bunch of data + * and eventually it spits out some HTML. Should have interface + * roughly equivalent to PHPTAL 0.7. + * + * @param string $classname + * @param bool|string $repository Subdirectory where we keep template files + * @param bool|string $cache_dir + * @return QuickTemplate + * @private + */ + function setupTemplate( $classname, $repository = false, $cache_dir = false ) { + return new $classname( $this->getConfig() ); + } + + /** + * Generates array of language links for the current page + * + * @return array + */ + public function getLanguages() { + global $wgHideInterlanguageLinks; + if ( $wgHideInterlanguageLinks ) { + return array(); + } + + $userLang = $this->getLanguage(); + $languageLinks = array(); + + foreach ( $this->getOutput()->getLanguageLinks() as $languageLinkText ) { + $languageLinkParts = explode( ':', $languageLinkText, 2 ); + $class = 'interlanguage-link interwiki-' . $languageLinkParts[0]; + unset( $languageLinkParts ); + + $languageLinkTitle = Title::newFromText( $languageLinkText ); + if ( $languageLinkTitle ) { + $ilInterwikiCode = $languageLinkTitle->getInterwiki(); + $ilLangName = Language::fetchLanguageName( $ilInterwikiCode ); + + if ( strval( $ilLangName ) === '' ) { + $ilDisplayTextMsg = wfMessage( "interlanguage-link-$ilInterwikiCode" ); + if ( !$ilDisplayTextMsg->isDisabled() ) { + // Use custom MW message for the display text + $ilLangName = $ilDisplayTextMsg->text(); + } else { + // Last resort: fallback to the language link target + $ilLangName = $languageLinkText; + } + } else { + // Use the language autonym as display text + $ilLangName = $this->formatLanguageName( $ilLangName ); + } + + // CLDR extension or similar is required to localize the language name; + // otherwise we'll end up with the autonym again. + $ilLangLocalName = Language::fetchLanguageName( + $ilInterwikiCode, + $userLang->getCode() + ); + + $languageLinkTitleText = $languageLinkTitle->getText(); + if ( $ilLangLocalName === '' ) { + $ilFriendlySiteName = wfMessage( "interlanguage-link-sitename-$ilInterwikiCode" ); + if ( !$ilFriendlySiteName->isDisabled() ) { + if ( $languageLinkTitleText === '' ) { + $ilTitle = wfMessage( + 'interlanguage-link-title-nonlangonly', + $ilFriendlySiteName->text() + )->text(); + } else { + $ilTitle = wfMessage( + 'interlanguage-link-title-nonlang', + $languageLinkTitleText, + $ilFriendlySiteName->text() + )->text(); + } + } else { + // we have nothing friendly to put in the title, so fall back to + // displaying the interlanguage link itself in the title text + // (similar to what is done in page content) + $ilTitle = $languageLinkTitle->getInterwiki() . + ":$languageLinkTitleText"; + } + } elseif ( $languageLinkTitleText === '' ) { + $ilTitle = wfMessage( + 'interlanguage-link-title-langonly', + $ilLangLocalName + )->text(); + } else { + $ilTitle = wfMessage( + 'interlanguage-link-title', + $languageLinkTitleText, + $ilLangLocalName + )->text(); + } + + $ilInterwikiCodeBCP47 = wfBCP47( $ilInterwikiCode ); + $languageLink = array( + 'href' => $languageLinkTitle->getFullURL(), + 'text' => $ilLangName, + 'title' => $ilTitle, + 'class' => $class, + 'lang' => $ilInterwikiCodeBCP47, + 'hreflang' => $ilInterwikiCodeBCP47, + ); + wfRunHooks( + 'SkinTemplateGetLanguageLink', + array( &$languageLink, $languageLinkTitle, $this->getTitle() ) + ); + $languageLinks[] = $languageLink; + } + } + + return $languageLinks; + } + + protected function setupTemplateForOutput() { + wfProfileIn( __METHOD__ ); + + $request = $this->getRequest(); + $user = $this->getUser(); + $title = $this->getTitle(); + + wfProfileIn( __METHOD__ . '-init' ); + $tpl = $this->setupTemplate( $this->template, 'skins' ); + wfProfileOut( __METHOD__ . '-init' ); + + wfProfileIn( __METHOD__ . '-stuff' ); + $this->thispage = $title->getPrefixedDBkey(); + $this->titletxt = $title->getPrefixedText(); + $this->userpage = $user->getUserPage()->getPrefixedText(); + $query = array(); + if ( !$request->wasPosted() ) { + $query = $request->getValues(); + unset( $query['title'] ); + unset( $query['returnto'] ); + unset( $query['returntoquery'] ); + } + $this->thisquery = wfArrayToCgi( $query ); + $this->loggedin = $user->isLoggedIn(); + $this->username = $user->getName(); + + if ( $this->loggedin || $this->showIPinHeader() ) { + $this->userpageUrlDetails = self::makeUrlDetails( $this->userpage ); + } else { + # This won't be used in the standard skins, but we define it to preserve the interface + # To save time, we check for existence + $this->userpageUrlDetails = self::makeKnownUrlDetails( $this->userpage ); + } + + wfProfileOut( __METHOD__ . '-stuff' ); + + wfProfileOut( __METHOD__ ); + + return $tpl; + } + + /** + * initialize various variables and generate the template + * + * @param OutputPage $out + */ + function outputPage( OutputPage $out = null ) { + wfProfileIn( __METHOD__ ); + Profiler::instance()->setTemplated( true ); + + $oldContext = null; + if ( $out !== null ) { + // @todo Add wfDeprecated in 1.20 + $oldContext = $this->getContext(); + $this->setContext( $out->getContext() ); + } + + $out = $this->getOutput(); + + wfProfileIn( __METHOD__ . '-init' ); + $this->initPage( $out ); + wfProfileOut( __METHOD__ . '-init' ); + $tpl = $this->prepareQuickTemplate( $out ); + // execute template + wfProfileIn( __METHOD__ . '-execute' ); + $res = $tpl->execute(); + wfProfileOut( __METHOD__ . '-execute' ); + + // result may be an error + $this->printOrError( $res ); + + if ( $oldContext ) { + $this->setContext( $oldContext ); + } + + wfProfileOut( __METHOD__ ); + } + + /** + * initialize various variables and generate the template + * + * @since 1.23 + * @return QuickTemplate The template to be executed by outputPage + */ + protected function prepareQuickTemplate() { + global $wgContLang, $wgScript, $wgStylePath, $wgMimeType, $wgJsMimeType, + $wgDisableCounters, $wgSitename, $wgLogo, $wgMaxCredits, + $wgShowCreditsIfMax, $wgPageShowWatchingUsers, $wgArticlePath, + $wgScriptPath, $wgServer; + + wfProfileIn( __METHOD__ ); + + $title = $this->getTitle(); + $request = $this->getRequest(); + $out = $this->getOutput(); + $tpl = $this->setupTemplateForOutput(); + + wfProfileIn( __METHOD__ . '-stuff2' ); + $tpl->set( 'title', $out->getPageTitle() ); + $tpl->set( 'pagetitle', $out->getHTMLTitle() ); + $tpl->set( 'displaytitle', $out->mPageLinkTitle ); + + $tpl->setRef( 'thispage', $this->thispage ); + $tpl->setRef( 'titleprefixeddbkey', $this->thispage ); + $tpl->set( 'titletext', $title->getText() ); + $tpl->set( 'articleid', $title->getArticleID() ); + + $tpl->set( 'isarticle', $out->isArticle() ); + + $subpagestr = $this->subPageSubtitle(); + if ( $subpagestr !== '' ) { + $subpagestr = '' . $subpagestr . ''; + } + $tpl->set( 'subtitle', $subpagestr . $out->getSubtitle() ); + + $undelete = $this->getUndeleteLink(); + if ( $undelete === '' ) { + $tpl->set( 'undelete', '' ); + } else { + $tpl->set( 'undelete', '' . $undelete . '' ); + } + + $tpl->set( 'catlinks', $this->getCategories() ); + if ( $out->isSyndicated() ) { + $feeds = array(); + foreach ( $out->getSyndicationLinks() as $format => $link ) { + $feeds[$format] = array( + // Messages: feed-atom, feed-rss + 'text' => $this->msg( "feed-$format" )->text(), + 'href' => $link + ); + } + $tpl->setRef( 'feeds', $feeds ); + } else { + $tpl->set( 'feeds', false ); + } + + $tpl->setRef( 'mimetype', $wgMimeType ); + $tpl->setRef( 'jsmimetype', $wgJsMimeType ); + $tpl->set( 'charset', 'UTF-8' ); + $tpl->setRef( 'wgScript', $wgScript ); + $tpl->setRef( 'skinname', $this->skinname ); + $tpl->set( 'skinclass', get_class( $this ) ); + $tpl->setRef( 'skin', $this ); + $tpl->setRef( 'stylename', $this->stylename ); + $tpl->set( 'printable', $out->isPrintable() ); + $tpl->set( 'handheld', $request->getBool( 'handheld' ) ); + $tpl->setRef( 'loggedin', $this->loggedin ); + $tpl->set( 'notspecialpage', !$title->isSpecialPage() ); + $tpl->set( 'searchaction', $this->escapeSearchLink() ); + $tpl->set( 'searchtitle', SpecialPage::getTitleFor( 'Search' )->getPrefixedDBkey() ); + $tpl->set( 'search', trim( $request->getVal( 'search' ) ) ); + $tpl->setRef( 'stylepath', $wgStylePath ); + $tpl->setRef( 'articlepath', $wgArticlePath ); + $tpl->setRef( 'scriptpath', $wgScriptPath ); + $tpl->setRef( 'serverurl', $wgServer ); + $tpl->setRef( 'logopath', $wgLogo ); + $tpl->setRef( 'sitename', $wgSitename ); + + $userLang = $this->getLanguage(); + $userLangCode = $userLang->getHtmlCode(); + $userLangDir = $userLang->getDir(); + + $tpl->set( 'lang', $userLangCode ); + $tpl->set( 'dir', $userLangDir ); + $tpl->set( 'rtl', $userLang->isRTL() ); + + $tpl->set( 'capitalizeallnouns', $userLang->capitalizeAllNouns() ? ' capitalize-all-nouns' : '' ); + $tpl->set( 'showjumplinks', true ); // showjumplinks preference has been removed + $tpl->set( 'username', $this->loggedin ? $this->username : null ); + $tpl->setRef( 'userpage', $this->userpage ); + $tpl->setRef( 'userpageurl', $this->userpageUrlDetails['href'] ); + $tpl->set( 'userlang', $userLangCode ); + + // Users can have their language set differently than the + // content of the wiki. For these users, tell the web browser + // that interface elements are in a different language. + $tpl->set( 'userlangattributes', '' ); + $tpl->set( 'specialpageattributes', '' ); # obsolete + // Used by VectorBeta to insert HTML before content but after the + // heading for the page title. Defaults to empty string. + $tpl->set( 'prebodyhtml', '' ); + + if ( $userLangCode !== $wgContLang->getHtmlCode() || $userLangDir !== $wgContLang->getDir() ) { + $escUserlang = htmlspecialchars( $userLangCode ); + $escUserdir = htmlspecialchars( $userLangDir ); + // Attributes must be in double quotes because htmlspecialchars() doesn't + // escape single quotes + $attrs = " lang=\"$escUserlang\" dir=\"$escUserdir\""; + $tpl->set( 'userlangattributes', $attrs ); + } + + wfProfileOut( __METHOD__ . '-stuff2' ); + + wfProfileIn( __METHOD__ . '-stuff3' ); + $tpl->set( 'newtalk', $this->getNewtalks() ); + $tpl->set( 'logo', $this->logoText() ); + + $tpl->set( 'copyright', false ); + $tpl->set( 'viewcount', false ); + $tpl->set( 'lastmod', false ); + $tpl->set( 'credits', false ); + $tpl->set( 'numberofwatchingusers', false ); + if ( $out->isArticle() && $title->exists() ) { + if ( $this->isRevisionCurrent() ) { + if ( !$wgDisableCounters ) { + $viewcount = $this->getWikiPage()->getCount(); + if ( $viewcount ) { + $tpl->set( 'viewcount', $this->msg( 'viewcount' )->numParams( $viewcount )->parse() ); + } + } + + if ( $wgPageShowWatchingUsers ) { + $dbr = wfGetDB( DB_SLAVE ); + $num = $dbr->selectField( 'watchlist', 'COUNT(*)', + array( 'wl_title' => $title->getDBkey(), 'wl_namespace' => $title->getNamespace() ), + __METHOD__ + ); + if ( $num > 0 ) { + $tpl->set( 'numberofwatchingusers', + $this->msg( 'number_of_watching_users_pageview' )->numParams( $num )->parse() + ); + } + } + + if ( $wgMaxCredits != 0 ) { + $tpl->set( 'credits', Action::factory( 'credits', $this->getWikiPage(), + $this->getContext() )->getCredits( $wgMaxCredits, $wgShowCreditsIfMax ) ); + } else { + $tpl->set( 'lastmod', $this->lastModified() ); + } + } + $tpl->set( 'copyright', $this->getCopyright() ); + } + wfProfileOut( __METHOD__ . '-stuff3' ); + + wfProfileIn( __METHOD__ . '-stuff4' ); + $tpl->set( 'copyrightico', $this->getCopyrightIcon() ); + $tpl->set( 'poweredbyico', $this->getPoweredBy() ); + $tpl->set( 'disclaimer', $this->disclaimerLink() ); + $tpl->set( 'privacy', $this->privacyLink() ); + $tpl->set( 'about', $this->aboutLink() ); + + $tpl->set( 'footerlinks', array( + 'info' => array( + 'lastmod', + 'viewcount', + 'numberofwatchingusers', + 'credits', + 'copyright', + ), + 'places' => array( + 'privacy', + 'about', + 'disclaimer', + ), + ) ); + + global $wgFooterIcons; + $tpl->set( 'footericons', $wgFooterIcons ); + foreach ( $tpl->data['footericons'] as $footerIconsKey => &$footerIconsBlock ) { + if ( count( $footerIconsBlock ) > 0 ) { + foreach ( $footerIconsBlock as &$footerIcon ) { + if ( isset( $footerIcon['src'] ) ) { + if ( !isset( $footerIcon['width'] ) ) { + $footerIcon['width'] = 88; + } + if ( !isset( $footerIcon['height'] ) ) { + $footerIcon['height'] = 31; + } + } + } + } else { + unset( $tpl->data['footericons'][$footerIconsKey] ); + } + } + + $tpl->set( 'sitenotice', $this->getSiteNotice() ); + $tpl->set( 'bottomscripts', $this->bottomScripts() ); + $tpl->set( 'printfooter', $this->printSource() ); + + # An ID that includes the actual body text; without categories, contentSub, ... + $realBodyAttribs = array( 'id' => 'mw-content-text' ); + + # Add a mw-content-ltr/rtl class to be able to style based on text direction + # when the content is different from the UI language, i.e.: + # not for special pages or file pages AND only when viewing AND if the page exists + # (or is in MW namespace, because that has default content) + if ( !in_array( $title->getNamespace(), array( NS_SPECIAL, NS_FILE ) ) && + Action::getActionName( $this ) === 'view' && + ( $title->exists() || $title->getNamespace() == NS_MEDIAWIKI ) ) { + $pageLang = $title->getPageViewLanguage(); + $realBodyAttribs['lang'] = $pageLang->getHtmlCode(); + $realBodyAttribs['dir'] = $pageLang->getDir(); + $realBodyAttribs['class'] = 'mw-content-' . $pageLang->getDir(); + } + + $out->mBodytext = Html::rawElement( 'div', $realBodyAttribs, $out->mBodytext ); + $tpl->setRef( 'bodytext', $out->mBodytext ); + + $language_urls = $this->getLanguages(); + if ( count( $language_urls ) ) { + $tpl->setRef( 'language_urls', $language_urls ); + } else { + $tpl->set( 'language_urls', false ); + } + wfProfileOut( __METHOD__ . '-stuff4' ); + + wfProfileIn( __METHOD__ . '-stuff5' ); + # Personal toolbar + $tpl->set( 'personal_urls', $this->buildPersonalUrls() ); + $content_navigation = $this->buildContentNavigationUrls(); + $content_actions = $this->buildContentActionUrls( $content_navigation ); + $tpl->setRef( 'content_navigation', $content_navigation ); + $tpl->setRef( 'content_actions', $content_actions ); + + $tpl->set( 'sidebar', $this->buildSidebar() ); + $tpl->set( 'nav_urls', $this->buildNavUrls() ); + + // Set the head scripts near the end, in case the above actions resulted in added scripts + $tpl->set( 'headelement', $out->headElement( $this ) ); + + $tpl->set( 'debug', '' ); + $tpl->set( 'debughtml', $this->generateDebugHTML() ); + $tpl->set( 'reporttime', wfReportTime() ); + + // original version by hansm + if ( !wfRunHooks( 'SkinTemplateOutputPageBeforeExec', array( &$this, &$tpl ) ) ) { + wfDebug( __METHOD__ . ": Hook SkinTemplateOutputPageBeforeExec broke outputPage execution!\n" ); + } + + // Set the bodytext to another key so that skins can just output it on it's own + // and output printfooter and debughtml separately + $tpl->set( 'bodycontent', $tpl->data['bodytext'] ); + + // Append printfooter and debughtml onto bodytext so that skins that + // were already using bodytext before they were split out don't suddenly + // start not outputting information. + $tpl->data['bodytext'] .= Html::rawElement( + 'div', + array( 'class' => 'printfooter' ), + "\n{$tpl->data['printfooter']}" + ) . "\n"; + $tpl->data['bodytext'] .= $tpl->data['debughtml']; + + // allow extensions adding stuff after the page content. + // See Skin::afterContentHook() for further documentation. + $tpl->set( 'dataAfterContent', $this->afterContentHook() ); + wfProfileOut( __METHOD__ . '-stuff5' ); + + wfProfileOut( __METHOD__ ); + return $tpl; + } + + /** + * Get the HTML for the p-personal list + * @return string + */ + public function getPersonalToolsList() { + $tpl = $this->setupTemplateForOutput(); + $tpl->set( 'personal_urls', $this->buildPersonalUrls() ); + $html = ''; + foreach ( $tpl->getPersonalTools() as $key => $item ) { + $html .= $tpl->makeListItem( $key, $item ); + } + return $html; + } + + /** + * Format language name for use in sidebar interlanguage links list. + * By default it is capitalized. + * + * @param string $name Language name, e.g. "English" or "español" + * @return string + * @private + */ + function formatLanguageName( $name ) { + return $this->getLanguage()->ucfirst( $name ); + } + + /** + * Output the string, or print error message if it's + * an error object of the appropriate type. + * For the base class, assume strings all around. + * + * @param string $str + * @private + */ + function printOrError( $str ) { + echo $str; + } + + /** + * Output a boolean indicating if buildPersonalUrls should output separate + * login and create account links or output a combined link + * By default we simply return a global config setting that affects most skins + * This is setup as a method so that like with $wgLogo and getLogo() a skin + * can override this setting and always output one or the other if it has + * a reason it can't output one of the two modes. + * @return bool + */ + function useCombinedLoginLink() { + global $wgUseCombinedLoginLink; + return $wgUseCombinedLoginLink; + } + + /** + * build array of urls for personal toolbar + * @return array + */ + protected function buildPersonalUrls() { + $title = $this->getTitle(); + $request = $this->getRequest(); + $pageurl = $title->getLocalURL(); + wfProfileIn( __METHOD__ ); + + /* set up the default links for the personal toolbar */ + $personal_urls = array(); + + # Due to bug 32276, if a user does not have read permissions, + # $this->getTitle() will just give Special:Badtitle, which is + # not especially useful as a returnto parameter. Use the title + # from the request instead, if there was one. + if ( $this->getUser()->isAllowed( 'read' ) ) { + $page = $this->getTitle(); + } else { + $page = Title::newFromText( $request->getVal( 'title', '' ) ); + } + $page = $request->getVal( 'returnto', $page ); + $a = array(); + if ( strval( $page ) !== '' ) { + $a['returnto'] = $page; + $query = $request->getVal( 'returntoquery', $this->thisquery ); + if ( $query != '' ) { + $a['returntoquery'] = $query; + } + } + + $returnto = wfArrayToCgi( $a ); + if ( $this->loggedin ) { + $personal_urls['userpage'] = array( + 'text' => $this->username, + 'href' => &$this->userpageUrlDetails['href'], + 'class' => $this->userpageUrlDetails['exists'] ? false : 'new', + 'active' => ( $this->userpageUrlDetails['href'] == $pageurl ), + 'dir' => 'auto' + ); + $usertalkUrlDetails = $this->makeTalkUrlDetails( $this->userpage ); + $personal_urls['mytalk'] = array( + 'text' => $this->msg( 'mytalk' )->text(), + 'href' => &$usertalkUrlDetails['href'], + 'class' => $usertalkUrlDetails['exists'] ? false : 'new', + 'active' => ( $usertalkUrlDetails['href'] == $pageurl ) + ); + $href = self::makeSpecialUrl( 'Preferences' ); + $personal_urls['preferences'] = array( + 'text' => $this->msg( 'mypreferences' )->text(), + 'href' => $href, + 'active' => ( $href == $pageurl ) + ); + + if ( $this->getUser()->isAllowed( 'viewmywatchlist' ) ) { + $href = self::makeSpecialUrl( 'Watchlist' ); + $personal_urls['watchlist'] = array( + 'text' => $this->msg( 'mywatchlist' )->text(), + 'href' => $href, + 'active' => ( $href == $pageurl ) + ); + } + + # We need to do an explicit check for Special:Contributions, as we + # have to match both the title, and the target, which could come + # from request values (Special:Contributions?target=Jimbo_Wales) + # or be specified in "sub page" form + # (Special:Contributions/Jimbo_Wales). The plot + # thickens, because the Title object is altered for special pages, + # so it doesn't contain the original alias-with-subpage. + $origTitle = Title::newFromText( $request->getText( 'title' ) ); + if ( $origTitle instanceof Title && $origTitle->isSpecialPage() ) { + list( $spName, $spPar ) = SpecialPageFactory::resolveAlias( $origTitle->getText() ); + $active = $spName == 'Contributions' + && ( ( $spPar && $spPar == $this->username ) + || $request->getText( 'target' ) == $this->username ); + } else { + $active = false; + } + + $href = self::makeSpecialUrlSubpage( 'Contributions', $this->username ); + $personal_urls['mycontris'] = array( + 'text' => $this->msg( 'mycontris' )->text(), + 'href' => $href, + 'active' => $active + ); + $personal_urls['logout'] = array( + 'text' => $this->msg( 'pt-userlogout' )->text(), + 'href' => self::makeSpecialUrl( 'Userlogout', + // userlogout link must always contain an & character, otherwise we might not be able + // to detect a buggy precaching proxy (bug 17790) + $title->isSpecial( 'Preferences' ) ? 'noreturnto' : $returnto + ), + 'active' => false + ); + } else { + $useCombinedLoginLink = $this->useCombinedLoginLink(); + $loginlink = $this->getUser()->isAllowed( 'createaccount' ) && $useCombinedLoginLink + ? 'nav-login-createaccount' + : 'pt-login'; + $is_signup = $request->getText( 'type' ) == 'signup'; + + $login_url = array( + 'text' => $this->msg( $loginlink )->text(), + 'href' => self::makeSpecialUrl( 'Userlogin', $returnto ), + 'active' => $title->isSpecial( 'Userlogin' ) + && ( $loginlink == 'nav-login-createaccount' || !$is_signup ), + ); + $createaccount_url = array( + 'text' => $this->msg( 'pt-createaccount' )->text(), + 'href' => self::makeSpecialUrl( 'Userlogin', "$returnto&type=signup" ), + 'active' => $title->isSpecial( 'Userlogin' ) && $is_signup, + ); + + if ( $this->showIPinHeader() ) { + $href = &$this->userpageUrlDetails['href']; + $personal_urls['anonuserpage'] = array( + 'text' => $this->username, + 'href' => $href, + 'class' => $this->userpageUrlDetails['exists'] ? false : 'new', + 'active' => ( $pageurl == $href ) + ); + $usertalkUrlDetails = $this->makeTalkUrlDetails( $this->userpage ); + $href = &$usertalkUrlDetails['href']; + $personal_urls['anontalk'] = array( + 'text' => $this->msg( 'anontalk' )->text(), + 'href' => $href, + 'class' => $usertalkUrlDetails['exists'] ? false : 'new', + 'active' => ( $pageurl == $href ) + ); + } + + if ( $this->getUser()->isAllowed( 'createaccount' ) && !$useCombinedLoginLink ) { + $personal_urls['createaccount'] = $createaccount_url; + } + + $personal_urls['login'] = $login_url; + } + + wfRunHooks( 'PersonalUrls', array( &$personal_urls, &$title, $this ) ); + wfProfileOut( __METHOD__ ); + return $personal_urls; + } + + /** + * Builds an array with tab definition + * + * @param Title $title Page Where the tab links to + * @param string|array $message Message key or an array of message keys (will fall back) + * @param bool $selected Display the tab as selected + * @param string $query Query string attached to tab URL + * @param bool $checkEdit Check if $title exists and mark with .new if one doesn't + * + * @return array + */ + function tabAction( $title, $message, $selected, $query = '', $checkEdit = false ) { + $classes = array(); + if ( $selected ) { + $classes[] = 'selected'; + } + if ( $checkEdit && !$title->isKnown() ) { + $classes[] = 'new'; + if ( $query !== '' ) { + $query = 'action=edit&redlink=1&' . $query; + } else { + $query = 'action=edit&redlink=1'; + } + } + + // wfMessageFallback will nicely accept $message as an array of fallbacks + // or just a single key + $msg = wfMessageFallback( $message )->setContext( $this->getContext() ); + if ( is_array( $message ) ) { + // for hook compatibility just keep the last message name + $message = end( $message ); + } + if ( $msg->exists() ) { + $text = $msg->text(); + } else { + global $wgContLang; + $text = $wgContLang->getFormattedNsText( + MWNamespace::getSubject( $title->getNamespace() ) ); + } + + $result = array(); + if ( !wfRunHooks( 'SkinTemplateTabAction', array( &$this, + $title, $message, $selected, $checkEdit, + &$classes, &$query, &$text, &$result ) ) ) { + return $result; + } + + return array( + 'class' => implode( ' ', $classes ), + 'text' => $text, + 'href' => $title->getLocalURL( $query ), + 'primary' => true ); + } + + function makeTalkUrlDetails( $name, $urlaction = '' ) { + $title = Title::newFromText( $name ); + if ( !is_object( $title ) ) { + throw new MWException( __METHOD__ . " given invalid pagename $name" ); + } + $title = $title->getTalkPage(); + self::checkTitle( $title, $name ); + return array( + 'href' => $title->getLocalURL( $urlaction ), + 'exists' => $title->getArticleID() != 0, + ); + } + + function makeArticleUrlDetails( $name, $urlaction = '' ) { + $title = Title::newFromText( $name ); + $title = $title->getSubjectPage(); + self::checkTitle( $title, $name ); + return array( + 'href' => $title->getLocalURL( $urlaction ), + 'exists' => $title->getArticleID() != 0, + ); + } + + /** + * a structured array of links usually used for the tabs in a skin + * + * There are 4 standard sections + * namespaces: Used for namespace tabs like special, page, and talk namespaces + * views: Used for primary page views like read, edit, history + * actions: Used for most extra page actions like deletion, protection, etc... + * variants: Used to list the language variants for the page + * + * Each section's value is a key/value array of links for that section. + * The links themselves have these common keys: + * - class: The css classes to apply to the tab + * - text: The text to display on the tab + * - href: The href for the tab to point to + * - rel: An optional rel= for the tab's link + * - redundant: If true the tab will be dropped in skins using content_actions + * this is useful for tabs like "Read" which only have meaning in skins that + * take special meaning from the grouped structure of content_navigation + * + * Views also have an extra key which can be used: + * - primary: If this is not true skins like vector may try to hide the tab + * when the user has limited space in their browser window + * + * content_navigation using code also expects these ids to be present on the + * links, however these are usually automatically generated by SkinTemplate + * itself and are not necessary when using a hook. The only things these may + * matter to are people modifying content_navigation after it's initial creation: + * - id: A "preferred" id, most skins are best off outputting this preferred + * id for best compatibility. + * - tooltiponly: This is set to true for some tabs in cases where the system + * believes that the accesskey should not be added to the tab. + * + * @return array + */ + protected function buildContentNavigationUrls() { + global $wgDisableLangConversion; + + wfProfileIn( __METHOD__ ); + + // Display tabs for the relevant title rather than always the title itself + $title = $this->getRelevantTitle(); + $onPage = $title->equals( $this->getTitle() ); + + $out = $this->getOutput(); + $request = $this->getRequest(); + $user = $this->getUser(); + + $content_navigation = array( + 'namespaces' => array(), + 'views' => array(), + 'actions' => array(), + 'variants' => array() + ); + + // parameters + $action = $request->getVal( 'action', 'view' ); + + $userCanRead = $title->quickUserCan( 'read', $user ); + + $preventActiveTabs = false; + wfRunHooks( 'SkinTemplatePreventOtherActiveTabs', array( &$this, &$preventActiveTabs ) ); + + // Checks if page is some kind of content + if ( $title->canExist() ) { + // Gets page objects for the related namespaces + $subjectPage = $title->getSubjectPage(); + $talkPage = $title->getTalkPage(); + + // Determines if this is a talk page + $isTalk = $title->isTalkPage(); + + // Generates XML IDs from namespace names + $subjectId = $title->getNamespaceKey( '' ); + + if ( $subjectId == 'main' ) { + $talkId = 'talk'; + } else { + $talkId = "{$subjectId}_talk"; + } + + $skname = $this->skinname; + + // Adds namespace links + $subjectMsg = array( "nstab-$subjectId" ); + if ( $subjectPage->isMainPage() ) { + array_unshift( $subjectMsg, 'mainpage-nstab' ); + } + $content_navigation['namespaces'][$subjectId] = $this->tabAction( + $subjectPage, $subjectMsg, !$isTalk && !$preventActiveTabs, '', $userCanRead + ); + $content_navigation['namespaces'][$subjectId]['context'] = 'subject'; + $content_navigation['namespaces'][$talkId] = $this->tabAction( + $talkPage, array( "nstab-$talkId", 'talk' ), $isTalk && !$preventActiveTabs, '', $userCanRead + ); + $content_navigation['namespaces'][$talkId]['context'] = 'talk'; + + if ( $userCanRead ) { + $isForeignFile = $title->inNamespace( NS_FILE ) && $this->canUseWikiPage() && + $this->getWikiPage() instanceof WikiFilePage && !$this->getWikiPage()->isLocal(); + + // Adds view view link + if ( $title->exists() || $isForeignFile ) { + $content_navigation['views']['view'] = $this->tabAction( + $isTalk ? $talkPage : $subjectPage, + array( "$skname-view-view", 'view' ), + ( $onPage && ( $action == 'view' || $action == 'purge' ) ), '', true + ); + // signal to hide this from simple content_actions + $content_navigation['views']['view']['redundant'] = true; + } + + // If it is a non-local file, show a link to the file in its own repository + if ( $isForeignFile ) { + $file = $this->getWikiPage()->getFile(); + $content_navigation['views']['view-foreign'] = array( + 'class' => '', + 'text' => wfMessageFallback( "$skname-view-foreign", 'view-foreign' )-> + setContext( $this->getContext() )-> + params( $file->getRepo()->getDisplayName() )->text(), + 'href' => $file->getDescriptionUrl(), + 'primary' => false, + ); + } + + wfProfileIn( __METHOD__ . '-edit' ); + + // Checks if user can edit the current page if it exists or create it otherwise + if ( $title->quickUserCan( 'edit', $user ) + && ( $title->exists() || $title->quickUserCan( 'create', $user ) ) + ) { + // Builds CSS class for talk page links + $isTalkClass = $isTalk ? ' istalk' : ''; + // Whether the user is editing the page + $isEditing = $onPage && ( $action == 'edit' || $action == 'submit' ); + // Whether to show the "Add a new section" tab + // Checks if this is a current rev of talk page and is not forced to be hidden + $showNewSection = !$out->forceHideNewSectionLink() + && ( ( $isTalk && $this->isRevisionCurrent() ) || $out->showNewSectionLink() ); + $section = $request->getVal( 'section' ); + + if ( $title->exists() + || ( $title->getNamespace() == NS_MEDIAWIKI + && $title->getDefaultMessageText() !== false + ) + ) { + $msgKey = $isForeignFile ? 'edit-local' : 'edit'; + } else { + $msgKey = $isForeignFile ? 'create-local' : 'create'; + } + $content_navigation['views']['edit'] = array( + 'class' => ( $isEditing && ( $section !== 'new' || !$showNewSection ) + ? 'selected' + : '' + ) . $isTalkClass, + 'text' => wfMessageFallback( "$skname-view-$msgKey", $msgKey ) + ->setContext( $this->getContext() )->text(), + 'href' => $title->getLocalURL( $this->editUrlOptions() ), + 'primary' => !$isForeignFile, // don't collapse this in vector + ); + + // section link + if ( $showNewSection ) { + // Adds new section link + //$content_navigation['actions']['addsection'] + $content_navigation['views']['addsection'] = array( + 'class' => ( $isEditing && $section == 'new' ) ? 'selected' : false, + 'text' => wfMessageFallback( "$skname-action-addsection", 'addsection' ) + ->setContext( $this->getContext() )->text(), + 'href' => $title->getLocalURL( 'action=edit§ion=new' ) + ); + } + // Checks if the page has some kind of viewable content + } elseif ( $title->hasSourceText() ) { + // Adds view source view link + $content_navigation['views']['viewsource'] = array( + 'class' => ( $onPage && $action == 'edit' ) ? 'selected' : false, + 'text' => wfMessageFallback( "$skname-action-viewsource", 'viewsource' ) + ->setContext( $this->getContext() )->text(), + 'href' => $title->getLocalURL( $this->editUrlOptions() ), + 'primary' => true, // don't collapse this in vector + ); + } + wfProfileOut( __METHOD__ . '-edit' ); + + wfProfileIn( __METHOD__ . '-live' ); + // Checks if the page exists + if ( $title->exists() ) { + // Adds history view link + $content_navigation['views']['history'] = array( + 'class' => ( $onPage && $action == 'history' ) ? 'selected' : false, + 'text' => wfMessageFallback( "$skname-view-history", 'history_short' ) + ->setContext( $this->getContext() )->text(), + 'href' => $title->getLocalURL( 'action=history' ), + 'rel' => 'archives', + ); + + if ( $title->quickUserCan( 'delete', $user ) ) { + $content_navigation['actions']['delete'] = array( + 'class' => ( $onPage && $action == 'delete' ) ? 'selected' : false, + 'text' => wfMessageFallback( "$skname-action-delete", 'delete' ) + ->setContext( $this->getContext() )->text(), + 'href' => $title->getLocalURL( 'action=delete' ) + ); + } + + if ( $title->quickUserCan( 'move', $user ) ) { + $moveTitle = SpecialPage::getTitleFor( 'Movepage', $title->getPrefixedDBkey() ); + $content_navigation['actions']['move'] = array( + 'class' => $this->getTitle()->isSpecial( 'Movepage' ) ? 'selected' : false, + 'text' => wfMessageFallback( "$skname-action-move", 'move' ) + ->setContext( $this->getContext() )->text(), + 'href' => $moveTitle->getLocalURL() + ); + } + } else { + // article doesn't exist or is deleted + if ( $user->isAllowed( 'deletedhistory' ) ) { + $n = $title->isDeleted(); + if ( $n ) { + $undelTitle = SpecialPage::getTitleFor( 'Undelete' ); + // If the user can't undelete but can view deleted + // history show them a "View .. deleted" tab instead. + $msgKey = $user->isAllowed( 'undelete' ) ? 'undelete' : 'viewdeleted'; + $content_navigation['actions']['undelete'] = array( + 'class' => $this->getTitle()->isSpecial( 'Undelete' ) ? 'selected' : false, + 'text' => wfMessageFallback( "$skname-action-$msgKey", "{$msgKey}_short" ) + ->setContext( $this->getContext() )->numParams( $n )->text(), + 'href' => $undelTitle->getLocalURL( array( 'target' => $title->getPrefixedDBkey() ) ) + ); + } + } + } + + if ( $title->quickUserCan( 'protect', $user ) && $title->getRestrictionTypes() && + MWNamespace::getRestrictionLevels( $title->getNamespace(), $user ) !== array( '' ) + ) { + $mode = $title->isProtected() ? 'unprotect' : 'protect'; + $content_navigation['actions'][$mode] = array( + 'class' => ( $onPage && $action == $mode ) ? 'selected' : false, + 'text' => wfMessageFallback( "$skname-action-$mode", $mode ) + ->setContext( $this->getContext() )->text(), + 'href' => $title->getLocalURL( "action=$mode" ) + ); + } + + wfProfileOut( __METHOD__ . '-live' ); + + // Checks if the user is logged in + if ( $this->loggedin && $user->isAllowedAll( 'viewmywatchlist', 'editmywatchlist' ) ) { + /** + * The following actions use messages which, if made particular to + * the any specific skins, would break the Ajax code which makes this + * action happen entirely inline. OutputPage::getJSVars + * defines a set of messages in a javascript object - and these + * messages are assumed to be global for all skins. Without making + * a change to that procedure these messages will have to remain as + * the global versions. + */ + $mode = $user->isWatched( $title ) ? 'unwatch' : 'watch'; + $token = WatchAction::getWatchToken( $title, $user, $mode ); + $content_navigation['actions'][$mode] = array( + 'class' => $onPage && ( $action == 'watch' || $action == 'unwatch' ) ? 'selected' : false, + // uses 'watch' or 'unwatch' message + 'text' => $this->msg( $mode )->text(), + 'href' => $title->getLocalURL( array( 'action' => $mode, 'token' => $token ) ) + ); + } + } + + wfRunHooks( 'SkinTemplateNavigation', array( &$this, &$content_navigation ) ); + + if ( $userCanRead && !$wgDisableLangConversion ) { + $pageLang = $title->getPageLanguage(); + // Gets list of language variants + $variants = $pageLang->getVariants(); + // Checks that language conversion is enabled and variants exist + // And if it is not in the special namespace + if ( count( $variants ) > 1 ) { + // Gets preferred variant (note that user preference is + // only possible for wiki content language variant) + $preferred = $pageLang->getPreferredVariant(); + if ( Action::getActionName( $this ) === 'view' ) { + $params = $request->getQueryValues(); + unset( $params['title'] ); + } else { + $params = array(); + } + // Loops over each variant + foreach ( $variants as $code ) { + // Gets variant name from language code + $varname = $pageLang->getVariantname( $code ); + // Appends variant link + $content_navigation['variants'][] = array( + 'class' => ( $code == $preferred ) ? 'selected' : false, + 'text' => $varname, + 'href' => $title->getLocalURL( array( 'variant' => $code ) + $params ), + 'lang' => wfBCP47( $code ), + 'hreflang' => wfBCP47( $code ), + ); + } + } + } + } else { + // If it's not content, it's got to be a special page + $content_navigation['namespaces']['special'] = array( + 'class' => 'selected', + 'text' => $this->msg( 'nstab-special' )->text(), + 'href' => $request->getRequestURL(), // @see: bug 2457, bug 2510 + 'context' => 'subject' + ); + + wfRunHooks( 'SkinTemplateNavigation::SpecialPage', + array( &$this, &$content_navigation ) ); + } + + // Equiv to SkinTemplateContentActions + wfRunHooks( 'SkinTemplateNavigation::Universal', array( &$this, &$content_navigation ) ); + + // Setup xml ids and tooltip info + foreach ( $content_navigation as $section => &$links ) { + foreach ( $links as $key => &$link ) { + $xmlID = $key; + if ( isset( $link['context'] ) && $link['context'] == 'subject' ) { + $xmlID = 'ca-nstab-' . $xmlID; + } elseif ( isset( $link['context'] ) && $link['context'] == 'talk' ) { + $xmlID = 'ca-talk'; + } elseif ( $section == 'variants' ) { + $xmlID = 'ca-varlang-' . $xmlID; + } else { + $xmlID = 'ca-' . $xmlID; + } + $link['id'] = $xmlID; + } + } + + # We don't want to give the watch tab an accesskey if the + # page is being edited, because that conflicts with the + # accesskey on the watch checkbox. We also don't want to + # give the edit tab an accesskey, because that's fairly + # superfluous and conflicts with an accesskey (Ctrl-E) often + # used for editing in Safari. + if ( in_array( $action, array( 'edit', 'submit' ) ) ) { + if ( isset( $content_navigation['views']['edit'] ) ) { + $content_navigation['views']['edit']['tooltiponly'] = true; + } + if ( isset( $content_navigation['actions']['watch'] ) ) { + $content_navigation['actions']['watch']['tooltiponly'] = true; + } + if ( isset( $content_navigation['actions']['unwatch'] ) ) { + $content_navigation['actions']['unwatch']['tooltiponly'] = true; + } + } + + wfProfileOut( __METHOD__ ); + + return $content_navigation; + } + + /** + * an array of edit links by default used for the tabs + * @param array $content_navigation + * @return array + */ + private function buildContentActionUrls( $content_navigation ) { + + wfProfileIn( __METHOD__ ); + + // content_actions has been replaced with content_navigation for backwards + // compatibility and also for skins that just want simple tabs content_actions + // is now built by flattening the content_navigation arrays into one + + $content_actions = array(); + + foreach ( $content_navigation as $links ) { + foreach ( $links as $key => $value ) { + if ( isset( $value['redundant'] ) && $value['redundant'] ) { + // Redundant tabs are dropped from content_actions + continue; + } + + // content_actions used to have ids built using the "ca-$key" pattern + // so the xmlID based id is much closer to the actual $key that we want + // for that reason we'll just strip out the ca- if present and use + // the latter potion of the "id" as the $key + if ( isset( $value['id'] ) && substr( $value['id'], 0, 3 ) == 'ca-' ) { + $key = substr( $value['id'], 3 ); + } + + if ( isset( $content_actions[$key] ) ) { + wfDebug( __METHOD__ . ": Found a duplicate key for $key while flattening " . + "content_navigation into content_actions.\n" ); + continue; + } + + $content_actions[$key] = $value; + } + } + + wfProfileOut( __METHOD__ ); + + return $content_actions; + } + + /** + * build array of common navigation links + * @return array + */ + protected function buildNavUrls() { + global $wgUploadNavigationUrl; + + wfProfileIn( __METHOD__ ); + + $out = $this->getOutput(); + $request = $this->getRequest(); + + $nav_urls = array(); + $nav_urls['mainpage'] = array( 'href' => self::makeMainPageUrl() ); + if ( $wgUploadNavigationUrl ) { + $nav_urls['upload'] = array( 'href' => $wgUploadNavigationUrl ); + } elseif ( UploadBase::isEnabled() && UploadBase::isAllowed( $this->getUser() ) === true ) { + $nav_urls['upload'] = array( 'href' => self::makeSpecialUrl( 'Upload' ) ); + } else { + $nav_urls['upload'] = false; + } + $nav_urls['specialpages'] = array( 'href' => self::makeSpecialUrl( 'Specialpages' ) ); + + $nav_urls['print'] = false; + $nav_urls['permalink'] = false; + $nav_urls['info'] = false; + $nav_urls['whatlinkshere'] = false; + $nav_urls['recentchangeslinked'] = false; + $nav_urls['contributions'] = false; + $nav_urls['log'] = false; + $nav_urls['blockip'] = false; + $nav_urls['emailuser'] = false; + $nav_urls['userrights'] = false; + + // A print stylesheet is attached to all pages, but nobody ever + // figures that out. :) Add a link... + if ( !$out->isPrintable() && ( $out->isArticle() || $this->getTitle()->isSpecialPage() ) ) { + $nav_urls['print'] = array( + 'text' => $this->msg( 'printableversion' )->text(), + 'href' => $this->getTitle()->getLocalURL( + $request->appendQueryValue( 'printable', 'yes', true ) ) + ); + } + + if ( $out->isArticle() ) { + // Also add a "permalink" while we're at it + $revid = $this->getRevisionId(); + if ( $revid ) { + $nav_urls['permalink'] = array( + 'text' => $this->msg( 'permalink' )->text(), + 'href' => $this->getTitle()->getLocalURL( "oldid=$revid" ) + ); + } + + // Use the copy of revision ID in case this undocumented, shady hook tries to mess with internals + wfRunHooks( 'SkinTemplateBuildNavUrlsNav_urlsAfterPermalink', + array( &$this, &$nav_urls, &$revid, &$revid ) ); + } + + if ( $out->isArticleRelated() ) { + $nav_urls['whatlinkshere'] = array( + 'href' => SpecialPage::getTitleFor( 'Whatlinkshere', $this->thispage )->getLocalURL() + ); + + $nav_urls['info'] = array( + 'text' => $this->msg( 'pageinfo-toolboxlink' )->text(), + 'href' => $this->getTitle()->getLocalURL( "action=info" ) + ); + + if ( $this->getTitle()->getArticleID() ) { + $nav_urls['recentchangeslinked'] = array( + 'href' => SpecialPage::getTitleFor( 'Recentchangeslinked', $this->thispage )->getLocalURL() + ); + } + } + + $user = $this->getRelevantUser(); + if ( $user ) { + $rootUser = $user->getName(); + + $nav_urls['contributions'] = array( + 'text' => $this->msg( 'contributions', $rootUser )->text(), + 'href' => self::makeSpecialUrlSubpage( 'Contributions', $rootUser ) + ); + + $nav_urls['log'] = array( + 'href' => self::makeSpecialUrlSubpage( 'Log', $rootUser ) + ); + + if ( $this->getUser()->isAllowed( 'block' ) ) { + $nav_urls['blockip'] = array( + 'text' => $this->msg( 'blockip', $rootUser )->text(), + 'href' => self::makeSpecialUrlSubpage( 'Block', $rootUser ) + ); + } + + if ( $this->showEmailUser( $user ) ) { + $nav_urls['emailuser'] = array( + 'href' => self::makeSpecialUrlSubpage( 'Emailuser', $rootUser ) + ); + } + + if ( !$user->isAnon() ) { + $sur = new UserrightsPage; + $sur->setContext( $this->getContext() ); + if ( $sur->userCanExecute( $this->getUser() ) ) { + $nav_urls['userrights'] = array( + 'href' => self::makeSpecialUrlSubpage( 'Userrights', $rootUser ) + ); + } + } + } + + wfProfileOut( __METHOD__ ); + return $nav_urls; + } + + /** + * Generate strings used for xml 'id' names + * @return string + */ + protected function getNameSpaceKey() { + return $this->getTitle()->getNamespaceKey(); + } +} + +/** + * Generic wrapper for template functions, with interface + * compatible with what we use of PHPTAL 0.7. + * @ingroup Skins + */ +abstract class QuickTemplate { + + /** @var Config $config */ + protected $config; + /** + * @var Config $config + */ + function __construct( Config $config = null ) { + $this->data = array(); + $this->translator = new MediaWikiI18N(); + if ( $config === null ) { + wfDebug( __METHOD__ . ' was called with no Config instance passed to it' ); + $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' ); + } + $this->config = $config; + } + + /** + * Sets the value $value to $name + * @param string $name + * @param mixed $value + */ + public function set( $name, $value ) { + $this->data[$name] = $value; + } + + /** + * Gets the template data requested + * @since 1.22 + * @param string $name Key for the data + * @param mixed $default Optional default (or null) + * @return mixed The value of the data requested or the deafult + */ + public function get( $name, $default = null ) { + if ( isset( $this->data[$name] ) ) { + return $this->data[$name]; + } else { + return $default; + } + } + + /** + * @param string $name + * @param mixed $value + */ + public function setRef( $name, &$value ) { + $this->data[$name] =& $value; + } + + /** + * @param MediaWikiI18N $t + */ + public function setTranslator( &$t ) { + $this->translator = &$t; + } + + /** + * Main function, used by classes that subclass QuickTemplate + * to show the actual HTML output + */ + abstract public function execute(); + + /** + * @private + * @param string $str + * @return string + */ + function text( $str ) { + echo htmlspecialchars( $this->data[$str] ); + } + + /** + * @private + * @param string $str + * @return string + */ + function html( $str ) { + echo $this->data[$str]; + } + + /** + * @private + * @param string $str + * @return string + */ + function msg( $str ) { + echo htmlspecialchars( $this->translator->translate( $str ) ); + } + + /** + * @private + * @param string $str + * @return string + */ + function msgHtml( $str ) { + echo $this->translator->translate( $str ); + } + + /** + * An ugly, ugly hack. + * @private + * @param string $str + * @return string + */ + function msgWiki( $str ) { + global $wgOut; + + $text = $this->translator->translate( $str ); + echo $wgOut->parse( $text ); + } + + /** + * @private + * @param string $str + * @return bool + */ + function haveData( $str ) { + return isset( $this->data[$str] ); + } + + /** + * @private + * + * @param string $str + * @return bool + */ + function haveMsg( $str ) { + $msg = $this->translator->translate( $str ); + return ( $msg != '-' ) && ( $msg != '' ); # ???? + } + + /** + * Get the Skin object related to this object + * + * @return Skin + */ + public function getSkin() { + return $this->data['skin']; + } + + /** + * Fetch the output of a QuickTemplate and return it + * + * @since 1.23 + * @return string + */ + public function getHTML() { + ob_start(); + $this->execute(); + $html = ob_get_contents(); + ob_end_clean(); + return $html; + } +} + +/** + * New base template for a skin's template extended from QuickTemplate + * this class features helper methods that provide common ways of interacting + * with the data stored in the QuickTemplate + */ +abstract class BaseTemplate extends QuickTemplate { + + /** + * Get a Message object with its context set + * + * @param string $name Message name + * @return Message + */ + public function getMsg( $name ) { + return $this->getSkin()->msg( $name ); + } + + function msg( $str ) { + echo $this->getMsg( $str )->escaped(); + } + + function msgHtml( $str ) { + echo $this->getMsg( $str )->text(); + } + + function msgWiki( $str ) { + echo $this->getMsg( $str )->parseAsBlock(); + } + + /** + * Create an array of common toolbox items from the data in the quicktemplate + * stored by SkinTemplate. + * The resulting array is built according to a format intended to be passed + * through makeListItem to generate the html. + * @return array + */ + function getToolbox() { + wfProfileIn( __METHOD__ ); + + $toolbox = array(); + if ( isset( $this->data['nav_urls']['whatlinkshere'] ) + && $this->data['nav_urls']['whatlinkshere'] + ) { + $toolbox['whatlinkshere'] = $this->data['nav_urls']['whatlinkshere']; + $toolbox['whatlinkshere']['id'] = 't-whatlinkshere'; + } + if ( isset( $this->data['nav_urls']['recentchangeslinked'] ) + && $this->data['nav_urls']['recentchangeslinked'] + ) { + $toolbox['recentchangeslinked'] = $this->data['nav_urls']['recentchangeslinked']; + $toolbox['recentchangeslinked']['msg'] = 'recentchangeslinked-toolbox'; + $toolbox['recentchangeslinked']['id'] = 't-recentchangeslinked'; + } + if ( isset( $this->data['feeds'] ) && $this->data['feeds'] ) { + $toolbox['feeds']['id'] = 'feedlinks'; + $toolbox['feeds']['links'] = array(); + foreach ( $this->data['feeds'] as $key => $feed ) { + $toolbox['feeds']['links'][$key] = $feed; + $toolbox['feeds']['links'][$key]['id'] = "feed-$key"; + $toolbox['feeds']['links'][$key]['rel'] = 'alternate'; + $toolbox['feeds']['links'][$key]['type'] = "application/{$key}+xml"; + $toolbox['feeds']['links'][$key]['class'] = 'feedlink'; + } + } + foreach ( array( 'contributions', 'log', 'blockip', 'emailuser', + 'userrights', 'upload', 'specialpages' ) as $special + ) { + if ( isset( $this->data['nav_urls'][$special] ) && $this->data['nav_urls'][$special] ) { + $toolbox[$special] = $this->data['nav_urls'][$special]; + $toolbox[$special]['id'] = "t-$special"; + } + } + if ( isset( $this->data['nav_urls']['print'] ) && $this->data['nav_urls']['print'] ) { + $toolbox['print'] = $this->data['nav_urls']['print']; + $toolbox['print']['id'] = 't-print'; + $toolbox['print']['rel'] = 'alternate'; + $toolbox['print']['msg'] = 'printableversion'; + } + if ( isset( $this->data['nav_urls']['permalink'] ) && $this->data['nav_urls']['permalink'] ) { + $toolbox['permalink'] = $this->data['nav_urls']['permalink']; + if ( $toolbox['permalink']['href'] === '' ) { + unset( $toolbox['permalink']['href'] ); + $toolbox['ispermalink']['tooltiponly'] = true; + $toolbox['ispermalink']['id'] = 't-ispermalink'; + $toolbox['ispermalink']['msg'] = 'permalink'; + } else { + $toolbox['permalink']['id'] = 't-permalink'; + } + } + if ( isset( $this->data['nav_urls']['info'] ) && $this->data['nav_urls']['info'] ) { + $toolbox['info'] = $this->data['nav_urls']['info']; + $toolbox['info']['id'] = 't-info'; + } + + wfRunHooks( 'BaseTemplateToolbox', array( &$this, &$toolbox ) ); + wfProfileOut( __METHOD__ ); + return $toolbox; + } + + /** + * Create an array of personal tools items from the data in the quicktemplate + * stored by SkinTemplate. + * The resulting array is built according to a format intended to be passed + * through makeListItem to generate the html. + * This is in reality the same list as already stored in personal_urls + * however it is reformatted so that you can just pass the individual items + * to makeListItem instead of hardcoding the element creation boilerplate. + * @return array + */ + function getPersonalTools() { + $personal_tools = array(); + foreach ( $this->get( 'personal_urls' ) as $key => $plink ) { + # The class on a personal_urls item is meant to go on the instead + # of the
  • so we have to use a single item "links" array instead + # of using most of the personal_url's keys directly. + $ptool = array( + 'links' => array( + array( 'single-id' => "pt-$key" ), + ), + 'id' => "pt-$key", + ); + if ( isset( $plink['active'] ) ) { + $ptool['active'] = $plink['active']; + } + foreach ( array( 'href', 'class', 'text', 'dir' ) as $k ) { + if ( isset( $plink[$k] ) ) { + $ptool['links'][0][$k] = $plink[$k]; + } + } + $personal_tools[$key] = $ptool; + } + return $personal_tools; + } + + function getSidebar( $options = array() ) { + // Force the rendering of the following portals + $sidebar = $this->data['sidebar']; + if ( !isset( $sidebar['SEARCH'] ) ) { + $sidebar['SEARCH'] = true; + } + if ( !isset( $sidebar['TOOLBOX'] ) ) { + $sidebar['TOOLBOX'] = true; + } + if ( !isset( $sidebar['LANGUAGES'] ) ) { + $sidebar['LANGUAGES'] = true; + } + + if ( !isset( $options['search'] ) || $options['search'] !== true ) { + unset( $sidebar['SEARCH'] ); + } + if ( isset( $options['toolbox'] ) && $options['toolbox'] === false ) { + unset( $sidebar['TOOLBOX'] ); + } + if ( isset( $options['languages'] ) && $options['languages'] === false ) { + unset( $sidebar['LANGUAGES'] ); + } + + $boxes = array(); + foreach ( $sidebar as $boxName => $content ) { + if ( $content === false ) { + continue; + } + switch ( $boxName ) { + case 'SEARCH': + // Search is a special case, skins should custom implement this + $boxes[$boxName] = array( + 'id' => 'p-search', + 'header' => $this->getMsg( 'search' )->text(), + 'generated' => false, + 'content' => true, + ); + break; + case 'TOOLBOX': + $msgObj = $this->getMsg( 'toolbox' ); + $boxes[$boxName] = array( + 'id' => 'p-tb', + 'header' => $msgObj->exists() ? $msgObj->text() : 'toolbox', + 'generated' => false, + 'content' => $this->getToolbox(), + ); + break; + case 'LANGUAGES': + if ( $this->data['language_urls'] ) { + $msgObj = $this->getMsg( 'otherlanguages' ); + $boxes[$boxName] = array( + 'id' => 'p-lang', + 'header' => $msgObj->exists() ? $msgObj->text() : 'otherlanguages', + 'generated' => false, + 'content' => $this->data['language_urls'], + ); + } + break; + default: + $msgObj = $this->getMsg( $boxName ); + $boxes[$boxName] = array( + 'id' => "p-$boxName", + 'header' => $msgObj->exists() ? $msgObj->text() : $boxName, + 'generated' => true, + 'content' => $content, + ); + break; + } + } + + // HACK: Compatibility with extensions still using SkinTemplateToolboxEnd + $hookContents = null; + if ( isset( $boxes['TOOLBOX'] ) ) { + ob_start(); + // We pass an extra 'true' at the end so extensions using BaseTemplateToolbox + // can abort and avoid outputting double toolbox links + wfRunHooks( 'SkinTemplateToolboxEnd', array( &$this, true ) ); + $hookContents = ob_get_contents(); + ob_end_clean(); + if ( !trim( $hookContents ) ) { + $hookContents = null; + } + } + // END hack + + if ( isset( $options['htmlOnly'] ) && $options['htmlOnly'] === true ) { + foreach ( $boxes as $boxName => $box ) { + if ( is_array( $box['content'] ) ) { + $content = '
      '; + foreach ( $box['content'] as $key => $val ) { + $content .= "\n " . $this->makeListItem( $key, $val ); + } + // HACK, shove the toolbox end onto the toolbox if we're rendering itself + if ( $hookContents ) { + $content .= "\n $hookContents"; + } + // END hack + $content .= "\n
    \n"; + $boxes[$boxName]['content'] = $content; + } + } + } else { + if ( $hookContents ) { + $boxes['TOOLBOXEND'] = array( + 'id' => 'p-toolboxend', + 'header' => $boxes['TOOLBOX']['header'], + 'generated' => false, + 'content' => "
      {$hookContents}
    ", + ); + // HACK: Make sure that TOOLBOXEND is sorted next to TOOLBOX + $boxes2 = array(); + foreach ( $boxes as $key => $box ) { + if ( $key === 'TOOLBOXEND' ) { + continue; + } + $boxes2[$key] = $box; + if ( $key === 'TOOLBOX' ) { + $boxes2['TOOLBOXEND'] = $boxes['TOOLBOXEND']; + } + } + $boxes = $boxes2; + // END hack + } + } + + return $boxes; + } + + /** + * @param string $name + */ + protected function renderAfterPortlet( $name ) { + $content = ''; + wfRunHooks( 'BaseTemplateAfterPortlet', array( $this, $name, &$content ) ); + + if ( $content !== '' ) { + echo "
    $content
    "; + } + + } + + /** + * Makes a link, usually used by makeListItem to generate a link for an item + * in a list used in navigation lists, portlets, portals, sidebars, etc... + * + * @param string $key Usually a key from the list you are generating this + * link from. + * @param array $item Contains some of a specific set of keys. + * + * The text of the link will be generated either from the contents of the + * "text" key in the $item array, if a "msg" key is present a message by + * that name will be used, and if neither of those are set the $key will be + * used as a message name. + * + * If a "href" key is not present makeLink will just output htmlescaped text. + * The "href", "id", "class", "rel", and "type" keys are used as attributes + * for the link if present. + * + * If an "id" or "single-id" (if you don't want the actual id to be output + * on the link) is present it will be used to generate a tooltip and + * accesskey for the link. + * + * The keys "context" and "primary" are ignored; these keys are used + * internally by skins and are not supposed to be included in the HTML + * output. + * + * If you don't want an accesskey, set $item['tooltiponly'] = true; + * + * @param array $options Can be used to affect the output of a link. + * Possible options are: + * - 'text-wrapper' key to specify a list of elements to wrap the text of + * a link in. This should be an array of arrays containing a 'tag' and + * optionally an 'attributes' key. If you only have one element you don't + * need to wrap it in another array. eg: To use
    ... + * in all links use array( 'text-wrapper' => array( 'tag' => 'span' ) ) + * for your options. + * - 'link-class' key can be used to specify additional classes to apply + * to all links. + * - 'link-fallback' can be used to specify a tag to use instead of "" + * if there is no link. eg: If you specify 'link-fallback' => 'span' than + * any non-link will output a "" instead of just text. + * + * @return string + */ + function makeLink( $key, $item, $options = array() ) { + if ( isset( $item['text'] ) ) { + $text = $item['text']; + } else { + $text = $this->translator->translate( isset( $item['msg'] ) ? $item['msg'] : $key ); + } + + $html = htmlspecialchars( $text ); + + if ( isset( $options['text-wrapper'] ) ) { + $wrapper = $options['text-wrapper']; + if ( isset( $wrapper['tag'] ) ) { + $wrapper = array( $wrapper ); + } + while ( count( $wrapper ) > 0 ) { + $element = array_pop( $wrapper ); + $html = Html::rawElement( $element['tag'], isset( $element['attributes'] ) + ? $element['attributes'] + : null, $html ); + } + } + + if ( isset( $item['href'] ) || isset( $options['link-fallback'] ) ) { + $attrs = $item; + foreach ( array( 'single-id', 'text', 'msg', 'tooltiponly', 'context', 'primary' ) as $k ) { + unset( $attrs[$k] ); + } + + if ( isset( $item['id'] ) && !isset( $item['single-id'] ) ) { + $item['single-id'] = $item['id']; + } + if ( isset( $item['single-id'] ) ) { + if ( isset( $item['tooltiponly'] ) && $item['tooltiponly'] ) { + $title = Linker::titleAttrib( $item['single-id'] ); + if ( $title !== false ) { + $attrs['title'] = $title; + } + } else { + $tip = Linker::tooltipAndAccesskeyAttribs( $item['single-id'] ); + if ( isset( $tip['title'] ) && $tip['title'] !== false ) { + $attrs['title'] = $tip['title']; + } + if ( isset( $tip['accesskey'] ) && $tip['accesskey'] !== false ) { + $attrs['accesskey'] = $tip['accesskey']; + } + } + } + if ( isset( $options['link-class'] ) ) { + if ( isset( $attrs['class'] ) ) { + $attrs['class'] .= " {$options['link-class']}"; + } else { + $attrs['class'] = $options['link-class']; + } + } + $html = Html::rawElement( isset( $attrs['href'] ) + ? 'a' + : $options['link-fallback'], $attrs, $html ); + } + + return $html; + } + + /** + * Generates a list item for a navigation, portlet, portal, sidebar... list + * + * @param string $key Usually a key from the list you are generating this link from. + * @param array $item Array of list item data containing some of a specific set of keys. + * The "id", "class" and "itemtitle" keys will be used as attributes for the list item, + * if "active" contains a value of true a "active" class will also be appended to class. + * + * @param array $options + * + * If you want something other than a "
  • " you can pass a tag name such as + * "tag" => "span" in the $options array to change the tag used. + * link/content data for the list item may come in one of two forms + * A "links" key may be used, in which case it should contain an array with + * a list of links to include inside the list item, see makeLink for the + * format of individual links array items. + * + * Otherwise the relevant keys from the list item $item array will be passed + * to makeLink instead. Note however that "id" and "class" are used by the + * list item directly so they will not be passed to makeLink + * (however the link will still support a tooltip and accesskey from it) + * If you need an id or class on a single link you should include a "links" + * array with just one link item inside of it. If you want to add a title + * to the list item itself, you can set "itemtitle" to the value. + * $options is also passed on to makeLink calls + * + * @return string + */ + function makeListItem( $key, $item, $options = array() ) { + if ( isset( $item['links'] ) ) { + $links = array(); + foreach ( $item['links'] as $linkKey => $link ) { + $links[] = $this->makeLink( $linkKey, $link, $options ); + } + $html = implode( ' ', $links ); + } else { + $link = $item; + // These keys are used by makeListItem and shouldn't be passed on to the link + foreach ( array( 'id', 'class', 'active', 'tag', 'itemtitle' ) as $k ) { + unset( $link[$k] ); + } + if ( isset( $item['id'] ) && !isset( $item['single-id'] ) ) { + // The id goes on the
  • not on the for single links + // but makeSidebarLink still needs to know what id to use when + // generating tooltips and accesskeys. + $link['single-id'] = $item['id']; + } + $html = $this->makeLink( $key, $link, $options ); + } + + $attrs = array(); + foreach ( array( 'id', 'class' ) as $attr ) { + if ( isset( $item[$attr] ) ) { + $attrs[$attr] = $item[$attr]; + } + } + if ( isset( $item['active'] ) && $item['active'] ) { + if ( !isset( $attrs['class'] ) ) { + $attrs['class'] = ''; + } + $attrs['class'] .= ' active'; + $attrs['class'] = trim( $attrs['class'] ); + } + if ( isset( $item['itemtitle'] ) ) { + $attrs['title'] = $item['itemtitle']; + } + return Html::rawElement( isset( $options['tag'] ) ? $options['tag'] : 'li', $attrs, $html ); + } + + function makeSearchInput( $attrs = array() ) { + $realAttrs = array( + 'type' => 'search', + 'name' => 'search', + 'placeholder' => wfMessage( 'searchsuggest-search' )->text(), + 'value' => $this->get( 'search', '' ), + ); + $realAttrs = array_merge( $realAttrs, Linker::tooltipAndAccesskeyAttribs( 'search' ), $attrs ); + return Html::element( 'input', $realAttrs ); + } + + function makeSearchButton( $mode, $attrs = array() ) { + switch ( $mode ) { + case 'go': + case 'fulltext': + $realAttrs = array( + 'type' => 'submit', + 'name' => $mode, + 'value' => $this->translator->translate( + $mode == 'go' ? 'searcharticle' : 'searchbutton' ), + ); + $realAttrs = array_merge( + $realAttrs, + Linker::tooltipAndAccesskeyAttribs( "search-$mode" ), + $attrs + ); + return Html::element( 'input', $realAttrs ); + case 'image': + $buttonAttrs = array( + 'type' => 'submit', + 'name' => 'button', + ); + $buttonAttrs = array_merge( + $buttonAttrs, + Linker::tooltipAndAccesskeyAttribs( 'search-fulltext' ), + $attrs + ); + unset( $buttonAttrs['src'] ); + unset( $buttonAttrs['alt'] ); + unset( $buttonAttrs['width'] ); + unset( $buttonAttrs['height'] ); + $imgAttrs = array( + 'src' => $attrs['src'], + 'alt' => isset( $attrs['alt'] ) + ? $attrs['alt'] + : $this->translator->translate( 'searchbutton' ), + 'width' => isset( $attrs['width'] ) ? $attrs['width'] : null, + 'height' => isset( $attrs['height'] ) ? $attrs['height'] : null, + ); + return Html::rawElement( 'button', $buttonAttrs, Html::element( 'img', $imgAttrs ) ); + default: + throw new MWException( 'Unknown mode passed to BaseTemplate::makeSearchButton' ); + } + } + + /** + * Returns an array of footerlinks trimmed down to only those footer links that + * are valid. + * If you pass "flat" as an option then the returned array will be a flat array + * of footer icons instead of a key/value array of footerlinks arrays broken + * up into categories. + * @param string $option + * @return array|mixed + */ + function getFooterLinks( $option = null ) { + $footerlinks = $this->get( 'footerlinks' ); + + // Reduce footer links down to only those which are being used + $validFooterLinks = array(); + foreach ( $footerlinks as $category => $links ) { + $validFooterLinks[$category] = array(); + foreach ( $links as $link ) { + if ( isset( $this->data[$link] ) && $this->data[$link] ) { + $validFooterLinks[$category][] = $link; + } + } + if ( count( $validFooterLinks[$category] ) <= 0 ) { + unset( $validFooterLinks[$category] ); + } + } + + if ( $option == 'flat' ) { + // fold footerlinks into a single array using a bit of trickery + $validFooterLinks = call_user_func_array( + 'array_merge', + array_values( $validFooterLinks ) + ); + } + + return $validFooterLinks; + } + + /** + * Returns an array of footer icons filtered down by options relevant to how + * the skin wishes to display them. + * If you pass "icononly" as the option all footer icons which do not have an + * image icon set will be filtered out. + * If you pass "nocopyright" then MediaWiki's copyright icon will not be included + * in the list of footer icons. This is mostly useful for skins which only + * display the text from footericons instead of the images and don't want a + * duplicate copyright statement because footerlinks already rendered one. + * @param string $option + * @return string + */ + function getFooterIcons( $option = null ) { + // Generate additional footer icons + $footericons = $this->get( 'footericons' ); + + if ( $option == 'icononly' ) { + // Unset any icons which don't have an image + foreach ( $footericons as &$footerIconsBlock ) { + foreach ( $footerIconsBlock as $footerIconKey => $footerIcon ) { + if ( !is_string( $footerIcon ) && !isset( $footerIcon['src'] ) ) { + unset( $footerIconsBlock[$footerIconKey] ); + } + } + } + // Redo removal of any empty blocks + foreach ( $footericons as $footerIconsKey => &$footerIconsBlock ) { + if ( count( $footerIconsBlock ) <= 0 ) { + unset( $footericons[$footerIconsKey] ); + } + } + } elseif ( $option == 'nocopyright' ) { + unset( $footericons['copyright']['copyright'] ); + if ( count( $footericons['copyright'] ) <= 0 ) { + unset( $footericons['copyright'] ); + } + } + + return $footericons; + } + + /** + * Output the basic end-page trail including bottomscripts, reporttime, and + * debug stuff. This should be called right before outputting the closing + * body and html tags. + */ + function printTrail() { ?> +getSkin()->getContext() ); ?> +html( 'bottomscripts' ); /* JS call to runBodyOnloadHook */ ?> +html( 'reporttime' ) ?> +getMethod( 'makeResourceLoaderLink' ); $method->setAccessible( true ); $ctx = new RequestContext(); - $ctx->setSkin( Skin::newFromKey( 'vector' ) ); + $ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) ); $ctx->setLanguage( 'en' ); $out = new OutputPage( $ctx ); $rl = $out->getResourceLoader(); diff --git a/tests/phpunit/includes/SkinTemplateTest.php b/tests/phpunit/includes/SkinTemplateTest.php deleted file mode 100644 index baa995d4e6..0000000000 --- a/tests/phpunit/includes/SkinTemplateTest.php +++ /dev/null @@ -1,43 +0,0 @@ - - */ - -class SkinTemplateTest extends MediaWikiTestCase { - /** - * @dataProvider makeListItemProvider - */ - public function testMakeListItem( $expected, $key, $item, $options, $message ) { - $template = $this->getMockForAbstractClass( 'BaseTemplate' ); - - $this->assertEquals( - $expected, - $template->makeListItem( $key, $item, $options ), - $message - ); - } - - public function makeListItemProvider() { - return array( - array( - '
  • text
  • ', - '', - array( - 'class' => 'class', - 'itemtitle' => 'itemtitle', - 'href' => 'url', - 'title' => 'title', - 'text' => 'text' - ), - array(), - 'Test makteListItem with normal values' - ) - ); - } -} diff --git a/tests/phpunit/includes/skins/SkinFactoryTest.php b/tests/phpunit/includes/skins/SkinFactoryTest.php new file mode 100644 index 0000000000..4497cbabec --- /dev/null +++ b/tests/phpunit/includes/skins/SkinFactoryTest.php @@ -0,0 +1,38 @@ +register( 'fallback', 'Fallback', function() { + return new SkinFallback(); + } ); + $this->assertTrue( true ); // No exception thrown + $this->setExpectedException( 'InvalidArgumentException' ); + $factory->register( 'invalid', 'Invalid', 'Invalid callback' ); + } + + /** + * @covers SkinFactory::makeSkin + */ + public function testMakeSkinWithNoBuilders() { + $factory = new SkinFactory(); + $this->setExpectedException( 'SkinException' ); + $factory->makeSkin( 'nobuilderregistered' ); + } + + /** + * @covers SkinFactory::makeSkin + */ + public function testMakeSkinWithInvalidCallback() { + $factory = new SkinFactory(); + $factory->register( 'unittest', 'Unittest', function () { + return true; // Not a Skin object + } ); + $this->setExpectedException( 'UnexpectedValueException' ); + $factory->makeSkin( 'unittest' ); + } +} diff --git a/tests/phpunit/includes/skins/SkinTemplateTest.php b/tests/phpunit/includes/skins/SkinTemplateTest.php new file mode 100644 index 0000000000..baa995d4e6 --- /dev/null +++ b/tests/phpunit/includes/skins/SkinTemplateTest.php @@ -0,0 +1,43 @@ + + */ + +class SkinTemplateTest extends MediaWikiTestCase { + /** + * @dataProvider makeListItemProvider + */ + public function testMakeListItem( $expected, $key, $item, $options, $message ) { + $template = $this->getMockForAbstractClass( 'BaseTemplate' ); + + $this->assertEquals( + $expected, + $template->makeListItem( $key, $item, $options ), + $message + ); + } + + public function makeListItemProvider() { + return array( + array( + '
  • text
  • ', + '', + array( + 'class' => 'class', + 'itemtitle' => 'itemtitle', + 'href' => 'url', + 'title' => 'title', + 'text' => 'text' + ), + array(), + 'Test makteListItem with normal values' + ) + ); + } +}